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
2b82e224b16c7c115ef4b944dee244180a657f2b
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/UnrealLoader.cpp
1f9075045643b18a06265d6a561168af3859e838
[ "BSD-3-Clause" ]
permissive
spring/assimp
fb53b91228843f7677fe8ec18b61d7b5886a6fd3
db29c9a20d0dfa9f98c8fd473824bba5a895ae9e
refs/heads/master
2021-01-17T23:19:56.511185
2011-11-08T12:15:18
2011-11-08T12:15:18
2,017,841
1
1
null
null
null
null
UTF-8
C++
false
false
14,793
cpp
/* --------------------------------------------------------------------------- Open Asset Import Library (ASSIMP) --------------------------------------------------------------------------- Copyright (c) 2006-2010, ASSIMP Development Team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ASSIMP team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the ASSIMP Development Team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file UnrealLoader.cpp * @brief Implementation of the UNREAL (*.3D) importer class * * Sources: * http://local.wasp.uwa.edu.au/~pbourke/dataformats/unreal/ */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_3D_IMPORTER #include "UnrealLoader.h" #include "StreamReader.h" #include "ParsingUtils.h" #include "fast_atof.h" #include "ConvertToLHProcess.h" using namespace Assimp; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer UnrealImporter::UnrealImporter() : configFrameID (0) , configHandleFlags (true) {} // ------------------------------------------------------------------------------------------------ // Destructor, private as well UnrealImporter::~UnrealImporter() {} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. bool UnrealImporter::CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool /*checkSig*/) const { return SimpleExtensionCheck(pFile,"3d","uc"); } // ------------------------------------------------------------------------------------------------ // Build a string of all file extensions supported void UnrealImporter::GetExtensionList(std::set<std::string>& extensions) { extensions.insert("3d"); extensions.insert("uc"); } // ------------------------------------------------------------------------------------------------ // Setup configuration properties for the loader void UnrealImporter::SetupProperties(const Importer* pImp) { // The // AI_CONFIG_IMPORT_UNREAL_KEYFRAME option overrides the // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_KEYFRAME,-1); if(static_cast<unsigned int>(-1) == configFrameID) { configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0); } // AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS, default is true configHandleFlags = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS,1)); } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void UnrealImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { // For any of the 3 files being passed get the three correct paths // First of all, determine file extension std::string::size_type pos = pFile.find_last_of('.'); std::string extension = GetExtension(pFile); std::string d_path,a_path,uc_path; if (extension == "3d") { // jjjj_d.3d // jjjj_a.3d pos = pFile.find_last_of('_'); if (std::string::npos == pos) { throw DeadlyImportError("UNREAL: Unexpected naming scheme"); } extension = pFile.substr(0,pos); } else { extension = pFile.substr(0,pos); } // build proper paths d_path = extension+"_d.3d"; a_path = extension+"_a.3d"; uc_path = extension+".uc"; DefaultLogger::get()->debug("UNREAL: data file is " + d_path); DefaultLogger::get()->debug("UNREAL: aniv file is " + a_path); DefaultLogger::get()->debug("UNREAL: uc file is " + uc_path); // and open the files ... we can't live without them IOStream* p = pIOHandler->Open(d_path); if (!p) throw DeadlyImportError("UNREAL: Unable to open _d file"); StreamReaderLE d_reader(pIOHandler->Open(d_path)); const uint16_t numTris = d_reader.GetI2(); const uint16_t numVert = d_reader.GetI2(); d_reader.IncPtr(44); if (!numTris || numVert < 3) throw DeadlyImportError("UNREAL: Invalid number of vertices/triangles"); // maximum texture index unsigned int maxTexIdx = 0; // collect triangles std::vector<Unreal::Triangle> triangles(numTris); for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) { Unreal::Triangle& tri = *it; for (unsigned int i = 0; i < 3;++i) { tri.mVertex[i] = d_reader.GetI2(); if (tri.mVertex[i] >= numTris) { DefaultLogger::get()->warn("UNREAL: vertex index out of range"); tri.mVertex[i] = 0; } } tri.mType = d_reader.GetI1(); // handle mesh flagss? if (configHandleFlags) tri.mType = Unreal::MF_NORMAL_OS; else { // ignore MOD and MASKED for the moment, treat them as two-sided if (tri.mType == Unreal::MF_NORMAL_MOD_TS || tri.mType == Unreal::MF_NORMAL_MASKED_TS) tri.mType = Unreal::MF_NORMAL_TS; } d_reader.IncPtr(1); for (unsigned int i = 0; i < 3;++i) for (unsigned int i2 = 0; i2 < 2;++i2) tri.mTex[i][i2] = d_reader.GetI1(); tri.mTextureNum = d_reader.GetI1(); maxTexIdx = std::max(maxTexIdx,(unsigned int)tri.mTextureNum); d_reader.IncPtr(1); } p = pIOHandler->Open(a_path); if (!p) throw DeadlyImportError("UNREAL: Unable to open _a file"); StreamReaderLE a_reader(pIOHandler->Open(a_path)); // read number of frames const uint32_t numFrames = a_reader.GetI2(); if (configFrameID >= numFrames) throw DeadlyImportError("UNREAL: The requested frame does not exist"); uint32_t st = a_reader.GetI2(); if (st != numVert*4) throw DeadlyImportError("UNREAL: Unexpected aniv file length"); // skip to our frame a_reader.IncPtr(configFrameID *numVert*4); // collect vertices std::vector<aiVector3D> vertices(numVert); for (std::vector<aiVector3D>::iterator it = vertices.begin(), end = vertices.end(); it != end; ++it) { int32_t val = a_reader.GetI4(); Unreal::DecompressVertex(*it,val); } // list of textures. std::vector< std::pair<unsigned int, std::string> > textures; // allocate the output scene aiNode* nd = pScene->mRootNode = new aiNode(); nd->mName.Set("<UnrealRoot>"); // we can live without the uc file if necessary boost::scoped_ptr<IOStream> pb (pIOHandler->Open(uc_path)); if (pb.get()) { std::vector<char> _data; TextFileToBuffer(pb.get(),_data); const char* data = &_data[0]; std::vector< std::pair< std::string,std::string > > tempTextures; // do a quick search in the UC file for some known, usually texture-related, tags for (;*data;++data) { if (TokenMatchI(data,"#exec",5)) { SkipSpacesAndLineEnd(&data); // #exec TEXTURE IMPORT [...] NAME=jjjjj [...] FILE=jjjj.pcx [...] if (TokenMatchI(data,"TEXTURE",7)) { SkipSpacesAndLineEnd(&data); if (TokenMatchI(data,"IMPORT",6)) { tempTextures.push_back(std::pair< std::string,std::string >()); std::pair< std::string,std::string >& me = tempTextures.back(); for (;!IsLineEnd(*data);++data) { if (!::ASSIMP_strincmp(data,"NAME=",5)) { const char *d = data+=5; for (;!IsSpaceOrNewLine(*data);++data); me.first = std::string(d,(size_t)(data-d)); } else if (!::ASSIMP_strincmp(data,"FILE=",5)) { const char *d = data+=5; for (;!IsSpaceOrNewLine(*data);++data); me.second = std::string(d,(size_t)(data-d)); } } if (!me.first.length() || !me.second.length()) tempTextures.pop_back(); } } // #exec MESHMAP SETTEXTURE MESHMAP=box NUM=1 TEXTURE=Jtex1 // #exec MESHMAP SCALE MESHMAP=box X=0.1 Y=0.1 Z=0.2 else if (TokenMatchI(data,"MESHMAP",7)) { SkipSpacesAndLineEnd(&data); if (TokenMatchI(data,"SETTEXTURE",10)) { textures.push_back(std::pair<unsigned int, std::string>()); std::pair<unsigned int, std::string>& me = textures.back(); for (;!IsLineEnd(*data);++data) { if (!::ASSIMP_strincmp(data,"NUM=",4)) { data += 4; me.first = strtoul10(data,&data); } else if (!::ASSIMP_strincmp(data,"TEXTURE=",8)) { data += 8; const char *d = data; for (;!IsSpaceOrNewLine(*data);++data); me.second = std::string(d,(size_t)(data-d)); // try to find matching path names, doesn't care if we don't find them for (std::vector< std::pair< std::string,std::string > >::const_iterator it = tempTextures.begin(); it != tempTextures.end(); ++it) { if ((*it).first == me.second) { me.second = (*it).second; break; } } } } } else if (TokenMatchI(data,"SCALE",5)) { for (;!IsLineEnd(*data);++data) { if (data[0] == 'X' && data[1] == '=') { data = fast_atof_move(data+2,(float&)nd->mTransformation.a1); } else if (data[0] == 'Y' && data[1] == '=') { data = fast_atof_move(data+2,(float&)nd->mTransformation.b2); } else if (data[0] == 'Z' && data[1] == '=') { data = fast_atof_move(data+2,(float&)nd->mTransformation.c3); } } } } } } } else { DefaultLogger::get()->error("Unable to open .uc file"); } std::vector<Unreal::TempMat> materials; materials.reserve(textures.size()*2+5); // find out how many output meshes and materials we'll have and build material indices for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) { Unreal::Triangle& tri = *it; Unreal::TempMat mat(tri); std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat); if (nt == materials.end()) { // add material tri.matIndex = materials.size(); mat.numFaces = 1; materials.push_back(mat); ++pScene->mNumMeshes; } else { tri.matIndex = static_cast<unsigned int>(nt-materials.begin()); ++nt->numFaces; } } if (!pScene->mNumMeshes) { throw DeadlyImportError("UNREAL: Unable to find valid mesh data"); } // allocate meshes and bind them to the node graph pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]; pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials = pScene->mNumMeshes]; nd->mNumMeshes = pScene->mNumMeshes; nd->mMeshes = new unsigned int[nd->mNumMeshes]; for (unsigned int i = 0; i < pScene->mNumMeshes;++i) { aiMesh* m = pScene->mMeshes[i] = new aiMesh(); m->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; const unsigned int num = materials[i].numFaces; m->mFaces = new aiFace [num]; m->mVertices = new aiVector3D [num*3]; m->mTextureCoords[0] = new aiVector3D [num*3]; nd->mMeshes[i] = i; // create materials, too aiMaterial* mat = new aiMaterial(); pScene->mMaterials[i] = mat; // all white by default - texture rulez aiColor3D color(1.f,1.f,1.f); aiString s; ::sprintf(s.data,"mat%i_tx%i_",i,materials[i].tex); // set the two-sided flag if (materials[i].type == Unreal::MF_NORMAL_TS) { const int twosided = 1; mat->AddProperty(&twosided,1,AI_MATKEY_TWOSIDED); ::strcat(s.data,"ts_"); } else ::strcat(s.data,"os_"); // make TRANS faces 90% opaque that RemRedundantMaterials won't catch us if (materials[i].type == Unreal::MF_NORMAL_TRANS_TS) { const float opac = 0.9f; mat->AddProperty(&opac,1,AI_MATKEY_OPACITY); ::strcat(s.data,"tran_"); } else ::strcat(s.data,"opaq_"); // a special name for the weapon attachment point if (materials[i].type == Unreal::MF_WEAPON_PLACEHOLDER) { s.length = ::sprintf(s.data,"$WeaponTag$"); color = aiColor3D(0.f,0.f,0.f); } // set color and name mat->AddProperty(&color,1,AI_MATKEY_COLOR_DIFFUSE); s.length = ::strlen(s.data); mat->AddProperty(&s,AI_MATKEY_NAME); // set texture, if any const unsigned int tex = materials[i].tex; for (std::vector< std::pair< unsigned int, std::string > >::const_iterator it = textures.begin();it != textures.end();++it) { if ((*it).first == tex) { s.Set((*it).second); mat->AddProperty(&s,AI_MATKEY_TEXTURE_DIFFUSE(0)); break; } } } // fill them. for (std::vector<Unreal::Triangle>::iterator it = triangles.begin(), end = triangles.end();it != end; ++it) { Unreal::Triangle& tri = *it; Unreal::TempMat mat(tri); std::vector<Unreal::TempMat>::iterator nt = std::find(materials.begin(),materials.end(),mat); aiMesh* mesh = pScene->mMeshes[nt-materials.begin()]; aiFace& f = mesh->mFaces[mesh->mNumFaces++]; f.mIndices = new unsigned int[f.mNumIndices = 3]; for (unsigned int i = 0; i < 3;++i,mesh->mNumVertices++) { f.mIndices[i] = mesh->mNumVertices; mesh->mVertices[mesh->mNumVertices] = vertices[ tri.mVertex[i] ]; mesh->mTextureCoords[0][mesh->mNumVertices] = aiVector3D( tri.mTex[i][0] / 255.f, 1.f - tri.mTex[i][1] / 255.f, 0.f); } } // convert to RH MakeLeftHandedProcess hero; hero.Execute(pScene); FlipWindingOrderProcess flipper; flipper.Execute(pScene); } #endif // !! ASSIMP_BUILD_NO_3D_IMPORTER
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 426 ] ] ]
ba5a6594c703a6f8810685bec710c09c8bb21908
98438819cc4c13994cb0dc5aec3f5ea4bd1759ab
/examples/muser/threads.cpp
846bd650d6d9ffffa2a45f310527742b1bf26ef3
[ "MIT" ]
permissive
mjs513/threadkit
fea04497a67515de00b1a74ca4bb77c9f25b1317
c59f8abcb1b4dba39337a1ed28e53a89ae2ee39a
refs/heads/master
2020-04-08T06:51:57.646460
2011-10-04T20:25:53
2011-10-04T20:25:53
41,066,952
1
0
null
null
null
null
UTF-8
C++
false
false
5,257
cpp
// File threads.cpp // Copyright 2011 Daniel Ozick // Include #include <WProgram.h> #include <avr/pgmspace.h> #include "ThreadKit.h" #include "iodefs.h" #include "timers.h" #include "songs.h" // Constants // declare user events EVENTS ( VOICE_1_START, VOICE_2_START ); /* midi_frequencies Frequencies of MIDI note numbers from 0 to 108. Created programmatically using equal temperament formula. A0 ==> 21 ==> lowest note on piano C4 ==> 60 ==> middle C A4 ==> 69 ==> concert A C8 ==> 108 ==> highest note on piano Note: The extern declaration of a PROGMEM table is required to defeat C++ warnings. See "C++ warning with PROGMEM" at http://www.avrfreaks.net. */ extern const uint16_t midi_frequencies [] PROGMEM; const uint16_t midi_frequencies [] = { 8, 9, 9, 10, 10, 11, 12, 12, 13, 14, 15, 15, 16, 17, 18, 19, 21, 22, 23, 24, 26, 28, 29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 58, 62, 65, 69, 73, 78, 82, 87, 92, 98, 104, 110, 117, 123, 131, 139, 147, 156, 165, 175, 185, 196, 208, 220, 233, 247, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494, 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, 1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, 2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951, 4186 }; // Variables boolean voice_2_done; /* The following are intended to be U.I. variables controllable through a console. */ boolean print_scheduler_info = false; int song_delay = 5000; int tempo_factor = 240; int note_gap = 50; // Functions // user_setup -- called before any threads start void user_setup () { // setup I/O pinMode (LED_0, OUTPUT); pinMode (LED_1, OUTPUT); Serial.println ("user_setup: finished"); } // midi_frequency -- retrieve frequency of midi note from PROGMEM table uint16_t midi_frequency (uint8_t midi_number) { return (pgm_read_word_near (midi_frequencies + midi_number)); } // Threads THREAD (blink) { BEGIN_THREAD (STARTUP); while (true) { digitalWrite (LED_0, HIGH); WAIT_DELAY (100); digitalWrite (LED_0, LOW); WAIT_DELAY (100); } END_THREAD; } THREAD (scheduler_monitor) { BEGIN_THREAD (STARTUP); while (true) { WAIT (print_scheduler_info); print_scheduler_info = false; printf ("scheduler_idle_count: %d \n", scheduler_idle_count); printf ("scheduler_used_time: %d \n", scheduler_used_time); } END_THREAD; } THREAD (song_player_1) { BEGIN_THREAD (VOICE_1_START); /* Note: variables whose value must be preserved across invocations of ThreadKit scheduling macros must be declared static. */ static int i; for (i = 0; true; i++) { int pitch = song_joan [i] . pitch; int duration = song_joan [i] . duration; // if end of song if (pitch == 0) break; // start second part of round if (i == 5) broadcast (VOICE_2_START); // play note and gap timer_1_tone (midi_frequency (pitch)); WAIT_DELAY ((tempo_factor * duration) - note_gap); timer_1_tone (0); WAIT_DELAY (note_gap); } END_THREAD; } THREAD (song_player_2) { BEGIN_THREAD (VOICE_2_START); /* Note: variables whose value must be preserved across invocations of ThreadKit scheduling macros must be declared static. */ static int i; for (i = 0; true; i++) { int pitch = song_joan [i] . pitch; int duration = song_joan [i] . duration; // if end of song if (pitch == 0) break; // play note and gap timer_2_tone (midi_frequency (pitch)); WAIT_DELAY ((tempo_factor * duration) - note_gap); timer_2_tone (0); WAIT_DELAY (note_gap); } PULSE (voice_2_done); END_THREAD; } THREAD (tone_tester) { BEGIN_THREAD (NEVER); /* Note: variables whose value must be preserved across invocations of ThreadKit scheduling macros must be declared static. */ static int i; // From A0 (lowest piano key) to C8 (highest piano key) for (i = 21; i <= 108; i++) { Serial.println (midi_frequency (i)); timer_1_tone (midi_frequency (i)); timer_2_tone (midi_frequency (i)); WAIT_DELAY (200); timer_1_tone (0); timer_2_tone (0); WAIT_DELAY (50); } END_THREAD; } THREAD (song_starter) { BEGIN_THREAD (STARTUP); while (true) { WAIT_DELAY (song_delay); broadcast (VOICE_1_START); WAIT (voice_2_done); } END_THREAD; } THREAD (yield_tester) { BEGIN_THREAD (STARTUP); /* Note: variables whose value must be preserved across invocations of ThreadKit scheduling macros must be declared static. */ static int i; while (true) { i = 1000; while (i--) { YIELD (); // spin wait for 1 ms to show what happens to scheduler idle time delay (1); } WAIT_DELAY (1000); } END_THREAD; } THREADS ( blink, scheduler_monitor, song_player_1, song_player_2, tone_tester, yield_tester, song_starter );
[ [ [ 1, 285 ] ] ]
9090d7461d9a5a8c4613322f781b261a7e2a6189
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Components/Optimizers/FullSearch/itkFullSearchOptimizer.cxx
b50c78f46d5aa36128c9a5cbb740a615064e8bd0
[]
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
13,036
cxx
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __itkFullSearchOptimizer_cxx #define __itkFullSearchOptimizer_cxx #include "itkFullSearchOptimizer.h" #include "itkCommand.h" #include "itkEventObject.h" #include "itkExceptionObject.h" #include "itkNumericTraits.h" namespace itk { /** * ************************ Constructor ************************** */ FullSearchOptimizer ::FullSearchOptimizer() { itkDebugMacro("Constructor"); m_CurrentIteration = 0; m_Maximize = false; m_Value = 0.0; m_BestValue = 0.0; m_StopCondition = FullRangeSearched; m_Stop = false; m_NumberOfSearchSpaceDimensions = 0; m_SearchSpace = 0; m_LastSearchSpaceChanges = 0; } //end constructor /** * ***************** Start the optimization ********************** */ void FullSearchOptimizer ::StartOptimization( void ) { itkDebugMacro("StartOptimization"); m_CurrentIteration = 0; this->ProcessSearchSpaceChanges(); m_CurrentIndexInSearchSpace.Fill(0); m_BestIndexInSearchSpace.Fill(0); m_CurrentPointInSearchSpace = this->IndexToPoint(m_CurrentIndexInSearchSpace); m_BestPointInSearchSpace = m_CurrentPointInSearchSpace; this->SetCurrentPosition( this->PointToPosition( m_CurrentPointInSearchSpace ) ); if (m_Maximize) { m_BestValue = NumericTraits<double>::NonpositiveMin(); } else { m_BestValue = NumericTraits<double>::max(); } this->ResumeOptimization(); } /** * ******************** Resume the optimization ****************** */ void FullSearchOptimizer ::ResumeOptimization( void ) { itkDebugMacro("ResumeOptimization"); m_Stop = false; InvokeEvent( StartEvent() ); while( !m_Stop ) { try { m_Value = m_CostFunction->GetValue( this->GetCurrentPosition() ); } catch( ExceptionObject& err ) { // An exception has occurred. // Terminate immediately. m_StopCondition = MetricError; StopOptimization(); // Pass exception to caller throw err; } if( m_Stop ) { break; } /** Check if the value is a minimum or maximum */ if ( ( m_Value < m_BestValue ) ^ m_Maximize ) // ^ = xor, yields true if only one of the expressions is true { m_BestValue = m_Value; m_BestPointInSearchSpace = m_CurrentPointInSearchSpace; m_BestIndexInSearchSpace = m_CurrentIndexInSearchSpace; } this->InvokeEvent( IterationEvent() ); /** Prepare for next step */ m_CurrentIteration++; if( m_CurrentIteration >= this->GetNumberOfIterations() ) { m_StopCondition = FullRangeSearched; StopOptimization(); break; } /** Set the next position in search space. */ this->UpdateCurrentPosition(); } // end while } //end function ResumeOptimization /** * ************************** Stop optimization ****************** */ void FullSearchOptimizer ::StopOptimization( void ) { itkDebugMacro("StopOptimization"); m_Stop = true; this->SetCurrentPosition( this->PointToPosition(m_BestPointInSearchSpace) ); InvokeEvent( EndEvent() ); } // end function StopOptimization /** * ********************* UpdateCurrentPosition ******************* * * Goes to the next point in search space * * example of sequence of indices in a 3d search space: * * dim1: 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 * dim2: 0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2 0 0 0 1 1 1 2 2 2 * dim3: 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 * * The indices are transformed to points in search space with the formula: * point[i] = min[i] + stepsize[i]*index[i] for all i. * * Then the appropriate parameters in the ParameterArray are updated. */ void FullSearchOptimizer ::UpdateCurrentPosition( void ) { itkDebugMacro("Current position updated."); /** Get the current parameters; const_cast, because we want to adapt it later. */ ParametersType & currentPosition = const_cast<ParametersType &>( this->GetCurrentPosition() ); /** Get the dimension and sizes of the searchspace. */ const unsigned int searchSpaceDimension = this->GetNumberOfSearchSpaceDimensions(); const SearchSpaceSizeType & searchSpaceSize = this->GetSearchSpaceSize(); /** Derive the index of the next search space point */ bool JustSetPreviousDimToZero = true; for (unsigned int ssdim = 0; ssdim < searchSpaceDimension; ssdim++) //loop over all dimensions of the search space { /** if the full range of ssdim-1 has been searched (so, if its * index has just been set back to 0) then increase index[ssdim] */ if ( JustSetPreviousDimToZero ) { /** reset the bool */ JustSetPreviousDimToZero = false; /** determine the new value of m_CurrentIndexInSearchSpace[ssdim] */ unsigned int dummy = m_CurrentIndexInSearchSpace[ssdim] + 1; if ( dummy == searchSpaceSize[ssdim] ) { m_CurrentIndexInSearchSpace[ssdim] = 0; JustSetPreviousDimToZero = true; } else { m_CurrentIndexInSearchSpace[ssdim] = dummy; } } // end if justsetprevdimtozero } // end for /** Initialise the iterator. */ SearchSpaceIteratorType it( m_SearchSpace->Begin() ); /** Transform the index to a point in search space. * Change the appropriate parameters in the ParameterArray. * * The IndexToPoint and PointToParameter functions are not used here, * because we edit directly in the currentPosition (faster). */ for (unsigned int ssdim = 0; ssdim < searchSpaceDimension; ssdim++) { /** Transform the index to a point; point = min + step*index */ RangeType range = it.Value(); m_CurrentPointInSearchSpace[ssdim] = range[0] + static_cast<double>( range[2] * m_CurrentIndexInSearchSpace[ssdim] ); /** Update the array of parameters. */ currentPosition[ it.Index() ] = m_CurrentPointInSearchSpace[ssdim] ; it++; } // end for } // end UpdateCurrentPosition /** * ********************* ProcessSearchSpaceChanges ************** */ void FullSearchOptimizer ::ProcessSearchSpaceChanges(void) { if ( m_SearchSpace->GetMTime() > m_LastSearchSpaceChanges ) { /** Update the number of search space dimensions. */ m_NumberOfSearchSpaceDimensions = static_cast<unsigned int>( m_SearchSpace->Size() ); /** Set size of arrays accordingly */ m_SearchSpaceSize.SetSize( m_NumberOfSearchSpaceDimensions ); m_CurrentIndexInSearchSpace.SetSize( m_NumberOfSearchSpaceDimensions ); m_CurrentPointInSearchSpace.SetSize( m_NumberOfSearchSpaceDimensions ); m_BestIndexInSearchSpace.SetSize( m_NumberOfSearchSpaceDimensions ); m_BestPointInSearchSpace.SetSize( m_NumberOfSearchSpaceDimensions ); /** Initialise an iterator over the search space map. */ SearchSpaceIteratorType it( m_SearchSpace->Begin() ); for (unsigned int ssdim = 0; ssdim < m_NumberOfSearchSpaceDimensions; ssdim++) { RangeType range = it.Value(); m_SearchSpaceSize[ssdim] = static_cast<unsigned long>( (range[1]-range[0])/range[2] ) + 1 ; it++; } } // end if search space modified /** Remember the time of the last processed changes */ m_LastSearchSpaceChanges = m_SearchSpace->GetMTime(); } // end function ProcessSearchSpaceChanges /** * ********************** AddSearchDimension ******************** * * Add a dimension to the SearchSpace */ void FullSearchOptimizer ::AddSearchDimension( unsigned int param_nr, RangeValueType minimum, RangeValueType maximum, RangeValueType step ) { if (!m_SearchSpace) { m_SearchSpace = SearchSpaceType::New(); } /** Fill a range array */ RangeType range; range[0]=minimum; range[1]=maximum; range[2]=step; /** Delete the range if it already was defined before */ m_SearchSpace->DeleteIndex(param_nr); /** Insert the new range specification */ m_SearchSpace->InsertElement(param_nr,range); } /** * ******************* RemoveSearchDimension ******************** * * Remove a dimension from the SearchSpace */ void FullSearchOptimizer ::RemoveSearchDimension(unsigned int param_nr) { if (m_SearchSpace) { m_SearchSpace->DeleteIndex(param_nr); } } /** * ***************** GetNumberOfIterations ********************** * * Get the total number of iterations = sizes[0]*sizes[1]*sizes[2]* etc..... */ const unsigned long FullSearchOptimizer ::GetNumberOfIterations(void) { SearchSpaceSizeType sssize = this->GetSearchSpaceSize(); unsigned int maxssdim = this->GetNumberOfSearchSpaceDimensions(); unsigned long nr_it = 0; if ( maxssdim>0 ) { nr_it = sssize[0]; for (unsigned int ssdim = 1; ssdim < maxssdim; ssdim++) { nr_it *= sssize[ssdim]; } } // end if return nr_it; } /** * ******************** GetNumberOfSearchSpaceDimensions ******** * * Get the Dimension of the SearchSpace. */ const unsigned int FullSearchOptimizer ::GetNumberOfSearchSpaceDimensions(void) { this->ProcessSearchSpaceChanges(); return this->m_NumberOfSearchSpaceDimensions; } /** * ******************** GetSearchSpaceSize ********************** * * Returns an array containing trunc((max-min)/step) for each * SearchSpaceDimension) */ const FullSearchOptimizer::SearchSpaceSizeType & FullSearchOptimizer ::GetSearchSpaceSize(void) { this->ProcessSearchSpaceChanges(); return this->m_SearchSpaceSize; } /** * ********************* PointToPosition ************************ */ FullSearchOptimizer::ParametersType FullSearchOptimizer ::PointToPosition(const SearchSpacePointType & point) { const unsigned int searchSpaceDimension = this->GetNumberOfSearchSpaceDimensions(); /** \todo check if point has the same dimension. */ ParametersType param = this->GetInitialPosition(); /** Initialise the iterator. */ SearchSpaceIteratorType it( m_SearchSpace->Begin() ); /** Transform the index to a point in search space. */ for (unsigned int ssdim = 0; ssdim < searchSpaceDimension; ssdim++) { /** Update the array of parameters. */ param[ it.Index() ] = point[ssdim] ; /** go to next dimension in search space */ it++; } return param; } // end point to position /** * ********************* IndexToPosition ************************ */ FullSearchOptimizer::ParametersType FullSearchOptimizer ::IndexToPosition(const SearchSpaceIndexType & index) { return this->PointToPosition( this->IndexToPoint(index) ); } /** * ********************* IndexToPoint *************************** */ FullSearchOptimizer::SearchSpacePointType FullSearchOptimizer ::IndexToPoint(const SearchSpaceIndexType & index) { const unsigned int searchSpaceDimension = this->GetNumberOfSearchSpaceDimensions(); SearchSpacePointType point( searchSpaceDimension ); /** Initialise the iterator. */ SearchSpaceIteratorType it( m_SearchSpace->Begin() ); /** Transform the index to a point in search space. */ for (unsigned int ssdim = 0; ssdim < searchSpaceDimension; ssdim++) { /** point = min + step*index */ RangeType range = it.Value(); point[ssdim] = range[0] + static_cast<double>( range[2]*index[ssdim] ); /** go to next dimension in search space */ it++; } // end for return point; } // end IndexToPoint } // end namespace itk #endif // #ifndef __itkFullSearchOptimizer_cxx
[ [ [ 1, 470 ] ] ]
346d69184382af4e29a8198c1d99e2e4aeaa9c12
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Samples/AIAD/LevelUpWindow.cpp
e0e8488a8d41ef3fb10e1be1663ee74a39ea5722
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: LevelUpWindow.cpp Version: 0.01 --------------------------------------------------------------------------- */ #include "LevelUpWindow.h" using nGENE::byte; #include "PlayerCharacter.h" #include "Engine.h" #include "TextureDX9.h" #include "TextureManager.h" #include "App.h" LevelUpWindow::LevelUpWindow(): GUIWindow(WND_TRANSPARENT) { this->setWidth(800); this->setHeight(600); this->setPosition(0, 0); this->setVisible(false); this->onPaint.bind(this, &LevelUpWindow::onWindowPaint); } //---------------------------------------------------------------------- void LevelUpWindow::addControls() { } //---------------------------------------------------------------------- void LevelUpWindow::onWindowPaint() { } //----------------------------------------------------------------------
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 43 ] ] ]
ffc4761b9c26a9808e82e1cd324b5d7bac99aff5
c9390a163ae5f0bc6fdc1560be59939dcbe3eb07
/multifxVST.h
63a6b2d53aa067c3565e74711bd181c5b5771927
[]
no_license
trimpage/multifxvst
2ceae9da1768428288158319fcf03d603ba47672
1cb40f8e0cc873f389f2818b2f40665d2ba2b18b
refs/heads/master
2020-04-06T13:23:41.059632
2010-11-04T14:32:54
2010-11-04T14:32:54
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,125
h
//------------------------------------------------------// //- CopyLeft : CTAF //- //- gestion du VST (communication avec l'host) //- //------------------------------------------------------// #ifndef __multifxVST__ #define __multifxVST__ #ifndef __audioeffectx__ #include "audioeffectx.h" #endif enum { kChainTag = 0, kNumParams }; class CStockEffetLst; class CCVSTHost; class CEffectWnd; class CEffectTxTDlg; class CStockEffetLst; class CCVSTHost; class CMainDlg; class CChainDlg; class multifxVSTEditor; class multifxVST; class CControleurDlg; class CControleurLst; class CParameterLst; class CAboutDlg; //pointeur global qui stoque les object pour chaque instance class CAppPointer { public : CAppPointer(){ chaine_eff = 0; host = 0; pChain = 0; pEffEditDlg = 0; pEffParmDlg = 0; pMainDlg = 0; editor = 0; effect = 0; current_chaine = 0; parameter = 0; mnu = 0; pAboutDlg = 0; } CStockEffetLst * chaine_eff;//chaines d'effet CCVSTHost * host; //host VST virtuel (pr effet fils) CChainDlg * pChain; //dlg avec les listes de chaines CControleurDlg * pControleur;//dlg azvec les controleurs midis CControleurLst * controleur; //liste des controleurs midi CEffectWnd * pEffEditDlg; //fenetre d'effet CEffectTxTDlg * pEffParmDlg; //fenetre d'effet générique CMainDlg * pMainDlg; //fenetre principale multifxVSTEditor * editor; //fenetre VST contenant la fenetre principale multifxVST * effect; //Notre effet CParameterLst * parameter; //automatisation des parametres CMenu * mnu; //menu contenant les effets CAboutDlg * pAboutDlg; //fenetre about CEvent * m_waitfade; int current_chaine; }; //--------------------------------------------------------- class multifxVST : public AudioEffectX { public: multifxVST (audioMasterCallback audioMaster); ~multifxVST (); virtual long vendorSpecific (long lArg1, long lArg2, void* ptrArg, float floatArg); virtual void process (float **inputs, float **outputs, long sampleFrames); virtual void processReplacing (float **inputs, float **outputs, long sampleFrames); virtual long processEvents(VstEvents *events); virtual long canDo (char* text); virtual void setBlockSize (long blockSize); virtual void setParameter (long index, float value); virtual float getParameter (long index); virtual void getParameterLabel(long index, char *label); virtual void getParameterDisplay(long index, char *text); virtual void getParameterName(long index, char *text); virtual bool needIdle(){return 1;}; virtual long fxIdle(){return 0;}; void SetUpdateChaine(int chaine){}; void mIdle () {masterIdle ();} virtual void suspend (); virtual void resume (); virtual long startProcess (); // Called one time before the start of process call virtual long stopProcess (); // Called after the stop of process call virtual void setSampleRate(float sampleRate); virtual bool keysRequired (); virtual bool getProductString(char *text){strcpy(text,"MultifxVST"); return TRUE;} virtual bool getVendorString (char* text){strcpy(text,"CTAF Audio - Cédric GESTES");return TRUE;} virtual bool getEffectName (char* name){strcpy(name,"MultifxVST");return TRUE;} virtual void close(); virtual void open(); void UpdatehostAPP(); virtual void setParameterAutomated(long index ,float value); /*virtual int getInputLatency(); virtual int getOutputLatency();*/ //virtual void setParameterAutomated (long index, float value); virtual bool string2parameter (long index, char* text); virtual long getChunk(void **data,bool isPreset); virtual long setChunk(void *data,long byteSize,bool isPreset); protected: CAppPointer APP; void * dat; //pour les sauvegardes dans l'hote }; #endif
[ "CTAF@3e78e570-a0aa-6544-9a6b-7e87a0c009bc" ]
[ [ [ 1, 129 ] ] ]
865e96e01add954660410fc56cfa27da5602fa0e
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/CodeLite/cl_process.cpp
79e758dc83d825288d38415b1c85502c83c73718
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
1,701
cpp
#include "cl_process.h" #include <wx/txtstrm.h> #include <wx/sstream.h> #include "procutils.h" clProcess::clProcess(int id, const wxString &cmdLine) : wxProcess(NULL, id) , m_pid(-1) , m_uid(id) , m_cmd(cmdLine) { } clProcess::~clProcess() { } long clProcess::GetPid() { return m_pid; } void clProcess::SetPid(long pid) { m_pid = pid; } void clProcess::Terminate() { wxKillError rc; #ifdef __WXMSW__ std::map<unsigned long, bool> tree; ProcUtils pu; pu.GetProcTree(tree, GetPid()); std::map<unsigned long, bool>::iterator iter = tree.begin(); for(; iter != tree.end(); iter++){ wxKill(iter->first, wxSIGKILL, &rc); } #else wxKill(GetPid(), wxSIGKILL, &rc, wxKILL_CHILDREN); #endif // Sleep for 20 ms to allow the process to be killed and // the main frame to handle the event or else we can get // memory leak wxMilliSleep( 150 ); } long clProcess::Start(bool hide) { Redirect(); long flags = wxEXEC_ASYNC | wxEXEC_MAKE_GROUP_LEADER ; if( !hide ){ flags |= wxEXEC_NOHIDE; } m_pid = wxExecute(m_cmd, flags, this); return m_pid; } bool clProcess::HasInput(wxString &input, wxString &errors) { bool hasInput = false; while ( IsInputAvailable() ) { wxTextInputStream tis(*GetInputStream()); // this assumes that the output is always line buffered input << tis.ReadLine(); if(!input.EndsWith(wxT("\n"))){ input << wxT("\n"); } hasInput = true; } while ( IsErrorAvailable() ) { wxTextInputStream tis(*GetErrorStream()); errors << tis.ReadLine(); if(!errors.EndsWith(wxT("\n"))){ errors << wxT("\n"); } hasInput = true; } return hasInput; }
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 90 ] ] ]
2ac19090536eb47fd9a9a75decab079815ef3590
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/ModCtf/NetCtfPlugins.cpp
640f72e26b85ea8aa8dbc05a46a1a6f9af401ff9
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
12,665
cpp
//----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // 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 EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "NetCtfPlugins.h" #include "NetCtfEntityFactory.h" #include "OpenSteerUT/PluginArray.h" #include "OpenSteerUT/GridPlugin.h" #include "OpenSteerUT/CameraPlugin.h" #include "OpenSteerUT/LocalPlayer.h" #include "EduNetConnect/ClientPlugin.h" #include "EduNetConnect/PeerPlugin.h" #include "EduNetConnect/AbstractEntityReplica.h" #include "EduNetConnect/AbstractEntityReplicaConnection.h" #define ET_TEST_PLAYERREPLICATION 1 //----------------------------------------------------------------------------- // network plugins //----------------------------------------------------------------------------- typedef PeerPlugin<NetCtfPlugin> TCtfPeerPlugin; typedef ClientPlugin<NetCtfPlugin> TCtfClientPlugin; //----------------------------------------------------------------------------- // peer plugin //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CtfPeerPlugin::CtfPeerPlugin( bool bAddToRegistry ): BaseClass( bAddToRegistry ) { this->setGamePluginReplicaManager( &this->m_kReplicaManager ); this->m_kReplicaManager.setPlugin( &this->m_kGamePlugin ); // remap the entity factory this->m_pkPeerEntityFactory = ET_NEW AbstractEntityReplicaFactory( &this->m_kReplicaManager ); this->m_kGamePlugin.setEntityFactory( this->m_pkPeerEntityFactory ); } //----------------------------------------------------------------------------- CtfPeerPlugin::~CtfPeerPlugin() { ET_SAFE_DELETE( this->m_pkPeerEntityFactory ); } //----------------------------------------------------------------------------- const char* CtfPeerPlugin::name() const { return this->getClassName(); } //----------------------------------------------------------------------------- void CtfPeerPlugin::StartNetworkSession( void ) { BaseClass::StartNetworkSession(); this->m_pNetInterface->AttachPlugin(&this->m_kReplicaManager); } //----------------------------------------------------------------------------- void CtfPeerPlugin::CreateContent( void ) { BaseClass::CreateContent(); } //----------------------------------------------------------------------------- void CtfPeerPlugin::handleFunctionKeys (int keyNumber) { } //----------------------------------------------------------------------------- void CtfPeerPlugin::initGui( void* pkUserdata ) { BaseClass::initGui( pkUserdata ); } //----------------------------------------------------------------------------- void CtfPeerPlugin::DeleteContent( void ) { BaseClass::DeleteContent(); } //----------------------------------------------------------------------------- // client plugin //----------------------------------------------------------------------------- #define ET_TEST_PLAYERREPLICATION 1 //----------------------------------------------------------------------------- CtfClientPlugin::CtfClientPlugin( bool bAddToRegistry ): BaseClass( bAddToRegistry ), m_pkNetworkPlayer( NULL ) { this->setGamePluginReplicaManager( &this->m_kReplicaManager ); #if ET_TEST_PLAYERREPLICATION this->m_pkClientEntityFactory = ET_NEW AbstractEntityReplicaFactory( &this->m_kReplicaManager ); #else this->m_pkClientEntityFactory = NULL; #endif this->m_kReplicaManager.setPlugin( &this->m_kGamePlugin ); this->m_kGamePlugin.setEntityFactory( NULL ); } //----------------------------------------------------------------------------- CtfClientPlugin::~CtfClientPlugin() { ET_SAFE_DELETE( this->m_pkClientEntityFactory ); } //----------------------------------------------------------------------------- const char* CtfClientPlugin::name() const { return this->getClassName(); }; //----------------------------------------------------------------------------- void CtfClientPlugin::StartNetworkSession( void ) { BaseClass::StartNetworkSession(); this->m_pNetInterface->AttachPlugin( &this->m_kReplicaManager ); } //----------------------------------------------------------------------------- void CtfClientPlugin::CreateContent( void ) { BaseClass::CreateContent(); #if ET_TEST_PLAYERREPLICATION this->m_kGamePlugin.setEntityFactory( this->m_pkClientEntityFactory ); this->m_pkNetworkPlayer = this->m_pkClientEntityFactory->createEntity( OS_CID_PLAYER ); osAbstractController* pkController = OpenSteer::CastToAbstractPlayer( this->m_pkNetworkPlayer )->accessController(); if( NULL != pkController ) { pkController->setCustomUpdated( OpenSteer::LocalPlayerController::accessLocalPlayerController() ); } this->m_kGamePlugin.setEntityFactory( NULL ); this->m_kGamePlugin.addPlayer( OpenSteer::CastToAbstractPlayer( this->m_pkNetworkPlayer ) ); #endif } //----------------------------------------------------------------------------- void CtfClientPlugin::DeleteContent( void ) { #if ET_TEST_PLAYERREPLICATION this->m_kGamePlugin.setEntityFactory( this->m_pkClientEntityFactory ); this->m_kGamePlugin.removePlayer( OpenSteer::CastToAbstractPlayer( this->m_pkNetworkPlayer ) ); this->m_kGamePlugin.setEntityFactory( NULL ); this->m_pkClientEntityFactory->destroyEntity( this->m_pkNetworkPlayer ); this->m_pkNetworkPlayer = NULL; #endif BaseClass::DeleteContent(); } //----------------------------------------------------------------------------- void CtfClientPlugin::update (const float currentTime, const float elapsedTime) { if( NULL != this->m_pkNetworkPlayer ) { OpenSteer::CastToAbstractUpdated( m_pkNetworkPlayer )->update( currentTime, elapsedTime ); } BaseClass::update( currentTime, elapsedTime ); } //----------------------------------------------------------------------------- // offline client //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class OfflineCtfPlugin : public OpenSteer::PluginArray { ET_DECLARE_BASE(OpenSteer::PluginArray) public: OfflineCtfPlugin( bool bAddToRegistry = true ): BaseClass( bAddToRegistry ) { } OS_IMPLEMENT_CLASSNAME( OfflineCtfPlugin ) virtual void initGui(void* pkUserdata) { this->addPlugin( ET_NEW OpenSteer::CameraPlugin() ); this->addPlugin( ET_NEW OpenSteer::GridPlugin() ); this->addPlugin( ET_NEW NetCtfPlugin( false ) ); BaseClass::initGui( pkUserdata ); } virtual void open(void) { BaseClass::open(); } virtual void close(void) { BaseClass::close(); } }; //----------------------------------------------------------------------------- // render client plugin //----------------------------------------------------------------------------- CtfRenderClientPlugin::CtfRenderClientPlugin( bool bAddToRegistry ):BaseClass( bAddToRegistry ) { } //----------------------------------------------------------------------------- CtfRenderClientPlugin::~CtfRenderClientPlugin() { } //----------------------------------------------------------------------------- void CtfRenderClientPlugin::initGui(void* pkUserdata) { BaseClass::initGui( pkUserdata ); } //----------------------------------------------------------------------------- void CtfRenderClientPlugin::open(void) { BaseClass::open(); } //----------------------------------------------------------------------------- void CtfRenderClientPlugin::close(void) { BaseClass::close(); } void CtfRenderClientPlugin::prepareOpen( void ) { this->addPlugin( ET_NEW CtfClientPlugin( false ) ); } //----------------------------------------------------------------------------- // render server plugin //----------------------------------------------------------------------------- CtfRenderPeerPlugin::CtfRenderPeerPlugin( bool bAddToRegistry ):BaseClass( bAddToRegistry ) { } CtfRenderPeerPlugin::~CtfRenderPeerPlugin() {}; //----------------------------------------------------------------------------- void CtfRenderPeerPlugin::initGui(void* pkUserdata) { BaseClass::initGui( pkUserdata ); } //----------------------------------------------------------------------------- void CtfRenderPeerPlugin::open(void) { BaseClass::open(); } //----------------------------------------------------------------------------- void CtfRenderPeerPlugin::close(void) { BaseClass::close(); } void CtfRenderPeerPlugin::prepareOpen( void ) { this->addPlugin( ET_NEW CtfPeerPlugin( false ) ); } //----------------------------------------------------------------------------- // client server plugin //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CtfClientServerPlugin::CtfClientServerPlugin( bool bAddToRegistry ): BaseClass( bAddToRegistry ) { } //----------------------------------------------------------------------------- CtfClientServerPlugin::~CtfClientServerPlugin() { } //----------------------------------------------------------------------------- void CtfClientServerPlugin::open(void) { BaseClass::open(); } //----------------------------------------------------------------------------- void CtfClientServerPlugin::close(void) { BaseClass::close(); } //----------------------------------------------------------------------------- void CtfClientServerPlugin::initGui( void* pkUserdata ) { BaseClass::initGui( pkUserdata ); GLUI* glui = ::getRootGLUI(); GLUI_Panel* pluginPanel = static_cast<GLUI_Panel*>( pkUserdata ); } ////////////////////////////////////////////////////////////////////////// void CtfClientServerPlugin::prepareOpen( void ) { this->addPlugin( ET_NEW CtfPeerPlugin( false ) ); this->addPlugin( ET_NEW CtfClientPlugin( false ) ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- OfflineCtfPlugin* ctfPlugin = NULL; CtfRenderClientPlugin* ctfClientPlugin = NULL; CtfRenderPeerPlugin* ctfPeerPlugin = NULL; CtfClientServerPlugin* clientServerPlugin = NULL; //----------------------------------------------------------------------------- namespace EduNet { void initializeDynamicPlugins( ) { NetCtfPlugin::allocateEntityFactory(); ctfPlugin = ET_NEW OfflineCtfPlugin(); ctfClientPlugin = ET_NEW CtfRenderClientPlugin( true ); ctfPeerPlugin = ET_NEW CtfRenderPeerPlugin( true ); clientServerPlugin = ET_NEW CtfClientServerPlugin(); } void shutdownDynamicPlugins( ) { ET_SAFE_DELETE( ctfPlugin ); ET_SAFE_DELETE( ctfClientPlugin ); ET_SAFE_DELETE( ctfPeerPlugin ); ET_SAFE_DELETE( clientServerPlugin ); NetCtfPlugin::destroyEntityFactory(); } }
[ "janfietz@localhost" ]
[ [ [ 1, 360 ] ] ]
365ba8217e1acffe70576c4cb3318d60b3fbdb49
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/vfx/shakeeffecthelper.cc
e0279f166ab17d2cbec1c6f49d44abb321b3e63e
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,444
cc
//------------------------------------------------------------------------------ // vfx/shakeeffecthelper.cc // (C) 2005 Radon Labs GmbH //------------------------------------------------------------------------------ #include "vfx/shakeeffecthelper.h" #include "vfx/server.h" namespace VFX { //------------------------------------------------------------------------------ /** */ ShakeEffectHelper::ShakeEffectHelper() : maxDisplacement(1.0f, 1.0f, 1.0f), maxTumble(10.0f, 10.0f, 10.0f), lastTime(0.0) { // empty } //------------------------------------------------------------------------------ /** */ void ShakeEffectHelper::Update() { // only update displace and tumble at some relatively low frame rate // this prevents the shake effect from "flickering" if the // frame rate is very high nTime curTime = VFX::Server::Instance()->GetTime(); if ((0.0 == this->lastTime) || ((curTime - this->lastTime) > 0.01)) { this->lastTime = curTime; // compute a random displacement vector this->curDisplace.set(((n_rand() * 2.0f) - 1.0f) * this->maxDisplacement.x, ((n_rand() * 2.0f) - 1.0f) * this->maxDisplacement.y, ((n_rand() * 2.0f) - 1.0f) * this->maxDisplacement.z); // compute random tumble angles this->curTumble.set(((n_rand() * 2.0f) - 1.0f) * this->maxTumble.x, ((n_rand() * 2.0f) - 1.0f) * this->maxTumble.y, ((n_rand() * 2.0f) - 1.0f) * this->maxTumble.z); } // get current accumulated shake intensity at my position float shakeIntensity = VFX::Server::Instance()->ComputeShakeIntensityAtPosition(this->cameraMatrix44.pos_component()); // update the current incoming camera matrix by the displace and tumble vectors if (shakeIntensity > 0.0f) { matrix44 shakeMatrix; shakeMatrix.rotate_x(this->curTumble.x * shakeIntensity); shakeMatrix.rotate_y(this->curTumble.y * shakeIntensity); shakeMatrix.rotate_z(this->curTumble.z * shakeIntensity); shakeMatrix.translate(this->cameraMatrix33 * (this->curDisplace * shakeIntensity)); this->shakeCameraMatrix = shakeMatrix * this->cameraMatrix44; } else { this->shakeCameraMatrix = this->cameraMatrix44; } } } // namespace VFX
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 67 ] ] ]
921244c013ab5d8f58644a01fcc6e4b201894111
2b80036db6f86012afcc7bc55431355fc3234058
/src/cube/SettingsView.hpp
3578418a07a3998845a4ccff142bd0a8f9a64446
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,042
hpp
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright © 2007, mC2 Team // // Sources and Binaries of: mC2, win32cpp // // 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 author nor the names of other 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 ////////////////////////////////////////////////////////////////////////////// // Forward declare namespace win32cpp{ class Button; class ListView; class Label; } ////////////////////////////////////////////////////////////////////////////// #include <win32cpp/Frame.hpp> #include <win32cpp/CheckBox.hpp> ////////////////////////////////////////////////////////////////////////////// using namespace win32cpp; namespace musik { namespace cube { ////////////////////////////////////////////////////////////////////////////// // forward class SettingsController; ////////////////////////////////////////////////////////////////////////////// class SettingsView: public Frame { public: /*ctor*/ SettingsView(); protected: virtual void OnPressTestCheckbox(CheckBox* checkbox , int state); virtual void OnCreated(); friend class SettingsController; Button *addPathButton,*removePathButton; ListView *pathList; Label *libraryStatus; }; ////////////////////////////////////////////////////////////////////////////// } } // musik::cube
[ "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 49 ], [ 51, 66 ], [ 70, 79 ] ], [ [ 50, 50 ], [ 67, 69 ] ] ]
063e9f4f8a0fab48bdcf11138b973d6ebd9978c4
4de35be6f0b79bb7eeae32b540c6b1483b933219
/aura/socket.cpp
1aa4dbe1e48266dcfb4629f9c161af3ec3da0607
[]
no_license
NoodleBoy/aura-bot
67b2cfb44a0c8453f54cbde0526924e416a2a567
2a7d84dc56653c7a4a8edc1552a90bc848b5a5a9
refs/heads/master
2021-01-17T06:52:05.819609
2010-12-30T15:18:41
2010-12-30T15:18:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,254
cpp
/* Copyright [2010] [Josko Nikolic] 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. CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #include "aura.h" #include "util.h" #include "socket.h" #include <string.h> #ifndef WIN32 int GetLastError( ) { return errno; } #endif // // CSocket // CSocket :: CSocket( ) : m_Socket( INVALID_SOCKET ), m_HasError( false ), m_Error( 0 ) { memset( &m_SIN, 0, sizeof( m_SIN ) ); } CSocket :: CSocket( SOCKET nSocket, struct sockaddr_in nSIN ) : m_Socket( nSocket ), m_SIN( nSIN ), m_HasError( false ), m_Error( 0 ) { } CSocket :: ~CSocket( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); } BYTEARRAY CSocket :: GetPort( ) { return UTIL_CreateByteArray( m_SIN.sin_port, false ); } BYTEARRAY CSocket :: GetIP( ) { return UTIL_CreateByteArray( (uint32_t)m_SIN.sin_addr.s_addr, false ); } string CSocket :: GetIPString( ) { return inet_ntoa( m_SIN.sin_addr ); } string CSocket :: GetErrorString( ) { if( !m_HasError ) return "NO ERROR"; switch( m_Error ) { case EWOULDBLOCK: return "EWOULDBLOCK"; case EINPROGRESS: return "EINPROGRESS"; case EALREADY: return "EALREADY"; case ENOTSOCK: return "ENOTSOCK"; case EDESTADDRREQ: return "EDESTADDRREQ"; case EMSGSIZE: return "EMSGSIZE"; case EPROTOTYPE: return "EPROTOTYPE"; case ENOPROTOOPT: return "ENOPROTOOPT"; case EPROTONOSUPPORT: return "EPROTONOSUPPORT"; case ESOCKTNOSUPPORT: return "ESOCKTNOSUPPORT"; case EOPNOTSUPP: return "EOPNOTSUPP"; case EPFNOSUPPORT: return "EPFNOSUPPORT"; case EAFNOSUPPORT: return "EAFNOSUPPORT"; case EADDRINUSE: return "EADDRINUSE"; case EADDRNOTAVAIL: return "EADDRNOTAVAIL"; case ENETDOWN: return "ENETDOWN"; case ENETUNREACH: return "ENETUNREACH"; case ENETRESET: return "ENETRESET"; case ECONNABORTED: return "ECONNABORTED"; case ENOBUFS: return "ENOBUFS"; case EISCONN: return "EISCONN"; case ENOTCONN: return "ENOTCONN"; case ESHUTDOWN: return "ESHUTDOWN"; case ETOOMANYREFS: return "ETOOMANYREFS"; case ETIMEDOUT: return "ETIMEDOUT"; case ECONNREFUSED: return "ECONNREFUSED"; case ELOOP: return "ELOOP"; case ENAMETOOLONG: return "ENAMETOOLONG"; case EHOSTDOWN: return "EHOSTDOWN"; case EHOSTUNREACH: return "EHOSTUNREACH"; case ENOTEMPTY: return "ENOTEMPTY"; case EUSERS: return "EUSERS"; case EDQUOT: return "EDQUOT"; case ESTALE: return "ESTALE"; case EREMOTE: return "EREMOTE"; case ECONNRESET: return "Connection reset by peer"; } return "UNKNOWN ERROR (" + UTIL_ToString( m_Error ) + ")"; } void CSocket :: SetFD( fd_set *fd, fd_set *send_fd, int *nfds ) { if( m_Socket == INVALID_SOCKET ) return; FD_SET( m_Socket, fd ); FD_SET( m_Socket, send_fd ); #ifndef WIN32 if( m_Socket > *nfds ) *nfds = m_Socket; #endif } void CSocket :: Allocate( int type ) { m_Socket = socket( AF_INET, type, 0 ); if( m_Socket == INVALID_SOCKET ) { m_HasError = true; m_Error = GetLastError( ); Print( "[SOCKET] error (socket) - " + GetErrorString( ) ); return; } } void CSocket :: Reset( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); m_Socket = INVALID_SOCKET; memset( &m_SIN, 0, sizeof( m_SIN ) ); m_HasError = false; m_Error = 0; } // // CTCPSocket // CTCPSocket :: CTCPSocket( ) : m_Socket( INVALID_SOCKET ), m_HasError( false ), m_Error( 0 ), m_Connected( false ), m_LastRecv( GetTime( ) ), m_LastSend( GetTime( ) ) { memset( &m_SIN, 0, sizeof( m_SIN ) ); Allocate( SOCK_STREAM ); // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif } CTCPSocket :: CTCPSocket( SOCKET nSocket, struct sockaddr_in nSIN ) : m_Socket( nSocket ), m_SIN( nSIN ), m_HasError( false ), m_Error( 0 ), m_Connected( true ), m_LastRecv( GetTime( ) ), m_LastSend( GetTime( ) ) { // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif } CTCPSocket :: ~CTCPSocket( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); } void CTCPSocket :: Reset( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); Allocate( SOCK_STREAM ); m_Socket = INVALID_SOCKET; memset( &m_SIN, 0, sizeof( m_SIN ) ); m_HasError = false; m_Error = 0; m_Connected = false; m_RecvBuffer.clear( ); m_SendBuffer.clear( ); m_LastRecv = m_LastSend = GetTime( ); // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif } void CTCPSocket :: PutBytes( const string &bytes ) { m_SendBuffer += bytes; } void CTCPSocket :: PutBytes( const BYTEARRAY &bytes ) { m_SendBuffer += string( bytes.begin( ), bytes.end( ) ); } void CTCPSocket :: DoRecv( fd_set *fd ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connected ) return; if( FD_ISSET( m_Socket, fd ) ) { // data is waiting, receive it char buffer[1024]; int c = recv( m_Socket, buffer, 1024, 0 ); if( c > 0 ) { // success! add the received data to the buffer m_RecvBuffer += string( buffer, c ); m_LastRecv = GetTime( ); } else if( c == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // receive error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSOCKET] error (recv) - " + GetErrorString( ) ); return; } else if( c == 0 ) { // the other end closed the connection Print( "[TCPSOCKET] closed by remote host" ); m_Connected = false; } } } void CTCPSocket :: DoSend( fd_set *send_fd ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connected || m_SendBuffer.empty( ) ) return; if( FD_ISSET( m_Socket, send_fd ) ) { // socket is ready, send it int s = send( m_Socket, m_SendBuffer.c_str( ), (int)m_SendBuffer.size( ), MSG_NOSIGNAL ); if( s > 0 ) { // success! only some of the data may have been sent, remove it from the buffer m_SendBuffer = m_SendBuffer.substr( s ); m_LastSend = GetTime( ); } else if( s == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // send error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSOCKET] error (send) - " + GetErrorString( ) ); return; } } } void CTCPSocket :: Disconnect( ) { if( m_Socket != INVALID_SOCKET ) shutdown( m_Socket, SHUT_RDWR ); m_Connected = false; } void CTCPSocket :: SetNoDelay( ) { int OptVal = 1; setsockopt( m_Socket, IPPROTO_TCP, TCP_NODELAY, (const char *)&OptVal, sizeof( int ) ); } BYTEARRAY CTCPSocket :: GetPort( ) { return UTIL_CreateByteArray( m_SIN.sin_port, false ); } BYTEARRAY CTCPSocket :: GetIP( ) { return UTIL_CreateByteArray( (uint32_t)m_SIN.sin_addr.s_addr, false ); } string CTCPSocket :: GetIPString( ) { return inet_ntoa( m_SIN.sin_addr ); } string CTCPSocket :: GetErrorString( ) { if( !m_HasError ) return "NO ERROR"; switch( m_Error ) { case EWOULDBLOCK: return "EWOULDBLOCK"; case EINPROGRESS: return "EINPROGRESS"; case EALREADY: return "EALREADY"; case ENOTSOCK: return "ENOTSOCK"; case EDESTADDRREQ: return "EDESTADDRREQ"; case EMSGSIZE: return "EMSGSIZE"; case EPROTOTYPE: return "EPROTOTYPE"; case ENOPROTOOPT: return "ENOPROTOOPT"; case EPROTONOSUPPORT: return "EPROTONOSUPPORT"; case ESOCKTNOSUPPORT: return "ESOCKTNOSUPPORT"; case EOPNOTSUPP: return "EOPNOTSUPP"; case EPFNOSUPPORT: return "EPFNOSUPPORT"; case EAFNOSUPPORT: return "EAFNOSUPPORT"; case EADDRINUSE: return "EADDRINUSE"; case EADDRNOTAVAIL: return "EADDRNOTAVAIL"; case ENETDOWN: return "ENETDOWN"; case ENETUNREACH: return "ENETUNREACH"; case ENETRESET: return "ENETRESET"; case ECONNABORTED: return "ECONNABORTED"; case ENOBUFS: return "ENOBUFS"; case EISCONN: return "EISCONN"; case ENOTCONN: return "ENOTCONN"; case ESHUTDOWN: return "ESHUTDOWN"; case ETOOMANYREFS: return "ETOOMANYREFS"; case ETIMEDOUT: return "ETIMEDOUT"; case ECONNREFUSED: return "ECONNREFUSED"; case ELOOP: return "ELOOP"; case ENAMETOOLONG: return "ENAMETOOLONG"; case EHOSTDOWN: return "EHOSTDOWN"; case EHOSTUNREACH: return "EHOSTUNREACH"; case ENOTEMPTY: return "ENOTEMPTY"; case EUSERS: return "EUSERS"; case EDQUOT: return "EDQUOT"; case ESTALE: return "ESTALE"; case EREMOTE: return "EREMOTE"; case ECONNRESET: return "Connection reset by peer"; } return "UNKNOWN ERROR (" + UTIL_ToString( m_Error ) + ")"; } void CTCPSocket :: SetFD( fd_set *fd, fd_set *send_fd, int *nfds ) { if( m_Socket == INVALID_SOCKET ) return; FD_SET( m_Socket, fd ); FD_SET( m_Socket, send_fd ); #ifndef WIN32 if( m_Socket > *nfds ) *nfds = m_Socket; #endif } void CTCPSocket :: Allocate( int type ) { m_Socket = socket( AF_INET, type, 0 ); if( m_Socket == INVALID_SOCKET ) { m_HasError = true; m_Error = GetLastError( ); Print( "[SOCKET] error (socket) - " + GetErrorString( ) ); return; } } // // CTCPClient // CTCPClient :: CTCPClient( ) : m_Socket( INVALID_SOCKET ), m_HasError( false ), m_Error( 0 ), m_Connected( false ), m_Connecting( false ), m_LastRecv( GetTime( ) ), m_LastSend( GetTime( ) ) { memset( &m_SIN, 0, sizeof( m_SIN ) ); Allocate( SOCK_STREAM ); // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif } CTCPClient :: ~CTCPClient( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); } void CTCPClient :: Reset( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); Allocate( SOCK_STREAM ); m_Socket = INVALID_SOCKET; memset( &m_SIN, 0, sizeof( m_SIN ) ); m_HasError = false; m_Error = 0; m_Connected = false; m_RecvBuffer.clear( ); m_SendBuffer.clear( ); m_LastRecv = m_LastSend = GetTime( ); // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif m_Connecting = false; } void CTCPClient :: Disconnect( ) { if( m_Socket != INVALID_SOCKET ) shutdown( m_Socket, SHUT_RDWR ); m_Connected = false; m_Connecting = false; } void CTCPClient :: Connect( const string &localaddress, const string &address, uint16_t port ) { if( m_Socket == INVALID_SOCKET || m_HasError || m_Connecting || m_Connected ) return; if( !localaddress.empty( ) ) { struct sockaddr_in LocalSIN; memset( &LocalSIN, 0, sizeof( LocalSIN ) ); LocalSIN.sin_family = AF_INET; if( ( LocalSIN.sin_addr.s_addr = inet_addr( localaddress.c_str( ) ) ) == INADDR_NONE ) LocalSIN.sin_addr.s_addr = INADDR_ANY; LocalSIN.sin_port = htons( 0 ); if( bind( m_Socket, (struct sockaddr *)&LocalSIN, sizeof( LocalSIN ) ) == SOCKET_ERROR ) { m_HasError = true; m_Error = GetLastError( ); Print( "[TCPCLIENT] error (bind) - " + GetErrorString( ) ); return; } } // get IP address struct hostent *HostInfo; uint32_t HostAddress; HostInfo = gethostbyname( address.c_str( ) ); if( !HostInfo ) { m_HasError = true; // m_Error = h_error; Print( "[TCPCLIENT] error (gethostbyname)" ); return; } memcpy( &HostAddress, HostInfo->h_addr, HostInfo->h_length ); // connect m_SIN.sin_family = AF_INET; m_SIN.sin_addr.s_addr = HostAddress; m_SIN.sin_port = htons( port ); if( connect( m_Socket, (struct sockaddr *)&m_SIN, sizeof( m_SIN ) ) == SOCKET_ERROR ) { if( GetLastError( ) != EINPROGRESS && GetLastError( ) != EWOULDBLOCK ) { // connect error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPCLIENT] error (connect) - " + GetErrorString( ) ); return; } } m_Connecting = true; } bool CTCPClient :: CheckConnect( ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connecting ) return false; fd_set fd; FD_ZERO( &fd ); FD_SET( m_Socket, &fd ); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; // check if the socket is connected #ifdef WIN32 if( select( 1, NULL, &fd, NULL, &tv ) == SOCKET_ERROR ) #else if( select( m_Socket + 1, NULL, &fd, NULL, &tv ) == SOCKET_ERROR ) #endif { m_HasError = true; m_Error = GetLastError( ); return false; } if( FD_ISSET( m_Socket, &fd ) ) { m_Connecting = false; m_Connected = true; return true; } return false; } void CTCPClient :: PutBytes( const string &bytes ) { m_SendBuffer += bytes; } void CTCPClient :: PutBytes( const BYTEARRAY &bytes ) { m_SendBuffer += string( bytes.begin( ), bytes.end( ) ); } void CTCPClient :: FlushRecv( fd_set *fd ) { if( FD_ISSET( m_Socket, fd ) ) { char buffer[1024]; recv( m_Socket, buffer, 1024, 0 ); } } void CTCPClient :: DoRecv( fd_set *fd ) { if( FD_ISSET( m_Socket, fd ) ) { // data is waiting, receive it char buffer[1024]; int c = recv( m_Socket, buffer, 1024, 0 ); if( c > 0 ) { // success! add the received data to the buffer m_RecvBuffer += string( buffer, c ); m_LastRecv = GetTime( ); } else if( c == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // receive error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSOCKET] error (recv) - " + GetErrorString( ) ); return; } else if( c == 0 ) { // the other end closed the connection Print( "[TCPSOCKET] closed by remote host" ); m_Connected = false; } } } void CTCPClient :: DoSend( fd_set *send_fd ) { if( FD_ISSET( m_Socket, send_fd ) ) { // socket is ready, send it int s = send( m_Socket, m_SendBuffer.c_str( ), (int)m_SendBuffer.size( ), MSG_NOSIGNAL ); if( s > 0 ) { // success! only some of the data may have been sent, remove it from the buffer m_SendBuffer = m_SendBuffer.substr( s ); m_LastSend = GetTime( ); } else if( s == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // send error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSOCKET] error (send) - " + GetErrorString( ) ); return; } } } void CTCPClient :: SetNoDelay( ) { int OptVal = 1; setsockopt( m_Socket, IPPROTO_TCP, TCP_NODELAY, (const char *)&OptVal, sizeof( int ) ); } void CTCPClient :: SetKeepAlive( ) { // set the keep alive sending int OptVal = 1; setsockopt( m_Socket, SOL_SOCKET, SO_KEEPALIVE, (const char *)&OptVal, sizeof( int ) ); // Windows users need to edit the registry for the following options :( // http://support.microsoft.com/kb/158474 #if !defined( WIN32 ) && !defined(__APPLE__) // set the time after which keep alives are started to be sent, in seconds OptVal = 900; setsockopt( m_Socket, SOL_TCP, TCP_KEEPIDLE, (const char *)&OptVal, sizeof( int ) ); // set the interval between two consecutive keep alives, in seconds OptVal = 60; setsockopt( m_Socket, SOL_TCP, TCP_KEEPINTVL, (const char *)&OptVal, sizeof( int ) ); #endif } BYTEARRAY CTCPClient :: GetPort( ) { return UTIL_CreateByteArray( m_SIN.sin_port, false ); } BYTEARRAY CTCPClient :: GetIP( ) { return UTIL_CreateByteArray( (uint32_t)m_SIN.sin_addr.s_addr, false ); } string CTCPClient :: GetIPString( ) { return inet_ntoa( m_SIN.sin_addr ); } string CTCPClient :: GetErrorString( ) { if( !m_HasError ) return "NO ERROR"; switch( m_Error ) { case EWOULDBLOCK: return "EWOULDBLOCK"; case EINPROGRESS: return "EINPROGRESS"; case EALREADY: return "EALREADY"; case ENOTSOCK: return "ENOTSOCK"; case EDESTADDRREQ: return "EDESTADDRREQ"; case EMSGSIZE: return "EMSGSIZE"; case EPROTOTYPE: return "EPROTOTYPE"; case ENOPROTOOPT: return "ENOPROTOOPT"; case EPROTONOSUPPORT: return "EPROTONOSUPPORT"; case ESOCKTNOSUPPORT: return "ESOCKTNOSUPPORT"; case EOPNOTSUPP: return "EOPNOTSUPP"; case EPFNOSUPPORT: return "EPFNOSUPPORT"; case EAFNOSUPPORT: return "EAFNOSUPPORT"; case EADDRINUSE: return "EADDRINUSE"; case EADDRNOTAVAIL: return "EADDRNOTAVAIL"; case ENETDOWN: return "ENETDOWN"; case ENETUNREACH: return "ENETUNREACH"; case ENETRESET: return "ENETRESET"; case ECONNABORTED: return "ECONNABORTED"; case ENOBUFS: return "ENOBUFS"; case EISCONN: return "EISCONN"; case ENOTCONN: return "ENOTCONN"; case ESHUTDOWN: return "ESHUTDOWN"; case ETOOMANYREFS: return "ETOOMANYREFS"; case ETIMEDOUT: return "ETIMEDOUT"; case ECONNREFUSED: return "ECONNREFUSED"; case ELOOP: return "ELOOP"; case ENAMETOOLONG: return "ENAMETOOLONG"; case EHOSTDOWN: return "EHOSTDOWN"; case EHOSTUNREACH: return "EHOSTUNREACH"; case ENOTEMPTY: return "ENOTEMPTY"; case EUSERS: return "EUSERS"; case EDQUOT: return "EDQUOT"; case ESTALE: return "ESTALE"; case EREMOTE: return "EREMOTE"; case ECONNRESET: return "Connection reset by peer"; } return "UNKNOWN ERROR (" + UTIL_ToString( m_Error ) + ")"; } void CTCPClient :: SetFD( fd_set *fd, fd_set *send_fd, int *nfds ) { if( m_Socket == INVALID_SOCKET ) return; FD_SET( m_Socket, fd ); FD_SET( m_Socket, send_fd ); #ifndef WIN32 if( m_Socket > *nfds ) *nfds = m_Socket; #endif } void CTCPClient :: Allocate( int type ) { m_Socket = socket( AF_INET, type, 0 ); if( m_Socket == INVALID_SOCKET ) { m_HasError = true; m_Error = GetLastError( ); Print( "[SOCKET] error (socket) - " + GetErrorString( ) ); return; } } // // CTCPServer // CTCPServer :: CTCPServer( ) : m_Socket( INVALID_SOCKET ), m_HasError( false ), m_Error( 0 ), m_Connected( false ), m_LastRecv( GetTime( ) ), m_LastSend( GetTime( ) ) { memset( &m_SIN, 0, sizeof( m_SIN ) ); Allocate( SOCK_STREAM ); // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif // set the socket to reuse the address in case it hasn't been released yet int optval = 1; #ifdef WIN32 setsockopt( m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&optval, sizeof( int ) ); #else setsockopt( m_Socket, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof( int ) ); #endif } CTCPServer :: ~CTCPServer( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); } bool CTCPServer :: Listen( const string &address, uint16_t port ) { if( m_Socket == INVALID_SOCKET || m_HasError ) return false; m_SIN.sin_family = AF_INET; if( !address.empty( ) ) { if( ( m_SIN.sin_addr.s_addr = inet_addr( address.c_str( ) ) ) == INADDR_NONE ) m_SIN.sin_addr.s_addr = INADDR_ANY; } else m_SIN.sin_addr.s_addr = INADDR_ANY; m_SIN.sin_port = htons( port ); if( bind( m_Socket, (struct sockaddr *)&m_SIN, sizeof( m_SIN ) ) == SOCKET_ERROR ) { m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSERVER] error (bind) - " + GetErrorString( ) ); return false; } // listen, queue length 8 if( listen( m_Socket, 8 ) == SOCKET_ERROR ) { m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSERVER] error (listen) - " + GetErrorString( ) ); return false; } return true; } CTCPSocket *CTCPServer :: Accept( fd_set *fd ) { if( m_Socket == INVALID_SOCKET || m_HasError ) return NULL; if( FD_ISSET( m_Socket, fd ) ) { // a connection is waiting, accept it struct sockaddr_in Addr; int AddrLen = sizeof( Addr ); SOCKET NewSocket; #ifdef WIN32 if( ( NewSocket = accept( m_Socket, (struct sockaddr *)&Addr, &AddrLen ) ) == INVALID_SOCKET ) #else if( ( NewSocket = accept( m_Socket, (struct sockaddr *)&Addr, (socklen_t *)&AddrLen ) ) == INVALID_SOCKET ) #endif { // accept error, ignore it } else { // success! return the new socket return new CTCPSocket( NewSocket, Addr ); } } return NULL; } void CTCPServer :: Reset( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); Allocate( SOCK_STREAM ); m_Socket = INVALID_SOCKET; memset( &m_SIN, 0, sizeof( m_SIN ) ); m_HasError = false; m_Error = 0; m_Connected = false; m_RecvBuffer.clear( ); m_SendBuffer.clear( ); m_LastRecv = m_LastSend = GetTime( ); // make socket non blocking #ifdef WIN32 int iMode = 1; ioctlsocket( m_Socket, FIONBIO, (u_long FAR *)&iMode ); #else fcntl( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); #endif } void CTCPServer :: PutBytes( const string &bytes ) { m_SendBuffer += bytes; } void CTCPServer :: PutBytes( const BYTEARRAY &bytes ) { m_SendBuffer += string( bytes.begin( ), bytes.end( ) ); } void CTCPServer :: DoRecv( fd_set *fd ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connected ) return; if( FD_ISSET( m_Socket, fd ) ) { // data is waiting, receive it char buffer[1024]; int c = recv( m_Socket, buffer, 1024, 0 ); if( c > 0 ) { // success! add the received data to the buffer m_RecvBuffer += string( buffer, c ); m_LastRecv = GetTime( ); } else if( c == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // receive error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSOCKET] error (recv) - " + GetErrorString( ) ); return; } else if( c == 0 ) { // the other end closed the connection Print( "[TCPSOCKET] closed by remote host" ); m_Connected = false; } } } void CTCPServer :: DoSend( fd_set *send_fd ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connected || m_SendBuffer.empty( ) ) return; if( FD_ISSET( m_Socket, send_fd ) ) { // socket is ready, send it int s = send( m_Socket, m_SendBuffer.c_str( ), (int)m_SendBuffer.size( ), MSG_NOSIGNAL ); if( s > 0 ) { // success! only some of the data may have been sent, remove it from the buffer m_SendBuffer = m_SendBuffer.substr( s ); m_LastSend = GetTime( ); } else if( s == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // send error m_HasError = true; m_Error = GetLastError( ); Print( "[TCPSOCKET] error (send) - " + GetErrorString( ) ); return; } } } void CTCPServer :: Disconnect( ) { if( m_Socket != INVALID_SOCKET ) shutdown( m_Socket, SHUT_RDWR ); m_Connected = false; } void CTCPServer :: SetNoDelay( ) { int OptVal = 1; setsockopt( m_Socket, IPPROTO_TCP, TCP_NODELAY, (const char *)&OptVal, sizeof( int ) ); } BYTEARRAY CTCPServer :: GetPort( ) { return UTIL_CreateByteArray( m_SIN.sin_port, false ); } BYTEARRAY CTCPServer :: GetIP( ) { return UTIL_CreateByteArray( (uint32_t)m_SIN.sin_addr.s_addr, false ); } string CTCPServer :: GetIPString( ) { return inet_ntoa( m_SIN.sin_addr ); } string CTCPServer :: GetErrorString( ) { if( !m_HasError ) return "NO ERROR"; switch( m_Error ) { case EWOULDBLOCK: return "EWOULDBLOCK"; case EINPROGRESS: return "EINPROGRESS"; case EALREADY: return "EALREADY"; case ENOTSOCK: return "ENOTSOCK"; case EDESTADDRREQ: return "EDESTADDRREQ"; case EMSGSIZE: return "EMSGSIZE"; case EPROTOTYPE: return "EPROTOTYPE"; case ENOPROTOOPT: return "ENOPROTOOPT"; case EPROTONOSUPPORT: return "EPROTONOSUPPORT"; case ESOCKTNOSUPPORT: return "ESOCKTNOSUPPORT"; case EOPNOTSUPP: return "EOPNOTSUPP"; case EPFNOSUPPORT: return "EPFNOSUPPORT"; case EAFNOSUPPORT: return "EAFNOSUPPORT"; case EADDRINUSE: return "EADDRINUSE"; case EADDRNOTAVAIL: return "EADDRNOTAVAIL"; case ENETDOWN: return "ENETDOWN"; case ENETUNREACH: return "ENETUNREACH"; case ENETRESET: return "ENETRESET"; case ECONNABORTED: return "ECONNABORTED"; case ENOBUFS: return "ENOBUFS"; case EISCONN: return "EISCONN"; case ENOTCONN: return "ENOTCONN"; case ESHUTDOWN: return "ESHUTDOWN"; case ETOOMANYREFS: return "ETOOMANYREFS"; case ETIMEDOUT: return "ETIMEDOUT"; case ECONNREFUSED: return "ECONNREFUSED"; case ELOOP: return "ELOOP"; case ENAMETOOLONG: return "ENAMETOOLONG"; case EHOSTDOWN: return "EHOSTDOWN"; case EHOSTUNREACH: return "EHOSTUNREACH"; case ENOTEMPTY: return "ENOTEMPTY"; case EUSERS: return "EUSERS"; case EDQUOT: return "EDQUOT"; case ESTALE: return "ESTALE"; case EREMOTE: return "EREMOTE"; case ECONNRESET: return "Connection reset by peer"; } return "UNKNOWN ERROR (" + UTIL_ToString( m_Error ) + ")"; } void CTCPServer :: SetFD( fd_set *fd, fd_set *send_fd, int *nfds ) { if( m_Socket == INVALID_SOCKET ) return; FD_SET( m_Socket, fd ); FD_SET( m_Socket, send_fd ); #ifndef WIN32 if( m_Socket > *nfds ) *nfds = m_Socket; #endif } void CTCPServer :: Allocate( int type ) { m_Socket = socket( AF_INET, type, 0 ); if( m_Socket == INVALID_SOCKET ) { m_HasError = true; m_Error = GetLastError( ); Print( "[SOCKET] error (socket) - " + GetErrorString( ) ); return; } } // // CUDPSocket // CUDPSocket :: CUDPSocket( ) : m_Socket( INVALID_SOCKET ), m_HasError( false ), m_Error( 0 ) { Allocate( SOCK_DGRAM ); // enable broadcast support int OptVal = 1; setsockopt( m_Socket, SOL_SOCKET, SO_BROADCAST, (const char *)&OptVal, sizeof( int ) ); // set default broadcast target m_BroadcastTarget.s_addr = INADDR_BROADCAST; } CUDPSocket :: ~CUDPSocket( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); } bool CUDPSocket :: SendTo( struct sockaddr_in sin, const BYTEARRAY &message ) { if( m_Socket == INVALID_SOCKET || m_HasError ) return false; string MessageString = string( message.begin( ), message.end( ) ); if( sendto( m_Socket, MessageString.c_str( ), MessageString.size( ), 0, (struct sockaddr *)&sin, sizeof( sin ) ) == -1 ) return false; return true; } bool CUDPSocket :: SendTo( const string &address, uint16_t port, const BYTEARRAY &message ) { if( m_Socket == INVALID_SOCKET || m_HasError ) return false; // get IP address struct hostent *HostInfo; uint32_t HostAddress; HostInfo = gethostbyname( address.c_str( ) ); if( !HostInfo ) { m_HasError = true; // m_Error = h_error; Print( "[UDPSOCKET] error (gethostbyname)" ); return false; } memcpy( &HostAddress, HostInfo->h_addr, HostInfo->h_length ); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = HostAddress; sin.sin_port = htons( port ); return SendTo( sin, message ); } bool CUDPSocket :: Broadcast( uint16_t port, const BYTEARRAY &message ) { if( m_Socket == INVALID_SOCKET || m_HasError ) return false; struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = m_BroadcastTarget.s_addr; sin.sin_port = htons( port ); string MessageString = string( message.begin( ), message.end( ) ); if( sendto( m_Socket, MessageString.c_str( ), MessageString.size( ), 0, (struct sockaddr *)&sin, sizeof( sin ) ) == -1 ) { Print( "[UDPSOCKET] failed to broadcast packet (port " + UTIL_ToString( port ) + ", size " + UTIL_ToString( MessageString.size( ) ) + " bytes)" ); return false; } return true; } void CUDPSocket :: SetBroadcastTarget( const string &subnet ) { if( subnet.empty( ) ) { Print( "[UDPSOCKET] using default broadcast target" ); m_BroadcastTarget.s_addr = INADDR_BROADCAST; } else { // this function does not check whether the given subnet is a valid subnet the user is on // convert string representation of ip/subnet to in_addr Print( "[UDPSOCKET] using broadcast target [" + subnet + "]" ); m_BroadcastTarget.s_addr = inet_addr( subnet.c_str( ) ); // if conversion fails, inet_addr( ) returns INADDR_NONE if( m_BroadcastTarget.s_addr == INADDR_NONE ) { Print( "[UDPSOCKET] invalid broadcast target, using default broadcast target" ); m_BroadcastTarget.s_addr = INADDR_BROADCAST; } } } void CUDPSocket :: SetDontRoute( bool dontRoute ) { int OptVal = 0; if( dontRoute ) OptVal = 1; // don't route packets; make them ignore routes set by routing table and send them to the interface // belonging to the target address directly setsockopt( m_Socket, SOL_SOCKET, SO_DONTROUTE, (const char *)&OptVal, sizeof( int ) ); } BYTEARRAY CUDPSocket :: GetPort( ) { return UTIL_CreateByteArray( m_SIN.sin_port, false ); } BYTEARRAY CUDPSocket :: GetIP( ) { return UTIL_CreateByteArray( (uint32_t)m_SIN.sin_addr.s_addr, false ); } string CUDPSocket :: GetIPString( ) { return inet_ntoa( m_SIN.sin_addr ); } string CUDPSocket :: GetErrorString( ) { if( !m_HasError ) return "NO ERROR"; switch( m_Error ) { case EWOULDBLOCK: return "EWOULDBLOCK"; case EINPROGRESS: return "EINPROGRESS"; case EALREADY: return "EALREADY"; case ENOTSOCK: return "ENOTSOCK"; case EDESTADDRREQ: return "EDESTADDRREQ"; case EMSGSIZE: return "EMSGSIZE"; case EPROTOTYPE: return "EPROTOTYPE"; case ENOPROTOOPT: return "ENOPROTOOPT"; case EPROTONOSUPPORT: return "EPROTONOSUPPORT"; case ESOCKTNOSUPPORT: return "ESOCKTNOSUPPORT"; case EOPNOTSUPP: return "EOPNOTSUPP"; case EPFNOSUPPORT: return "EPFNOSUPPORT"; case EAFNOSUPPORT: return "EAFNOSUPPORT"; case EADDRINUSE: return "EADDRINUSE"; case EADDRNOTAVAIL: return "EADDRNOTAVAIL"; case ENETDOWN: return "ENETDOWN"; case ENETUNREACH: return "ENETUNREACH"; case ENETRESET: return "ENETRESET"; case ECONNABORTED: return "ECONNABORTED"; case ENOBUFS: return "ENOBUFS"; case EISCONN: return "EISCONN"; case ENOTCONN: return "ENOTCONN"; case ESHUTDOWN: return "ESHUTDOWN"; case ETOOMANYREFS: return "ETOOMANYREFS"; case ETIMEDOUT: return "ETIMEDOUT"; case ECONNREFUSED: return "ECONNREFUSED"; case ELOOP: return "ELOOP"; case ENAMETOOLONG: return "ENAMETOOLONG"; case EHOSTDOWN: return "EHOSTDOWN"; case EHOSTUNREACH: return "EHOSTUNREACH"; case ENOTEMPTY: return "ENOTEMPTY"; case EUSERS: return "EUSERS"; case EDQUOT: return "EDQUOT"; case ESTALE: return "ESTALE"; case EREMOTE: return "EREMOTE"; case ECONNRESET: return "Connection reset by peer"; } return "UNKNOWN ERROR (" + UTIL_ToString( m_Error ) + ")"; } void CUDPSocket :: SetFD( fd_set *fd, fd_set *send_fd, int *nfds ) { if( m_Socket == INVALID_SOCKET ) return; FD_SET( m_Socket, fd ); FD_SET( m_Socket, send_fd ); #ifndef WIN32 if( m_Socket > *nfds ) *nfds = m_Socket; #endif } void CUDPSocket :: Allocate( int type ) { m_Socket = socket( AF_INET, type, 0 ); if( m_Socket == INVALID_SOCKET ) { m_HasError = true; m_Error = GetLastError( ); Print( "[SOCKET] error (socket) - " + GetErrorString( ) ); return; } } void CUDPSocket :: Reset( ) { if( m_Socket != INVALID_SOCKET ) closesocket( m_Socket ); m_Socket = INVALID_SOCKET; memset( &m_SIN, 0, sizeof( m_SIN ) ); m_HasError = false; m_Error = 0; }
[ "[email protected]@268e31a9-a219-ec89-1cb4-ecc417c412f6", "[email protected]" ]
[ [ [ 1, 2 ], [ 4, 19 ], [ 21, 655 ], [ 657, 1297 ] ], [ [ 3, 3 ], [ 20, 20 ], [ 656, 656 ] ] ]
018c8b78f58245a62682ed6d54d281d560480a33
6c8c4728e608a4badd88de181910a294be56953a
/CommunicationModule/TelepathyIM/FriendRequest.cpp
441fe4980e53e53a0dcd639c1a6869f3b94fb84d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,379
cpp
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "FriendRequest.h" #include "MemoryLeakCheck.h" namespace TelepathyIM { FriendRequest::FriendRequest(Tp::ContactPtr contact) : state_(STATE_PENDING), tp_contact_(contact) { } QString FriendRequest::GetOriginatorName() const { return tp_contact_->alias(); } QString FriendRequest::GetOriginatorID() const { return tp_contact_->id(); } Communication::FriendRequestInterface::State FriendRequest::GetState() const { return state_; } void FriendRequest::Accept() { QString message; message = ""; // we don't want to send any particular message at this point Tp::PendingOperation* p = tp_contact_->authorizePresencePublication(message); QObject::connect(p, SIGNAL(finished(Tp::PendingOperation*)), SLOT(OnPresencePublicationAuthorized(Tp::PendingOperation*)) ); // Request presence subscription from friend request originator so that // publicity is on the same level to both directions if (tp_contact_->subscriptionState() == Tp::Contact::PresenceStateYes ) { emit Accepted(this); } else { message = ""; // we don't want to send any particular message at this point Tp::PendingOperation* op = tp_contact_->requestPresenceSubscription(message); connect(op, SIGNAL( finished(Tp::PendingOperation*) ), SLOT( OnPresenceSubscriptionResult(Tp::PendingOperation*) ) ); } state_ = STATE_ACCEPTED; } void FriendRequest::Reject() { QString message = ""; // we don't want to send any particular message at this point Tp::PendingOperation* p = tp_contact_->removePresencePublication(message); //! todo connect signal state_ = STATE_REJECTED; } void FriendRequest::OnPresencePublicationAuthorized(Tp::PendingOperation* op) { if (op->isError()) { LogError("Cannot publish presence for a friend contact."); } } void FriendRequest::OnPresenceSubscriptionResult(Tp::PendingOperation* op) { if (op->isError()) { //! If the contact doesn't allow presence subscription of the presence //! then we don't want to publish our. tp_contact_->removePresencePublication(); emit Canceled(this); return; } connect(tp_contact_.data(), SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState) ), SLOT( OnPresenceSubscriptionChanged(Tp::Contact::PresenceState) )); } void FriendRequest::OnPresenceSubscriptionChanged(Tp::Contact::PresenceState state) { switch (state) { case Tp::Contact::PresenceStateYes: emit Accepted(this); break; case Tp::Contact::PresenceStateNo: break; emit Canceled(this); break; case Tp::Contact::PresenceStateAsk: break; } } Tp::ContactPtr FriendRequest::GetOriginatorTpContact() { return tp_contact_; } } // end of namespace: TelepathyIM
[ "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3", "mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3", "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 3 ], [ 5, 5 ] ], [ [ 4, 4 ], [ 8, 9 ] ], [ [ 6, 7 ], [ 10, 11 ], [ 20, 20 ], [ 25, 25 ], [ 30, 30 ], [ 37, 37 ], [ 40, 45 ], [ 49, 49 ], [ 52, 52 ], [ 60, 60 ], [ 63, 66 ], [ 68, 68 ], [ 71, 79 ], [ 81, 104 ] ], [ [ 12, 19 ], [ 21, 24 ], [ 26, 29 ], [ 31, 36 ], [ 38, 39 ], [ 46, 48 ], [ 50, 51 ], [ 53, 59 ], [ 61, 62 ], [ 67, 67 ], [ 69, 70 ], [ 80, 80 ] ] ]
c916b05712179ff663a3765b7f607324071048fb
3970f1a70df104f46443480d1ba86e246d8f3b22
/imebra/src/imebra/include/MONOCHROME2ToYBRFULL.h
51303a2a3a2600764966d7b5d8a3d5ec38a70d46
[]
no_license
zhan2016/vimrid
9f8ea8a6eb98153300e6f8c1264b2c042c23ee22
28ae31d57b77df883be3b869f6b64695df441edb
refs/heads/master
2021-01-20T16:24:36.247136
2009-07-28T18:32:31
2009-07-28T18:32:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,970
h
/* 0.0.46 Imebra: a C++ dicom library. Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 for more details. You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 along with this program; If not, see http://www.gnu.org/licenses/ ------------------- If you want to use Imebra commercially then you have to buy the commercial license available at http://puntoexe.com After you buy the commercial license then you can use Imebra according to the terms described in the Imebra Commercial License Version 1. A copy of the Imebra Commercial License Version 1 is available in the documentation pages. Imebra is available at http://puntoexe.com The author can be contacted by email at [email protected] or by mail at the following address: Paolo Brandoli Preglov trg 6 1000 Ljubljana Slovenia */ /*! \file MONOCHROME2ToYBRFULL.h \brief Declaration of the class MONOCHROME2ToYBRFULL. */ #if !defined(imebraMONOCHROME2ToYBRFULL_E27C63E7_A907_4899_9BD3_8026AD7D110C__INCLUDED_) #define imebraMONOCHROME2ToYBRFULL_E27C63E7_A907_4899_9BD3_8026AD7D110C__INCLUDED_ #include "colorTransform.h" /////////////////////////////////////////////////////////// // // Everything is in the namespace puntoexe::imebra // /////////////////////////////////////////////////////////// namespace puntoexe { namespace imebra { namespace transforms { namespace colorTransforms { /////////////////////////////////////////////////////////// /// \brief Transforms an image from the colorspace /// MONOCHROME2 into the color space YBR_FULL. /// /// The input image has to have the colorspace MONOCHROME2, /// while the output image is created by the transform /// and will have the colorspace YBR_FULL. /// /////////////////////////////////////////////////////////// class MONOCHROME2ToYBRFULL: public colorTransform { public: virtual std::wstring getInitialColorSpace(); virtual std::wstring getFinalColorSpace(); virtual ptr<colorTransform> createColorTransform(); protected: virtual void doColorTransform(imbxInt32* pSourceMem, imbxInt32* pDestMem, imbxUint32 pixelsNumber, imbxInt32 inputMinValue, imbxInt32 inputMaxValue, imbxInt32 outputMinValue, imbxInt32 outputMaxValue); }; } // namespace colorTransforms } // namespace transforms } // namespace imebra } // namespace puntoexe #endif // !defined(imebraMONOCHROME2ToYBRFULL_E27C63E7_A907_4899_9BD3_8026AD7D110C__INCLUDED_)
[ [ [ 1, 98 ] ] ]
c9aca48a02be23ce9fad4f0d15bc24aec7c5bcde
ce0622a0f49dd0ca172db04efdd9484064f20973
/tools/GameList/Common/AtgXmlParser.h
8d2fd68538ac9f4acd65ba0b563794f5e57f0bb2
[]
no_license
maninha22crazy/xboxplayer
a78b0699d4002058e12c8f2b8c83b1cbc3316500
e9ff96899ad8e8c93deb3b2fe9168239f6a61fe1
refs/heads/master
2020-12-24T18:42:28.174670
2010-03-14T13:57:37
2010-03-14T13:57:37
56,190,024
1
0
null
null
null
null
UTF-8
C++
false
false
5,135
h
//------------------------------------------------------------------------------------- // AtgXmlParser.h // // XMLParser and SAX interface declaration // // Xbox Advanced Technology Group // Copyright (C) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------------- #pragma once #ifndef ATGXMLPARSER_H #define ATGXMLPARSER_H namespace ATG { //----------------------------------------------------------------------------- // error returns from XMLParse //----------------------------------------------------------------------------- #define _ATGFAC 0x61B #define E_COULD_NOT_OPEN_FILE MAKE_HRESULT(1, _ATGFAC, 0x0001 ) #define E_INVALID_XML_SYNTAX MAKE_HRESULT(1, _ATGFAC, 0x0002 ) CONST UINT XML_MAX_ATTRIBUTES_PER_ELEMENT = 32; CONST UINT XML_MAX_NAME_LENGTH = 128; CONST UINT XML_READ_BUFFER_SIZE = 2048; CONST UINT XML_WRITE_BUFFER_SIZE = 2048; // No tag can be longer than XML_WRITE_BUFFER_SIZE - an error will be returned if // it is //------------------------------------------------------------------------------------- struct XMLAttribute { WCHAR* strName; UINT NameLen; WCHAR* strValue; UINT ValueLen; }; //------------------------------------------------------------------------------------- class ISAXCallback { friend class XMLParser; public: ISAXCallback() {}; virtual ~ISAXCallback() {}; virtual HRESULT StartDocument() = 0; virtual HRESULT EndDocument() = 0; virtual HRESULT ElementBegin( CONST WCHAR* strName, UINT NameLen, CONST XMLAttribute *pAttributes, UINT NumAttributes ) = 0; virtual HRESULT ElementContent( CONST WCHAR *strData, UINT DataLen, BOOL More ) = 0; virtual HRESULT ElementEnd( CONST WCHAR *strName, UINT NameLen ) = 0; virtual HRESULT CDATABegin( ) = 0; virtual HRESULT CDATAData( CONST WCHAR *strCDATA, UINT CDATALen, BOOL bMore ) = 0; virtual HRESULT CDATAEnd( ) = 0; virtual VOID Error( HRESULT hError, CONST CHAR *strMessage ) = 0; virtual VOID SetParseProgress( DWORD dwProgress ) { } const CHAR* GetFilename() { return m_strFilename; } UINT GetLineNumber() { return m_LineNum; } UINT GetLinePosition() { return m_LinePos; } private: CONST CHAR *m_strFilename; UINT m_LineNum; UINT m_LinePos; }; //------------------------------------------------------------------------------------- class XMLParser { public: XMLParser(); ~XMLParser(); // Register an interface inheiriting from ISAXCallback VOID RegisterSAXCallbackInterface( ISAXCallback *pISAXCallback ); // Get the registered interface ISAXCallback* GetSAXCallbackInterface(); // ParseXMLFile returns one of the following: // E_COULD_NOT_OPEN_FILE - couldn't open the file // E_INVALID_XML_SYNTAX - bad XML syntax according to this parser // E_NOINTERFACE - RegisterSAXCallbackInterface not called // E_ABORT - callback returned a fail code // S_OK - file parsed and completed HRESULT ParseXMLFile( CONST CHAR *strFilename); // Parses from a buffer- if you pass a WCHAR buffer (and cast it), it will // correctly detect it and use unicode instead. Return codes are the // same as for ParseXMLFile HRESULT ParseXMLBuffer( CONST CHAR* strBuffer, UINT uBufferSize ); private: HRESULT MainParseLoop(); HRESULT AdvanceCharacter( BOOL bOkToFail = FALSE ); VOID SkipNextAdvance(); HRESULT ConsumeSpace(); HRESULT ConvertEscape(); HRESULT AdvanceElement(); HRESULT AdvanceName(); HRESULT AdvanceAttrVal(); HRESULT AdvanceCDATA(); HRESULT AdvanceComment(); VOID FillBuffer(); VOID Error( HRESULT hRet, CONST CHAR* strFormat, ... ); ISAXCallback* m_pISAXCallback; HANDLE m_hFile; CONST CHAR* m_pInXMLBuffer; UINT m_uInXMLBufferCharsLeft; DWORD m_dwCharsTotal; DWORD m_dwCharsConsumed; BYTE m_pReadBuf[ XML_READ_BUFFER_SIZE + 2 ]; // room for a trailing NULL WCHAR m_pWriteBuf[ XML_WRITE_BUFFER_SIZE ]; BYTE* m_pReadPtr; WCHAR* m_pWritePtr; // write pointer within m_pBuf BOOL m_bUnicode; // TRUE = 16-bits, FALSE = 8-bits BOOL m_bReverseBytes; // TRUE = reverse bytes, FALSE = don't reverse BOOL m_bSkipNextAdvance; WCHAR m_Ch; // Current character being parsed }; } // namespace ATG #endif
[ "goohome@343f5ee6-a13e-11de-ba2c-3b65426ee844", "eme915@343f5ee6-a13e-11de-ba2c-3b65426ee844" ]
[ [ [ 1, 96 ], [ 98, 146 ] ], [ [ 97, 97 ] ] ]
3328bab0b37330b1accde3ba750447f6eca3675f
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/projects/FilterSetting/DNSSetting.h
5dcceb69a03ca52b0d50aef4e154091efca8ee14
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,772
h
// DNSSetting.h : CDNSSetting µÄÉùÃ÷ #pragma once #include "resource.h" // Ö÷·ûºÅ #include "FilterSetting.h" // CDNSSetting class ATL_NO_VTABLE CDNSSetting : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CDNSSetting, &CLSID_DNSSetting>, public ISupportErrorInfo, public IDispatchImpl<IDNSSetting, &IID_IDNSSetting, &LIBID_FilterSettingLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { public: CDNSSetting() { } DECLARE_REGISTRY_RESOURCEID(IDR_DNSSETTING) BEGIN_COM_MAP(CDNSSetting) COM_INTERFACE_ENTRY(IDNSSetting) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { AddRef(); return S_OK; } void FinalRelease() { } public: STDMETHOD(addBlackDNS)(BSTR dns); STDMETHOD(addWhiteDNS)(BSTR dns); STDMETHOD(removeBlackDNS)(BSTR blackDNS); STDMETHOD(removeWhiteDNS)(BSTR whiteDNS); STDMETHOD(enableWhiteDNSCheck)(VARIANT_BOOL enable); STDMETHOD(enableBlackDNSCheck)(VARIANT_BOOL enable); STDMETHOD(checkDNS)(BSTR dns_name, VARIANT_BOOL* passed); STDMETHOD(justEnableWhiteDNS)(VARIANT_BOOL enabled); STDMETHOD(isWhiteDNS)(BSTR dns, VARIANT_BOOL* White); STDMETHOD(getFirstWhiteDNS)(BSTR* dns); STDMETHOD(getNextWhiteDNS)(BSTR cur, BSTR* next); STDMETHOD(getFirstBlackDNS)(BSTR* dns); STDMETHOD(getNextBlackDNS)(BSTR cur, BSTR* next); STDMETHOD(isWhiteDNSSettingEnable)(VARIANT_BOOL *enabled); STDMETHOD(isBlackDNSSettingEnable)(VARIANT_BOOL* enabled); STDMETHOD(isJustEnableWhiteDNS)(VARIANT_BOOL* enabled); }; OBJECT_ENTRY_AUTO(__uuidof(DNSSetting), CDNSSetting)
[ [ [ 1, 65 ] ] ]
e2d2a5cd2618a9b022b82644f3b2d434cc6ebc52
02c2e62bcb9a54738bfbd95693978b8709e88fdb
/opencv/cvcalibration.cpp
2a087a09746dfe73a7570d300cfa1c422d3f76aa
[]
no_license
ThadeuFerreira/sift-coprojeto
7ab823926e135f0ac388ae267c40e7069e39553a
bba43ef6fa37561621eb5f2126e5aa7d1c3f7024
refs/heads/master
2021-01-10T15:15:21.698124
2009-05-08T17:38:51
2009-05-08T17:38:51
45,042,655
0
0
null
null
null
null
UTF-8
C++
false
false
58,463
cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "_cv.h" /* This is stright forward port v2 of Matlab calibration engine by Jean-Yves Bouguet that is (in a large extent) based on the paper: Z. Zhang. "A flexible new technique for camera calibration". IEEE Transactions on Pattern Analysis and Machine Intelligence, 22(11):1330-1334, 2000. The 1st initial port was done by Valery Mosyagin. */ static void icvGaussNewton( const CvMat* J, const CvMat* err, CvMat* delta, CvMat* JtJ=0, CvMat* JtErr=0, CvMat* JtJW=0, CvMat* JtJV=0 ) { CvMat* _temp_JtJ = 0; CvMat* _temp_JtErr = 0; CvMat* _temp_JtJW = 0; CvMat* _temp_JtJV = 0; CV_FUNCNAME( "icvGaussNewton" ); __BEGIN__; if( !CV_IS_MAT(J) || !CV_IS_MAT(err) || !CV_IS_MAT(delta) ) CV_ERROR( CV_StsBadArg, "Some of required arguments is not a valid matrix" ); if( !JtJ ) { CV_CALL( _temp_JtJ = cvCreateMat( J->cols, J->cols, J->type )); JtJ = _temp_JtJ; } else if( !CV_IS_MAT(JtJ) ) CV_ERROR( CV_StsBadArg, "JtJ is not a valid matrix" ); if( !JtErr ) { CV_CALL( _temp_JtErr = cvCreateMat( J->cols, 1, J->type )); JtErr = _temp_JtErr; } else if( !CV_IS_MAT(JtErr) ) CV_ERROR( CV_StsBadArg, "JtErr is not a valid matrix" ); if( !JtJW ) { CV_CALL( _temp_JtJW = cvCreateMat( J->cols, 1, J->type )); JtJW = _temp_JtJW; } else if( !CV_IS_MAT(JtJW) ) CV_ERROR( CV_StsBadArg, "JtJW is not a valid matrix" ); if( !JtJV ) { CV_CALL( _temp_JtJV = cvCreateMat( J->cols, J->cols, J->type )); JtJV = _temp_JtJV; } else if( !CV_IS_MAT(JtJV) ) CV_ERROR( CV_StsBadArg, "JtJV is not a valid matrix" ); cvMulTransposed( J, JtJ, 1 ); cvGEMM( J, err, 1, 0, 0, JtErr, CV_GEMM_A_T ); cvSVD( JtJ, JtJW, 0, JtJV, CV_SVD_MODIFY_A + CV_SVD_V_T ); cvSVBkSb( JtJW, JtJV, JtJV, JtErr, delta, CV_SVD_U_T + CV_SVD_V_T ); __END__; if( _temp_JtJ || _temp_JtErr || _temp_JtJW || _temp_JtJV ) { cvReleaseMat( &_temp_JtJ ); cvReleaseMat( &_temp_JtErr ); cvReleaseMat( &_temp_JtJW ); cvReleaseMat( &_temp_JtJV ); } } /*static double calc_repr_err( const double* object_points, int o_step, const double* image_points, const double* h, int count ) { double err = 0; for( int i = 0; i < count; i++ ) { double X = object_points[i*o_step], Y = object_points[i*o_step + 1]; double x0 = image_points[i*2], y0 = image_points[i*2 + 1]; double d = 1./(h[6]*X + h[7]*Y + h[8]); double x = (h[0]*X + h[1]*Y + h[2])*d; double y = (h[3]*X + h[4]*Y + h[5])*d; err += fabs(x - x0) + fabs(y - y0); } return err; }*/ // finds perspective transformation H between the object plane and image plane, // so that (sxi,syi,s) ~ H*(Xi,Yi,1) CV_IMPL void cvFindHomography( const CvMat* object_points, const CvMat* image_points, CvMat* __H ) { CvMat *_m = 0, *_M = 0; CvMat *_L = 0; CV_FUNCNAME( "cvFindHomography" ); __BEGIN__; int h_type; int i, k, count, count2; CvPoint2D64f *m, *M; CvPoint2D64f cm = {0,0}, sm = {0,0}; double inv_Hnorm[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 1 }; double H[9]; CvMat _inv_Hnorm = cvMat( 3, 3, CV_64FC1, inv_Hnorm ); CvMat _H = cvMat( 3, 3, CV_64FC1, H ); double LtL[9*9], LW[9], LV[9*9]; CvMat* _Lp; double* L; CvMat _LtL = cvMat( 9, 9, CV_64FC1, LtL ); CvMat _LW = cvMat( 9, 1, CV_64FC1, LW ); CvMat _LV = cvMat( 9, 9, CV_64FC1, LV ); CvMat _Hrem = cvMat( 3, 3, CV_64FC1, LV + 8*9 ); if( !CV_IS_MAT(image_points) || !CV_IS_MAT(object_points) || !CV_IS_MAT(__H) ) CV_ERROR( CV_StsBadArg, "one of arguments is not a valid matrix" ); h_type = CV_MAT_TYPE(__H->type); if( h_type != CV_32FC1 && h_type != CV_64FC1 ) CV_ERROR( CV_StsUnsupportedFormat, "Homography matrix must have 32fC1 or 64fC1 type" ); if( __H->rows != 3 || __H->cols != 3 ) CV_ERROR( CV_StsBadSize, "Homography matrix must be 3x3" ); count = MAX(image_points->cols, image_points->rows); count2 = MAX(object_points->cols, object_points->rows); if( count != count2 ) CV_ERROR( CV_StsUnmatchedSizes, "Numbers of image and object points do not match" ); CV_CALL( _m = cvCreateMat( 1, count, CV_64FC2 )); CV_CALL( cvConvertPointsHomogenious( image_points, _m )); m = (CvPoint2D64f*)_m->data.ptr; CV_CALL( _M = cvCreateMat( 1, count, CV_64FC2 )); CV_CALL( cvConvertPointsHomogenious( object_points, _M )); M = (CvPoint2D64f*)_M->data.ptr; // calculate the normalization transformation Hnorm. for( i = 0; i < count; i++ ) cm.x += m[i].x, cm.y += m[i].y; cm.x /= count; cm.y /= count; for( i = 0; i < count; i++ ) { double x = m[i].x - cm.x; double y = m[i].y - cm.y; sm.x += fabs(x); sm.y += fabs(y); } sm.x /= count; sm.y /= count; inv_Hnorm[0] = sm.x; inv_Hnorm[4] = sm.y; inv_Hnorm[2] = cm.x; inv_Hnorm[5] = cm.y; sm.x = 1./sm.x; sm.y = 1./sm.y; CV_CALL( _Lp = _L = cvCreateMat( 2*count, 9, CV_64FC1 ) ); L = _L->data.db; for( i = 0; i < count; i++, L += 18 ) { double x = -(m[i].x - cm.x)*sm.x, y = -(m[i].y - cm.y)*sm.y; L[0] = L[9 + 3] = M[i].x; L[1] = L[9 + 4] = M[i].y; L[2] = L[9 + 5] = 1; L[9 + 0] = L[9 + 1] = L[9 + 2] = L[3] = L[4] = L[5] = 0; L[6] = x*M[i].x; L[7] = x*M[i].y; L[8] = x; L[9 + 6] = y*M[i].x; L[9 + 7] = y*M[i].y; L[9 + 8] = y; } if( count > 4 ) { cvMulTransposed( _L, &_LtL, 1 ); _Lp = &_LtL; } _LW.rows = MIN(count*2, 9); cvSVD( _Lp, &_LW, 0, &_LV, CV_SVD_MODIFY_A + CV_SVD_V_T ); cvScale( &_Hrem, &_Hrem, 1./_Hrem.data.db[8] ); cvMatMul( &_inv_Hnorm, &_Hrem, &_H ); if( count > 4 ) { // reuse the available storage for jacobian and other vars CvMat _J = cvMat( 2*count, 8, CV_64FC1, _L->data.db ); CvMat _err = cvMat( 2*count, 1, CV_64FC1, _L->data.db + 2*count*8 ); CvMat _JtJ = cvMat( 8, 8, CV_64FC1, LtL ); CvMat _JtErr = cvMat( 8, 1, CV_64FC1, LtL + 8*8 ); CvMat _JtJW = cvMat( 8, 1, CV_64FC1, LW ); CvMat _JtJV = cvMat( 8, 8, CV_64FC1, LV ); CvMat _Hinnov = cvMat( 8, 1, CV_64FC1, LV + 8*8 ); for( k = 0; k < 10; k++ ) { double* J = _J.data.db, *err = _err.data.db; for( i = 0; i < count; i++, J += 16, err += 2 ) { double di = 1./(H[6]*M[i].x + H[7]*M[i].y + 1.); double _xi = (H[0]*M[i].x + H[1]*M[i].y + H[2])*di; double _yi = (H[3]*M[i].x + H[4]*M[i].y + H[5])*di; err[0] = m[i].x - _xi; err[1] = m[i].y - _yi; J[0] = M[i].x*di; J[1] = M[i].y*di; J[2] = di; J[8+3] = M[i].x; J[8+4] = M[i].y; J[8+5] = di; J[6] = -J[0]*_xi; J[7] = -J[1]*_xi; J[8+6] = -J[8+3]*_yi; J[8+7] = -J[8+4]*_yi; J[3] = J[4] = J[5] = J[8+0] = J[8+1] = J[8+2] = 0.; } icvGaussNewton( &_J, &_err, &_Hinnov, &_JtJ, &_JtErr, &_JtJW, &_JtJV ); for( i = 0; i < 8; i++ ) H[i] += _Hinnov.data.db[i]; } } cvConvert( &_H, __H ); __END__; cvReleaseMat( &_m ); cvReleaseMat( &_M ); cvReleaseMat( &_L ); } CV_IMPL int cvRodrigues2( const CvMat* src, CvMat* dst, CvMat* jacobian ) { int result = 0; CV_FUNCNAME( "cvRogrigues2" ); __BEGIN__; int depth, elem_size; int i, k; double J[27]; CvMat _J = cvMat( 3, 9, CV_64F, J ); if( !CV_IS_MAT(src) ) CV_ERROR( !src ? CV_StsNullPtr : CV_StsBadArg, "Input argument is not a valid matrix" ); if( !CV_IS_MAT(dst) ) CV_ERROR( !dst ? CV_StsNullPtr : CV_StsBadArg, "The first output argument is not a valid matrix" ); depth = CV_MAT_DEPTH(src->type); elem_size = CV_ELEM_SIZE(depth); if( depth != CV_32F && depth != CV_64F ) CV_ERROR( CV_StsUnsupportedFormat, "The matrices must have 32f or 64f data type" ); if( !CV_ARE_DEPTHS_EQ(src, dst) ) CV_ERROR( CV_StsUnmatchedFormats, "All the matrices must have the same data type" ); if( jacobian ) { if( !CV_IS_MAT(jacobian) ) CV_ERROR( CV_StsBadArg, "Jacobian is not a valid matrix" ); if( !CV_ARE_DEPTHS_EQ(src, jacobian) || CV_MAT_CN(jacobian->type) != 1 ) CV_ERROR( CV_StsUnmatchedFormats, "Jacobian must have 32fC1 or 64fC1 datatype" ); if( (jacobian->rows != 9 || jacobian->cols != 3) && (jacobian->rows != 3 || jacobian->cols != 9)) CV_ERROR( CV_StsBadSize, "Jacobian must be 3x9 or 9x3" ); } if( src->cols == 1 || src->rows == 1 ) { double rx, ry, rz, theta; int step = src->rows > 1 ? src->step / elem_size : 1; if( src->rows + src->cols*CV_MAT_CN(src->type) - 1 != 3 ) CV_ERROR( CV_StsBadSize, "Input matrix must be 1x3, 3x1 or 3x3" ); if( dst->rows != 3 || dst->cols != 3 || CV_MAT_CN(dst->type) != 1 ) CV_ERROR( CV_StsBadSize, "Output matrix must be 3x3, single-channel floating point matrix" ); if( depth == CV_32F ) { rx = src->data.fl[0]; ry = src->data.fl[step]; rz = src->data.fl[step*2]; } else { rx = src->data.db[0]; ry = src->data.db[step]; rz = src->data.db[step*2]; } theta = sqrt(rx*rx + ry*ry + rz*rz); if( theta < DBL_EPSILON ) { cvSetIdentity( dst ); if( jacobian ) { memset( J, 0, sizeof(J) ); J[5] = J[15] = J[19] = 1; J[7] = J[11] = J[21] = -1; } } else { const double I[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; double c = cos(theta); double s = sin(theta); double c1 = 1. - c; double itheta = theta ? 1./theta : 0.; rx *= itheta; ry *= itheta; rz *= itheta; double rrt[] = { rx*rx, rx*ry, rx*rz, rx*ry, ry*ry, ry*rz, rx*rz, ry*rz, rz*rz }; double _r_x_[] = { 0, -rz, ry, rz, 0, -rx, -ry, rx, 0 }; double R[9]; CvMat _R = cvMat( 3, 3, CV_64F, R ); // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] for( k = 0; k < 9; k++ ) R[k] = c*I[k] + c1*rrt[k] + s*_r_x_[k]; cvConvert( &_R, dst ); if( jacobian ) { double drrt[] = { rx+rx, ry, rz, ry, 0, 0, rz, 0, 0, 0, rx, 0, rx, ry+ry, rz, 0, rz, 0, 0, 0, rx, 0, 0, ry, rx, ry, rz+rz }; double d_r_x_[] = { 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0 }; for( i = 0; i < 3; i++ ) { double ri = i == 0 ? rx : i == 1 ? ry : rz; double a0 = -s*ri, a1 = (s - 2*c1*itheta)*ri, a2 = c1*itheta; double a3 = (c - s*itheta)*ri, a4 = s*itheta; for( k = 0; k < 9; k++ ) J[i*9+k] = a0*I[k] + a1*rrt[k] + a2*drrt[i*9+k] + a3*_r_x_[k] + a4*d_r_x_[i*9+k]; } } } } else if( src->cols == 3 && src->rows == 3 ) { double R[9], rx, ry, rz; CvMat _R = cvMat( 3, 3, CV_64F, R ); double theta, s, c; int step = dst->rows > 1 ? dst->step / elem_size : 1; if( (dst->rows != 1 || dst->cols*CV_MAT_CN(dst->type) != 3) && (dst->rows != 3 || dst->cols != 1 || CV_MAT_CN(dst->type) != 1)) CV_ERROR( CV_StsBadSize, "Output matrix must be 1x3 or 3x1" ); cvConvert( src, &_R ); if( !cvCheckArr( &_R, CV_CHECK_RANGE+CV_CHECK_QUIET, -100, 100 ) ) { cvZero(dst); if( jacobian ) cvZero(jacobian); EXIT; } rx = R[7] - R[5]; ry = R[2] - R[6]; rz = R[3] - R[1]; c = (R[0] + R[4] + R[8] - 1)*0.5; c = c > 1. ? 1. : c < -1. ? -1. : c; theta = acos(c); s = sin(theta); if( fabs(s) < 1e-5 ) { double t; if( c > 0 ) rx = ry = rz = 0; else { t = (R[0] + 1)*0.5; rx = theta*sqrt(MAX(t,0.)); t = (R[4] + 1)*0.5; ry = theta*sqrt(MAX(t,0.))*(R[1] < 0 ? -1. : 1.); t = (R[8] + 1)*0.5; rz = theta*sqrt(MAX(t,0.))*(R[2] < 0 ? -1. : 1.); } if( jacobian ) { memset( J, 0, sizeof(J) ); if( c > 0 ) { J[5] = J[15] = J[19] = -0.5; J[7] = J[11] = J[21] = 0.5; } } } else { double vth = 1/(2*s); if( jacobian ) { double t, dtheta_dtr = -1./sqrt(1 - c*c); // var1 = [vth;theta] // var = [om1;var1] = [om1;vth;theta] double dvth_dtheta = -vth*c/s; double d1 = 0.5*dvth_dtheta*dtheta_dtr; double d2 = 0.5*dtheta_dtr; // dvar1/dR = dvar1/dtheta*dtheta/dR = [dvth/dtheta; 1] * dtheta/dtr * dtr/dR double dvardR[5*9] = { 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, d1, 0, 0, 0, d1, 0, 0, 0, d1, d2, 0, 0, 0, d2, 0, 0, 0, d2 }; // var2 = [om;theta] double dvar2dvar[] = { vth, 0, 0, rx, 0, 0, vth, 0, ry, 0, 0, 0, vth, rz, 0, 0, 0, 0, 0, 1 }; double domegadvar2[] = { theta, 0, 0, rx*vth, 0, theta, 0, ry*vth, 0, 0, theta, rz*vth }; CvMat _dvardR = cvMat( 5, 9, CV_64FC1, dvardR ); CvMat _dvar2dvar = cvMat( 4, 5, CV_64FC1, dvar2dvar ); CvMat _domegadvar2 = cvMat( 3, 4, CV_64FC1, domegadvar2 ); double t0[3*5]; CvMat _t0 = cvMat( 3, 5, CV_64FC1, t0 ); cvMatMul( &_domegadvar2, &_dvar2dvar, &_t0 ); cvMatMul( &_t0, &_dvardR, &_J ); // transpose every row of _J (treat the rows as 3x3 matrices) CV_SWAP(J[1], J[3], t); CV_SWAP(J[2], J[6], t); CV_SWAP(J[5], J[7], t); CV_SWAP(J[10], J[12], t); CV_SWAP(J[11], J[15], t); CV_SWAP(J[14], J[16], t); CV_SWAP(J[19], J[21], t); CV_SWAP(J[20], J[24], t); CV_SWAP(J[23], J[25], t); } vth *= theta; rx *= vth; ry *= vth; rz *= vth; } if( depth == CV_32F ) { dst->data.fl[0] = (float)rx; dst->data.fl[step] = (float)ry; dst->data.fl[step*2] = (float)rz; } else { dst->data.db[0] = rx; dst->data.db[step] = ry; dst->data.db[step*2] = rz; } } if( jacobian ) { if( depth == CV_32F ) { if( jacobian->rows == _J.rows ) cvConvert( &_J, jacobian ); else { float Jf[3*9]; CvMat _Jf = cvMat( _J.rows, _J.cols, CV_32FC1, Jf ); cvConvert( &_J, &_Jf ); cvTranspose( &_Jf, jacobian ); } } else if( jacobian->rows == _J.rows ) cvCopy( &_J, jacobian ); else cvTranspose( &_J, jacobian ); } result = 1; __END__; return result; } CV_IMPL void cvProjectPoints2( const CvMat* obj_points, const CvMat* r_vec, const CvMat* t_vec, const CvMat* A, const CvMat* dist_coeffs, CvMat* img_points, CvMat* dpdr, CvMat* dpdt, CvMat* dpdf, CvMat* dpdc, CvMat* dpdk ) { CvMat *_M = 0, *_m = 0; CvMat *_dpdr = 0, *_dpdt = 0, *_dpdc = 0, *_dpdf = 0, *_dpdk = 0; CV_FUNCNAME( "cvProjectPoints2" ); __BEGIN__; int i, j, count; int calc_derivatives; const CvPoint3D64f* M; CvPoint2D64f* m; double r[3], R[9], dRdr[27], t[3], a[9], k[4] = {0,0,0,0}, fx, fy, cx, cy; CvMat _r, _t, _a = cvMat( 3, 3, CV_64F, a ), _k; CvMat _R = cvMat( 3, 3, CV_64F, R ), _dRdr = cvMat( 3, 9, CV_64F, dRdr ); double *dpdr_p = 0, *dpdt_p = 0, *dpdk_p = 0, *dpdf_p = 0, *dpdc_p = 0; int dpdr_step = 0, dpdt_step = 0, dpdk_step = 0, dpdf_step = 0, dpdc_step = 0; if( !CV_IS_MAT(obj_points) || !CV_IS_MAT(r_vec) || !CV_IS_MAT(t_vec) || !CV_IS_MAT(A) || /*!CV_IS_MAT(dist_coeffs) ||*/ !CV_IS_MAT(img_points) ) CV_ERROR( CV_StsBadArg, "One of required arguments is not a valid matrix" ); count = MAX(obj_points->rows, obj_points->cols); if( CV_IS_CONT_MAT(obj_points->type) && CV_MAT_DEPTH(obj_points->type) == CV_64F && (obj_points->rows == 1 && CV_MAT_CN(obj_points->type) == 3 || obj_points->rows == count && CV_MAT_CN(obj_points->type)*obj_points->cols == 3)) _M = (CvMat*)obj_points; else { CV_CALL( _M = cvCreateMat( 1, count, CV_64FC3 )); CV_CALL( cvConvertPointsHomogenious( obj_points, _M )); } if( CV_IS_CONT_MAT(img_points->type) && CV_MAT_DEPTH(img_points->type) == CV_64F && (img_points->rows == 1 && CV_MAT_CN(img_points->type) == 2 || img_points->rows == count && CV_MAT_CN(img_points->type)*img_points->cols == 2)) _m = img_points; else CV_CALL( _m = cvCreateMat( 1, count, CV_64FC2 )); M = (CvPoint3D64f*)_M->data.db; m = (CvPoint2D64f*)_m->data.db; if( CV_MAT_DEPTH(r_vec->type) != CV_64F && CV_MAT_DEPTH(r_vec->type) != CV_32F || (r_vec->rows != 1 && r_vec->cols != 1 || r_vec->rows*r_vec->cols*CV_MAT_CN(r_vec->type) != 3) && (r_vec->rows != 3 && r_vec->cols != 3 || CV_MAT_CN(r_vec->type) != 1)) CV_ERROR( CV_StsBadArg, "Rotation must be represented by 1x3 or 3x1 " "floating-point rotation vector, or 3x3 rotation matrix" ); if( r_vec->rows == 3 && r_vec->cols == 3 ) { _r = cvMat( 3, 1, CV_64FC1, r ); CV_CALL( cvRodrigues2( r_vec, &_r )); CV_CALL( cvRodrigues2( &_r, &_R, &_dRdr )); cvCopy( r_vec, &_R ); } else { _r = cvMat( r_vec->rows, r_vec->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(r_vec->type)), r ); CV_CALL( cvConvert( r_vec, &_r )); CV_CALL( cvRodrigues2( &_r, &_R, &_dRdr ) ); } if( CV_MAT_DEPTH(t_vec->type) != CV_64F && CV_MAT_DEPTH(t_vec->type) != CV_32F || t_vec->rows != 1 && t_vec->cols != 1 || t_vec->rows*t_vec->cols*CV_MAT_CN(t_vec->type) != 3 ) CV_ERROR( CV_StsBadArg, "Translation vector must be 1x3 or 3x1 floating-point vector" ); _t = cvMat( t_vec->rows, t_vec->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(t_vec->type)), t ); CV_CALL( cvConvert( t_vec, &_t )); if( CV_MAT_TYPE(A->type) != CV_64FC1 && CV_MAT_TYPE(A->type) != CV_32FC1 || A->rows != 3 || A->cols != 3 ) CV_ERROR( CV_StsBadArg, "Instrinsic parameters must be 3x3 floating-point matrix" ); CV_CALL( cvConvert( A, &_a )); fx = a[0]; fy = a[4]; cx = a[2]; cy = a[5]; if( dist_coeffs ) { if( !CV_IS_MAT(dist_coeffs) || CV_MAT_DEPTH(dist_coeffs->type) != CV_64F && CV_MAT_DEPTH(dist_coeffs->type) != CV_32F || dist_coeffs->rows != 1 && dist_coeffs->cols != 1 || dist_coeffs->rows*dist_coeffs->cols*CV_MAT_CN(dist_coeffs->type) != 4 ) CV_ERROR( CV_StsBadArg, "Distortion coefficients must be 1x4 or 4x1 floating-point vector" ); _k = cvMat( dist_coeffs->rows, dist_coeffs->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(dist_coeffs->type)), k ); CV_CALL( cvConvert( dist_coeffs, &_k )); } if( dpdr ) { if( !CV_IS_MAT(dpdr) || CV_MAT_TYPE(dpdr->type) != CV_32FC1 && CV_MAT_TYPE(dpdr->type) != CV_64FC1 || dpdr->rows != count*2 || dpdr->cols != 3 ) CV_ERROR( CV_StsBadArg, "dp/drot must be 2Nx3 floating-point matrix" ); if( CV_MAT_TYPE(dpdr->type) == CV_64FC1 ) _dpdr = dpdr; else CV_CALL( _dpdr = cvCreateMat( 2*count, 3, CV_64FC1 )); dpdr_p = _dpdr->data.db; dpdr_step = _dpdr->step/sizeof(dpdr_p[0]); } if( dpdt ) { if( !CV_IS_MAT(dpdt) || CV_MAT_TYPE(dpdt->type) != CV_32FC1 && CV_MAT_TYPE(dpdt->type) != CV_64FC1 || dpdt->rows != count*2 || dpdt->cols != 3 ) CV_ERROR( CV_StsBadArg, "dp/dT must be 2Nx3 floating-point matrix" ); if( CV_MAT_TYPE(dpdt->type) == CV_64FC1 ) _dpdt = dpdt; else CV_CALL( _dpdt = cvCreateMat( 2*count, 3, CV_64FC1 )); dpdt_p = _dpdt->data.db; dpdt_step = _dpdt->step/sizeof(dpdt_p[0]); } if( dpdf ) { if( !CV_IS_MAT(dpdf) || CV_MAT_TYPE(dpdf->type) != CV_32FC1 && CV_MAT_TYPE(dpdf->type) != CV_64FC1 || dpdf->rows != count*2 || dpdf->cols != 2 ) CV_ERROR( CV_StsBadArg, "dp/df must be 2Nx2 floating-point matrix" ); if( CV_MAT_TYPE(dpdf->type) == CV_64FC1 ) _dpdf = dpdf; else CV_CALL( _dpdf = cvCreateMat( 2*count, 2, CV_64FC1 )); dpdf_p = _dpdf->data.db; dpdf_step = _dpdf->step/sizeof(dpdf_p[0]); } if( dpdc ) { if( !CV_IS_MAT(dpdc) || CV_MAT_TYPE(dpdc->type) != CV_32FC1 && CV_MAT_TYPE(dpdc->type) != CV_64FC1 || dpdc->rows != count*2 || dpdc->cols != 2 ) CV_ERROR( CV_StsBadArg, "dp/dc must be 2Nx2 floating-point matrix" ); if( CV_MAT_TYPE(dpdc->type) == CV_64FC1 ) _dpdc = dpdc; else CV_CALL( _dpdc = cvCreateMat( 2*count, 2, CV_64FC1 )); dpdc_p = _dpdc->data.db; dpdc_step = _dpdc->step/sizeof(dpdc_p[0]); } if( dpdk ) { if( !CV_IS_MAT(dpdk) || CV_MAT_TYPE(dpdk->type) != CV_32FC1 && CV_MAT_TYPE(dpdk->type) != CV_64FC1 || dpdk->rows != count*2 || (dpdk->cols != 4 && dpdk->cols != 2) ) CV_ERROR( CV_StsBadArg, "dp/df must be 2Nx4 or 2Nx2 floating-point matrix" ); if( !dist_coeffs ) CV_ERROR( CV_StsNullPtr, "dist_coeffs is NULL while dpdk is not" ); if( CV_MAT_TYPE(dpdk->type) == CV_64FC1 ) _dpdk = dpdk; else CV_CALL( _dpdk = cvCreateMat( dpdk->rows, dpdk->cols, CV_64FC1 )); dpdk_p = _dpdk->data.db; dpdk_step = _dpdk->step/sizeof(dpdk_p[0]); } calc_derivatives = dpdr || dpdt || dpdf || dpdc || dpdk; for( i = 0; i < count; i++ ) { double X = M[i].x, Y = M[i].y, Z = M[i].z; double x = R[0]*X + R[1]*Y + R[2]*Z + t[0]; double y = R[3]*X + R[4]*Y + R[5]*Z + t[1]; double z = R[6]*X + R[7]*Y + R[8]*Z + t[2]; double r2, r4, a1, a2, a3, cdist; double xd, yd; z = z ? 1./z : 1; x *= z; y *= z; r2 = x*x + y*y; r4 = r2*r2; a1 = 2*x*y; a2 = r2 + 2*x*x; a3 = r2 + 2*y*y; cdist = 1 + k[0]*r2 + k[1]*r4; xd = x*cdist + k[2]*a1 + k[3]*a2; yd = y*cdist + k[2]*a3 + k[3]*a1; m[i].x = xd*fx + cx; m[i].y = yd*fy + cy; if( calc_derivatives ) { if( dpdc_p ) { dpdc_p[0] = 1; dpdc_p[1] = 0; dpdc_p[dpdc_step] = 0; dpdc_p[dpdc_step+1] = 1; dpdc_p += dpdc_step*2; } if( dpdf_p ) { dpdf_p[0] = xd; dpdf_p[1] = 0; dpdf_p[dpdf_step] = 0; dpdf_p[dpdf_step+1] = yd; dpdf_p += dpdf_step*2; } if( dpdk_p ) { dpdk_p[0] = fx*x*r2; dpdk_p[1] = fx*x*r4; dpdk_p[dpdk_step] = fy*y*r2; dpdk_p[dpdk_step+1] = fy*y*r4; if( _dpdk->cols > 2 ) { dpdk_p[2] = fx*a1; dpdk_p[3] = fx*a2; dpdk_p[dpdk_step+2] = fy*a3; dpdk_p[dpdk_step+3] = fy*a1; } dpdk_p += dpdk_step*2; } if( dpdt_p ) { double dxdt[] = { z, 0, -x*z }, dydt[] = { 0, z, -y*z }; for( j = 0; j < 3; j++ ) { double dr2dt = 2*x*dxdt[j] + 2*y*dydt[j]; double dcdist_dt = k[0]*dr2dt + 2*k[1]*r2*dr2dt; double da1dt = 2*(x*dydt[j] + y*dxdt[j]); double dmxdt = fx*(dxdt[j]*cdist + x*dcdist_dt + k[2]*da1dt + k[3]*(dr2dt + 2*x*dxdt[j])); double dmydt = fy*(dydt[j]*cdist + y*dcdist_dt + k[2]*(dr2dt + 2*y*dydt[j]) + k[3]*da1dt); dpdt_p[j] = dmxdt; dpdt_p[dpdt_step+j] = dmydt; } dpdt_p += dpdt_step*2; } if( dpdr_p ) { double dx0dr[] = { X*dRdr[0] + Y*dRdr[1] + Z*dRdr[2], X*dRdr[9] + Y*dRdr[10] + Z*dRdr[11], X*dRdr[18] + Y*dRdr[19] + Z*dRdr[20] }; double dy0dr[] = { X*dRdr[3] + Y*dRdr[4] + Z*dRdr[5], X*dRdr[12] + Y*dRdr[13] + Z*dRdr[14], X*dRdr[21] + Y*dRdr[22] + Z*dRdr[23] }; double dz0dr[] = { X*dRdr[6] + Y*dRdr[7] + Z*dRdr[8], X*dRdr[15] + Y*dRdr[16] + Z*dRdr[17], X*dRdr[24] + Y*dRdr[25] + Z*dRdr[26] }; for( j = 0; j < 3; j++ ) { double dxdr = z*(dx0dr[j] - x*dz0dr[j]); double dydr = z*(dy0dr[j] - y*dz0dr[j]); double dr2dr = 2*x*dxdr + 2*y*dydr; double dcdist_dr = k[0]*dr2dr + 2*k[1]*r2*dr2dr; double da1dr = 2*(x*dydr + y*dxdr); double dmxdr = fx*(dxdr*cdist + x*dcdist_dr + k[2]*da1dr + k[3]*(dr2dr + 2*x*dxdr)); double dmydr = fy*(dydr*cdist + y*dcdist_dr + k[2]*(dr2dr + 2*y*dydr) + k[3]*da1dr); dpdr_p[j] = dmxdr; dpdr_p[dpdr_step+j] = dmydr; } dpdr_p += dpdr_step*2; } } } if( _m != img_points ) cvConvertPointsHomogenious( _m, img_points ); if( _dpdr != dpdr ) cvConvert( _dpdr, dpdr ); if( _dpdt != dpdt ) cvConvert( _dpdt, dpdt ); if( _dpdf != dpdf ) cvConvert( _dpdf, dpdf ); if( _dpdc != dpdc ) cvConvert( _dpdc, dpdc ); if( _dpdk != dpdk ) cvConvert( _dpdk, dpdk ); __END__; if( _M != obj_points ) cvReleaseMat( &_M ); if( _m != img_points ) cvReleaseMat( &_m ); if( _dpdr != dpdr ) cvReleaseMat( &_dpdr ); if( _dpdt != dpdt ) cvReleaseMat( &_dpdt ); if( _dpdf != dpdf ) cvReleaseMat( &_dpdf ); if( _dpdc != dpdc ) cvReleaseMat( &_dpdc ); if( _dpdk != dpdk ) cvReleaseMat( &_dpdk ); } CV_IMPL void cvFindExtrinsicCameraParams2( const CvMat* obj_points, const CvMat* img_points, const CvMat* A, const CvMat* dist_coeffs, CvMat* r_vec, CvMat* t_vec ) { const int max_iter = 20; CvMat *_M = 0, *_Mxy = 0, *_m = 0, *_mn = 0, *_L = 0, *_J = 0; CV_FUNCNAME( "cvFindExtrinsicCameraParams2" ); __BEGIN__; int i, j, count; double a[9], k[4] = { 0, 0, 0, 0 }, R[9], ifx, ify, cx, cy; double Mc[3] = {0, 0, 0}, MM[9], U[9], V[9], W[3]; double JtJ[6*6], JtErr[6], JtJW[6], JtJV[6*6], delta[6], param[6]; CvPoint3D64f* M = 0; CvPoint2D64f *m = 0, *mn = 0; CvMat _a = cvMat( 3, 3, CV_64F, a ); CvMat _R = cvMat( 3, 3, CV_64F, R ); CvMat _r = cvMat( 3, 1, CV_64F, param ); CvMat _t = cvMat( 3, 1, CV_64F, param + 3 ); CvMat _Mc = cvMat( 1, 3, CV_64F, Mc ); CvMat _MM = cvMat( 3, 3, CV_64F, MM ); CvMat _U = cvMat( 3, 3, CV_64F, U ); CvMat _V = cvMat( 3, 3, CV_64F, V ); CvMat _W = cvMat( 3, 1, CV_64F, W ); CvMat _JtJ = cvMat( 6, 6, CV_64F, JtJ ); CvMat _JtErr = cvMat( 6, 1, CV_64F, JtErr ); CvMat _JtJW = cvMat( 6, 1, CV_64F, JtJW ); CvMat _JtJV = cvMat( 6, 6, CV_64F, JtJV ); CvMat _delta = cvMat( 6, 1, CV_64F, delta ); CvMat _param = cvMat( 6, 1, CV_64F, param ); CvMat _dpdr, _dpdt; if( !CV_IS_MAT(obj_points) || !CV_IS_MAT(img_points) || !CV_IS_MAT(A) || !CV_IS_MAT(r_vec) || !CV_IS_MAT(t_vec) ) CV_ERROR( CV_StsBadArg, "One of required arguments is not a valid matrix" ); count = MAX(obj_points->cols, obj_points->rows); CV_CALL( _M = cvCreateMat( 1, count, CV_64FC3 )); CV_CALL( _Mxy = cvCreateMat( 1, count, CV_64FC2 )); CV_CALL( _m = cvCreateMat( 1, count, CV_64FC2 )); CV_CALL( _mn = cvCreateMat( 1, count, CV_64FC2 )); M = (CvPoint3D64f*)_M->data.db; m = (CvPoint2D64f*)_m->data.db; mn = (CvPoint2D64f*)_mn->data.db; CV_CALL( cvConvertPointsHomogenious( obj_points, _M )); CV_CALL( cvConvertPointsHomogenious( img_points, _m )); CV_CALL( cvConvert( A, &_a )); if( dist_coeffs ) { CvMat _k; if( !CV_IS_MAT(dist_coeffs) || CV_MAT_DEPTH(dist_coeffs->type) != CV_64F && CV_MAT_DEPTH(dist_coeffs->type) != CV_32F || dist_coeffs->rows != 1 && dist_coeffs->cols != 1 || dist_coeffs->rows*dist_coeffs->cols*CV_MAT_CN(dist_coeffs->type) != 4 ) CV_ERROR( CV_StsBadArg, "Distortion coefficients must be 1x4 or 4x1 floating-point vector" ); _k = cvMat( dist_coeffs->rows, dist_coeffs->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(dist_coeffs->type)), k ); CV_CALL( cvConvert( dist_coeffs, &_k )); } if( CV_MAT_DEPTH(r_vec->type) != CV_64F && CV_MAT_DEPTH(r_vec->type) != CV_32F || r_vec->rows != 1 && r_vec->cols != 1 || r_vec->rows*r_vec->cols*CV_MAT_CN(r_vec->type) != 3 ) CV_ERROR( CV_StsBadArg, "Rotation vector must be 1x3 or 3x1 floating-point vector" ); if( CV_MAT_DEPTH(t_vec->type) != CV_64F && CV_MAT_DEPTH(t_vec->type) != CV_32F || t_vec->rows != 1 && t_vec->cols != 1 || t_vec->rows*t_vec->cols*CV_MAT_CN(t_vec->type) != 3 ) CV_ERROR( CV_StsBadArg, "Translation vector must be 1x3 or 3x1 floating-point vector" ); ifx = 1./a[0]; ify = 1./a[4]; cx = a[2]; cy = a[5]; // normalize image points // (unapply the intrinsic matrix transformation and distortion) for( i = 0; i < count; i++ ) { double x = m[i].x, y = m[i].y; x = (x - cx)*ifx; y = (y - cy)*ify; // compensate distortion iteratively if( dist_coeffs ) for( j = 0; j < 5; j++ ) { double r2 = x*x + y*y; double icdist = 1./(1 + k[0]*r2 + k[1]*r2*r2); double delta_x = 2*k[2]*x*y + k[3]*(r2 + 2*x*x); double delta_y = k[2]*(r2 + 2*y*y) + 2*k[3]*x*y; x = (x - delta_x)*icdist; y = (y - delta_y)*icdist; } mn[i].x = x; mn[i].y = y; // calc mean(M) Mc[0] += M[i].x; Mc[1] += M[i].y; Mc[2] += M[i].z; } Mc[0] /= count; Mc[1] /= count; Mc[2] /= count; cvReshape( _M, _M, 1, count ); cvMulTransposed( _M, &_MM, 1, &_Mc ); cvSVD( &_MM, &_W, 0, &_V, CV_SVD_MODIFY_A + CV_SVD_V_T ); // initialize extrinsic parameters if( W[2]/W[1] < 1e-3 || count < 4 ) { // a planar structure case (all M's lie in the same plane) double tt[3], h[9], h1_norm, h2_norm; CvMat* R_transform = &_V; CvMat T_transform = cvMat( 3, 1, CV_64F, tt ); CvMat _H = cvMat( 3, 3, CV_64F, h ); CvMat _h1, _h2, _h3; if( V[2]*V[2] + V[5]*V[5] < 1e-10 ) cvSetIdentity( R_transform ); if( cvDet(R_transform) < 0 ) cvScale( R_transform, R_transform, -1 ); cvGEMM( R_transform, &_Mc, -1, 0, 0, &T_transform, CV_GEMM_B_T ); for( i = 0; i < count; i++ ) { const double* Rp = R_transform->data.db; const double* Tp = T_transform.data.db; const double* src = _M->data.db + i*3; double* dst = _Mxy->data.db + i*2; dst[0] = Rp[0]*src[0] + Rp[1]*src[1] + Rp[2]*src[2] + Tp[0]; dst[1] = Rp[3]*src[0] + Rp[4]*src[1] + Rp[5]*src[2] + Tp[1]; } cvFindHomography( _Mxy, _mn, &_H ); cvGetCol( &_H, &_h1, 0 ); _h2 = _h1; _h2.data.db++; _h3 = _h2; _h3.data.db++; h1_norm = sqrt(h[0]*h[0] + h[3]*h[3] + h[6]*h[6]); h2_norm = sqrt(h[1]*h[1] + h[4]*h[4] + h[7]*h[7]); cvScale( &_h1, &_h1, 1./h1_norm ); cvScale( &_h2, &_h2, 1./h2_norm ); cvScale( &_h3, &_t, 2./(h1_norm + h2_norm)); cvCrossProduct( &_h1, &_h2, &_h3 ); cvRodrigues2( &_H, &_r ); cvRodrigues2( &_r, &_H ); cvMatMulAdd( &_H, &T_transform, &_t, &_t ); cvMatMul( &_H, R_transform, &_R ); cvRodrigues2( &_R, &_r ); } else { // non-planar structure. Use DLT method double* L; double LL[12*12], LW[12], LV[12*12], sc; CvMat _LL = cvMat( 12, 12, CV_64F, LL ); CvMat _LW = cvMat( 12, 1, CV_64F, LW ); CvMat _LV = cvMat( 12, 12, CV_64F, LV ); CvMat _RRt, _RR, _tt; CV_CALL( _L = cvCreateMat( 2*count, 12, CV_64F )); L = _L->data.db; for( i = 0; i < count; i++, L += 24 ) { double x = -mn[i].x, y = -mn[i].y; L[0] = L[16] = M[i].x; L[1] = L[17] = M[i].y; L[2] = L[18] = M[i].z; L[3] = L[19] = 1.; L[4] = L[5] = L[6] = L[7] = 0.; L[12] = L[13] = L[14] = L[15] = 0.; L[8] = x*M[i].x; L[9] = x*M[i].y; L[10] = x*M[i].z; L[11] = x; L[20] = y*M[i].x; L[21] = y*M[i].y; L[22] = y*M[i].z; L[23] = y; } cvMulTransposed( &_L, &_LL, 1 ); cvSVD( &_LL, &_LW, 0, &_LV, CV_SVD_MODIFY_A + CV_SVD_V_T ); _RRt = cvMat( 3, 4, CV_64F, LV + 11*12 ); cvGetCols( &_RRt, &_RR, 0, 3 ); cvGetCol( &_RRt, &_tt, 3 ); if( cvDet(&_RR) < 0 ) cvScale( &_RRt, &_RRt, -1 ); sc = cvNorm(&_RR); cvSVD( &_RR, &_W, &_U, &_V, CV_SVD_MODIFY_A + CV_SVD_U_T + CV_SVD_V_T ); cvGEMM( &_U, &_V, 1, 0, 0, &_R, CV_GEMM_A_T ); cvScale( &_tt, &_t, cvNorm(&_R)/sc ); cvRodrigues2( &_R, &_r ); cvReleaseMat( &_L ); } CV_CALL( _J = cvCreateMat( 2*count, 6, CV_64FC1 )); cvGetCols( _J, &_dpdr, 0, 3 ); cvGetCols( _J, &_dpdt, 3, 6 ); // refine extrinsic parameters using iterative algorithm for( i = 0; i < max_iter; i++ ) { double n1, n2; cvReshape( _mn, _mn, 2, 1 ); cvProjectPoints2( _M, &_r, &_t, &_a, dist_coeffs, _mn, &_dpdr, &_dpdt, 0, 0, 0 ); cvSub( _m, _mn, _mn ); cvReshape( _mn, _mn, 1, 2*count ); cvMulTransposed( _J, &_JtJ, 1 ); cvGEMM( _J, _mn, 1, 0, 0, &_JtErr, CV_GEMM_A_T ); cvSVD( &_JtJ, &_JtJW, 0, &_JtJV, CV_SVD_MODIFY_A + CV_SVD_V_T ); if( JtJW[5]/JtJW[0] < 1e-12 ) break; cvSVBkSb( &_JtJW, &_JtJV, &_JtJV, &_JtErr, &_delta, CV_SVD_U_T + CV_SVD_V_T ); cvAdd( &_delta, &_param, &_param ); n1 = cvNorm( &_delta ); n2 = cvNorm( &_param ); if( n1/n2 < 1e-10 ) break; } _r = cvMat( r_vec->rows, r_vec->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(r_vec->type)), param ); _t = cvMat( t_vec->rows, t_vec->cols, CV_MAKETYPE(CV_64F,CV_MAT_CN(t_vec->type)), param + 3 ); cvConvert( &_r, r_vec ); cvConvert( &_t, t_vec ); __END__; cvReleaseMat( &_M ); cvReleaseMat( &_m ); cvReleaseMat( &_mn ); cvReleaseMat( &_L ); cvReleaseMat( &_J ); } static void icvInitIntrinsicParams2D( const CvMat* obj_points, const CvMat* img_points, const CvMat* point_counts, CvSize image_size, CvMat* intrinsic_matrix, double aspect_ratio ) { CvMat *_A = 0, *_b = 0; CV_FUNCNAME( "icvInitIntrinsicParams2D" ); __BEGIN__; int i, j, pos, img_count; double a[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 1 }; double H[9], AtA[4], AtAW[2], AtAV[4], Atb[2], f[2]; CvMat _a = cvMat( 3, 3, CV_64F, a ); CvMat _H = cvMat( 3, 3, CV_64F, H ); CvMat _AtA = cvMat( 2, 2, CV_64F, AtA ); CvMat _AtAW = cvMat( 2, 1, CV_64F, AtAW ); CvMat _AtAV = cvMat( 2, 2, CV_64F, AtAV ); CvMat _Atb = cvMat( 2, 1, CV_64F, Atb ); CvMat _f = cvMat( 2, 1, CV_64F, f ); assert( CV_MAT_TYPE(point_counts->type) == CV_32SC1 && CV_IS_MAT_CONT(point_counts->type) ); img_count = point_counts->rows + point_counts->cols - 1; if( CV_MAT_TYPE(obj_points->type) != CV_32FC3 && CV_MAT_TYPE(obj_points->type) != CV_64FC3 || CV_MAT_TYPE(img_points->type) != CV_32FC2 && CV_MAT_TYPE(img_points->type) != CV_64FC2 ) CV_ERROR( CV_StsUnsupportedFormat, "Both object points and image points must be 2D" ); if( obj_points->rows != 1 || img_points->rows != 1 ) CV_ERROR( CV_StsBadSize, "object points and image points must be a single-row matrices" ); CV_CALL( _A = cvCreateMat( 2*img_count, 2, CV_64F )); CV_CALL( _b = cvCreateMat( 2*img_count, 1, CV_64F )); a[2] = (image_size.width - 1)*0.5; a[5] = (image_size.height - 1)*0.5; // extract vanishing points in order to obtain initial value for the focal length for( i = 0, pos = 0; i < img_count; i++ ) { double* Ap = _A->data.db + i*4; double* bp = _b->data.db + i*2; int count = point_counts->data.i[i]; double h[3], v[3], d1[3], d2[3]; double n[4] = {0,0,0,0}; CvMat _m, _M; cvGetCols( obj_points, &_M, pos, pos + count ); cvGetCols( img_points, &_m, pos, pos + count ); pos += count; CV_CALL( cvFindHomography( &_M, &_m, &_H )); H[0] -= H[6]*a[2]; H[1] -= H[7]*a[2]; H[2] -= H[8]*a[2]; H[3] -= H[6]*a[5]; H[4] -= H[7]*a[5]; H[5] -= H[8]*a[5]; for( j = 0; j < 3; j++ ) { double t0 = H[j*3], t1 = H[j*3+1]; h[j] = t0; v[j] = t1; d1[j] = (t0 + t1)*0.5; d2[j] = (t0 - t1)*0.5; n[0] += t0*t0; n[1] += t1*t1; n[2] += d1[j]*d1[j]; n[3] += d2[j]*d2[j]; } for( j = 0; j < 4; j++ ) n[j] = 1./sqrt(n[j]); for( j = 0; j < 3; j++ ) { h[j] *= n[0]; v[j] *= n[1]; d1[j] *= n[2]; d2[j] *= n[3]; } Ap[0] = h[0]*v[0]; Ap[1] = h[1]*v[1]; Ap[2] = d1[0]*d2[0]; Ap[3] = d1[1]*d2[1]; bp[0] = -h[2]*v[2]; bp[1] = -d1[2]*d2[2]; } // while it is not about gradient descent search, // the formula is the same: f = inv(At*A)*At*b icvGaussNewton( _A, _b, &_f, &_AtA, &_Atb, &_AtAW, &_AtAV ); a[0] = sqrt(fabs(1./f[0])); a[4] = sqrt(fabs(1./f[1])); if( aspect_ratio != 0 ) { double tf = (a[0] + a[4])/(aspect_ratio + 1.); a[0] = aspect_ratio*tf; a[4] = tf; } cvConvert( &_a, intrinsic_matrix ); __END__; cvReleaseMat( &_A ); cvReleaseMat( &_b ); } /* finds intrinsic and extrinsic camera parameters from a few views of known calibration pattern */ CV_IMPL void cvCalibrateCamera2( const CvMat* obj_points, const CvMat* img_points, const CvMat* point_counts, CvSize image_size, CvMat* A, CvMat* dist_coeffs, CvMat* r_vecs, CvMat* t_vecs, int flags ) { double alpha_smooth = 0.4; CvMat *counts = 0, *_M = 0, *_m = 0; CvMat *_Ji = 0, *_Je = 0, *_JtJ = 0, *_JtErr = 0, *_JtJW = 0, *_JtJV = 0; CvMat *_param = 0, *_param_innov = 0, *_err = 0; CV_FUNCNAME( "cvCalibrateCamera2" ); __BEGIN__; double a[9]; CvMat _a = cvMat( 3, 3, CV_64F, a ), _k; CvMat _Mi, _mi, _ri, _ti, _part; CvMat _dpdr, _dpdt, _dpdf, _dpdc, _dpdk; CvMat _sr_part = cvMat( 1, 3, CV_64F ), _st_part = cvMat( 1, 3, CV_64F ), _r_part, _t_part; int i, j, pos, iter, img_count, count = 0, max_count = 0, total = 0, param_count; int r_depth = 0, t_depth = 0, r_step = 0, t_step = 0, cn, dims; int output_r_matrices = 0; double aspect_ratio = 0.; if( !CV_IS_MAT(obj_points) || !CV_IS_MAT(img_points) || !CV_IS_MAT(point_counts) || !CV_IS_MAT(A) || !CV_IS_MAT(dist_coeffs) ) CV_ERROR( CV_StsBadArg, "One of required vector arguments is not a valid matrix" ); if( image_size.width <= 0 || image_size.height <= 0 ) CV_ERROR( CV_StsOutOfRange, "image width and height must be positive" ); if( CV_MAT_TYPE(point_counts->type) != CV_32SC1 || point_counts->rows != 1 && point_counts->cols != 1 ) CV_ERROR( CV_StsUnsupportedFormat, "the array of point counters must be 1-dimensional integer vector" ); CV_CALL( counts = cvCreateMat( point_counts->rows, point_counts->width, CV_32SC1 )); cvCopy( point_counts, counts ); img_count = counts->rows + counts->cols - 1; if( r_vecs ) { r_depth = CV_MAT_DEPTH(r_vecs->type); r_step = r_vecs->rows == 1 ? 3*CV_ELEM_SIZE(r_depth) : r_vecs->step; cn = CV_MAT_CN(r_vecs->type); if( !CV_IS_MAT(r_vecs) || r_depth != CV_32F && r_depth != CV_64F || (r_vecs->rows != img_count || r_vecs->cols*cn != 3 && r_vecs->cols*cn != 9) && (r_vecs->rows != 1 || r_vecs->cols != img_count || cn != 3) ) CV_ERROR( CV_StsBadArg, "the output array of rotation vectors must be 3-channel " "1xn or nx1 array or 1-channel nx3 or nx9 array, where n is the number of views" ); output_r_matrices = r_vecs->rows == img_count && r_vecs->cols*cn == 9; } if( t_vecs ) { t_depth = CV_MAT_DEPTH(t_vecs->type); t_step = t_vecs->rows == 1 ? 3*CV_ELEM_SIZE(t_depth) : t_vecs->step; cn = CV_MAT_CN(t_vecs->type); if( !CV_IS_MAT(t_vecs) || t_depth != CV_32F && t_depth != CV_64F || (t_vecs->rows != img_count || t_vecs->cols*cn != 3) && (t_vecs->rows != 1 || t_vecs->cols != img_count || cn != 3) ) CV_ERROR( CV_StsBadArg, "the output array of rotation vectors must be 3-channel " "1xn or nx1 array or 1-channel nx3 array, where n is the number of views" ); } if( CV_MAT_TYPE(A->type) != CV_32FC1 && CV_MAT_TYPE(A->type) != CV_64FC1 || A->rows != 3 || A->cols != 3 ) CV_ERROR( CV_StsBadArg, "Intrinsic parameters must be 3x3 floating-point matrix" ); if( CV_MAT_TYPE(dist_coeffs->type) != CV_32FC1 && CV_MAT_TYPE(dist_coeffs->type) != CV_64FC1 || (dist_coeffs->rows != 4 || dist_coeffs->cols != 1) && (dist_coeffs->cols != 4 || dist_coeffs->rows != 1)) CV_ERROR( CV_StsBadArg, "Distortion coefficients must be 4x1 or 1x4 floating-point matrix" ); for( i = 0; i < img_count; i++ ) { int temp_count = counts->data.i[i]; if( temp_count < 4 ) { char buf[100]; sprintf( buf, "The number of points in the view #%d is <4", i ); CV_ERROR( CV_StsOutOfRange, buf ); } max_count = MAX( max_count, temp_count ); total += temp_count; } dims = CV_MAT_CN(obj_points->type)*(obj_points->rows == 1 ? 1 : obj_points->cols); if( CV_MAT_DEPTH(obj_points->type) != CV_32F && CV_MAT_DEPTH(obj_points->type) != CV_64F || (obj_points->rows != total || dims != 3 && dims != 2) && (obj_points->rows != 1 || obj_points->cols != total || (dims != 3 && dims != 2)) ) CV_ERROR( CV_StsBadArg, "Object points must be 1xn or nx1, 2- or 3-channel matrix, " "or nx3 or nx2 single-channel matrix" ); cn = CV_MAT_CN(img_points->type); if( CV_MAT_DEPTH(img_points->type) != CV_32F && CV_MAT_DEPTH(img_points->type) != CV_64F || (img_points->rows != total || img_points->cols*cn != 2) && (img_points->rows != 1 || img_points->cols != total || cn != 2) ) CV_ERROR( CV_StsBadArg, "Image points must be 1xn or nx1, 2-channel matrix, " "or nx2 single-channel matrix" ); CV_CALL( _M = cvCreateMat( 1, total, CV_64FC3 )); CV_CALL( _m = cvCreateMat( 1, total, CV_64FC2 )); CV_CALL( cvConvertPointsHomogenious( obj_points, _M )); CV_CALL( cvConvertPointsHomogenious( img_points, _m )); param_count = 8 + img_count*6; CV_CALL( _param = cvCreateMat( param_count, 1, CV_64FC1 )); CV_CALL( _param_innov = cvCreateMat( param_count, 1, CV_64FC1 )); CV_CALL( _JtJ = cvCreateMat( param_count, param_count, CV_64FC1 )); CV_CALL( _JtErr = cvCreateMat( param_count, 1, CV_64FC1 )); CV_CALL( _JtJW = cvCreateMat( param_count, 1, CV_64FC1 )); CV_CALL( _JtJV = cvCreateMat( param_count, param_count, CV_64FC1 )); CV_CALL( _Ji = cvCreateMat( max_count*2, 8, CV_64FC1 )); CV_CALL( _Je = cvCreateMat( max_count*2, 6, CV_64FC1 )); CV_CALL( _err = cvCreateMat( max_count*2, 1, CV_64FC1 )); cvGetCols( _Je, &_dpdr, 0, 3 ); cvGetCols( _Je, &_dpdt, 3, 6 ); cvGetCols( _Ji, &_dpdf, 0, 2 ); cvGetCols( _Ji, &_dpdc, 2, 4 ); cvGetCols( _Ji, &_dpdk, 4, flags & CV_CALIB_ZERO_TANGENT_DIST ? 6 : 8 ); cvZero( _Ji ); // 1. initialize intrinsic parameters if( flags & CV_CALIB_USE_INTRINSIC_GUESS ) { cvConvert( A, &_a ); if( a[0] <= 0 || a[4] <= 0 ) CV_ERROR( CV_StsOutOfRange, "Focal length (fx and fy) must be positive" ); if( a[2] < 0 || a[2] >= image_size.width || a[5] < 0 || a[5] >= image_size.height ) CV_ERROR( CV_StsOutOfRange, "Principal point must be within the image" ); if( fabs(a[1]) > 1e-5 ) CV_ERROR( CV_StsOutOfRange, "Non-zero skew is not supported by the function" ); if( fabs(a[3]) > 1e-5 || fabs(a[6]) > 1e-5 || fabs(a[7]) > 1e-5 || fabs(a[8]-1) > 1e-5 ) CV_ERROR( CV_StsOutOfRange, "The intrinsic matrix must have [fx 0 cx; 0 fy cy; 0 0 1] shape" ); a[1] = a[3] = a[6] = a[7] = 0.; a[8] = 1.; if( flags & CV_CALIB_FIX_ASPECT_RATIO ) aspect_ratio = a[0]/a[4]; } else { if( dims == 3 ) { CvScalar mean, sdv; cvAvgSdv( _M, &mean, &sdv ); if( fabs(mean.val[2]) > 1e-5 && fabs(mean.val[2] - 1) > 1e-5 || fabs(sdv.val[2]) > 1e-5 ) CV_ERROR( CV_StsBadArg, "For non-planar calibration rigs the initial intrinsic matrix must be specified" ); } for( i = 0; i < total; i++ ) ((CvPoint3D64f*)(_M->data.db + i*3))->z = 0.; if( flags & CV_CALIB_FIX_ASPECT_RATIO ) { aspect_ratio = cvmGet(A,0,0); aspect_ratio /= cvmGet(A,1,1); if( aspect_ratio < 0.01 || aspect_ratio > 100 ) CV_ERROR( CV_StsOutOfRange, "The specified aspect ratio (=a(0,0)/a(1,1)) is incorrect" ); } icvInitIntrinsicParams2D( _M, _m, counts, image_size, &_a, aspect_ratio ); } _k = cvMat( dist_coeffs->rows, dist_coeffs->cols, CV_64FC1, _param->data.db + 4 ); cvZero( &_k ); // 2. initialize extrinsic parameters for( i = 0, pos = 0; i < img_count; i++, pos += count ) { count = counts->data.i[i]; _ri = cvMat( 1, 3, CV_64FC1, _param->data.db + 8 + i*6 ); _ti = cvMat( 1, 3, CV_64FC1, _param->data.db + 8 + i*6 + 3 ); cvGetCols( _M, &_Mi, pos, pos + count ); cvGetCols( _m, &_mi, pos, pos + count ); cvFindExtrinsicCameraParams2( &_Mi, &_mi, &_a, &_k, &_ri, &_ti ); } _param->data.db[0] = a[0]; _param->data.db[1] = a[4]; _param->data.db[2] = a[2]; _param->data.db[3] = a[5]; // 3. run the optimization for( iter = 0; iter < 30; iter++ ) { double* jj = _JtJ->data.db; double change; for( i = 0, pos = 0; i < img_count; i++, pos += count ) { count = counts->data.i[i]; _ri = cvMat( 1, 3, CV_64FC1, _param->data.db + 8 + i*6); _ti = cvMat( 1, 3, CV_64FC1, _param->data.db + 8 + i*6 + 3); cvGetCols( _M, &_Mi, pos, pos + count ); _mi = cvMat( count*2, 1, CV_64FC1, _m->data.db + pos*2 ); _dpdr.rows = _dpdt.rows = _dpdf.rows = _dpdc.rows = _dpdk.rows = count*2; _err->cols = 1; _err->rows = count*2; cvReshape( _err, _err, 2, count ); cvProjectPoints2( &_Mi, &_ri, &_ti, &_a, &_k, _err, &_dpdr, &_dpdt, &_dpdf, flags & CV_CALIB_FIX_PRINCIPAL_POINT ? 0 : &_dpdc, &_dpdk ); // alter dpdf in case if only one of the focal // parameters (fy) is independent variable if( flags & CV_CALIB_FIX_ASPECT_RATIO ) for( j = 0; j < count; j++ ) { double* dpdf_j = (double*)(_dpdf.data.ptr + j*_dpdf.step*2); dpdf_j[1] = dpdf_j[0]*aspect_ratio; dpdf_j[0] = 0.; } cvReshape( _err, _err, 1, count*2 ); cvSub( &_mi, _err, _err ); _Je->rows = _Ji->rows = count*2; cvGetSubRect( _JtJ, &_part, cvRect(0,0,8,8) ); cvGEMM( _Ji, _Ji, 1, &_part, i > 0, &_part, CV_GEMM_A_T ); cvGetSubRect( _JtJ, &_part, cvRect(8+i*6,8+i*6,6,6) ); cvMulTransposed( _Je, &_part, 1 ); cvGetSubRect( _JtJ, &_part, cvRect(8+i*6,0,6,8) ); cvGEMM( _Ji, _Je, 1, 0, 0, &_part, CV_GEMM_A_T ); cvGetRows( _JtErr, &_part, 0, 8 ); cvGEMM( _Ji, _err, 1, &_part, i > 0, &_part, CV_GEMM_A_T ); cvGetRows( _JtErr, &_part, 8 + i*6, 8 + (i+1)*6 ); cvGEMM( _Je, _err, 1, 0, 0, &_part, CV_GEMM_A_T ); } // make the matrix JtJ exactly symmetrical and add missing zeros for( i = 0; i < param_count; i++ ) { int mj = i < 8 ? param_count : ((i - 8)/6)*6 + 14; for( j = i+1; j < mj; j++ ) jj[j*param_count + i] = jj[i*param_count + j]; for( ; j < param_count; j++ ) jj[j*param_count + i] = jj[i*param_count + j] = 0; } cvSVD( _JtJ, _JtJW, 0, _JtJV, CV_SVD_MODIFY_A + CV_SVD_V_T ); cvSVBkSb( _JtJW, _JtJV, _JtJV, _JtErr, _param_innov, CV_SVD_U_T + CV_SVD_V_T ); cvScale( _param_innov, _param_innov, 1. - pow(1. - alpha_smooth, iter + 1.) ); cvGetRows( _param_innov, &_part, 0, 4 ); change = cvNorm( &_part ); cvGetRows( _param, &_part, 0, 4 ); change /= cvNorm( &_part ); if( flags & CV_CALIB_FIX_PRINCIPAL_POINT ) _param_innov->data.db[2] = _param_innov->data.db[3] = 0.; if( flags & CV_CALIB_ZERO_TANGENT_DIST ) _param_innov->data.db[6] = _param_innov->data.db[7] = 0.; cvAdd( _param, _param_innov, _param ); if( flags & CV_CALIB_FIX_ASPECT_RATIO ) _param->data.db[0] = _param->data.db[1]*aspect_ratio; a[0] = _param->data.db[0]; a[4] = _param->data.db[1]; a[2] = _param->data.db[2]; a[5] = _param->data.db[3]; if( change < FLT_EPSILON ) break; } cvConvert( &_a, A ); cvConvert( &_k, dist_coeffs ); _r_part = cvMat( output_r_matrices ? 3 : 1, 3, r_depth ); _t_part = cvMat( 1, 3, t_depth ); for( i = 0; i < img_count; i++ ) { if( r_vecs ) { _sr_part.data.db = _param->data.db + 8 + i*6; _r_part.data.ptr = r_vecs->data.ptr + i*r_step; if( !output_r_matrices ) cvConvert( &_sr_part, &_r_part ); else { cvRodrigues2( &_sr_part, &_a ); cvConvert( &_a, &_r_part ); } } if( t_vecs ) { _st_part.data.db = _param->data.db + 8 + i*6 + 3; _t_part.data.ptr = t_vecs->data.ptr + i*t_step; cvConvert( &_st_part, &_t_part ); } } __END__; cvReleaseMat( &counts ); cvReleaseMat( &_M ); cvReleaseMat( &_m ); cvReleaseMat( &_param ); cvReleaseMat( &_param_innov ); cvReleaseMat( &_JtJ ); cvReleaseMat( &_JtErr ); cvReleaseMat( &_JtJW ); cvReleaseMat( &_JtJV ); cvReleaseMat( &_Ji ); cvReleaseMat( &_Je ); cvReleaseMat( &_err ); } /* End of file. */
[ [ [ 1, 1602 ] ] ]
6065bb1f998832ac2aabf540dd124c0db0f346bc
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testsemwait/src/tsemwait.cpp
d347e12e00bff35c346a3d5f810eccc145e5c7f9
[]
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
2,605
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "tsemwait.h" #include <unistd.h> #include <errno.h> #include <stdio.h> #include <e32std.h> #include <stdlib.h> #include <string.h> CTestSemwait::~CTestSemwait() { } CTestSemwait::CTestSemwait(const TDesC& aStepName) { // MANDATORY Call to base class method to set up the human readable name for logging. SetTestStepName(aStepName); } TVerdict CTestSemwait::doTestStepPreambleL() { __UHEAP_MARK; SetTestStepResult(EPass); return TestStepResult(); } TVerdict CTestSemwait::doTestStepPostambleL() { __UHEAP_MARKEND; return TestStepResult(); } TVerdict CTestSemwait::doTestStepL() { int err; if(TestStepName() == KTestSem285) { INFO_PRINTF1(_L("TestSem285():")); err = TestSem285(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestSem286) { INFO_PRINTF1(_L("TestSem286():")); err = TestSem286(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestSem287) { INFO_PRINTF1(_L("TestSem287():")); err = TestSem287(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestSem288) { INFO_PRINTF1(_L("TestSem288():")); err = TestSem288(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestSem289) { INFO_PRINTF1(_L("TestSem289():")); err = TestSem289(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestSem290) { INFO_PRINTF1(_L("TestSem290():")); err = TestSem290(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == KTestSem699) { INFO_PRINTF1(_L("TestSem699():")); err = TestSem699(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } return TestStepResult(); }
[ "none@none" ]
[ [ [ 1, 105 ] ] ]
e09578706f18ab81bc0edcd29612bd53c3841916
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/UnitTests/UnitTest_Containers/MyGUI_Container.h
0507047919e716fc6418cf74b5d5672ffcd4dceb
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,425
h
/*! @file @author Alexander Ptakhin @date 02/2009 */ #ifndef __MYGUI_CONTAINER_H__ #define __MYGUI_CONTAINER_H__ #include "MyGUI_SizeDescription.h" #include "MyGUI_Spacer.h" namespace MyGUI { /** Abstract container class */ class /*MYGUI_EXPORT*/ Container : public Widget { MYGUI_RTTI_DERIVED( Container ) protected: Widget* baseCreateWidget(WidgetStyle _style, const std::string& _type, const std::string& _skin, const IntCoord& _coord, Align _align, const std::string& _layer, const std::string& _name); /// Attach widget to container virtual void add(Widget* widget) = 0; /// Detach widget from container virtual void remove(Widget* widget) = 0; /// Update all widget's positions. You've to do it manyally, because sometimes it's not so fast. virtual void update() = 0; //! @copydoc Widget::setSize(const IntSize& _size) void setSize(const IntSize& _size); //! @copydoc Widget::setCoord(const IntCoord& _coord) void setCoord(const IntCoord& _coord); /*internal:*/ virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle* _croppedParent, const std::string& _name); public: struct BaseWidgetInfo { Widget* widget; BaseWidgetInfo(Widget* _widget) : widget(_widget) {} }; }; } // namespace MyGUI #endif // __MYGUI_CONTAINER_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 51 ] ] ]
f71b2b0d106774f6eae878ce21155db7c063ef13
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/src/ParticleEmitters/ParticleUniverseSlaveEmitterTokens.cpp
57fc40c9bc26a7b7550169524c30d60b63415fde
[]
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
3,291
cpp
/* ----------------------------------------------------------------------------------------------- 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. ----------------------------------------------------------------------------------------------- */ #include "ParticleUniversePCH.h" #ifndef PARTICLE_UNIVERSE_EXPORTS #define PARTICLE_UNIVERSE_EXPORTS #endif #include "ParticleEmitters/ParticleUniverseSlaveEmitter.h" #include "ParticleEmitters/ParticleUniverseSlaveEmitterTokens.h" namespace ParticleUniverse { //----------------------------------------------------------------------- bool SlaveEmitterTranslator::translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { Ogre::PropertyAbstractNode* prop = reinterpret_cast<Ogre::PropertyAbstractNode*>(node.get()); ParticleEmitter* em = Ogre::any_cast<ParticleEmitter*>(prop->parent->context); SlaveEmitter* emitter = static_cast<SlaveEmitter*>(em); if (prop->name == token[TOKEN_MASTER_TECHNIQUE]) { // Property: master_technique_name if (passValidateProperty(compiler, prop, token[TOKEN_MASTER_TECHNIQUE], VAL_STRING)) { Ogre::String val; if(getString(prop->values.front(), &val)) { emitter->setMasterTechniqueName(val); return true; } } } else if (prop->name == token[TOKEN_MASTER_EMITTER]) { // Property: master_emitter_name if (passValidateProperty(compiler, prop, token[TOKEN_MASTER_EMITTER], VAL_STRING)) { Ogre::String val; if(getString(prop->values.front(), &val)) { emitter->setMasterEmitterName(val); return true; } } } return false; } //----------------------------------------------------------------------- bool SlaveEmitterTranslator::translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { // No objects return false; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- void SlaveEmitterWriter::write(ParticleScriptSerializer* serializer, const IElement* element) { // Cast the element to a SlaveEmitter const SlaveEmitter* emitter = static_cast<const SlaveEmitter*>(element); // Write the header of the SlaveEmitter serializer->writeLine(token[TOKEN_EMITTER], emitter->getEmitterType(), emitter->getName(), 8); serializer->writeLine("{", 8); // Write base attributes ParticleEmitterWriter::write(serializer, element); // Write own attributes if (emitter->getMasterTechniqueName() != Ogre::StringUtil::BLANK) serializer->writeLine( token[TOKEN_MASTER_TECHNIQUE], emitter->getMasterTechniqueName(), 12); if (emitter->getMasterEmitterName() != Ogre::StringUtil::BLANK) serializer->writeLine( token[TOKEN_MASTER_EMITTER], emitter->getMasterEmitterName(), 12); // Write the close bracket serializer->writeLine("}", 8); } }
[ [ [ 1, 90 ] ] ]
9e26ccc860ffc7d2a4cfce80c9f269c265612edc
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/capcom/cps_run.cpp
f3415399e65913ecf60850128b02bd606a704fca
[]
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
9,985
cpp
// CPS - Run #include "cps.h" // Inputs: unsigned char CpsReset = 0; unsigned char Cpi01A = 0, Cpi01C = 0, Cpi01E = 0; static int nInterrupt; static int nIrqLine, nIrqCycles; static bool bEnableAutoIrq50, bEnableAutoIrq52; // Trigger an interrupt every 32 scanlines static const int nFirstLine = 0x0C; // The first scanline of the display static const int nVBlank = 0x0106 - 0x0C; // The scanline at which the vblank interrupt is triggered static int nCpsCyclesExtra; int nIrqLine50, nIrqLine52; static int DrvReset() { extern unsigned char* CpsMem; if (CpsMem) memset (CpsMem, 0, 0x40000); // Clear GFX and main RAM // Reset machine if (Cps == 2 || (kludge == 5) || Cps1Qs == 1) EEPROMReset(); SekOpen(0); SekReset(); SekClose(); if (!Cps1Pic) { ZetOpen(0); ZetReset(); ZetClose(); } if (Cps == 2) { // Disable beam-synchronized interrupts #ifdef LSB_FIRST *((unsigned short*)(CpsReg + 0x4E)) = 0x0200; *((unsigned short*)(CpsReg + 0x50)) = 0x0106; *((unsigned short*)(CpsReg + 0x52)) = 0x0106; #else *((unsigned short*)(CpsReg + 0x4E)) = 0x0002; *((unsigned short*)(CpsReg + 0x50)) = 0x0601; *((unsigned short*)(CpsReg + 0x52)) = 0x0601; #endif } CpsMapObjectBanks(0); nCpsCyclesExtra = 0; if (Cps == 2 || Cps1Qs == 1) QsndReset(); // Sound init (QSound) BurnAfterReset(); return 0; } static const eeprom_interface qsound_eeprom_interface = { 7, /* address bits */ 8, /* data bits */ "0110", /* read command */ "0101", /* write command */ "0111", /* erase command */ 0, 0, 0, 0 }; static const eeprom_interface cps2_eeprom_interface = { 6, /* address bits */ 16, /* data bits */ "0110", /* read command */ "0101", /* write command */ "0111", /* erase command */ 0, 0, 0, 0 }; int Cps2RunInit() { nLagObjectPalettes = 0; nLagObjectPalettes = 1; SekInit(0, 0x68000); // Allocate 68000 if (Cps2MemInit()) // Memory init return 1; EEPROMInit(&cps2_eeprom_interface); CpsRwInit(); // Registers setup if (CpsPalInit()) // Palette init return 1; if (CpsObjInit()) // Sprite init return 1; // Sound init (QSound) if (QsndInit()) return 1; EEPROMReset(); DrvReset(); return 0; } int CpsRunInit() { nLagObjectPalettes = 0; if (Cps == 2) nLagObjectPalettes = 1; SekInit(0, 0x68000); // Allocate 68000 if (CpsMemInit()) { // Memory init return 1; } if (Cps == 2 || (kludge == 5)) EEPROMInit(&cps2_eeprom_interface); else { if (Cps1Qs == 1) EEPROMInit(&qsound_eeprom_interface); } CpsRwInit(); // Registers setup if (CpsPalInit()) // Palette init return 1; if (CpsObjInit()) // Sprite init return 1; if ((Cps & 1) && Cps1Qs == 0 && Cps1Pic == 0) { // Sound init (MSM6295 + YM2151) if (PsndInit()) return 1; } if (Cps == 2 || Cps1Qs == 1) { // Sound init (QSound) if (QsndInit()) return 1; } if (Cps == 2 || (kludge == 5) || Cps1Qs == 1) EEPROMReset(); DrvReset(); return 0; } int CpsRunExit() { if (Cps == 2 || (kludge == 5) || Cps1Qs == 1) EEPROMExit(); // Sound exit if (Cps == 2 || Cps1Qs == 1) QsndExit(); if (Cps != 2 && Cps1Qs == 0) PsndExit(); // Graphics exit CpsObjExit(); CpsPalExit(); // Sprite Masking exit ZBuf = NULL; // Memory exit CpsRwExit(); CpsMemExit(); SekExit(); return 0; } // nStart = 0-3, nCount=1-4 static inline void GetPalette(int nStart, int nCount) { // Update Palette (Ghouls points to the wrong place on boot up I think) unsigned short val = (*(unsigned short*)(CpsReg + 0x0A)); int nPal = (swapWord(val) << 8) & 0xFFF800; unsigned char* Find = CpsFindGfxRam(nPal, 0x1000); if (Find) memcpy(CpsSavePal + (nStart << 10), Find + (nStart << 10), nCount << 10); } static void GetStarPalette() { int nPal = (*((unsigned short*)(CpsReg + 0x0A)) << 8) & 0xFFF800; unsigned char* Find = CpsFindGfxRam(nPal, 256); if (Find) { memcpy(CpsSavePal + 4096, Find + 4096, 256); memcpy(CpsSavePal + 5120, Find + 5120, 256); } } #define CopyCpsReg(i) \ memcpy(CpsSaveReg[i], CpsReg, 0x0100); #define CopyCpsFrg(i) \ memcpy(CpsSaveFrg[i], CpsFrg, 0x0010); // Schedule a beam-synchronized interrupt #define ScheduleIRQ() \ int nLine = 0x0106; \ if (nIrqLine50 <= nLine) { \ nLine = nIrqLine50; \ } \ if (nIrqLine52 < nLine) { \ nLine = nIrqLine52; \ } \ if (nLine < 0x0106) { \ nIrqLine = nLine; \ nIrqCycles = (nLine * nCpsCycles / 0x0106) + 1; \ } else { \ nIrqCycles = nCpsCycles + 1; \ } // Execute a beam-synchronised interrupt and schedule the next one static void DoIRQ() { // 0x4E - bit 9 = 1: Beam Synchronized interrupts disabled // 0x50 - Beam synchronized interrupt #1 occurs at raster line. // 0x52 - Beam synchronized interrupt #2 occurs at raster line. // Trigger IRQ and copy registers. if (nIrqLine >= nFirstLine) { nInterrupt++; nRasterline[nInterrupt] = nIrqLine - nFirstLine; } SekSetIRQLine(4, SEK_IRQSTATUS_AUTO); SekRun(nCpsCycles * 0x01 / 0x0106); if (nRasterline[nInterrupt] < 224) { CopyCpsReg(nInterrupt); CopyCpsFrg(nInterrupt); } else nRasterline[nInterrupt] = 0; // Schedule next interrupt if (!bEnableAutoIrq50) { if (nIrqLine >= nIrqLine50) nIrqLine50 = 0x0106; } else { if (bEnableAutoIrq50 && nIrqLine == nIrqLine50) nIrqLine50 += 32; } if (!bEnableAutoIrq52 && nIrqLine >= nIrqLine52) nIrqLine52 = 0x0106; else { if (bEnableAutoIrq52 && nIrqLine == nIrqLine52) nIrqLine52 += 32; } ScheduleIRQ(); if (nIrqCycles < SekTotalCycles()) nIrqCycles = SekTotalCycles() + 1; return; } int Cps1Frame() { int nDisplayEnd, nNext, i; if (CpsReset) DrvReset(); SekNewFrame(); if (Cps1Qs == 1) QsndNewFrame(); else { if (!Cps1Pic) { ZetOpen(0); PsndNewFrame(); } } nCpsCycles = (int)((long long)nCPS68KClockspeed * nBurnCPUSpeedAdjust >> 8); Cps1RwGetInp(); // Update the input port values nDisplayEnd = (nCpsCycles * (nFirstLine + 224)) / 0x0106; // Account for VBlank SekOpen(0); SekIdle(nCpsCyclesExtra); SekRun(nCpsCycles * nFirstLine / 0x0106); // run 68K for the first few lines if (kludge != 10 && kludge != 21) CpsObjGet(); // Get objects for (i = 0; i < 4; i++) { nNext = ((i + 1) * nCpsCycles) >> 2; // find out next cycle count to run to if (SekTotalCycles() < nDisplayEnd && nNext > nDisplayEnd) { SekRun(nNext - nDisplayEnd); // run 68K memcpy(CpsSaveReg[0], CpsReg, 0x100); // Registers correct now GetPalette(0, 6); // Get palette if (CpsStar) { GetStarPalette(); } if (kludge == 10 || kludge == 21) { if (i == 3) CpsObjGet(); // Get objects } SekSetIRQLine(2, SEK_IRQSTATUS_AUTO); // Trigger VBlank interrupt } SekRun(nNext - SekTotalCycles()); // run 68K } if (pBurnDraw) CpsDraw(); // Draw frame if (Cps1Qs == 1) QsndEndFrame(); else { if (!Cps1Pic) { PsndSyncZ80(nCpsZ80Cycles); PsmUpdate(nBurnSoundLen); ZetClose(); } } nCpsCyclesExtra = SekTotalCycles() - nCpsCycles; SekClose(); return 0; } int Cps2Frame() { int nDisplayEnd, nNext; // variables to keep track of executed 68K cyles int i; if (CpsReset) DrvReset(); // extern int prevline; // prevline = -1; SekNewFrame(); QsndNewFrame(); nCpsCycles = (int)(((long long)nCPS68KClockspeed * nBurnCPUSpeedAdjust) >> 8); SekSetCyclesScanline(nCpsCycles / 262); Cps2RwGetInp(); // Update the input port values nDisplayEnd = nCpsCycles * (nFirstLine + 224) / 0x0106; // Account for VBlank nInterrupt = 0; for (i = 0; i < MAX_RASTER + 2; i++) nRasterline[i] = 0; // Determine which (if any) of the line counters generates the first IRQ bEnableAutoIrq50 = bEnableAutoIrq52 = false; nIrqLine50 = nIrqLine52 = 0x0106; if (swapWord(*((unsigned short*)(CpsReg + 0x50))) & 0x8000) bEnableAutoIrq50 = true; if (bEnableAutoIrq50 || (swapWord(*((unsigned short*)(CpsReg + 0x4E))) & 0x0200) == 0) nIrqLine50 = swapWord((*((unsigned short*)(CpsReg + 0x50))) & 0x01FF); if (swapWord(*((unsigned short*)(CpsReg + 0x52))) & 0x8000) bEnableAutoIrq52 = true; if (bEnableAutoIrq52 || (swapWord(*((unsigned short*)(CpsReg + 0x4E))) & 0x0200) == 0) nIrqLine52 = (swapWord(*((unsigned short*)(CpsReg + 0x52))) & 0x01FF); ScheduleIRQ(); SekOpen(0); SekIdle(nCpsCyclesExtra); if (nIrqCycles < nCpsCycles * nFirstLine / 0x0106) { SekRun(nIrqCycles); DoIRQ(); } nNext = nCpsCycles * nFirstLine / 0x0106; if (SekTotalCycles() < nNext) SekRun(nNext - SekTotalCycles()); CopyCpsReg(0); // Get initial copy of registers CopyCpsFrg(0); if (nIrqLine >= 0x0106 && (*((unsigned short*)(CpsReg + 0x4E)) & 0x0200) == 0) { nIrqLine50 = *((unsigned short*)(CpsReg + 0x50)) & 0x01FF; nIrqLine52 = *((unsigned short*)(CpsReg + 0x52)) & 0x01FF; ScheduleIRQ(); } GetPalette(0, 4); // Get palettes Cps2ObjGet(); // Get objects for (i = 0; i < 3; i++) { nNext = ((i + 1) * nDisplayEnd) / 3; // find out next cycle count to run to while (nNext > nIrqCycles && nInterrupt < MAX_RASTER) { SekRun(nIrqCycles - SekTotalCycles()); DoIRQ(); } SekRun(nNext - SekTotalCycles()); // run cpu } // nCpsCyclesSegment[0] = (nCpsCycles * nVBlank) / 0x0106; // nDone += SekRun(nCpsCyclesSegment[0] - nDone); SekSetIRQLine(2, SEK_IRQSTATUS_AUTO); // VBlank SekRun(nCpsCycles - SekTotalCycles()); if (pBurnDraw) Cps2Draw(); nCpsCyclesExtra = SekTotalCycles() - nCpsCycles; QsndEndFrame(); SekClose(); // bprintf(PRINT_NORMAL, _T(" -\n")); return 0; }
[ [ [ 1, 461 ] ] ]
422179e20cbab9e7441652fbb84a22eb1e83f6e0
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/mpl/test/vector_c.cpp
66daaa1f6552e2a9f407b1c1f4ac5b0416470973
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
2,021
cpp
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/test/vector_c.cpp,v $ // $Date: 2004/11/10 23:51:34 $ // $Revision: 1.3.2.1 $ #include <boost/mpl/vector_c.hpp> #include <boost/mpl/front.hpp> #include <boost/mpl/size.hpp> #include <boost/mpl/aux_/test.hpp> #if !BOOST_WORKAROUND(BOOST_MSVC, <=1200) MPL_TEST_CASE() { typedef vector_c<bool,true>::type v1; typedef vector_c<bool,false>::type v2; MPL_ASSERT(( is_same< v1::value_type, bool > )); MPL_ASSERT(( is_same< v2::value_type, bool > )); MPL_ASSERT_RELATION( front<v1>::type::value, ==, true ); MPL_ASSERT_RELATION( front<v2>::type::value, ==, false ); } #endif MPL_TEST_CASE() { typedef vector_c<int,-1> v1; typedef vector_c<int,0,1> v2; typedef vector_c<int,1,2,3> v3; MPL_ASSERT(( is_same< v1::value_type, int > )); MPL_ASSERT(( is_same< v2::value_type, int > )); MPL_ASSERT(( is_same< v3::value_type, int > )); MPL_ASSERT_RELATION( size<v1>::value, ==, 1 ); MPL_ASSERT_RELATION( size<v2>::value, ==, 2 ); MPL_ASSERT_RELATION( size<v3>::value, ==, 3 ); MPL_ASSERT_RELATION( front<v1>::type::value, ==, -1 ); MPL_ASSERT_RELATION( front<v2>::type::value, ==, 0 ); MPL_ASSERT_RELATION( front<v3>::type::value, ==, 1 ); } MPL_TEST_CASE() { typedef vector_c<unsigned,0> v1; typedef vector_c<unsigned,1,2> v2; MPL_ASSERT(( is_same< v1::value_type, unsigned > )); MPL_ASSERT(( is_same< v2::value_type, unsigned > )); MPL_ASSERT_RELATION( size<v1>::type::value, ==, 1 ); MPL_ASSERT_RELATION( size<v2>::type::value, ==, 2 ); MPL_ASSERT_RELATION( front<v1>::type::value, ==, 0 ); MPL_ASSERT_RELATION( front<v2>::type::value, ==, 1 ); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 66 ] ] ]
98f9c7ac7bb73609d1e5caa70f5eb777692136ae
aaf23f851e5c0ae43eb60c2d1a9f05462d7b964c
/src/huawei_a1/src/hw_asn1.cpp
db2785fafbcb01f0937427dc9f382561bf090a10
[]
no_license
ismailwissam/bill-parser
28ccb68857cb7d6be04207534e7250da82b5c55f
5e195d606fcbbb1f69cbe148dde2413450d381fb
refs/heads/master
2021-01-10T10:25:20.175318
2010-09-20T02:20:37
2010-09-20T02:20:37
50,747,248
0
0
null
null
null
null
GB18030
C++
false
false
2,526
cpp
#include "hw_asn1.hpp" #include <iostream> #include <stdexcept> /*! * 获得ASN1的Tag */ bool hwasn1GetTag(std::istream& input, int& tag) { unsigned char loc_Char; int loc_Tag = 0; // 读取第一个字符 loc_Char = input.get(); loc_Tag |= loc_Char; // 如果后 5 位都是 1,则后续N个字节也是Tag if((loc_Char & 0x1f) == 0x1f) { int loc_Len = 1; while((loc_Len++) <= 4) { if(input.bad() || input.eof()) { return false; } loc_Char = input.get(); //第一个后续字节的第7位到第1位不能全为0 if(loc_Len == 2) { if(!((loc_Char & 0x7f) | 0x00)) { return false; } } loc_Tag <<= 8; loc_Tag |= loc_Char; //后续字节除最后一个字节外,其他字节的第8位为1 //如果第8位为0,则说明是最后一个后续字节 if((loc_Char & 0x80) != 0x80) { break; } } // 华为格式里 Tag 不会大于 4 if(loc_Len > 4) { return false; } } tag = loc_Tag; return input.good(); } /*! * 获得ASN1的Len */ bool hwasn1GetLen(std::istream& input, size_t& len) { unsigned char loc_Char; size_t loc_Len = 0; // 读取第一个字符 loc_Char = input.get(); loc_Len |= loc_Char; // 如果第一位是1,则后7位表示长度所占的字节数 if((loc_Char & 0x80) == 0x80) { loc_Len = 0; int loc_LenSize = loc_Char & 0x7f; while((loc_LenSize--) > 0) { if(input.bad() || input.eof()) { return false; } loc_Char = input.get(); loc_Len <<= 8; loc_Len |= loc_Char; } } len = loc_Len; return input.good(); } /*! * 获得ASN1的Cont */ bool hwasn1GetCont(std::istream& input, size_t len, std::string& cont) { char* loc_Buff = new char[len]; input.read(loc_Buff, len); // 赋值给 cont try { cont.assign(loc_Buff, len); } catch(std::length_error & e) { delete []loc_Buff; return false; } delete []loc_Buff; return input.good(); }
[ "ewangplay@81b94f52-7618-9c36-a7be-76e94dd6e0e6" ]
[ [ [ 1, 117 ] ] ]
ddba2966608bb6753839f9d451891cb3373ffaa2
13cabe39277567e7d0f801bfcb69c42fe826995c
/Source/itkSingleBitBinaryImageNeighborhoodAccessorFunctor.h
55e6277d4dedf8bb25f2f9b038191d8144e14f21
[]
no_license
midas-journal/midas-journal-646
d749487f778de124063516df8d63798dbb970a8b
329cad922bcc2ac1d712b1a49218d04253afaa44
refs/heads/master
2021-01-10T22:07:50.458437
2011-08-22T13:24:59
2011-08-22T13:24:59
2,248,638
0
0
null
null
null
null
UTF-8
C++
false
false
4,676
h
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkSingleBitBinaryImageNeighborhoodAccessorFunctor.h,v $ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 __itkSingleBitBinaryImageNeighborhoodAccessorFunctor_h #define __itkSingleBitBinaryImageNeighborhoodAccessorFunctor_h #include "itkImageBoundaryCondition.h" #include "itkNeighborhood.h" #include "itkImageBase.h" namespace itk { /** \class SingleBitBinaryImageNeighborhoodAccessorFunctor * \brief Provides accessor interfaces to Access pixels and is meant to be * used on pointers to pixels held by the Neighborhood class. * * A typical user should not need to use this class. The class is internally * used by the neighborhood iterators. * * \author Dan Mueller, Philips Healthcare, PII Development * * This implementation was taken from the Insight Journal paper: * http://hdl.handle.net/10380/3068 * */ template< class TImage > class SingleBitBinaryImageNeighborhoodAccessorFunctor { public: typedef TImage ImageType; typedef typename ImageType::PixelType PixelType; typedef typename ImageType::InternalPixelType InternalPixelType; typedef unsigned int VectorLengthType; typedef typename ImageType::OffsetType OffsetType; typedef Neighborhood< InternalPixelType *, ::itk::GetImageDimension< TImage >::ImageDimension> NeighborhoodType; typedef ImageBoundaryCondition< ImageType > const *ImageBoundaryConditionConstPointerType; SingleBitBinaryImageNeighborhoodAccessorFunctor() {}; /** Set the pointer index to the start of the buffer. * This must be set by the iterators to the starting location of the buffer. * Typically a neighborhood iterator iterating on a neighborhood of an Image, * say \c image will set this in its constructor. For instance: * * \code * ConstNeighborhoodIterator( radius, image, ) * { * ... * m_NeighborhoodAccessorFunctor.SetBegin( image->GetBufferPointer() ); * } * \endcode */ inline void SetBegin( const InternalPixelType * begin ) { this->m_Begin = const_cast< InternalPixelType * >( begin ); } /** Method to dereference a pixel pointer. This is used from the * ConstNeighborhoodIterator as the equivalent operation to (*it). * This method should be preferred over the former (*it) notation. * The reason is that dereferencing a pointer to a location of * VectorImage pixel involves a different operation that simply * dereferencing the pointer. Here a PixelType (array of InternalPixelType s) * is created on the stack and returned. */ inline PixelType Get( const InternalPixelType *pixelPointer ) const { unsigned long offset = pixelPointer - m_Begin; unsigned long groupOffset = offset / 32; unsigned long bitOffset = offset % 32; InternalPixelType bitMask = 0x1 << bitOffset; return (m_Begin[groupOffset] & bitMask) == bitMask; } /** Method to set the pixel value at a certain pixel pointer */ inline void Set( InternalPixelType* &pixelPointer, const PixelType &p ) const { unsigned long offset = pixelPointer - m_Begin; unsigned long groupOffset = offset / 32; unsigned long bitOffset = offset % 32; InternalPixelType bitMask = ( 0x1 << bitOffset ); if ( p ) { m_Begin[groupOffset] |= bitMask; } else { m_Begin[groupOffset] &= ~bitMask; } } inline PixelType BoundaryCondition( const OffsetType& point_index, const OffsetType &boundary_offset, const NeighborhoodType *data, const ImageBoundaryConditionConstPointerType boundaryCondition) const { return boundaryCondition->operator()(point_index, boundary_offset, data, *this); } /** Required for some filters to compile. */ void SetVectorLength( VectorLengthType length ) { } /** Required for some filters to compile. */ VectorLengthType SetVectorLength() { return 0; } private: InternalPixelType *m_Begin; // Begin of the buffer }; } // end namespace itk #endif
[ [ [ 1, 132 ] ] ]
9882e316292c1e844b1beda68165a35f143df398
b8851fc2e5c4f24615365e0b58259c2c30dec5c4
/JogoSO/stdafx.cpp
a879eb8cf4d72e503201cfead97a498607a71e50
[]
no_license
cr0vax/estigsotg2
f1190ad4ea1dde319dd67d42551e43e128fcb517
6651d39e34b8098cb74c5f5183e95fd8d162177a
refs/heads/master
2021-01-10T12:41:53.423313
2011-07-05T04:55:45
2011-07-05T04:55:45
48,793,813
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
// stdafx.cpp : source file that includes just the standard includes // JogoSO.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ [ [ 1, 8 ] ] ]
064476be616ec561c7ed3548f3e52cb1159f230d
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/STLPort-4.0/stlport/stl/_hashtable.h
069fe4d2ce1f2e3a72648b308f350372432bb4d7
[ "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
19,754
h
/* * * Copyright (c) 1994 * Hewlett-Packard Company * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1997 * Moscow Center for SPARC Technology * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ /* NOTE: This is an internal header file, included by other STL headers. * You should not attempt to use it directly. */ #ifndef __SGI_STL_INTERNAL_HASHTABLE_H #define __SGI_STL_INTERNAL_HASHTABLE_H # ifndef __SGI_STL_INTERNAL_VECTOR_H # include <stl/_vector.h> # endif # ifndef __SGI_STL_INTERNAL_ITERATOR_H # include <stl/_iterator.h> # endif # ifndef __SGI_STL_INTERNAL_FUNCTION_H # include <stl/_function.h> # endif # ifndef __SGI_STL_INTERNAL_ALGO_H # include <stl/_algo.h> # endif # ifndef __SGI_STL_HASH_FUN_H # include <stl/_hash_fun.h> # endif // Hashtable class, used to implement the hashed associative containers // hash_set, hash_map, hash_multiset, and hash_multimap. #ifdef __STL_DEBUG # define hashtable __WORKAROUND_DBG_RENAME(hashtable) #endif __STL_BEGIN_NAMESPACE # if defined ( __STL_USE_ABBREVS ) # define _Hashtable_iterator _hT__It # define _Hashtable_const_iterator _hT__cIt # define _Hashtable_node _hT__N # define _Hashtable_base _hT__B # define _Ht_iterator _Ht_It # endif template <class _Val> struct _Hashtable_node { typedef _Hashtable_node<_Val> _Self; _Self* _M_next; _Val _M_val; __TRIVIAL_STUFF(_Hashtable_node) }; // some compilers require the names of template parameters to be the same template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> class hashtable; template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> struct _Hashtable_iterator { typedef hashtable<_Val,_Key,_HF,_ExK,_EqK,_All> _Hashtable; typedef _Hashtable_node<_Val> _Node; _Node* _M_cur; _Hashtable* _M_ht; _Hashtable_iterator(_Node* __n, _Hashtable* __tab) : _M_cur(__n), _M_ht(__tab) {} _Hashtable_iterator() {} _Node* _M_skip_to_next(); }; template <class _Val, class _Traits, class _Key, class _HF, class _ExK, class _EqK, class _All> struct _Ht_iterator : public _Hashtable_iterator< _Val, _Key,_HF, _ExK,_EqK,_All> { typedef _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All> _Base; // typedef _Ht_iterator<_Val, _Nonconst_traits<_Val>,_Key,_HF,_ExK,_EqK,_All> iterator; // typedef _Ht_iterator<_Val, _Const_traits<_Val>,_Key,_HF,_ExK,_EqK,_All> const_iterator; typedef _Ht_iterator<_Val, _Traits,_Key,_HF,_ExK,_EqK,_All> _Self; typedef hashtable<_Val,_Key,_HF,_ExK,_EqK,_All> _Hashtable; typedef _Hashtable_node<_Val> _Node; typedef _Val value_type; typedef forward_iterator_tag iterator_category; typedef ptrdiff_t difference_type; typedef size_t size_type; typedef typename _Traits::reference reference; typedef typename _Traits::pointer pointer; _Ht_iterator(const _Node* __n, const _Hashtable* __tab) : _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>((_Node*)__n, (_Hashtable*)__tab) {} _Ht_iterator() {} _Ht_iterator(const _Ht_iterator<_Val, _Nonconst_traits<_Val>,_Key,_HF,_ExK,_EqK,_All>& __it) : _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>(__it) {} reference operator*() const { return this->_M_cur->_M_val; } __STL_DEFINE_ARROW_OPERATOR _Self& operator++() { _Node* __n = this->_M_cur->_M_next; this->_M_cur = (__n !=0 ? __n : this->_M_skip_to_next()); return *this; } inline _Self operator++(int) { _Self __tmp = *this; ++*this; return __tmp; } }; template <class _Val, class _Traits, class _Traits1, class _Key, class _HF, class _ExK, class _EqK, class _All> inline bool operator==(const _Ht_iterator<_Val, _Traits,_Key,_HF,_ExK,_EqK,_All>& __x, const _Ht_iterator<_Val, _Traits1,_Key,_HF,_ExK,_EqK,_All>& __y) { return __x._M_cur == __y._M_cur; } #ifdef __STL_USE_SEPARATE_RELOPS_NAMESPACE template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline bool operator!=(const _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>& __x, const _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>& __y) { return __x._M_cur != __y._M_cur; } #else # if (defined (__GNUC__) && (__GNUC_MINOR__ < 8)) template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline bool operator!=(const _Ht_iterator<_Val, _Const_traits<_Val>,_Key,_HF,_ExK,_EqK,_All>& __x, const _Ht_iterator<_Val, _Nonconst_traits<_Val>,_Key,_HF,_ExK,_EqK,_All>& __y) { return __x._M_cur != __y._M_cur; } # endif template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline bool operator!=(const _Ht_iterator<_Val, _Nonconst_traits<_Val>,_Key,_HF,_ExK,_EqK,_All>& __x, const _Ht_iterator<_Val, _Const_traits<_Val>,_Key,_HF,_ExK,_EqK,_All>& __y) { return __x._M_cur != __y._M_cur; } #endif # ifdef __STL_USE_OLD_HP_ITERATOR_QUERIES template <class _Val, class _Traits, class _Key, class _HF, class _ExK, class _EqK, class _All> inline _Val* __VALUE_TYPE(const _Ht_iterator<_Val, _Traits,_Key,_HF,_ExK,_EqK,_All>&) { return (_Val*) 0; } template <class _Val, class _Traits, class _Key, class _HF, class _ExK, class _EqK, class _All> inline forward_iterator_tag __ITERATOR_CATEGORY(const _Ht_iterator<_Val, _Traits,_Key,_HF,_ExK,_EqK,_All>&) { return forward_iterator_tag(); } template <class _Val, class _Traits, class _Key, class _HF, class _ExK, class _EqK, class _All> inline ptrdiff_t* __DISTANCE_TYPE(const _Ht_iterator<_Val,_Traits,_Key,_HF,_ExK,_EqK,_All>&) { return (ptrdiff_t*) 0; } #endif #define __stl_num_primes 28 template <class _Tp> struct _Stl_prime { public: static const unsigned long _M_list[__stl_num_primes]; }; #define __stl_prime_list _Stl_prime_type::_M_list typedef _Stl_prime<bool> _Stl_prime_type; // Hashtables handle allocators a bit differently than other containers // do. If we're using standard-conforming allocators, then a hashtable // unconditionally has a member variable to hold its allocator, even if // it so happens that all instances of the allocator type are identical. // This is because, for hashtables, this extra storage is negligible. // Additionally, a base class wouldn't serve any other purposes; it // wouldn't, for example, simplify the exception-handling code. template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> class hashtable { typedef hashtable<_Val, _Key, _HF, _ExK, _EqK, _All> _Self; public: typedef _Key key_type; typedef _Val value_type; typedef _HF hasher; typedef _EqK key_equal; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef forward_iterator_tag _Iterator_category; hasher hash_funct() const { return _M_hash; } key_equal key_eq() const { return _M_equals; } private: typedef _Hashtable_node<_Val> _Node; private: typedef typename _Alloc_traits<_Node, _All>::allocator_type _M_node_allocator_type; typedef typename _Alloc_traits<void*, _All>::allocator_type _M_node_ptr_allocator_type; typedef __vector__<void*, _M_node_ptr_allocator_type> _BucketVector; public: typedef typename _Alloc_traits<_Val,_All>::allocator_type allocator_type; allocator_type get_allocator() const { return __STL_CONVERT_ALLOCATOR((const _M_node_allocator_type&)_M_num_elements, _Val); } private: hasher _M_hash; key_equal _M_equals; _ExK _M_get_key; _BucketVector _M_buckets; _STL_alloc_proxy<size_type, _Node, _M_node_allocator_type> _M_num_elements; const _Node* _M_get_bucket(size_t __n) const { return (_Node*)_M_buckets[__n]; } public: typedef _Const_traits<_Val> __const_val_traits; typedef _Nonconst_traits<_Val> __nonconst_val_traits; typedef _Ht_iterator<_Val, __const_val_traits,_Key,_HF,_ExK,_EqK, _All> const_iterator; typedef _Ht_iterator<_Val, __nonconst_val_traits,_Key,_HF,_ExK,_EqK,_All> iterator; friend struct _Hashtable_iterator<_Val,_Key,_HF,_ExK,_EqK,_All>; friend struct _Ht_iterator<_Val, _Nonconst_traits<_Val>,_Key,_HF,_ExK,_EqK,_All>; friend struct _Ht_iterator<_Val, _Const_traits<_Val>,_Key,_HF,_ExK,_EqK, _All>; public: hashtable(size_type __n, const _HF& __hf, const _EqK& __eql, const _ExK& __ext, const allocator_type& __a = allocator_type()) : _M_hash(__hf), _M_equals(__eql), _M_get_key(__ext), _M_buckets(__STL_CONVERT_ALLOCATOR(__a,void*)), _M_num_elements(__STL_CONVERT_ALLOCATOR(__a,_Node), (size_type)0) { _M_initialize_buckets(__n); } hashtable(size_type __n, const _HF& __hf, const _EqK& __eql, const allocator_type& __a = allocator_type()) : _M_hash(__hf), _M_equals(__eql), _M_get_key(_ExK()), _M_buckets(__STL_CONVERT_ALLOCATOR(__a,void*)), _M_num_elements(__STL_CONVERT_ALLOCATOR(__a,_Node), (size_type)0) { _M_initialize_buckets(__n); } hashtable(const _Self& __ht) : _M_hash(__ht._M_hash), _M_equals(__ht._M_equals), _M_get_key(__ht._M_get_key), _M_buckets(__STL_CONVERT_ALLOCATOR(__ht.get_allocator(),void*)), _M_num_elements((const _M_node_allocator_type&)__ht._M_num_elements, (size_type)0) { _M_copy_from(__ht); } _Self& operator= (const _Self& __ht) { if (&__ht != this) { clear(); _M_hash = __ht._M_hash; _M_equals = __ht._M_equals; _M_get_key = __ht._M_get_key; _M_copy_from(__ht); } return *this; } ~hashtable() { clear(); } size_type size() const { return _M_num_elements._M_data; } size_type max_size() const { return size_type(-1); } bool empty() const { return size() == 0; } void swap(_Self& __ht) { __STLPORT_STD::swap(_M_hash, __ht._M_hash); __STLPORT_STD::swap(_M_equals, __ht._M_equals); __STLPORT_STD::swap(_M_get_key, __ht._M_get_key); _M_buckets.swap(__ht._M_buckets); __STLPORT_STD::swap(_M_num_elements, __ht._M_num_elements); } iterator begin() { for (size_type __n = 0; __n < _M_buckets.size(); ++__n) if (_M_buckets[__n]) return iterator((_Node*)_M_buckets[__n], this); return end(); } iterator end() { return iterator((_Node*)0, this); } const_iterator begin() const { for (size_type __n = 0; __n < _M_buckets.size(); ++__n) if (_M_buckets[__n]) return const_iterator((_Node*)_M_buckets[__n], this); return end(); } const_iterator end() const { return const_iterator((_Node*)0, this); } static bool __STL_CALL _M_equal (const hashtable<_Val, _Key, _HF, _ExK, _EqK, _All>&, const hashtable<_Val, _Key, _HF, _ExK, _EqK, _All>&); public: size_type bucket_count() const { return _M_buckets.size(); } size_type max_bucket_count() const { return __stl_prime_list[(int)__stl_num_primes - 1]; } size_type elems_in_bucket(size_type __bucket) const { size_type __result = 0; for (_Node* __cur = (_Node*)_M_buckets[__bucket]; __cur; __cur = __cur->_M_next) __result += 1; return __result; } pair<iterator, bool> insert_unique(const value_type& __obj) { resize(_M_num_elements._M_data + 1); return insert_unique_noresize(__obj); } iterator insert_equal(const value_type& __obj) { resize(_M_num_elements._M_data + 1); return insert_equal_noresize(__obj); } pair<iterator, bool> insert_unique_noresize(const value_type& __obj); iterator insert_equal_noresize(const value_type& __obj); #ifdef __STL_MEMBER_TEMPLATES template <class _InputIterator> void insert_unique(_InputIterator __f, _InputIterator __l) { insert_unique(__f, __l, __ITERATOR_CATEGORY(__f)); } template <class _InputIterator> void insert_equal(_InputIterator __f, _InputIterator __l) { insert_equal(__f, __l, __ITERATOR_CATEGORY(__f)); } template <class _InputIterator> void insert_unique(_InputIterator __f, _InputIterator __l, input_iterator_tag) { for ( ; __f != __l; ++__f) insert_unique(*__f); } template <class _InputIterator> void insert_equal(_InputIterator __f, _InputIterator __l, input_iterator_tag) { for ( ; __f != __l; ++__f) insert_equal(*__f); } template <class _ForwardIterator> void insert_unique(_ForwardIterator __f, _ForwardIterator __l, forward_iterator_tag) { size_type __n = 0; distance(__f, __l, __n); resize(_M_num_elements._M_data + __n); for ( ; __n > 0; --__n, ++__f) insert_unique_noresize(*__f); } template <class _ForwardIterator> void insert_equal(_ForwardIterator __f, _ForwardIterator __l, forward_iterator_tag) { size_type __n = 0; distance(__f, __l, __n); resize(_M_num_elements._M_data + __n); for ( ; __n > 0; --__n, ++__f) insert_equal_noresize(*__f); } #else /* __STL_MEMBER_TEMPLATES */ void insert_unique(const value_type* __f, const value_type* __l) { size_type __n = __l - __f; resize(_M_num_elements._M_data + __n); for ( ; __n > 0; --__n, ++__f) insert_unique_noresize(*__f); } void insert_equal(const value_type* __f, const value_type* __l) { size_type __n = __l - __f; resize(_M_num_elements._M_data + __n); for ( ; __n > 0; --__n, ++__f) insert_equal_noresize(*__f); } void insert_unique(const_iterator __f, const_iterator __l) { size_type __n = 0; distance(__f, __l, __n); resize(_M_num_elements._M_data + __n); for ( ; __n > 0; --__n, ++__f) insert_unique_noresize(*__f); } void insert_equal(const_iterator __f, const_iterator __l) { size_type __n = 0; distance(__f, __l, __n); resize(_M_num_elements._M_data + __n); for ( ; __n > 0; --__n, ++__f) insert_equal_noresize(*__f); } #endif /*__STL_MEMBER_TEMPLATES */ reference find_or_insert(const value_type& __obj); iterator find(const key_type& __key) { size_type __n = _M_bkt_num_key(__key); _Node* __first; for ( __first = (_Node*)_M_buckets[__n]; __first && !_M_equals(_M_get_key(__first->_M_val), __key); __first = __first->_M_next) {} return iterator(__first, this); } const_iterator find(const key_type& __key) const { size_type __n = _M_bkt_num_key(__key); const _Node* __first; for ( __first = (_Node*)_M_buckets[__n]; __first && !_M_equals(_M_get_key(__first->_M_val), __key); __first = __first->_M_next) {} return const_iterator(__first, this); } size_type count(const key_type& __key) const { const size_type __n = _M_bkt_num_key(__key); size_type __result = 0; for (const _Node* __cur = (_Node*)_M_buckets[__n]; __cur; __cur = __cur->_M_next) if (_M_equals(_M_get_key(__cur->_M_val), __key)) ++__result; return __result; } pair<iterator, iterator> equal_range(const key_type& __key); pair<const_iterator, const_iterator> equal_range(const key_type& __key) const; size_type erase(const key_type& __key); // void erase(const iterator& __it); ` void erase(const const_iterator& __it) ; // void erase(const const_iterator& __first, const const_iterator __last) { // erase((const iterator&)__first, (const iterator&)__last); // } void erase(const_iterator __first, const_iterator __last); void resize(size_type __num_elements_hint); void clear(); private: size_type _M_next_size(size_type __n) const { const size_type* __first = (const size_type*)__stl_prime_list; const size_type* __last = (const size_type*)__stl_prime_list + (int)__stl_num_primes; const size_type* pos = lower_bound(__first, __last, __n); return (pos == __last ? *(__last - 1) : *pos); } void _M_initialize_buckets(size_type __n) { const size_type __n_buckets = _M_next_size(__n); _M_buckets.reserve(__n_buckets); _M_buckets.insert(_M_buckets.end(), __n_buckets, (void*) 0); _M_num_elements._M_data = 0; } size_type _M_bkt_num_key(const key_type& __key) const { return _M_bkt_num_key(__key, _M_buckets.size()); } size_type _M_bkt_num(const value_type& __obj) const { return _M_bkt_num_key(_M_get_key(__obj)); } size_type _M_bkt_num_key(const key_type& __key, size_t __n) const { return _M_hash(__key) % __n; } size_type _M_bkt_num(const value_type& __obj, size_t __n) const { return _M_bkt_num_key(_M_get_key(__obj), __n); } _Node* _M_new_node(const value_type& __obj) { _Node* __n = _M_num_elements.allocate(1); __n->_M_next = 0; __STL_TRY { _Construct(&__n->_M_val, __obj); // return __n; } __STL_UNWIND(_M_num_elements.deallocate(__n, 1)); return __n; } void _M_delete_node(_Node* __n) { _Destroy(&__n->_M_val); _M_num_elements.deallocate(__n, 1); } void _M_erase_bucket(const size_type __n, _Node* __first, _Node* __last); void _M_erase_bucket(const size_type __n, _Node* __last); void _M_copy_from(const _Self& __ht); }; template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline bool __STL_CALL operator==(const hashtable<_Val,_Key,_HF,_ExK,_EqK,_All>& __ht1, const hashtable<_Val,_Key,_HF,_ExK,_EqK,_All>& __ht2) { return hashtable<_Val,_Key,_HF,_ExK,_EqK,_All>::_M_equal( __ht1, __ht2 ); } #ifdef __STL_USE_SEPARATE_RELOPS_NAMESPACE template <class _Val, class _Key, class _HF, class _Ex, class _Eq, class _All> inline bool __STL_CALL operator!=(const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht1, const hashtable<_Val,_Key,_HF,_Ex,_Eq,_All>& __ht2) { return !(__ht1 == __ht2); } template <class _Val, class _Key, class _HF, class _ExK, class _EqK, class _All> inline void __STL_CALL swap(hashtable<_Val, _Key, _HF, _ExK, _EqK, _All>& __ht1, hashtable<_Val, _Key, _HF, _ExK, _EqK, _All>& __ht2) { __ht1.swap(__ht2); } #endif /* __STL_USE_SEPARATE_RELOPS_NAMESPACE */ __STL_END_NAMESPACE # undef __stl_prime_list # undef hashtable # if !defined (__STL_LINK_TIME_INSTANTIATION) # include <stl/_hashtable.c> # endif # if defined (__STL_DEBUG) # include <stl/debug/_hashtable.h> # endif #endif /* __SGI_STL_INTERNAL_HASHTABLE_H */ // Local Variables: // mode:C++ // End:
[ [ [ 1, 627 ] ] ]
06c82b434534b04a2f3ad00e7e69dae622edc415
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/src/instantiate_cpp_grammar.cpp
4c374942a980dd41402c1529bbeafc66642bfd3a
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,840
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001-2007 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #define BOOST_WAVE_SOURCE 1 #include <boost/wave/wave_config.hpp> #if BOOST_WAVE_SEPARATE_GRAMMAR_INSTANTIATION != 0 #include <string> #include <list> #include <boost/wave/cpplexer/cpp_lex_token.hpp> #include <boost/wave/cpplexer/cpp_lex_iterator.hpp> #include <boost/wave/grammars/cpp_grammar.hpp> // this must occur after all of the includes and before any code appears #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_PREFIX #endif /////////////////////////////////////////////////////////////////////////////// // // Explicit instantiation of the cpp_grammar_gen template with the correct // token type. This instantiates the corresponding pt_parse function, which // in turn instantiates the cpp_grammar object // (see wave/grammars/cpp_grammar.hpp) // /////////////////////////////////////////////////////////////////////////////// typedef boost::wave::cpplexer::lex_token<> token_type; typedef boost::wave::cpplexer::lex_iterator<token_type> lexer_type; typedef std::list<token_type, boost::fast_pool_allocator<token_type> > token_sequence_type; template struct boost::wave::grammars::cpp_grammar_gen<lexer_type, token_sequence_type>; // the suffix header occurs after all of the code #ifdef BOOST_HAS_ABI_HEADERS #include BOOST_ABI_SUFFIX #endif #endif // #if BOOST_WAVE_SEPARATE_GRAMMAR_INSTANTIATION != 0
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 50 ] ] ]
f2543506e6d884b26c8d719bae9ccb10bf9ab71f
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/PhysXMapping.cpp
efb2fd127493f1995eb34c0d3120ea1a040d88c2
[]
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
3,833
cpp
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: PhysXMapping.cpp Version: 0.04 --------------------------------------------------------------------------- */ #include "PrecompiledHeaders.h" #include "PhysXMapping.h" #include "ForceFieldTypes.h" #include "Matrix3x3.h" #include "NxExtended.h" #include "NxForceField.h" namespace nGENE { Vector3 PhysXMapping::nxVec3ToVector3(const NxVec3& _vec) { return Vector3(_vec.x, _vec.y, _vec.z); } //---------------------------------------------------------------------- Vector3 PhysXMapping::nxVec3ToVector3(const NxExtendedVec3& _vec) { return Vector3(_vec.x, _vec.y, _vec.z); } //---------------------------------------------------------------------- NxVec3 PhysXMapping::vector3ToNxVec3(const Vector3& _vec) { return NxVec3(_vec.x, _vec.y, _vec.z); } //---------------------------------------------------------------------- NxExtendedVec3 PhysXMapping::vector3ToNxExtendedVec3(const Vector3& _vec) { return NxExtendedVec3(_vec.x, _vec.y, _vec.z); } //---------------------------------------------------------------------- Quaternion PhysXMapping::nxQuatToQuaternion(const NxQuat& _quat) { return Quaternion(_quat.x, _quat.y, _quat.z, _quat.w); } //---------------------------------------------------------------------- NxQuat PhysXMapping::quaternionToNxQuat(const Quaternion& _quat) { NxQuat result; result.setXYZW(_quat.x, _quat.y, _quat.z, _quat.w); return result; } //---------------------------------------------------------------------- NxMat33 PhysXMapping::matrix3x3ToNxMat33(const Matrix3x3& _mat) { NxMat33 mat(NxVec3(_mat._m11, _mat._m12, _mat._m13), NxVec3(_mat._m21, _mat._m22, _mat._m23), NxVec3(_mat._m31, _mat._m32, _mat._m33)); return mat; } //---------------------------------------------------------------------- NxMat34 PhysXMapping::matrix4x4ToNxMat34(const Matrix4x4& _mat) { NxMat33 matRot(NxVec3(_mat._m11, _mat._m12, _mat._m13), NxVec3(_mat._m21, _mat._m22, _mat._m23), NxVec3(_mat._m31, _mat._m32, _mat._m33)); NxVec3 vecTrans(_mat._m41, _mat._m42, _mat._m43); NxMat34 mat(matRot, vecTrans); return mat; } //---------------------------------------------------------------------- NxForceFieldType PhysXMapping::ffiToNxForceFieldType(const FORCE_FIELD_INTERACTION& _interaction) { switch(_interaction) { case FFI_NONE: return NX_FF_TYPE_NO_INTERACTION; case FFI_GRAVITATION: return NX_FF_TYPE_GRAVITATIONAL; case FFI_OTHER: return NX_FF_TYPE_OTHER; default: return NX_FF_TYPE_OTHER; } } //---------------------------------------------------------------------- NxForceFieldCoordinates PhysXMapping::ffcToNxForceFieldCoordinates(const FORCE_FIELD_COORDINATES& _coordinates) { switch(_coordinates) { case FFC_CARTESIAN: return NX_FFC_CARTESIAN; case FFC_SPHERICAL: return NX_FFC_SPHERICAL; case FFC_CYLINDRICAL: return NX_FFC_CYLINDRICAL; case FFC_TOROIDAL: return NX_FFC_TOROIDAL; default: return NX_FFC_CARTESIAN; } } //---------------------------------------------------------------------- uint PhysXMapping::ffvsToNxForceFieldFlags(uint _scaling) { uint result = 0; if(_scaling & FFVS_RIGID_BODY) result |= NX_FFF_VOLUMETRIC_SCALING_RIGIDBODY; if(_scaling & FFVS_SOFT_BODY) result |= NX_FFF_VOLUMETRIC_SCALING_SOFTBODY; if(_scaling & FFVS_CLOTH) result |= NX_FFF_VOLUMETRIC_SCALING_CLOTH; if(_scaling & FFVS_FLUID) result |= NX_FFF_VOLUMETRIC_SCALING_FLUID; return result; } //---------------------------------------------------------------------- }
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 117 ] ] ]
1ca82e72098c6187d0809398dd6e7a701b8c7dc5
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Library/CHtml.cpp
b584a12896f6d26082a27026d205c9536321f7f5
[]
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
8,831
cpp
/* CHtml.cpp Classe base per interfaccia HTML. Luca Piergentili, 29/11/99 [email protected] */ #include "env.h" #include "pragma.h" #include "macro.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <fcntl.h> #include "CHtml.h" #include "traceexpr.h" //#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT //#define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG _TRFLAG_NOTRACE #define _TRACE_FLAG_INFO _TRFLAG_NOTRACE #define _TRACE_FLAG_WARN _TRFLAG_NOTRACE #define _TRACE_FLAG_ERR _TRFLAG_NOTRACE #if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL)) #ifdef PRAGMA_MESSAGE_VERBOSE #pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro") #endif #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /* CHtml() */ CHtml::CHtml() { m_pStream = (FILE*)NULL; m_OutputType = (HTMLOUTPUT_TYPE)0; } /* ~CHtml() */ CHtml::~CHtml() { Close(); } /* Open() Apre il file, se gia' esiste lo azzera. Passare NULL per usare stdout. */ int CHtml::Open(const char* file/*=NULL*/) { if(m_pStream) return(0); _fmode = _O_BINARY; HTMLOUTPUT_TYPE type = (file==NULL ? STDOUT : OUTPUTFILE); //check_type: switch(type) { #if 1 case OUTPUTFILE: strncpy(m_szFileName,file,sizeof(m_szFileName)-1); m_pStream = fopen(m_szFileName,"w+"); m_OutputType = OUTPUTFILE; break; #else case OUTPUTFILE: strncpy(m_szFileName,file,sizeof(m_szFileName)-1); if((m_pStream = fopen(m_szFileName,"wb"))==(FILE*)NULL) { type = STDOUT; goto check_type; } m_OutputType = OUTPUTFILE; break; #endif case STDOUT: memset(m_szFileName,'\0',sizeof(m_szFileName)); m_pStream = stdout; m_OutputType = STDOUT; break; } return(m_pStream!=(FILE*)NULL ? 1 : 0); } /* Close() Chiude il file (o svuota lo stream). */ int CHtml::Close(void) { if(m_pStream) { if(m_OutputType==OUTPUTFILE) fclose(m_pStream); else if(m_OutputType==STDOUT) fflush(m_pStream); m_pStream = (FILE*)NULL; } return(1); } /* Header() Imposta l'header. */ void CHtml::Header(const char* title/*=NULL */,const char* doctype/*=NULL */,const char* meta/*=NULL */) { if(doctype) fprintf(m_pStream,"%s\r\n",doctype); fwrite( "<html>\r\n<head>\r\n", sizeof(char), 16, m_pStream ); if(title) fprintf(m_pStream,"<title>%s</title>\r\n",title); if(meta) fprintf(m_pStream,"%s\r\n",meta); fwrite( "</head>\r\n<body>\r\n", sizeof(char), 17, m_pStream ); } /* Footer() Imposta il footer. */ void CHtml::Footer(void) { fwrite("\r\n</body>\r\n</html>",sizeof(char),18,m_pStream); } /* Text() Trascrive il testo nel file. Accetta il layout. */ void CHtml::Text(const char* string,HTMLLAYOUT* layout/*=NULL*/) { if(layout) { if(layout->font.type) fprintf(m_pStream,"<font face=\"%s\" size=\"%d\">",layout->font.type,layout->font.size); if(layout->style==HTMLSTYLE_BOLD) fwrite("<b>",sizeof(char),3,m_pStream); } fwrite(string,sizeof(char),strlen(string),m_pStream); if(layout) { if(layout->style==HTMLSTYLE_BOLD) fwrite("</b>",sizeof(char),4,m_pStream); if(layout->font.type) fwrite("</font>",sizeof(char),7,m_pStream); } } /* FormattedText() Formatta il testo trascrivendolo nel file. Non accetta il layout. */ void CHtml::FormattedText(const char* fmt,...) { char* arg = (char*)&fmt + sizeof(fmt); vfprintf(m_pStream,fmt,arg); } /* Line() Trascrive la linea di testo nel file. Accetta il layout. */ void CHtml::Line(const char* string,HTMLLAYOUT* layout/*=NULL*/) { CHtml::Text(string,layout); CHtml::NewLine(); } /* FormattedLine() Formatta la linea di testo trascrivendola nel file. Non accetta il layout. */ void CHtml::FormattedLine(const char* fmt,...) { char* arg = (char*)&fmt + sizeof(fmt); vfprintf(m_pStream,fmt,arg); CHtml::NewLine(); } /* TableOpen() Apre la tabella. */ void CHtml::TableOpen(HTMLTABLELAYOUT* tablelayout/*=NULL*/) { fwrite("\r\n<table",sizeof(char),8,m_pStream); if(tablelayout) { char width[16]; if(tablelayout->width > 100) sprintf(width,"%ld",tablelayout->width); else sprintf(width,"\"%d%%\"",tablelayout->width); fprintf( m_pStream, " border=%d cellpadding=%d cellspacing=%d width=%s", tablelayout->border, tablelayout->cellpadding, tablelayout->cellspacing, width ); if(tablelayout->classname[0]!='\0' && strcmp(tablelayout->classname,"")!=0) fprintf( m_pStream, " class=\"%s\"", tablelayout->classname ); } fwrite(">\r\n",sizeof(char),3,m_pStream); if(tablelayout) { if(tablelayout->title) { char font_begin[32] = {""}; char font_end[8] = {""}; if(tablelayout->htmllayout.font.type) { _snprintf(font_begin,sizeof(font_begin)-1,"<font face=\"%s\" size=\"%d\">",tablelayout->htmllayout.font.type,tablelayout->htmllayout.font.size); strcpy(font_end,"</font>"); } fprintf( m_pStream, "\r\n<caption align=center><b>%s%s%s</b></caption>\r\n", font_begin, tablelayout->title, font_end ); } } } /* TablePutCol() Inserisce la colonna nella tabella. */ void CHtml::TablePutCol(const char* text,HTMLLAYOUT* layout/*=NULL*/,const char* extra/*=NULL*/) { fwrite("<td",sizeof(char),3,m_pStream); char* align = NULL; if(layout) switch(layout->align) { case HTMLALIGN_LEFT: align = "left"; break; case HTMLALIGN_RIGHT: align = "right"; break; case HTMLALIGN_CENTER: align = "center"; break; case HTMLALIGN_NONE: default: align = NULL; break; } if(align) fprintf(m_pStream," align=%s",align); if(layout) if(layout->width > 0) fprintf(m_pStream," width=%d%%",layout->width); fwrite(">",sizeof(char),1,m_pStream); if(layout) if(layout->font.type) { fprintf(m_pStream,"<font face=\"%s\"",layout->font.type); fprintf(m_pStream," size=\"%d\"",layout->font.size); if(layout->font.color) fprintf(m_pStream," color=\"%s\"",layout->font.color); fwrite(">",sizeof(char),1,m_pStream); } if(layout) if(layout->style==HTMLSTYLE_BOLD) fwrite("<b>",sizeof(char),3,m_pStream); fwrite(text,sizeof(char),strlen(text),m_pStream); if(extra) fwrite(extra,sizeof(char),strlen(extra),m_pStream); if(layout) if(layout->style==HTMLSTYLE_BOLD) fwrite("</b>",sizeof(char),4,m_pStream); if(layout) if(layout->font.type) fwrite("</font>",sizeof(char),7,m_pStream); fwrite("</td>\r\n",sizeof(char),7,m_pStream); } void CHtml::TablePutCol(const char* text,CSSLAYOUT* layout/*=NULL*/,const char* extra/*=NULL*/) { fwrite("<td",sizeof(char),3,m_pStream); char* align = NULL; if(layout) switch(layout->align) { case HTMLALIGN_LEFT: align = "left"; break; case HTMLALIGN_RIGHT: align = "right"; break; case HTMLALIGN_CENTER: align = "center"; break; case HTMLALIGN_NONE: default: align = NULL; break; } if(align) fprintf(m_pStream," align=%s",align); if(layout) if(layout->width > 0) fprintf(m_pStream," width=%d%%",layout->width); fwrite(">",sizeof(char),1,m_pStream); if(layout) if(layout->tagname) { fprintf(m_pStream,"<%s",layout->tagname); if(strcmp(layout->classname,"")!=0) fprintf(m_pStream," class=\"%s\"",layout->classname); fwrite(">",sizeof(char),1,m_pStream); } // if(layout) // if(layout->style==HTMLSTYLE_BOLD) // fwrite("<b>",sizeof(char),3,m_pStream); fwrite(text,sizeof(char),strlen(text),m_pStream); if(extra) fwrite(extra,sizeof(char),strlen(extra),m_pStream); // if(layout) // if(layout->style==HTMLSTYLE_BOLD) // fwrite("</b>",sizeof(char),4,m_pStream); if(layout) if(layout->tagname) fprintf(m_pStream,"</%s>",layout->tagname); fwrite("</td>\r\n",sizeof(char),7,m_pStream); } /* TablePutColText() Trascrive il testo nella colonna. */ void CHtml::TablePutColText(const char* text,HTMLLAYOUT* layout/*=NULL*/) { if(layout) if(layout->font.type) fprintf(m_pStream,"<font face=\"%s\" size=\"%d\">",layout->font.type,layout->font.size); if(layout) if(layout->style==HTMLSTYLE_BOLD) fwrite("<b>",sizeof(char),3,m_pStream); fwrite(text,sizeof(char),strlen(text),m_pStream); if(layout) if(layout->style==HTMLSTYLE_BOLD) fwrite("</b>",sizeof(char),4,m_pStream); if(layout) if(layout->font.type) fwrite("</font>",sizeof(char),7,m_pStream); }
[ [ [ 1, 429 ] ] ]
3518c252e822dbe80a8065aee297452060b1dc95
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Application/SysCAD/QRYDLG.CPP
291fa60017c29fa60790f613b4c94fda2e93d906
[]
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
9,178
cpp
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== #include "stdafx.h" #include "sc_defs.h" #include "resource.h" #include "tagvdoc.h" #include "qrydlg.h" //#include "scd_wm.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- CQueryDlg::CQueryDlg(CWnd* pParent, pCTagVwDoc Doc, CTimeValue StartTime, CTimeValue EndTime) : CDialog(CQueryDlg::IDD, pParent) { pTTC = NULL; //{{AFX_DATA_INIT(CQueryDlg) m_Filename = _T(""); m_StartTime = _T(""); m_EndTime = _T(""); m_NoPts = 61; m_Tag = _T(""); m_Option = -1; m_Headings = FALSE; m_TimeOptFull = FALSE; m_TimeOptUnits = 0; //}}AFX_DATA_INIT pDoc = Doc; m_StartTime = StartTime.Format(TD_TimeDate); m_EndTime = EndTime.Format(TD_TimeDate); Create(CQueryDlg::IDD, pParent); } //-------------------------------------------------------------------------- CQueryDlg::~CQueryDlg() { delete pTTC; } //--------------------------------------------------------------------------- void CQueryDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CQueryDlg) DDX_Control(pDX, IDC_TAGLIST, m_TagList); DDX_Text(pDX, IDC_FILENAME, m_Filename); DDX_Text(pDX, IDC_STARTTIME, m_StartTime); DDX_Text(pDX, IDC_ENDTIME, m_EndTime); DDX_Text(pDX, IDC_NOPTS, m_NoPts); DDX_Text(pDX, IDC_TAG, m_Tag); DDX_Radio(pDX, IDC_OPTION, m_Option); DDX_Check(pDX, IDC_HEADINGS, m_Headings); DDX_Check(pDX, IDC_QTIMEOPTFULL, m_TimeOptFull); DDX_Radio(pDX, IDC_QTIME, m_TimeOptUnits); //}}AFX_DATA_MAP GetDlgItem(IDC_TAG)->EnableWindow(m_TagList.GetCount()>0); GetDlgItem(IDC_NOPTS)->EnableWindow(m_Option==1); } //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(CQueryDlg, CDialog) //{{AFX_MSG_MAP(CQueryDlg) ON_BN_CLICKED(IDC_ADDTAG, OnAddtag) ON_BN_CLICKED(IDC_REMOVETAG, OnRemovetag) ON_LBN_SELCHANGE(IDC_TAGLIST, OnSelchangeTaglist) ON_EN_CHANGE(IDC_TAG, OnChangeTag) ON_BN_CLICKED(IDC_OPTION, OnOption) ON_BN_CLICKED(IDC_OPTION1, OnOption1) //}}AFX_MSG_MAP ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTipNotify) END_MESSAGE_MAP() //--------------------------------------------------------------------------- BOOL CQueryDlg::OnInitDialog() { pTTC = new CCustomToolTipCtrl(this); CProfINIFile PF(PrjIniFile()); Strng s(PrjFilesAlias()); s += "query.csv"; s = PF.RdStr("Trends", "QryFilename", s()); s.FnExpand(); m_Filename = s(); //m_DBFilename = PF.RdStr("Trends", "QryDBFilename", "c:\\query.mdb")(); //m_DBTableName = PF.RdStr("Trends", "QryDBTablename", "HistData")(); m_Option = PF.RdInt("Trends", "QryOption", 0); m_TimeOptUnits = PF.RdInt("Trends", "QryTimeOptUnits", 1); m_TimeOptFull = (PF.RdInt("Trends", "QryTimeOptFull", 1)!=0); m_Headings = (PF.RdInt("Trends", "QryHeadings", 1)!=0); m_NoPts = PF.RdLong("Trends", "QryNoPoints", 61); CDialog::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } //--------------------------------------------------------------------------- BOOL CQueryDlg::PreTranslateMessage(MSG* pMsg) { if (pTTC && HelpMngr.ShowToolTips()) pTTC->RelayEvent(pMsg); return CDialog::PreTranslateMessage(pMsg); } //--------------------------------------------------------------------------- BOOL CQueryDlg::OnToolTipNotify(UINT id, NMHDR* pNMHDR, LRESULT* pResult) { if (pTTC && HelpMngr.ShowToolTips()) return pTTC->OnToolTipNotify(pNMHDR, CQueryDlg::IDD); return FALSE; } //--------------------------------------------------------------------------- void CQueryDlg::AddTag(char* Tag) { m_TagList.AddString(Tag); } //--------------------------------------------------------------------------- void CQueryDlg::PostNcDestroy() { CDialog::PostNcDestroy(); delete this; } //--------------------------------------------------------------------------- void CQueryDlg::SaveOptions() { CProfINIFile PF(PrjIniFile()); Strng s((const char*)m_Filename); s.FnContract(); PF.WrStr("Trends", "QryFilename", s()); //PF.WrStr("Trends", "QryDBFilename", (char*)(const char*)m_DBFilename); //PF.WrStr("Trends", "QryDBTablename", (char*)(const char*)m_DBTableName); PF.WrInt("Trends", "QryOption", m_Option); PF.WrInt("Trends", "QryTimeOptUnits", m_TimeOptUnits); PF.WrInt("Trends", "QryTimeOptFull", m_TimeOptFull); PF.WrInt("Trends", "QryHeadings", m_Headings); PF.WrLong("Trends", "QryNoPoints", m_NoPts); } //--------------------------------------------------------------------------- void CQueryDlg::OnOK() { UpdateData(True); SaveOptions(); CTimeValue StartTime; CTimeValue LastTime; flag Ok = StartTime.Parse(m_StartTime); Ok = LastTime.Parse(m_EndTime); short TagCnt = m_TagList.GetCount(); CXM_Route HRoute; flag GotHistorian = pDoc->XFindObject(pExecName_Historian, HRoute); if (GotHistorian && TagCnt>0) { //if querytype=mdb then ... else ... //TODO Implement option to retrieve historian trend data to MDB if (pDoc->StartFile((char*)(const char*)m_Filename)) { //HRoute.dbgDump("Historian Route "); CXM_QueryHistoryOther *xb=new CXM_QueryHistoryOther (StartTime.Seconds, LastTime.Seconds, (long)pDoc, (byte)m_Option, (byte)m_TimeOptUnits, m_TimeOptFull, m_Headings, m_NoPts, dNAN, 1/*File*/, NULL, NULL, 0, 0.0); CXMsgLst XM; for (int i=0; i<TagCnt; i++) { CString Txt; m_TagList.GetText(i, Txt); if (!xb->xAddTag((char*)(const char*)Txt)) {//??? XM.PackMsg(xb); XM.PackMsg(new CXM_Route(HRoute)); xb=new CXM_QueryHistoryOther (StartTime.Seconds, LastTime.Seconds, (long)pDoc, (byte)m_Option, (byte)m_TimeOptUnits, m_TimeOptFull, m_Headings, m_NoPts, dNAN, 1/*File*/, NULL, NULL, 0, 0.0); i--; } } if (!xb->Empty()) { XM.PackMsg(xb); XM.PackMsg(new CXM_Route(HRoute)); } else delete xb; pDoc->XSendMessage(XM, HRoute); } else LogError("Trend", 0, "Cannot open file '%s' to retrieve query.", (char*)(const char*)m_Filename); } else { if (!GotHistorian) LogError("Trend", 0, "No historian configured, cannot retrieve query to '%s'", (char*)(const char*)m_Filename); else LogError("Trend", 0, "No tags specified, cannot retrieve query to '%s'", (char*)(const char*)m_Filename); } DestroyWindow(); } //--------------------------------------------------------------------------- void CQueryDlg::OnCancel() { UpdateData(True); SaveOptions(); DestroyWindow(); } //--------------------------------------------------------------------------- void CQueryDlg::OnAddtag() { UpdateData(True); int i = m_TagList.GetCurSel(); if (i>=0) { m_TagList.InsertString(i, "NewTag"); m_TagList.SetCurSel(i); } else { m_TagList.AddString("NewTag"); m_TagList.SetCurSel(m_TagList.GetCount()-1); } UpdateData(False); OnSelchangeTaglist(); } //--------------------------------------------------------------------------- void CQueryDlg::OnRemovetag() { UpdateData(True); int i = m_TagList.GetCurSel(); if (i>=0) m_TagList.DeleteString(i); int Cnt = m_TagList.GetCount(); if (Cnt>0) { if (i<Cnt) m_TagList.SetCurSel(i); else m_TagList.SetCurSel(Cnt-1); } OnSelchangeTaglist(); UpdateData(False); } //--------------------------------------------------------------------------- void CQueryDlg::OnSelchangeTaglist() { UpdateData(True); int i = m_TagList.GetCurSel(); if (i>=0) { CString Txt; m_TagList.GetText(i, Txt); m_Tag = Txt; GotoDlgCtrl(GetDlgItem(IDC_TAG)); } UpdateData(False); } //--------------------------------------------------------------------------- void CQueryDlg::OnChangeTag() { UpdateData(True); int i = m_TagList.GetCurSel(); if (i>=0) { m_TagList.DeleteString(i); m_TagList.InsertString(i, m_Tag); m_TagList.SetCurSel(i); } UpdateData(False); } //--------------------------------------------------------------------------- void CQueryDlg::OnOption() { UpdateData(True); } //--------------------------------------------------------------------------- void CQueryDlg::OnOption1() { UpdateData(True); } //========================================================================= //---------------------------------------------------------------------------
[ [ [ 1, 19 ], [ 22, 36 ], [ 39, 163 ], [ 168, 179 ], [ 181, 189 ], [ 191, 313 ] ], [ [ 20, 21 ], [ 37, 38 ], [ 164, 167 ], [ 180, 180 ], [ 190, 190 ] ] ]
067f4b5995dff73205706debb4e78bec4251547f
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/WayFinder/symbian-r6/GuidePreviewPopUpContent.cpp
2339568c2aebddc43f9ce16eae3939595f75f978
[ "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
19,944
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined NAV2_CLIENT_SERIES60_V5 || defined NAV2_CLIENT_SERIES60_V32 // INCLUDE FILES #include <coemain.h> #include <coecontrolarray.h> #include <aknutils.h> #include <eiklabel.h> #include <aknsutils.h> #include <gdi.h> #include <eikapp.h> #include <gulicon.h> #include "RsgInclude.h" #include "WFLayoutUtils.h" #include "GuidePreviewPopUpContent.h" #define TITLE_LABEL_HEIGHT 0.8 _LIT(KDefaultText, ""); enum TControls { ECurrStreetTitleId, ECurrStreetLabelId, ENextStreetTitleId, ENextStreetLabelId, EDistLeftTitleId, EDistLeftLabelId, ETimeLeftTitleId, ETimeLeftLabelId, EArrTimeTitleId, EArrTimeLabelId }; CGuidePreviewPopUpContent* CGuidePreviewPopUpContent::NewL() { CGuidePreviewPopUpContent* self = CGuidePreviewPopUpContent::NewLC(); CleanupStack::Pop(self); return self; } CGuidePreviewPopUpContent* CGuidePreviewPopUpContent::NewLC() { CGuidePreviewPopUpContent* self = new (ELeave) CGuidePreviewPopUpContent(); CleanupStack::PushL(self); self->ConstructL(); return self; } void CGuidePreviewPopUpContent::ConstructL() { /* Do not call CreateWindowL() as the parent CAknPreviewPopUpController has a window. But when ConstructL() is called this has not yet been created (as the CAknPreviewPopUpController has not been created) so defer all construction which requires a window to InitialiseL() which is called after CAknPreviewPopUpController has been constructed. */ } void CGuidePreviewPopUpContent::InitialiseL(const TRect& aRect) { // Do not call CreateWindowL() as parent CAknPreviewPopUpController owns window InitComponentArrayL(); MAknsSkinInstance* skin = AknsUtils::SkinInstance(); AknsUtils::GetCachedColor(skin, iSkinTextColor, KAknsIIDQsnTextColors, EAknsCIQsnTextColorsCG55); HBufC* tmp = NULL; // Create all the labels. tmp = CCoeEnv::Static()->AllocReadResourceLC(R_WF_YOU_ARE_ON); iCurrStreetTitle = new (ELeave) CEikLabel(); iCurrStreetTitle->SetContainerWindowL(*this); Components().AppendLC(iCurrStreetTitle, ECurrStreetTitleId); iCurrStreetTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iCurrStreetTitle->SetTextL(*tmp); CleanupStack::Pop(iCurrStreetTitle); CleanupStack::PopAndDestroy(tmp); iCurrStreetLabel = new (ELeave) CEikLabel(); iCurrStreetLabel->SetContainerWindowL(*this); Components().AppendLC(iCurrStreetLabel, ECurrStreetLabelId); iCurrStreetLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iCurrStreetLabel->SetTextL(KDefaultText); CleanupStack::Pop(iCurrStreetLabel); tmp = CCoeEnv::Static()->AllocReadResourceLC(R_WF_NEXT_STREET); iNextStreetTitle = new (ELeave) CEikLabel(); iNextStreetTitle->SetContainerWindowL(*this); Components().AppendLC(iNextStreetTitle, ENextStreetTitleId); iNextStreetTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iNextStreetTitle->SetTextL(*tmp); CleanupStack::Pop(iNextStreetTitle); CleanupStack::PopAndDestroy(tmp); iNextStreetLabel = new (ELeave) CEikLabel(); iNextStreetLabel->SetContainerWindowL(*this); Components().AppendLC(iNextStreetLabel, ENextStreetLabelId); iNextStreetLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iNextStreetLabel->SetTextL(KDefaultText); CleanupStack::Pop(iNextStreetLabel); tmp = CCoeEnv::Static()->AllocReadResourceLC(R_WF_DISTANCE_LEFT); iDistLeftTitle = new (ELeave) CEikLabel(); iDistLeftTitle->SetContainerWindowL(*this); Components().AppendLC(iDistLeftTitle, EDistLeftTitleId); iDistLeftTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iDistLeftTitle->SetTextL(*tmp); CleanupStack::Pop(iDistLeftTitle); CleanupStack::PopAndDestroy(tmp); iDistLeftLabel = new (ELeave) CEikLabel(); iDistLeftLabel->SetContainerWindowL(*this); Components().AppendLC(iDistLeftLabel, EDistLeftLabelId); iDistLeftLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iDistLeftLabel->SetTextL(KDefaultText); CleanupStack::Pop(iDistLeftLabel); tmp = CCoeEnv::Static()->AllocReadResourceLC(R_WF_TIME_LEFT); iTimeLeftTitle = new (ELeave) CEikLabel(); iTimeLeftTitle->SetContainerWindowL(*this); Components().AppendLC(iTimeLeftTitle, ETimeLeftTitleId); iTimeLeftTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iTimeLeftTitle->SetTextL(*tmp); CleanupStack::Pop(iTimeLeftTitle); CleanupStack::PopAndDestroy(tmp); iTimeLeftLabel = new (ELeave) CEikLabel(); iTimeLeftLabel->SetContainerWindowL(*this); Components().AppendLC(iTimeLeftLabel, ETimeLeftLabelId); iTimeLeftLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iTimeLeftLabel->SetTextL(KDefaultText); CleanupStack::Pop(iTimeLeftLabel); tmp = CCoeEnv::Static()->AllocReadResourceLC(R_WF_WAYFINDER_ARRIVAL_TIME); iArrTimeTitle = new (ELeave) CEikLabel(); iArrTimeTitle->SetContainerWindowL(*this); Components().AppendLC(iArrTimeTitle, EArrTimeTitleId); iArrTimeTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iArrTimeTitle->SetTextL(*tmp); CleanupStack::Pop(iArrTimeTitle); CleanupStack::PopAndDestroy(tmp); iArrTimeLabel = new (ELeave) CEikLabel(); iArrTimeLabel->SetContainerWindowL(*this); Components().AppendLC(iArrTimeLabel, EArrTimeLabelId); iArrTimeLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iArrTimeLabel->SetTextL(KDefaultText); CleanupStack::Pop(iArrTimeLabel); // Create a font for the title labels based on the standard label // font but a little bit smaller. UpdateLabelsFont(); // Set the standard rect. iComponentRect = aRect; // Set the windows size SetRect(aRect); // Activate the window, which makes it ready to be drawn ActivateL(); } CGuidePreviewPopUpContent::CGuidePreviewPopUpContent() : iIsNightMode(EFalse) { } CGuidePreviewPopUpContent::~CGuidePreviewPopUpContent() { } void CGuidePreviewPopUpContent::SizeChanged() { TRect rect = Rect(); iComponentRect = rect; iComponentRect.Shrink(iPadding, iPadding); // Update the font for the title labels based on the standard label // font but a bit smaller. (We need to do this before using fonts below). UpdateLabelsFont(); // Get some size info on the different fonts. TInt titleFontHeight = iCurrStreetTitle->Font()->HeightInPixels(); TInt titleFontDescent = iCurrStreetTitle->Font()->DescentInPixels(); // The height of one title label. TInt titleLabelHeight = titleFontHeight + titleFontDescent; TInt textFontHeight = iCurrStreetLabel->Font()->HeightInPixels(); TInt textFontDescent = iCurrStreetLabel->Font()->DescentInPixels(); // The height of one text label. TInt textLabelHeight = textFontHeight + textFontDescent; if (WFLayoutUtils::LandscapeMode()) { // Phone is in landscape layout it accordingly. // Get the max width needed by any of the title labels.. TInt maxWidth= Max(iCurrStreetTitle->MinimumSize().iWidth, iNextStreetTitle->MinimumSize().iWidth); maxWidth = Max(maxWidth, iDistLeftTitle->MinimumSize().iWidth); maxWidth = Max(maxWidth, iTimeLeftTitle->MinimumSize().iWidth); maxWidth = Max(maxWidth, iArrTimeTitle->MinimumSize().iWidth); // The rect available to title labels. TRect titleLabelRect = TRect(iComponentRect.iTl, TSize(maxWidth + iPadding * 3, titleLabelHeight)); // The rect available to text labels. TRect textLabelRect = TRect(TPoint(titleLabelRect.iBr.iX, iComponentRect.iTl.iY), TSize(iComponentRect.Width() - titleLabelRect.Width(), textLabelHeight)); // The difference in height between the two fonts. TInt fontHeightDiff = textFontHeight - titleFontHeight; // Set the rects for the labels in landscape mode. titleLabelRect.Move(0, fontHeightDiff); iCurrStreetTitle->SetRect(titleLabelRect); iCurrStreetLabel->SetRect(textLabelRect); titleLabelRect.Move(0, textLabelHeight); textLabelRect.Move(0, textLabelHeight); iNextStreetTitle->SetRect(titleLabelRect); iNextStreetLabel->SetRect(textLabelRect); titleLabelRect.Move(0, textLabelHeight); textLabelRect.Move(0, textLabelHeight); iDistLeftTitle->SetRect(titleLabelRect); iDistLeftLabel->SetRect(textLabelRect); titleLabelRect.Move(0, textLabelHeight); textLabelRect.Move(0, textLabelHeight); iTimeLeftTitle->SetRect(titleLabelRect); iTimeLeftLabel->SetRect(textLabelRect); titleLabelRect.Move(0, textLabelHeight); textLabelRect.Move(0, textLabelHeight); iArrTimeTitle->SetRect(titleLabelRect); iArrTimeLabel->SetRect(textLabelRect); } else { // Phone is in portrait use that layout. // The rect available to title labels. TRect titleLabelRect = TRect(iComponentRect.iTl, TSize(iComponentRect.Width(), titleLabelHeight)); // The rect available to text labels. TRect textLabelRect = TRect(iComponentRect.iTl, TSize(iComponentRect.Width(), textLabelHeight)); // Set the rects for the labels in portrait mode. iCurrStreetTitle->SetRect(titleLabelRect); textLabelRect.Move(0, titleLabelHeight); iCurrStreetLabel->SetRect(textLabelRect); titleLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iNextStreetTitle->SetRect(titleLabelRect); textLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iNextStreetLabel->SetRect(textLabelRect); titleLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iDistLeftTitle->SetRect(titleLabelRect); textLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iDistLeftLabel->SetRect(textLabelRect); titleLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iTimeLeftTitle->SetRect(titleLabelRect); textLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iTimeLeftLabel->SetRect(textLabelRect); titleLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iArrTimeTitle->SetRect(titleLabelRect); textLabelRect.Move(0, titleLabelHeight + textLabelHeight + iPadding); iArrTimeLabel->SetRect(textLabelRect); } // Hide labels if they are outside our allowed rect. UpdateLabelsVisibility(); //Window().Invalidate(); } void CGuidePreviewPopUpContent::UpdateLabelsFont() { // Create a font for the title labels based on the standard label // font but a little bit smaller. CWsScreenDevice* screenDev = CEikonEnv::Static()->ScreenDevice(); const CFont* tmpFont = iCurrStreetLabel->Font(); TFontSpec fontSpec = tmpFont->FontSpecInTwips(); fontSpec.iHeight = TInt(fontSpec.iHeight * TITLE_LABEL_HEIGHT); fontSpec.iFontStyle.SetStrokeWeight(EStrokeWeightNormal); CFont* font; screenDev->GetNearestFontToDesignHeightInTwips(font, fontSpec); // Set the title labels fonts, we need to re-set them in SizeChanged // since a layout switch might cause us having to use a different font. iCurrStreetTitle->SetFont(font); iCurrStreetTitle->SetAlignment(EHLeftVCenter); iNextStreetTitle->SetFont(font); iNextStreetTitle->SetAlignment(EHLeftVCenter); iDistLeftTitle->SetFont(font); iDistLeftTitle->SetAlignment(EHLeftVCenter); iTimeLeftTitle->SetFont(font); iTimeLeftTitle->SetAlignment(EHLeftVCenter); iArrTimeTitle->SetFont(font); iArrTimeTitle->SetAlignment(EHLeftVCenter); // Release the font. screenDev->ReleaseFont(font); } void CGuidePreviewPopUpContent::UpdateLabelsVisibility() { // Hide labels if they are outside our allowed rect. TInt xPos = iComponentRect.iBr.iX / 2; if (!iComponentRect.Contains(TPoint(xPos, iDistLeftLabel->Rect().iBr.iY)) || !iComponentRect.Contains(TPoint(xPos, iDistLeftTitle->Rect().iBr.iY))) { Components().RemoveById(EDistLeftTitleId); Components().RemoveById(EDistLeftLabelId); } else { CCoeControlArray::TCursor it = Components().Find(EDistLeftTitleId); if (!it.IsValid()) { Components().AppendLC(iDistLeftTitle, EDistLeftTitleId); CleanupStack::Pop(iDistLeftTitle); } it = Components().Find(EDistLeftLabelId); if (!it.IsValid()) { Components().AppendLC(iDistLeftLabel, EDistLeftLabelId); CleanupStack::Pop(iDistLeftLabel); } } if (!iComponentRect.Contains(TPoint(xPos, iTimeLeftLabel->Rect().iBr.iY)) || !iComponentRect.Contains(TPoint(xPos, iTimeLeftTitle->Rect().iBr.iY))) { Components().RemoveById(ETimeLeftTitleId); Components().RemoveById(ETimeLeftLabelId); } else { CCoeControlArray::TCursor it = Components().Find(ETimeLeftTitleId); if (!it.IsValid()) { Components().AppendLC(iTimeLeftTitle, ETimeLeftTitleId); CleanupStack::Pop(iTimeLeftTitle); } it = Components().Find(ETimeLeftLabelId); if (!it.IsValid()) { Components().AppendLC(iTimeLeftLabel, ETimeLeftLabelId); CleanupStack::Pop(iTimeLeftLabel); } } if (!iComponentRect.Contains(TPoint(xPos, iArrTimeLabel->Rect().iBr.iY)) || !iComponentRect.Contains(TPoint(xPos, iArrTimeTitle->Rect().iBr.iY))) { Components().RemoveById(EArrTimeTitleId); Components().RemoveById(EArrTimeLabelId); } else { CCoeControlArray::TCursor it = Components().Find(EArrTimeTitleId); if (!it.IsValid()) { Components().AppendLC(iArrTimeTitle, EArrTimeTitleId); CleanupStack::Pop(iArrTimeTitle); } it = Components().Find(EArrTimeLabelId); if (!it.IsValid()) { Components().AppendLC(iArrTimeLabel, EArrTimeLabelId); CleanupStack::Pop(iArrTimeLabel); } } } TSize CGuidePreviewPopUpContent::MinimumSize() { TRect rect(Rect()); TSize size(rect.Width(), rect.Height()); return size; } void CGuidePreviewPopUpContent::Draw(const TRect& /*aRect*/) const { // Get the standard graphics context CWindowGc& gc = SystemGc(); TRect rect(Rect()); gc.SetClippingRect(rect); if (iIsNightMode) { TRect rect(Rect()); gc.SetPenColor(iNightBackColor); gc.SetPenStyle(CGraphicsContext::ESolidPen); gc.SetBrushColor(iNightBackColor); gc.SetBrushStyle(CGraphicsContext::ESolidBrush); gc.DrawRect(rect); } } void CGuidePreviewPopUpContent::SetSizeAndLayout(TRect aRect, TInt aPadding) { iComponentRect = aRect; iComponentRect.Shrink(aPadding, aPadding); iPadding = aPadding; SetRect(aRect); } void CGuidePreviewPopUpContent::SetStreetsL(const TDesC& aCurrName, const TDesC& aNextName) { if (iCurrStreetLabel && iNextStreetLabel) { iCurrStreetLabel->SetTextL(aCurrName); iCurrStreetLabel->CropText(); Window().Invalidate(iCurrStreetLabel->Rect()); //iCurrStreetLabel->DrawDeferred(); iNextStreetLabel->SetTextL(aNextName); iNextStreetLabel->CropText(); Window().Invalidate(iNextStreetLabel->Rect()); //iCurrStreetLabel->DrawDeferred(); } } void CGuidePreviewPopUpContent::SetDistanceToGoalL(const TDesC& aDistance) { if (iDistLeftLabel) { iDistLeftLabel->SetTextL(aDistance); Window().Invalidate(iDistLeftLabel->Rect()); } } void CGuidePreviewPopUpContent::SetEtgL(const TDesC& aTimeLeft) { if (iTimeLeftLabel) { iTimeLeftLabel->SetTextL(aTimeLeft); Window().Invalidate(iTimeLeftLabel->Rect()); } } void CGuidePreviewPopUpContent::SetEtaL(const TDesC& aArrivalTime) { if (iArrTimeLabel) { iArrTimeLabel->SetTextL(aArrivalTime); Window().Invalidate(iArrTimeLabel->Rect()); } } void CGuidePreviewPopUpContent::SetNightModeL(TBool aNightMode, TRgb aFgColor, TRgb aBgColor) { iIsNightMode = aNightMode; iNightTextColor = aFgColor; iNightBackColor = aBgColor; if (aNightMode) { // Night mode on, set label colors to nightmode color. iCurrStreetTitle->OverrideColorL(EColorLabelText, iNightTextColor); iCurrStreetLabel->OverrideColorL(EColorLabelText, iNightTextColor); iNextStreetTitle->OverrideColorL(EColorLabelText, iNightTextColor); iNextStreetLabel->OverrideColorL(EColorLabelText, iNightTextColor); iDistLeftTitle->OverrideColorL(EColorLabelText, iNightTextColor); iDistLeftLabel->OverrideColorL(EColorLabelText, iNightTextColor); iTimeLeftTitle->OverrideColorL(EColorLabelText, iNightTextColor); iTimeLeftLabel->OverrideColorL(EColorLabelText, iNightTextColor); iArrTimeTitle->OverrideColorL(EColorLabelText, iNightTextColor); iArrTimeLabel->OverrideColorL(EColorLabelText, iNightTextColor); } else { // Night mode off, set label colors to standard skin color. iCurrStreetTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iCurrStreetLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iNextStreetTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iNextStreetLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iDistLeftTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iDistLeftLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iTimeLeftTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iTimeLeftLabel->OverrideColorL(EColorLabelText, iSkinTextColor); iArrTimeTitle->OverrideColorL(EColorLabelText, iSkinTextColor); iArrTimeLabel->OverrideColorL(EColorLabelText, iSkinTextColor); } Window().Invalidate(); } #endif //NAV2_CLIENT_SERIES60_V5
[ [ [ 1, 494 ] ] ]
2586067b84941d4395be0f05ad13c0ec0af449af
65f587a75567b51375bde5793b4ec44e4b79bc7d
/sklepSeqPlaylist.h
d7a9b4191bac05f899148ed5f36e4161f86300fa
[]
no_license
discordance/sklepseq
ce4082074afbdb7e4f7185f042ce9e34d42087ef
8d4fa5a2710ba947e51f5572238eececba4fef74
refs/heads/master
2021-01-13T00:15:23.218795
2008-07-20T20:48:44
2008-07-20T20:48:44
49,079,555
0
0
null
null
null
null
UTF-8
C++
false
false
652
h
#ifndef __JUCER_HEADER_SKLEPSEQPLAYLIST_SKLEPSEQPLAYLIST_C0CEEDD__ #define __JUCER_HEADER_SKLEPSEQPLAYLIST_SKLEPSEQPLAYLIST_C0CEEDD__ #include <juce.h> #include "sklepSeqPlaylistView.h" class sklepSeqTransportComponent; class sklepSeqPlaylist : public DocumentWindow { public: sklepSeqPlaylist (sklepSeqTransportComponent *_p); ~sklepSeqPlaylist(); void closeButtonPressed(); juce_UseDebuggingNewOperator private: sklepSeqPlaylistView* playlistView; sklepSeqTransportComponent *parent; sklepSeqPlaylist (const sklepSeqPlaylist&); const sklepSeqPlaylist& operator= (const sklepSeqPlaylist&); }; #endif
[ "kubiak.roman@0c9c7eae-764f-0410-aff0-6774c5161e44" ]
[ [ [ 1, 25 ] ] ]
0c06daecedb98f4a2ec8a4a984811b71c5a7cb51
1775576281b8c24b5ce36b8685bc2c6919b35770
/tags/release_1.0/bsp.cpp
620e69a9c497542c0f27cf1bb9126813a588d531
[]
no_license
BackupTheBerlios/gtkslade-svn
933a1268545eaa62087f387c057548e03497b412
03890e3ba1735efbcccaf7ea7609d393670699c1
refs/heads/master
2016-09-06T18:35:25.336234
2006-01-01T11:05:50
2006-01-01T11:05:50
40,615,146
0
0
null
null
null
null
UTF-8
C++
false
false
12,137
cpp
#include "main.h" #include "struct_3d.h" #include "camera.h" #include "map.h" #include "render.h" #include "bsp.h" #include "mathstuff.h" gl_vertex_t *gl_verts = NULL; gl_seg_t *gl_segs = NULL; gl_ssect_t *gl_ssects = NULL; gl_node_t *gl_nodes = NULL; DWORD n_gl_verts = 0; DWORD n_gl_segs = 0; DWORD n_gl_ssects = 0; int n_gl_nodes = 0; BYTE vis_buffer[3600]; extern Map map; extern Camera camera; extern sectinfo_t *sector_info; extern vector<line3d_t> lines_3d; extern vector<ssect3d_t> ssects_3d; // build_gl_nodes: Builds and loads in GL node data for the current map // ----------------------------------------------------------------- >> void build_gl_nodes() { FILE *fp; int current_lump = 0; int unit_size = 0; int unit_count = 0; // Save map and build nodes Wad tempwad; tempwad.path = "sladetemp.wad"; map.add_to_wad(&tempwad); tempwad.save(false); #ifdef WIN32 system("glbsp -v3 sladetemp.wad"); #else system("./glbsp -v3 sladetemp.wad"); #endif remove("sladetemp.wad.bak"); // Open GWA file Wad wad; if (!wad.open("sladetemp.gwa")) printf("Failed to build GL nodes!\n"); // << ---------------------- >> // << -- Load GL vertices -- >> // << ---------------------- >> current_lump = wad.get_lump_index("GL_VERT"); if (current_lump == -1) { print(true, "Gwa has no GL_VERT lump.\n"); return; } // Setup sizes unit_size = sizeof(gl_vertex_t); unit_count = (wad.directory[current_lump]->Size() - 4) / unit_size; n_gl_verts = unit_count; // Setup array gl_verts = (gl_vertex_t *)realloc(gl_verts, unit_size * unit_count); // Read vertices from file int temp; fp = fopen(wad.path.c_str(), "rb"); fseek(fp, wad.directory[current_lump]->Offset() + 4, SEEK_SET); for (DWORD v = 0; v < n_gl_verts; v++) { fread(&temp, 4, 1, fp); gl_verts[v].x = (temp >> 16); fread(&temp, 4, 1, fp); gl_verts[v].y = (temp >> 16); } // << ------------------ >> // << -- Load GL segs -- >> // << ------------------ >> current_lump = wad.get_lump_index("GL_SEGS"); if (current_lump == -1) { print(true, "Gwa has no GL_SEGS lump.\n"); return; } // Setup sizes unit_size = sizeof(gl_seg_t); unit_count = (wad.directory[current_lump]->Size() - 4) / unit_size; n_gl_segs = unit_count; // Setup array gl_segs = (gl_seg_t *)realloc(gl_segs, unit_size * unit_count); fseek(fp, wad.directory[current_lump]->Offset() + 4, SEEK_SET); fread(gl_segs, unit_size, unit_count, fp); //for (int o = 0; o < unit_count; o++) //print(true, "%d %d\n", gl_segs[o].vertex1, gl_segs[o].vertex2); // << ---------------------- >> // << -- Load GL ssectors -- >> // << ---------------------- >> current_lump = wad.get_lump_index("GL_SSECT"); if (current_lump == -1) { print(true, "Gwa has no GL_SSECT lump.\n"); return; } // Setup sizes unit_size = sizeof(gl_ssect_t); unit_count = (wad.directory[current_lump]->Size() - 4) / unit_size; n_gl_ssects = unit_count; // Setup array gl_ssects = (gl_ssect_t *)realloc(gl_ssects, unit_size * unit_count); fseek(fp, wad.directory[current_lump]->Offset() + 4, SEEK_SET); fread(gl_ssects, unit_size, unit_count, fp); // << ------------------- >> // << -- Load GL nodes -- >> // << ------------------- >> current_lump = wad.get_lump_index("GL_NODES"); if (current_lump == -1) { print(true, "Gwa has no GL_NODES lump.\n"); return; } // Setup sizes unit_size = sizeof(gl_node_t); unit_count = (wad.directory[current_lump]->Size()) / unit_size; n_gl_nodes = unit_count; // Setup array gl_nodes = (gl_node_t *)realloc(gl_nodes, unit_size * unit_count); fseek(fp, wad.directory[current_lump]->Offset(), SEEK_SET); for (int n = 0; n < n_gl_nodes; n++) { fread(&gl_nodes[n].x, 2, 1, fp); fread(&gl_nodes[n].y, 2, 1, fp); fread(&gl_nodes[n].dx, 2, 1, fp); fread(&gl_nodes[n].dy, 2, 1, fp); fread(gl_nodes[n].right_bbox, 2, 4, fp); fread(gl_nodes[n].left_bbox, 2, 4, fp); fread(&gl_nodes[n].right_child, 2, 1, fp); fread(&gl_nodes[n].left_child, 2, 1, fp); } fclose(fp); } void clear_visibility() { for (int a = 0; a < map.n_lines; a++) lines_3d[a].visible = false; for (int a = 0; a < n_gl_ssects; a++) ssects_3d[a].visible = false; for (int a = 0; a < map.n_sectors; a++) sector_info[a].visible = false; } void set_visbuffer(int blocked) { for (int a = 0; a < 3600; a++) vis_buffer[a] = blocked; } void open_view() { float mmod = (camera.view.z - camera.position.z) * 1000.0f; //int mlook_mod = (int)mmod; int mlook_mod = 0; if (mlook_mod < 0) mlook_mod = -mlook_mod; if (mlook_mod > 3000) mlook_mod = 3000; for (int a = 0; a < 600 + mlook_mod; a++) vis_buffer[a] = 0; for (int a = 3000 - mlook_mod; a < 3600; a++) vis_buffer[a] = 0; //memset(vis_buffer, 0, 3600); } bool seg_is_visible(float x1, float y1, float x2, float y2) { // Check with camera point3_t strafe = camera.position + camera.strafe; if (determine_line_side(camera.position.x, camera.position.y, strafe.x, strafe.y, x1, y1) && determine_line_side(camera.position.x, camera.position.y, strafe.x, strafe.y, x2, y2)) return false; point3_t vec1(x1 - camera.position.x, y1 - camera.position.y, 0.0f); point3_t vec2(x2 - camera.position.x, y2 - camera.position.y, 0.0f); vec1 = vec1.normalize(); vec2 = vec2.normalize(); unsigned short a1 = (short)(get_2d_angle(camera.view - camera.position, vec1) * 10.0f); unsigned short a2 = (short)(get_2d_angle(camera.view - camera.position, vec2) * 10.0f); if (a2 > 3600) a2 = 3600; if (a1 > 3600) a1 = 3600; // A cheap hack for now until I can figure out why sometimes I get 'backwards' segs if (a1 > a2 && a1 - a2 < 450) { unsigned short temp = a1; a1 = a2; a2 = temp; } if (a1 > a2) { for (unsigned short a = a1; a < 3600; a++) { if (vis_buffer[a] == 0) return true; } for (unsigned short a = 0; a < a2; a++) { if (vis_buffer[a] == 0) return true; } } else { for (unsigned short a = a1; a < a2; a++) { if (vis_buffer[a] == 0) return true; } } return false; } void block_seg(float x1, float y1, float x2, float y2) { point3_t vec1(x1 - camera.position.x, y1 - camera.position.y, 0.0f); point3_t vec2(x2 - camera.position.x, y2 - camera.position.y, 0.0f); vec1 = vec1.normalize(); vec2 = vec2.normalize(); unsigned short a1 = (short)(get_2d_angle(camera.view - camera.position, vec1) * 10.0f); unsigned short a2 = (short)(get_2d_angle(camera.view - camera.position, vec2) * 10.0f); if (a2 > 3600) a2 = 3600; if (a1 > 3600) a1 = 3600; // A cheap hack for now until I can figure out why sometimes I get 'backwards' segs if (a1 > a2 && a1 - a2 < 450) { unsigned short temp = a1; a1 = a2; a2 = temp; } //log_message("seg from (%1.2f, %1.2f) to (%1.2f, %1.2f)\n", x1, y1, x2, y2); //log_message("block %d to %d\n", a1, a2); if (a1 > a2) { for (unsigned short a = a1; a < 3600; a++) vis_buffer[a] = 1; for (unsigned short a = 0; a < a2; a++) vis_buffer[a] = 1; } else { for (unsigned short a = a1; a < a2; a++) vis_buffer[a] = 1; } } bool view_buffer_full() { if (memchr(vis_buffer, 0, 3600) == NULL) return true; else return false; } void process_subsector(short subsect) { bool visible = false; int sector = -1; // Cycle through segs int start = gl_ssects[subsect].startseg; int end = start + gl_ssects[subsect].n_segs; for (int s = start; s < end; s++) { // Get x1,y1,x2,y2 of seg float x1 = 0.0f; float y1 = 0.0f; float x2 = 0.0f; float y2 = 0.0f; long v = gl_segs[s].vertex1; if (v & SEG_GLVERTEX) { x1 = gl_verts[v & ~SEG_GLVERTEX].x * SCALE_3D; y1 = gl_verts[v & ~SEG_GLVERTEX].y * SCALE_3D; } else { x1 = map.verts[v]->x * SCALE_3D; y1 = map.verts[v]->y * SCALE_3D; } v = gl_segs[s].vertex2; if (v & SEG_GLVERTEX) { x2 = gl_verts[v & ~SEG_GLVERTEX].x * SCALE_3D; y2 = gl_verts[v & ~SEG_GLVERTEX].y * SCALE_3D; } else { x2 = map.verts[v]->x * SCALE_3D; y2 = map.verts[v]->y * SCALE_3D; } // If seg runs along a line if (gl_segs[s].line != SEG_MINISEG && gl_segs[s].line >= 0 && gl_segs[s].line < lines_3d.size()) { bool side = true; if (gl_segs[s].flags & SEG_FLAGS_SIDE) side = false; // If we're on the right side of that line if (determine_line_side(gl_segs[s].line, camera.position.x / SCALE_3D, camera.position.y / SCALE_3D) == side) { // If the seg isn't blocked if (seg_is_visible(x1, y1, x2, y2)) { // Block the seg if the line is 1-sided if (map.lines[gl_segs[s].line]->side2 == -1 && side) block_seg(x1, y1, x2, y2); else { // Block the seg if it's floor and ceiling are equal or overlapping if (side) sector = map.l_getsector2(gl_segs[s].line); else sector = map.l_getsector1(gl_segs[s].line); if (sector != -1) { if (map.sectors[sector]->f_height >= map.sectors[sector]->c_height) block_seg(x1, y1, x2, y2); } } // The line and subsector are visible int line = gl_segs[s].line; lines_3d[line].visible = true; visible = true; } } } else // Seg doesn't run along a line { // If we're on the right side of the seg if (determine_line_side(x1, y1, x2, y2, camera.position.x, camera.position.y)) { // If the seg isn't blocked, the ssector is visible if (seg_is_visible(x1, y1, x2, y2)) visible = true; } } } if (visible) { if (sector != -1) sector_info[sector].visible = true; ssects_3d[subsect].visible = true; } } // walk_bsp_tree: Walks through the gl nodes (bsp tree) to determine visibility // ------------------------------------------------------------------------- >> void walk_bsp_tree(unsigned short node) { // If we have a subsector if (node & CHILD_IS_SUBSEC) { short subsect = node & ~CHILD_IS_SUBSEC; process_subsector(subsect); return; } if (view_buffer_full()) return; int x1 = gl_nodes[node].x; int y1 = gl_nodes[node].y; int x2 = x1 + gl_nodes[node].dx; int y2 = y1 + gl_nodes[node].dy; rect_t part(x1, y1, x2, y2); if (determine_line_side_f(part, camera.position.x * 100.0f, camera.position.y * 100.0f) > 0) { walk_bsp_tree(gl_nodes[node].right_child); walk_bsp_tree(gl_nodes[node].left_child); } else if (determine_line_side_f(part, camera.position.x * 100.0f, camera.position.y * 100.0f) < 0) { walk_bsp_tree(gl_nodes[node].left_child); walk_bsp_tree(gl_nodes[node].right_child); } else { if (determine_line_side(part, camera.view.x * 100.0f, camera.view.y * 100.0f)) { walk_bsp_tree(gl_nodes[node].right_child); walk_bsp_tree(gl_nodes[node].left_child); } else { walk_bsp_tree(gl_nodes[node].left_child); walk_bsp_tree(gl_nodes[node].right_child); } } } // determine_seg_side: Determines the side of a seg a point is on // ----------------------------------------------------------- >> bool determine_seg_side(DWORD s, float x, float y) { // Get x1,y1,x2,y2 of seg float x1 = 0.0f; float y1 = 0.0f; float x2 = 0.0f; float y2 = 0.0f; long v = gl_segs[s].vertex1; if (v & SEG_GLVERTEX) { x1 = gl_verts[v & ~SEG_GLVERTEX].x * SCALE_3D; y1 = gl_verts[v & ~SEG_GLVERTEX].y * SCALE_3D; } else { x1 = map.verts[v]->x * SCALE_3D; y1 = map.verts[v]->y * SCALE_3D; } v = gl_segs[s].vertex2; if (v & SEG_GLVERTEX) { x2 = gl_verts[v & ~SEG_GLVERTEX].x * SCALE_3D; y2 = gl_verts[v & ~SEG_GLVERTEX].y * SCALE_3D; } else { x2 = map.verts[v]->x * SCALE_3D; y2 = map.verts[v]->y * SCALE_3D; } if (determine_line_side(x1, y1, x2, y2, x, y)) return true; else return false; }
[ "veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be" ]
[ [ [ 1, 503 ] ] ]
baf9fe977035f3474495ca8cd9553c1e837ce219
09756520fa2cb26daf7842a5bad914f9b29d5a74
/sqrattest/Vector.cpp
77720efcda0436f9971c7eb62f4b8c4ebe6d7696
[]
no_license
splhack/sqrat
b60263e27f49ae4c5b591200a33f1a12a72b99a9
982ba7f1649a2aa9d709076d3c21433aed65c658
refs/heads/master
2021-01-18T01:59:39.951195
2011-07-16T16:00:59
2011-07-16T16:00:59
2,058,455
0
0
null
null
null
null
UTF-8
C++
false
false
2,117
cpp
// // Copyright (c) 2009 Brandon Jones // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // #include "Vector.h" #include <math.h> using namespace Sqrat; Vec2::Vec2( void ) : x(0.0f), y(0.0f) {}; Vec2::Vec2( const Vec2 &v ) : x(v.x), y(v.y) {}; Vec2::Vec2( const float vx, const float vy ) : x(vx), y(vy) {}; bool Vec2::operator ==( const Vec2 &v ) const { return (x == v.x && y == v.y); } Vec2 Vec2::operator -( void ) const { return Vec2(-x, -y); } Vec2 Vec2::operator +( const Vec2& v ) const { return Vec2(x + v.x, y + v.y); } Vec2 Vec2::operator -( const Vec2& v ) const { return Vec2(x - v.x, y - v.y); } Vec2 Vec2::operator *( const float f ) const { return Vec2(x * f, y * f); } Vec2 Vec2::operator /( const float f ) const { return Vec2(x / f, y / f); } Vec2& Vec2::operator =( const Vec2& v ) { x = v.x; y = v.y; return *this; } float Vec2::Length( void ) const { return sqrt( (x * x) + (y * y) ); } float Vec2::Distance( const Vec2 &v ) const { return sqrt( (x-v.x) * (x-v.x) + (y-v.y) * (y-v.y) ); } Vec2& Vec2::Normalize( void ) { float invLen = 1.0f / Length(); x *= invLen; y *= invLen; return *this; } float Vec2::Dot( const Vec2 &v ) const { return x*v.x + y*v.y; }
[ [ [ 1, 80 ] ] ]
85c6c43fd105ecb0f37f54564a55d9b955898fac
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TEST_MyGUI_Source/MyGUIEngine/include/MyGUI_ComboBox.h
55aff2f2aaf4e67d81075187ea073a35a30276a4
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,246
h
/*! @file @author Albert Semenov @date 12/2007 @module */ #ifndef __MYGUI_COMBO_BOX_H__ #define __MYGUI_COMBO_BOX_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_Edit.h" namespace MyGUI { class _MyGUIExport ComboBox : public Edit { // для вызова закрытого конструктора friend class factory::ComboBoxFactory; protected: ComboBox(const IntCoord& _coord, char _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, WidgetCreator * _creator, const Ogre::String & _name); ~ComboBox(); public: // тип данного виджета inline static const Ogre::String & _getType() {static Ogre::String type("ComboBox"); return type;} virtual const Ogre::String & getWidgetType() { return _getType(); } //------------------------------------------------------------------------------------// // методы для манипуляций строками size_t getItemCount(); void insertItem(size_t _index, const Ogre::DisplayString & _item); void addItem(const Ogre::DisplayString& _item); void setItem(size_t _index, const Ogre::DisplayString & _item); const Ogre::DisplayString & getItem(size_t _index); void deleteItem(size_t _index); void deleteAllItems(); void setItemSelect(size_t _index); inline size_t getItemSelect() { return mItemIndex; } //------------------------------------------------------------------------------------// // методы для управления отображением void setComboModeDrop(bool _drop); inline bool getComboModeDrop() { return mModeDrop; } inline bool getSmoothShow() { return mShowSmooth; } inline void setSmoothShow(bool _smooth) { mShowSmooth = _smooth; } //------------------------------------------------------------------------------------// protected: virtual void _onKeyButtonPressed(int _key, Char _char); void notifyButtonPressed(MyGUI::WidgetPtr _sender, bool _left); void notifyListLostFocus(MyGUI::WidgetPtr _sender, MyGUI::WidgetPtr _new); void notifyListSelectAccept(MyGUI::WidgetPtr _widget); void notifyListMouseItemActivate(MyGUI::WidgetPtr _widget, size_t _position); void notifyListChangePosition(MyGUI::WidgetPtr _widget, size_t _position); void notifyMouseWheel(MyGUI::WidgetPtr _sender, int _rel); void notifyMousePressed(MyGUI::WidgetPtr _sender, bool _left); void notifyEditTextChange(MyGUI::WidgetPtr _sender); void showList(); void hideList(); public: // event : нажат энтер в комбо режиме или выбран айтем в дроп режиме // signature : void method(MyGUI::WidgetPtr _widget) EventInfo_WidgetVoid eventComboAccept; // event : изменилась позиция // signature : void method(MyGUI::WidgetPtr _widget, size_t _index) EventInfo_WidgetSizeT eventComboChangePosition; private: ButtonPtr mButton; ListPtr mList; bool mListShow; int mMaxHeight; size_t mItemIndex; bool mModeDrop; bool mDropMouse; bool mShowSmooth; //float mDoAlpha; }; // class _MyGUIExport ComboBox : public Edit } // namespace MyGUI #endif // __MYGUI_COMBO_BOX_H__
[ [ [ 1, 97 ] ] ]
7ea1745a1f8eed3b35ff8c16f23e696aa12c9526
b22c254d7670522ec2caa61c998f8741b1da9388
/physXtest/SynchronizedTimeHandler.cpp
7e3d4626aad1cb39b2ac4e88206182511d2eb989
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
/* ------------------------[ Lbanet Source ]------------------------- Copyright (C) 2009 Author: Vivien Delage [Rincevent_123] Email : [email protected] -------------------------------[ GNU License ]------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ #include "SynchronizedTimeHandler.h" #include <windows.h> SynchronizedTimeHandler* SynchronizedTimeHandler::_singletonInstance = NULL; // singleton pattern SynchronizedTimeHandler * SynchronizedTimeHandler::getInstance() { if(!_singletonInstance) { _singletonInstance = new SynchronizedTimeHandler(); return _singletonInstance; } else { return _singletonInstance; } } //! get synchronized current time double SynchronizedTimeHandler::GetCurrentTimeDouble() { unsigned int currentTime = timeGetTime(); return (currentTime)*0.001; }
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 55 ] ] ]
76c3b511d471b6fc8ebe3d0b503c506892336be8
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/uiSelectMenu.cpp
4d74200358bf6b793cb1c8176dead566c6c0d174
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
2,646
cpp
#include "cltpch.h" #include "uiSelectMenu.h" #include "uiItemBoxContainer.h" #include "uiItemMenu.h" #include "uiTipMenu.h" #include "ClLobby.h" #include "LobbyScene.h" #include "KylinRoot.h" Kylin::SelectMenu::SelectMenu() : GuiBase(CLASS_TO(SelectMenu)) , mToolTip(NULL) , mItemBoxV(NULL) { } KBOOL Kylin::SelectMenu::Initialize() { MyGUI::FactoryManager::getInstance().registerFactory<ResourceItemInfo>("Resource"); MyGUI::Gui::getInstance().load("lobby_imageset.xml"); MyGUI::Gui::getInstance().load("ItemBox_skin.xml"); mToolTip = KNEW TipMenu(); mToolTip->Hide(); mItemBoxV = KNEW ItemBoxContainer("ItemBoxV.layout"); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero0", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero1", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero2", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero3", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero4", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero5", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero6", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero7", 3)); // mItemBoxV->getItemBox()->addItem(KNEW ItemMenu("info_Hero8", 3)); mItemBoxV->getItemBox()->eventNotifyItem = newDelegate(this, &SelectMenu::NotifyNotifyItem); mItemBoxV->getItemBox()->eventToolTip = newDelegate(this, &SelectMenu::NotifyToolTip); return true; } KVOID Kylin::SelectMenu::Render( KFLOAT fElapsed ) { } KVOID Kylin::SelectMenu::Destroy() { MyGUI::FactoryManager::getInstance().unregisterFactory<ResourceItemInfo>("Resource"); //--------------------------------------------------------------- SAFE_DEL(mItemBoxV); SAFE_DEL(mToolTip); } KVOID Kylin::SelectMenu::SetVisible( KBOOL bVisible ) { GuiBase::SetVisible(bVisible); } KVOID Kylin::SelectMenu::NotifyToolTip( wraps::BaseLayout * _sender, const MyGUI::ToolTipInfo & _info, ItemMenu * _data ) { if (_info.type == MyGUI::ToolTipInfo::Show) { mToolTip->Show(_data, _info.point); } else if (_info.type == MyGUI::ToolTipInfo::Hide) { mToolTip->Hide(); } } KVOID Kylin::SelectMenu::NotifyNotifyItem(wraps::BaseLayout * _sender, const MyGUI::IBNotifyItemData & _info) { if (_info.index != MyGUI::ITEM_NONE) { if (_info.notify == MyGUI::IBNotifyItemData::MouseReleased) { Kylin::ClLobby* pLobby = static_cast<ClLobby*>(KylinRoot::GetSingletonPtr()->GetCurrentGameStatus()); if (pLobby) { pLobby->GetLobbyScene()->SpawnActor(1); } } } }
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 20 ], [ 23, 54 ], [ 57, 92 ] ], [ [ 21, 22 ], [ 55, 56 ] ] ]
fe45433cb4d4f5f73bf6b283388f508683dc325b
46653590825ea44df39c88f5e5e761122239b882
/EseObjects/Positioning.hpp
a93fe7f8e7ad5967f8006d41005430ae6cceaea6
[]
no_license
CADbloke/eselinq
e46e24d41a09ba467cc54a94b5ad803d00e6e2d1
e19f217a32b23b2fd71149653fe792086c798cb8
refs/heads/master
2021-01-13T01:00:48.817112
2010-08-26T01:50:39
2010-08-26T01:50:39
36,408,696
0
0
null
null
null
null
UTF-8
C++
false
false
5,195
hpp
/////////////////////////////////////////////////////////////////////////////// // Project : EseLinq http://code.google.com/p/eselinq/ // Copyright : (c) 2009 Christopher Smith // Maintainer : [email protected] // Module : Positioning - Descriptions of seekable and limitable positions /////////////////////////////////////////////////////////////////////////////// // //This software is licenced under the terms of the MIT License: // //Copyright (c) 2009 Christopher Smith // //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. // /////////////////////////////////////////////////////////////////////////////// ///<summary>Internal interface representing values that can you can seek to.</summary> public ref struct Seekable abstract { internal: Seekable() {} virtual void SeekTo(bool %HasCurrency, bool %NotEqual, Cursor ^c) = 0; }; ///<summary>Internal interface representing values that you can set up a limit to.</summary> public ref struct Limitable abstract : public Seekable { internal: Limitable() {} virtual bool LimitTo(Cursor ^c, bool upper) = 0; }; public enum struct SeekRel { ///<summary>First entry equal to key. JET_bitSeekEQ in JetSeek.</summary> ///<remarks>Not valid with a key that is using any wildcard.</remarks> EQ, ///<summary>First entry greater or equal to key. JET_bitSeekGE in JetSeek.</summary> ///<remarks>Not valid with WildcardEnd or WildcardEndPrefix.</remarks> GE, ///<summary>First entry greater than key. JET_bitSeekGT in JetSeek.</summary> ///<remarks>Not valid with WildcardEnd or WildcardEndPrefix.</remarks> GT, ///<summary>Last entry less than key. JET_bitSeekLE in JetSeek.</summary> ///<remarks>Not valid with WildcardStart or WildcardStartPrefix.</remarks> LE, ///<summary>Last entry less than or equal to key. JET_bitSeekLT in JetSeek.</summary> ///<remarks>Not valid with WildcardStart or WildcardStartPrefix.</remarks> LT }; JET_GRBIT SeekRelToGrbit(SeekRel rel) { switch(rel) { case SeekRel::EQ: return JET_bitSeekEQ; case SeekRel::GE: return JET_bitSeekGE; case SeekRel::GT: return JET_bitSeekGT; case SeekRel::LE: return JET_bitSeekLE; case SeekRel::LT: return JET_bitSeekLT; default: throw gcnew ArgumentException("Invalid SeekRel"); } } bool SeekRelIsInclusive(SeekRel rel) { switch(rel) { case SeekRel::EQ: case SeekRel::GE: case SeekRel::LE: return true; case SeekRel::GT: case SeekRel::LT: return false; default: throw gcnew ArgumentException("Invalid SeekRel"); } } //5.0: needs to support the old wildcard method with JET_bitStrLimit and JET_bitSubStrLimit instead of these public enum struct Match { ///<summary>No wildcard used; fields are matched as specified.</summary> Full, ///<summary>Specified field values will be used, and any unspecified on the end will be matched to the last possible value. (JET_bitFullColumnEndLimit in JetMakeKey)</summary> WildcardEnd, ///<summary>Specified field values will be used, the last of which is only matched as a prefix. Any other fields unspecified on the end will be matched to the last possible value. (JET_bitPartialColumnEndLimit in JetMakeKey)</summary> WildcardEndPrefix, ///<summary>Specified field values will be used, and any unspecified on the end will be matched to the first possible value. (JET_bitFullColumnStartLimit in JetMakeKey)</summary> WildcardStart, ///<summary>Specified field values will be used, the last of which is only matched as a prefix. Any other fields unspecified on the end will be matched to the first possible value. (JET_bitPartialColumnStartLimit in JetMakeKey)</summary> WildcardStartPrefix }; JET_GRBIT MatchToGrbit(Match match) { switch(match) { case Match::Full: return 0; case Match::WildcardEnd: return JET_bitFullColumnEndLimit; case Match::WildcardStart: return JET_bitFullColumnStartLimit; case Match::WildcardEndPrefix: return JET_bitPartialColumnEndLimit; case Match::WildcardStartPrefix: return JET_bitPartialColumnStartLimit; default: throw gcnew ArgumentException("Invalid Match"); } }
[ [ [ 1, 136 ] ] ]
8f18712c55611e1558aafea2d7981db71bb7b678
e220295e53990c314fab38f90f8d1021b5e656a4
/Node.h
36ecab41dbbf0c35aa06c1c894d752857d855034
[]
no_license
mcteapot/TowerOfHanoi
41b917fb6635f073ca791826543f38a75572ab49
40e9982f957be4c64dc2aeafd95c3401f2b9c3c1
refs/heads/master
2016-09-06T10:19:38.126050
2011-04-25T00:38:06
2011-04-25T00:38:06
1,629,072
2
0
null
null
null
null
UTF-8
C++
false
false
1,573
h
#ifndef NODE_H #define NODE_H #include <iostream> #include <cstdlib> #include <string> #include <ctime> using namespace std; template<class T> struct node //Linked List of type 'node' for tower of Hanoi { T priority;//int data field for priority void nFresh();//initialez variables to defaults node();//constructor calls nFresh ~node();//destructor calls nFresh node(T arg);//single arguement constructor node(node *ptr);//copy constructor node& operator=(node *other);//assignment operator overload node *ptr; //tail //static int qCount; }; template<class T> void node<T>::nFresh() { priority = 0;//negative 1 is a dummy negative value that implies there is priority set for node //pole = 1; //L-R, 1 2 3{} one is starting position //data = NULL;//data field set to a default value. Might not use this data field but wouldn't hurt. ptr = NULL;//points to nothing } template<class T> node<T>::node()//constructor calls nFresh { nFresh(); } template<class T> node<T>::~node()//destructor calls nFresh { nFresh(); } template<class T> node<T>::node(T arg)//single arguement constructor { priority = arg; ptr = NULL; } template<class T> node<T>::node(node *other)//copy constructor { priority = other->priority; //pole = other->pole; ptr = other->ptr; } template<class T> node<T>& node<T>::operator=(node *other) { priority = other->priority; ptr = other->ptr; return *this; } #endif // NODE_H
[ [ [ 1, 75 ] ] ]
1f090f07c74ed05a2797650689380c9bf152cb49
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/tools/MeshTexer/src/system/System.h
be45c09e578dc299d9d7ae198cdc9546ff4af047
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
666
h
#ifndef __KERNEL_SYSTEM_H #define __KERNEL_SYSTEM_H #include <dingus/app/DingusApplication.h> namespace dingus { class IConsoleRenderingContext; class CD3DTextBoxConsoleRenderingContext; class CD3DFont; }; class CSystem : public IDingusApplication { public: virtual SAppStartupParams getStartupParams(); virtual IConsoleRenderingContext* createStdConsoleCtx( HWND hwnd ); virtual void setupBundles( const std::string& dataPath, dingus::CReloadableBundleManager& reloadManager ); virtual void setupContexts( HWND hwnd ); virtual void destroyContexts(); virtual void destroyBundles(); protected: HWND mHwnd; }; #endif
[ [ [ 1, 30 ] ] ]
be6f1bbebdfa3205bb80cbc80915d0faf11e75c0
fdfaf8e8449c5e80d93999ea665db48feaecccbe
/trunk/cg ex1/ParticleSystem.cpp
ae335776ead6c2e40d695242971815516503cebc
[]
no_license
BackupTheBerlios/glhuji2005-svn
879e60533f820d1bdcfa436fd27894774c27a0b7
3afe113b265704e385c94fabaf99a7d1ad1fdb02
refs/heads/master
2016-09-01T17:25:30.876585
2006-09-03T18:04:19
2006-09-03T18:04:19
40,673,356
0
0
null
null
null
null
UTF-8
C++
false
false
13,542
cpp
#include "StdAfx.h" #include "Vector3d.h" #include "Particle.h" #include "Spring.h" #include "constants.h" #include "MyMacros.h" #include "NumericalSolver.h" #include "Particlesystem.h" ParticleSystem::ParticleSystem( ) { mWidth = 0; mHeight = 0; mIsMidPoint = false; mSolver = NULL; mStepSize = 0; mStiffestSpring = 0; mGravity = 0; mAirResistance = 0; mWindDirection = Vector3d(0,0,0); mWind = Vector3d(0,0,0); mWindMinLen = 0.0; mWindMaxLen = 0.0; mWindMaxChange = 0.0; mParticlePos = NULL; mParticleVelocity = NULL; mParticleInvMass = NULL; mParticleInfo = NULL; mFaceNormals = NULL; mVertexNormals = NULL; } void ParticleSystem::step() { mSolver->step( mStepSize ); } void ParticleSystem::setStepSize( double inStepSize ) { mStepSize = inStepSize; } void ParticleSystem::setDimensions( idx_t inMeshWidth, idx_t inMeshHeight ) { //sanity assert( inMeshWidth > 0 && inMeshHeight > 0 ); freeParticleStorage(); //set dimensions mWidth = inMeshWidth; mHeight = inMeshHeight; //allocate storage idx_t numParticles = mWidth * mHeight; mParticleInfo = new ParticleInfo[numParticles]; mParticlePos = new Vector3d[numParticles]; mParticleInvMass = new double[numParticles]; mParticleVelocity = new Vector3d[numParticles]; mFaceNormals = new Vector3d[numParticles]; // actually we need a little less mVertexNormals = new Vector3d[numParticles]; } void ParticleSystem::autoCreateMesh( double inOriginX, double inOriginY, double inOriginZ, double inMass, double inXOfs, double inZofs ) { double xC = inOriginX; double yC = inOriginY; double zC = inOriginZ; for( idx_t yOfs = 0; yOfs < mHeight; yOfs++ ) { for( idx_t xOfs = 0; xOfs < mWidth; xOfs++ ) { Particle p( xC, yC, zC, inMass, false ); addParticleAt( xOfs, yOfs, p ); xC += inXOfs; } xC = inOriginX; zC += inZofs; } } void ParticleSystem::constructSprings( double inK, double inB, double shearK, double shearB, double flexK, double flexB ) { //set stiffest spring constant mStiffestSpring = max( inK, max(shearK, flexK) ); //useful macro for calculating indexes #define IDX(u,v) ( (u)+((v)*mWidth) ) //----- add 4-connectivity springs ---- for( idx_t y = 0; y < mHeight; y++ ) for( idx_t x = 0; x < mWidth; x++ ) { //connect spring to the right on all except for rightmost particle if( x!= mWidth-1) { idx_t a = IDX(x,y); idx_t b = IDX(x+1,y); Vector3d &p1V = mParticlePos[a]; Vector3d &p2V = mParticlePos[b]; double dist = (p2V-p1V).length(); if (dist < 0) dist *= -1; //double dist = 0.5; mSprings.push_back( Spring( a, b, dist, inK, inB, 0 ) ); } //connect springs down for all except bottom row if( y != mHeight-1 ) { idx_t a = IDX(x,y); idx_t b = IDX(x,y+1); Vector3d p1V = mParticlePos[a]; Vector3d p2V = mParticlePos[b]; double dist = (p2V-p1V).length(); if (dist < 0) dist *= -1; //double dist = 0.5; mSprings.push_back( Spring( a, b, dist, inK, inB, 0 ) ); } //Add backslashed Shear springs for all but rightmost particles and bottom row if( x!= mWidth-1 && y != mHeight-1 ) { idx_t a = IDX(x,y); idx_t b = IDX(x+1,y+1); Vector3d &p1V = mParticlePos[a]; Vector3d &p2V = mParticlePos[b]; //double dist = abs((p2V-p1V).length()); double dist = (p1V - p2V).length(); //Set rest distance as current distance mSprings.push_back( Spring( a, b, dist, shearK, shearB, 1 ) ); } //Add slashed Shear springs for all but leftmost particles and bottom row if( x != 0 && y != mHeight-1 ) { idx_t a = IDX(x,y); idx_t b = IDX(x-1,y+1); Vector3d &p1V = mParticlePos[a]; Vector3d &p2V = mParticlePos[b]; //double dist = abs((p2V-p1V).length()); double dist = (p1V - p2V).length(); //Set rest distance as current distance mSprings.push_back( Spring( a, b, dist, shearK, shearB, 1 ) ); } //Add flexion springs for all but 2 rightmost particles if( x < mWidth-2 ) { idx_t a = IDX(x,y); idx_t b = IDX(x+2,y); Vector3d &p1V = mParticlePos[a]; Vector3d &p2V = mParticlePos[b]; //double dist = abs((p2V-p1V).length()); double dist = (p1V - p2V).length(); //Set rest distance as current distance mSprings.push_back( Spring( a, b, dist, flexK, flexB, 2 ) ); } //Add flexion springs for all but 2 bottommost rows if( y < mHeight-2 ) { idx_t a = IDX(x,y); idx_t b = IDX(x,y+2); Vector3d &p1V = mParticlePos[a]; Vector3d &p2V = mParticlePos[b]; //double dist = abs((p2V-p1V).length()); double dist = (p1V - p2V).length(); //Set rest distance as current distance mSprings.push_back( Spring( a, b, dist, flexK, flexB, 2 ) ); } } #undef IDX } ParticleSystem::~ParticleSystem() { freeParticleStorage(); if( mSolver != NULL ) delete mSolver; } void ParticleSystem::freeParticleStorage() { SAFE_DELETE_ARR( mParticlePos ); SAFE_DELETE_ARR( mParticleVelocity ); SAFE_DELETE_ARR( mParticleInvMass ); SAFE_DELETE_ARR( mParticleInfo ); SAFE_DELETE_ARR( mFaceNormals ); SAFE_DELETE_ARR( mVertexNormals ); } void ParticleSystem::getSpatialDimensions( Vector3d &outCenter, double &outRadius ) { idx_t numParticles = getNumParticles(); //------------ Find Center Of Mass ------------- Vector3d center; center.print(); for( idx_t i = 0; i < numParticles; i++ ) { center += mParticlePos[i]; } center = center / numParticles; center.print(); outCenter = center; //------------ Find Radius ------------- double dist = 0; for( idx_t i = 0; i < numParticles; i++ ) { double tmp = ABS( center.dist(mParticlePos[i]) ); if( tmp > dist ) dist = tmp; } outRadius = dist; } void ParticleSystem::addParticleAt( idx_t inX, idx_t inY, Particle &inParticle ) { //sanity, check we're inside mesh bounds... assert( (inX < mWidth) && (inY < mHeight) ); idx_t i = inX + (inY*mWidth); //assign mParticlePos[ i ] = inParticle.getPos(); mParticleInvMass[ i ] = 1.0 / inParticle.getMass(); mParticleInfo[i] = ParticleInfo(); mParticleVelocity[i] = inParticle.getVelocity(); if( inParticle.isPinned() ) mParticleInfo[i].pin(); } Vector3d & ParticleSystem::getParticlePos( idx_t inX, idx_t inY ) { //sanity, check we're inside mesh bounds... assert( (inX < mWidth) && (inY < mHeight) ); return mParticlePos[ inX + (inY*mWidth) ]; } idx_t ParticleSystem::getNumParticles() { return mWidth*mHeight; } void ParticleSystem::pinParticle( idx_t inX, idx_t inY ) { //sanity, check we're inside mesh bounds... assert( (inX < mWidth) && (inY < mHeight) ); mParticleInfo[ inX + (inY*mWidth) ].pin(); } void ParticleSystem::setGravity( double inGravity ) { mGravity = inGravity; } void ParticleSystem::setAirResistance( int8 inAirResistancePercent ) { //air resistance specified in percent mAirResistance = 1-(0.01*inAirResistancePercent); } double ParticleSystem::getGravity() { return mGravity; } double ParticleSystem::getStiffestSpring() { return mStiffestSpring; } void ParticleSystem::setSolver( NumericalSolver *inSolver ) { if( mSolver != NULL ) delete mSolver; mSolver = inSolver; mSolver->attachToParticleSystem( this, mIsMidPoint ); } Vector3d ParticleSystem::getNewWind() { double change = mWindMaxChange*(1.0-double(rand())/double(RAND_MAX)); mWind += mWindDirection*change; double WindLen = mWind.length(); if (WindLen > mWindMaxLen) mWind = mWindDirection*mWindMaxLen; else if (WindLen < mWindMinLen) mWind = mWindDirection*mWindMinLen; return mWind; } Vector3d & ParticleSystem::getParticleNormal( idx_t inX, idx_t inY ) { //sanity, check we're inside mesh bounds... assert( (inX < mWidth) && (inY < mHeight) ); assert( mVertexNormals != NULL ); return mVertexNormals[ inX + (inY*mWidth) ]; } Vector3d & ParticleSystem::getParticleNormal( idx_t idx ) { //sanity, check we're inside mesh bounds... assert( idx < (mWidth*mHeight) ); assert( mVertexNormals != NULL ); return mVertexNormals[ idx ]; } void ParticleSystem::calculateNormals() { assert(mFaceNormals != NULL && mVertexNormals != NULL); #define IDX(u,v) ( (u)+((v)*mWidth) ) // normals calculation // calculate normals to faces for (int y=0; y<mHeight-1; y++){ for (int x=0; x<mWidth-1; x++){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x, y+1); Vector3d &p4 = getParticlePos(x+1, y); Vector3d v1 = p2-p1; Vector3d v2 = p4-p1; mFaceNormals[IDX(x,y)] = v1.cross(v2); mFaceNormals[IDX(x,y)].normalize(); } } // calculate normals to vertices Vector3d normal1, normal2, normal3, normal4; Vector3d normal; for (int y=0; y<mHeight; y++){ for (int x=0; x<mWidth; x++){ // corners if (x==0 && y==0){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x+1, y); Vector3d &p3 = getParticlePos(x, y+1); normal = calcTriangleNormal( p1, p2, p3); } else if (x==0 && y==mHeight-1){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x, y-1); Vector3d &p3 = getParticlePos(x+1, y); normal = calcTriangleNormal( p1, p2, p3); } else if (x==mWidth-1 && y==0){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x, y+1); Vector3d &p3 = getParticlePos(x-1, y); normal = calcTriangleNormal( p1, p2, p3); } else if (x==mWidth-1 && y==mHeight-1){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x-1, y); Vector3d &p3 = getParticlePos(x, y-1); normal = calcTriangleNormal( p1, p2, p3); } // edges else if (x==0){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x, y-1); Vector3d &p3 = getParticlePos(x+1, y); Vector3d &p4 = getParticlePos(x, y+1); normal1 = calcTriangleNormal( p1, p2, p3); normal2 = calcTriangleNormal( p1, p3, p4); normal = normal1 + normal2; } else if (x==mWidth-1){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x, y+1); Vector3d &p3 = getParticlePos(x-1, y); Vector3d &p4 = getParticlePos(x, y-1); normal1 = calcTriangleNormal( p1, p2, p3); normal2 = calcTriangleNormal( p1, p3, p4); normal = normal1 + normal2; } else if (y==0){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x+1, y); Vector3d &p3 = getParticlePos(x, y+1); Vector3d &p4 = getParticlePos(x-1, y); normal1 = calcTriangleNormal( p1, p2, p3); normal2 = calcTriangleNormal( p1, p3, p4); normal = normal1 + normal2; } else if (y==mHeight-1){ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x-1, y); Vector3d &p3 = getParticlePos(x, y-1); Vector3d &p4 = getParticlePos(x+1, y); normal1 = calcTriangleNormal( p1, p2, p3); normal2 = calcTriangleNormal( p1, p3, p4); normal = normal1 + normal2; } // inner vertices else{ Vector3d &p1 = getParticlePos(x, y); Vector3d &p2 = getParticlePos(x-1, y); Vector3d &p3 = getParticlePos(x, y-1); Vector3d &p4 = getParticlePos(x+1, y); Vector3d &p5 = getParticlePos(x, y+1); normal1 = calcTriangleNormal( p1, p2, p3); normal2 = calcTriangleNormal( p1, p3, p4); normal3 = calcTriangleNormal( p1, p4, p5); normal4 = calcTriangleNormal( p1, p5, p2); normal = normal1 + normal2 + normal3 + normal4; } normal.normalize(); mVertexNormals[IDX(x,y)] = normal; } } #undef IDX } void ParticleSystem::move( Vector3d direction ) { idx_t numParticles = getNumParticles(); for( idx_t i = 0; i < numParticles; i++ ) { mParticlePos[i] += direction; } } Vector3d ParticleSystem::calcTriangleNormal(Vector3d vertex1, Vector3d vertex2, Vector3d vertex3) { Vector3d normal = (vertex2 - vertex1).cross(vertex3 - vertex1); normal.normalize(); return normal; }
[ "playmobil@c8a6d0be-e207-0410-856a-d97b7f264bab", "itai@c8a6d0be-e207-0410-856a-d97b7f264bab", "dagan@c8a6d0be-e207-0410-856a-d97b7f264bab" ]
[ [ [ 1, 5 ], [ 7, 23 ], [ 30, 33 ], [ 38, 69 ], [ 73, 96 ], [ 98, 115 ], [ 120, 120 ], [ 122, 124 ], [ 126, 130 ], [ 135, 135 ], [ 144, 145 ], [ 156, 157 ], [ 170, 171 ], [ 182, 183 ], [ 188, 208 ], [ 211, 302 ], [ 304, 313 ], [ 315, 320 ] ], [ [ 6, 6 ], [ 24, 29 ], [ 97, 97 ], [ 116, 119 ], [ 121, 121 ], [ 125, 125 ], [ 131, 134 ], [ 136, 143 ], [ 146, 155 ], [ 158, 169 ], [ 172, 181 ], [ 184, 187 ], [ 303, 303 ], [ 314, 314 ], [ 321, 334 ], [ 346, 355 ] ], [ [ 34, 37 ], [ 70, 72 ], [ 209, 210 ], [ 335, 345 ], [ 356, 480 ] ] ]
635a0dd5bbc73873cb865cd0d95c0abede96ead6
f95341dd85222aa39eaa225262234353f38f6f97
/ScreenSavers/Flurry/Sources/Flurry/FlurrySettings.cpp
356eac03b9ae32d74e4751972dee36592eae0127
[]
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
10,507
cpp
/////////////////////////////////////////////////////////////////////////////////////////////// // // Flurry : Settings class // // Screen saver settings code, specific to Windows platform // // Copyright (c) 2003, Matt Ginzton // Copyright (c) 2005-2008, Julien Templier // All rights reserved. // /////////////////////////////////////////////////////////////////////////////////////////////// // * $LastChangedRevision$ // * $LastChangedDate$ // * $LastChangedBy$ /////////////////////////////////////////////////////////////////////////////////////////////// // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // o Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // o Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // o Neither the name of the author nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// #include <assert.h> #include "FlurrySettings.h" #include "FlurryPreset.h" using namespace Flurry; static const char flurryRegistryKey[] = "Software\\Flurry"; //////////////////////////////////////////////////////////////////////////////////////// Settings::Settings() : settingBufferMode(BUFFER_MODE_SINGLE), multiMonPosition(MULTIMON_ALLMONITORS), showFPSIndicator(0), bugBlockMode(0), bugWhiteout(0), globalPreset(0), shrinkPercentage(0), maxFrameProgressInMs(30) {} //////////////////////////////////////////////////////////////////////////////////////// void Settings::Read() { CRegKey reg; DWORD formatLen = sizeof(DWORD); // open the registry key BOOL opened = (ERROR_SUCCESS == reg.Open(HKEY_CURRENT_USER, flurryRegistryKey, KEY_READ)); // Read settings - we have to read visuals and monitors still, as they are initialized theres if (opened) { reg.QueryValue("Buffering mode", NULL, &settingBufferMode, &formatLen); reg.QueryValue("Multimon behavior", NULL, &multiMonPosition, &formatLen); reg.QueryValue("FPS display", NULL, &showFPSIndicator, &formatLen); reg.QueryValue("Freakshow: Block mode", NULL, &bugBlockMode, &formatLen); reg.QueryValue("Freakshow: Whiteout doublebuffer", NULL, &bugWhiteout, &formatLen); reg.QueryValue("Preset", NULL, &globalPreset, &formatLen); reg.QueryValue("Shrink by %", NULL, &shrinkPercentage, &formatLen); reg.QueryValue("Max frame progress", NULL, &maxFrameProgressInMs, &formatLen); } // read per-monitor and per-preset settings ReadVisuals(reg); ReadMonitors(reg); } //////////////////////////////////////////////////////////////////////////////////////// void Settings::Write() { CRegKey reg; // create the registry key if (ERROR_SUCCESS != reg.Create(HKEY_CURRENT_USER, flurryRegistryKey)) return; reg.SetValue("Buffering mode", REG_DWORD, &settingBufferMode, sizeof(DWORD)); reg.SetValue("Multimon behavior", REG_DWORD, &multiMonPosition, sizeof(DWORD)); reg.SetValue("FPS display", REG_DWORD, &showFPSIndicator, sizeof(DWORD)); reg.SetValue("Freakshow: Block mode", REG_DWORD, &bugBlockMode, sizeof(DWORD)); reg.SetValue("Freakshow: Whiteout doublebuffer", REG_DWORD, &bugWhiteout, sizeof(DWORD)); reg.SetValue("Preset", REG_DWORD, &globalPreset, sizeof(DWORD)); reg.SetValue("Shrink by %", REG_DWORD, &shrinkPercentage, sizeof(DWORD)); reg.SetValue("Max frame progress", REG_DWORD, &maxFrameProgressInMs, sizeof(DWORD)); // write per-monitor and per-preset settings WriteVisuals(reg); WriteMonitors(reg); } ////////////////////////////////////////////////////////////////////////// void Settings::ReadVisuals(CRegKey& reg) { // the first N are hardcoded; we put them in the registry so the user can // see what they look like for inspiration, but they can change them till // they're blue in the face and we won't care. char *PresetVisuals[] = { "Classic:{5,tiedye,100,1.0}", "RGB:{3,red,100,0.8};{3,blue,100,0.8};{3,green,100,0.8}", "Water:{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0};{1,blue,100.0,2.0}", "Fire:{12,slowCyclic,10000.0,0.0}", "Psychedelic:{10,rainbow,200.0,2.0}" }; static const int nPresets = sizeof PresetVisuals / sizeof PresetVisuals[0]; int i = 0; for (i = 0; i < nPresets; i++) { Spec *preset = new Spec(PresetVisuals[i]); if (preset->IsValid()) { visuals.push_back(preset); } else { _RPT0(_CRT_WARN, "Things are really messed up... preset doesn't match!\n"); delete preset; } } assert(visuals.size() > 0); // read the rest from the registry if (reg == NULL) return; CRegKey presets; if (ERROR_SUCCESS != presets.Open(reg, "Presets", KEY_READ)) return; while (true) { char customFormat[2000]; DWORD formatLen = sizeof customFormat; char nextValue[20]; _snprintf_s(nextValue, sizeof nextValue, "preset%02d", i++); //LONG result = presets.QueryValue(customFormat, nextValue, &formatLen); LONG result = presets.QueryValue(nextValue, NULL, customFormat, &formatLen); if (result != ERROR_SUCCESS) { _RPT2(_CRT_WARN, "ReadVisuals: failed to read %s: %d\n", nextValue, result); break; } Spec *preset = new Spec(customFormat); if (preset->IsValid()) { visuals.push_back(preset); } else { _RPT0(_CRT_WARN, "ReadVisuals: preset not parseable; WARNING will be removed on ok\n"); _RPT1(_CRT_WARN, " '%s'\n", customFormat); delete preset; } } } ////////////////////////////////////////////////////////////////////////// void Settings::WriteVisual(CRegKey& presets, int index) { if (visuals[index]->IsValid()) { string format = visuals[index]->GetTemplate(); char nextValue[20]; _snprintf_s(nextValue, sizeof nextValue, "preset%02d", index); //presets.SetValue(format, nextValue); presets.SetValue(nextValue, REG_SZ, format.c_str(), format.size() ); } else { _RPT1(_CRT_WARN, "WriteVisuals: Can't write preset %d!\n", index); } } //////////////////////////////////////////////////////////////////////////////////////// void Settings::WriteVisuals(CRegKey& reg) { // Cleanup Presets key reg.DeleteSubKey("Presets"); CRegKey presets; presets.Create(reg, "Presets"); for (int i = 0; i < (signed)visuals.size(); i++) { WriteVisual(presets, i); } } ////////////////////////////////////////////////////////////////////////// void Settings::UpdateVisual(int index) { if (index < 0 || index > (signed)visuals.size()) return; CRegKey reg; // create the registry key if (ERROR_SUCCESS != reg.Create(HKEY_CURRENT_USER, flurryRegistryKey)) return; CRegKey presets; presets.Create(reg, "Presets"); WriteVisual(presets, index); } //////////////////////////////////////////////////////////////////////////////////////// void Settings::ReadMonitors(CRegKey& reg) { int iMonitor = 0; if (reg == NULL) return; CRegKey monitors; if (ERROR_SUCCESS != monitors.Open(reg, "Monitors", KEY_READ)) return; while (true) { char nextValue[20]; _snprintf_s(nextValue, sizeof nextValue, "monitor%02dPreset", iMonitor++, 20*sizeof(char)); DWORD presetForMonitor; DWORD formatLen = sizeof(presetForMonitor); LONG result = monitors.QueryValue(nextValue, NULL, &presetForMonitor, &formatLen); if (result != ERROR_SUCCESS) { _RPT2(_CRT_WARN, "ReadMonitors: failed to read %s: %d\n", nextValue, result); break; } if (presetForMonitor >= visuals.size()) { presetForMonitor = globalPreset; } _RPT2(_CRT_WARN, "ReadMonitors: monitor %d using visual %d\n", multiMonPreset.size(), presetForMonitor); multiMonPreset.push_back(presetForMonitor); } } //////////////////////////////////////////////////////////////////////////////////////// void Settings::WriteMonitors(CRegKey& reg) { CRegKey monitors; monitors.Create(reg, "Monitors"); for (int iMonitor = 0; iMonitor < (signed)multiMonPreset.size(); iMonitor++) { char nextValue[20]; _snprintf_s(nextValue, sizeof nextValue, "monitor%02dPreset", iMonitor, 20*sizeof(char)); monitors.SetValue(nextValue, REG_DWORD, &multiMonPreset[iMonitor], sizeof(int) ); } } int Settings::GetPresetForMonitor(int monitor) { // return 0 (default preset), if we are passed a wrong parameter if (monitor < 0) return 0; // if there is no preset for that monitor, create a default one if (monitor >= (signed)multiMonPreset.size()) multiMonPreset.push_back(0); return multiMonPreset[monitor]; } ////////////////////////////////////////////////////////////////////////// // Delete the visual at index // if the current preset is the deleted one, reset to default preset void Settings::DeleteVisual(int index) { if (index < 0 || index > (signed)visuals.size()) return; visuals.erase(visuals.begin() + index); // Global preset if ((signed)globalPreset == index) globalPreset = 0; for (int i = 0; i < (signed)multiMonPreset.size(); i++) { if (multiMonPreset[i] != index) break; multiMonPreset[i] = 0; } }
[ "julien.templier@ab80709b-eb45-0410-bb3a-633ce738720d" ]
[ [ [ 1, 313 ] ] ]
e1848e1151e564ecc782923101fa5b1edab25e4a
62874cd4e97b2cfa74f4e507b798f6d5c7022d81
/src/StandardProcessors/global.h
cceea6fe6652b110e6023940d65f116fc98bebb9
[]
no_license
rjaramih/midi-me
6a4047e5f390a5ec851cbdc1b7495b7fe80a4158
6dd6a1a0111645199871f9951f841e74de0fe438
refs/heads/master
2021-03-12T21:31:17.689628
2011-07-31T22:42:05
2011-07-31T22:42:05
36,944,802
0
0
null
null
null
null
UTF-8
C++
false
false
1,838
h
#ifndef STANDARDPROCESSORS_GLOBAL_H #define STANDARDPROCESSORS_GLOBAL_H // Includes #ifdef HAVE_CONFIG_H #include <config.h> #endif // Windows and pocket pc #if defined(_WIN32_WCE) || defined(WIN32) // Identifier was truncated to '255' characters in the debug information #pragma warning (disable: 4786) // STL classes are not exported in the dll /*! @note This can be ignored, since none of the stl members are public, so they shouldn't be exported in the dll */ #pragma warning (disable: 4251) // Conversion from 'size_t' to 'unsigned int', possible loss of data /*! @note In VS.NET 7.1, it seems that size_t of STL is defined as a int in stead of a unsigned int. */ #pragma warning (disable: 4267) #define WIN32_LEAN_AND_MEAN #include <windows.h> // Windows dll defines #if defined(STANDARDPROCESSORS_EXPORTING) // Creating a dynamic library #define STANDARDPROCESSORS_API __declspec(dllexport) #elif defined(STANDARDPROCESSORS_STATIC) // Creating or using a static library #define STANDARDPROCESSORS_API #else // Using the dynamic lib #define STANDARDPROCESSORS_API __declspec(dllimport) #endif // Windows plugin defines #define PLUGIN_API extern "C" __declspec(dllexport) // Linux, Mac OS, ... #else // Make compatible with the windows function #define stricmp strcasecmp // No dll export macro needed #define STANDARDPROCESSORS_API // Plugin defines #define PLUGIN_API extern "C" #endif #include <string> using std::string; using std::wstring; #include <iostream> using std::cout; using std::wcout; using std::cin; using std::wcin; using std::cerr; using std::wcerr; using std::endl; #include <cassert> // Defines #ifndef NULL #define NULL 0 #endif // NULL #endif // STANDARDPROCESSORS_GLOBAL_H
[ "Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f" ]
[ [ [ 1, 79 ] ] ]
95314177da8c4e74793ffde6c9fab6c2fe2b064f
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/include/OECore/IOEShader.h
7de40b973cd851deea751a031dbeb005a7146401
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
1,600
h
/*! * \file IOEShader.h * \date 1-6-2009 15:42:06 * * * \author zjhlogo ([email protected]) */ #ifndef __IOESHADER_H__ #define __IOESHADER_H__ #include "../libOEBase/IOEObject.h" #include "../libOEMath/OEMath.h" #include "IOETexture.h" #include "IOEVertDecl.h" class IOEShader : public IOEObject { public: RTTI_DEF(IOEShader, IOEObject); IOEShader() {}; virtual ~IOEShader() {}; virtual bool SetInt(const tstring& strParamName, int nValue) = 0; virtual bool GetInt(int& nOut, const tstring& strParamName) = 0; virtual bool SetFloat(const tstring& strParamName, float fValue) = 0; virtual bool GetFloat(float& fOut, const tstring& strParamName) = 0; virtual bool SetVector(const tstring& strParamName, const CVector4& vIn) = 0; virtual bool SetVector(const tstring& strParamName, const CVector3& vIn) = 0; virtual bool GetVector(CVector4& vOut, const tstring& strParamName) = 0; virtual bool GetVector(CVector3& vOut, const tstring& strParamName) = 0; virtual bool SetMatrix(const tstring& strParamName, const CMatrix4x4& matIn) = 0; virtual bool GetMatrix(CMatrix4x4& matOut, const tstring& strParamName) = 0; virtual bool SetMatrixArray(const tstring& strParamName, const CMatrix4x4* pmatIn, uint nCount) = 0; virtual bool GetMatrixArray(CMatrix4x4* pmatOut, uint nCount, const tstring& strParamName) = 0; virtual bool SetTexture(const tstring& strParamName, IOETexture* pTexture) = 0; virtual bool SetTechnique(const tstring& strParamName) = 0; virtual IOEVertDecl* GetVertDecl() = 0; }; #endif // __IOESHADER_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 48 ] ] ]
4789041e2be5bea4b6638f34189aa75f18566097
c2a70374051ef8f96105d65c84023d97c90f4806
/bin/src/loadBmp/common/Filter/plfiltervideoinvert.cpp
f9d36c6e9347fbf41991159d30d06e01d0a3f8a0
[]
no_license
haselab-net/SpringheadOne
dcf6f10cb1144b17790a782f519ae25cbe522bb2
004335b64ec7bea748ae65a85463c0e85b98edbd
refs/heads/master
2023-08-04T20:27:17.158435
2006-04-15T16:49:35
2006-04-15T16:49:35
407,701,182
1
0
null
null
null
null
UTF-8
C++
false
false
3,705
cpp
/* /-------------------------------------------------------------------- | | $Id: plfiltervideoinvert.cpp,v 1.7 2004/06/15 10:26:13 uzadow Exp $ | | Copyright (c) 1996-2002 Ulrich von Zadow | \-------------------------------------------------------------------- */ #include "plstdpch.h" #include "plfilter.h" #include "plfiltervideoinvert.h" #include "plbitmap.h" #include "plhsvconvert.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// PLFilterVideoInvert::PLFilterVideoInvert() : PLFilter() { } PLFilterVideoInvert::~PLFilterVideoInvert() { } void PLFilterVideoInvert::Apply(PLBmpBase *pBmpSource, PLBmp *pBmpDest) const { // Only works for 32 bpp bitmaps at the moment. PLASSERT (pBmpSource->GetBitsPerPixel() == 32); pBmpDest->Create (pBmpSource->GetWidth(), pBmpSource->GetHeight(), 32, false, false, NULL, 0, pBmpSource->GetResolution()); PLBYTE ** pSrcLines = pBmpSource->GetLineArray(); PLBYTE ** pDstLines = pBmpDest->GetLineArray(); for (int y = 0; y<pBmpDest->GetHeight(); ++y) { // For each line PLBYTE * pSrcPixel = pSrcLines[y]; PLBYTE * pDstPixel = pDstLines[y]; for (int x = 0; x < pBmpDest->GetWidth(); ++x) { // For each pixel double v1, v2, v3; v1 = (double)pSrcPixel[PL_RGBA_RED]; v2 = (double)pSrcPixel[PL_RGBA_GREEN]; v3 = (double)pSrcPixel[PL_RGBA_BLUE]; fp_rgb_to_hsv(&v1, &v2, &v3); v3 = 255.0-v3; fp_hsv_to_rgb(&v1, &v2, &v3); *pDstPixel = (int)v3; pDstPixel++; *pDstPixel = (int)v2; pDstPixel++; *pDstPixel = (int)v1; pDstPixel++; pDstPixel++; /*PLBYTE (pSrcPixel[PL_RGBA_RED]*0.212671+ pSrcPixel[PL_RGBA_GREEN]*0.715160+ pSrcPixel[PL_RGBA_BLUE]*0.072169);*/ pSrcPixel += sizeof(PLPixel32); } } } /* /-------------------------------------------------------------------- | | $Log: /Project/Springhead/bin/src/loadBmp/common/Filter/plfiltervideoinvert.cpp $ * * 1 04/07/12 13:34 Hase | Revision 1.7 2004/06/15 10:26:13 uzadow | Initial nonfunctioning version of plbmpbase. | | Revision 1.6 2003/11/05 15:17:26 artcom | Added ability to specify initial data in PLBitmap::Create() | | Revision 1.5 2002/08/04 20:08:01 uzadow | Added PLBmpInfo class, ability to extract metainformation from images without loading the whole image and proper greyscale support. | | Revision 1.4 2002/03/31 13:36:42 uzadow | Updated copyright. | | Revision 1.3 2001/10/16 17:12:27 uzadow | Added support for resolution information (Luca Piergentili) | | Revision 1.2 2001/10/06 22:37:08 uzadow | Linux compatibility. | | Revision 1.1 2001/09/16 19:03:23 uzadow | Added global name prefix PL, changed most filenames. | | Revision 1.5 2001/02/04 14:31:52 uzadow | Member initialization list cleanup (Erik Hoffmann). | | Revision 1.4 2001/01/15 15:05:31 uzadow | Added PLBmp::ApplyFilter() and PLBmp::CreateFilteredCopy() | | Revision 1.3 2000/12/18 22:42:53 uzadow | Replaced RGBAPIXEL with PLPixel32. | | Revision 1.2 2000/10/12 21:56:12 uzadow | Moved local functions from VideoInvertFilter.cpp to | hsvconvert.* | | Revision 1.1 2000/03/31 12:20:06 Ulrich von Zadow | Video invert filter (beta) | | | \-------------------------------------------------------------------- */
[ "jumius@05cee5c3-a2e9-0310-9523-9dfc2f93dbe1" ]
[ [ [ 1, 123 ] ] ]
8404b64d46b82dade1fe13e119ea65ba2721587b
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/test/TestSoftwareEncrypt/stdafx.cpp
35a327af89953e9b6fbff629d1e9725b2100d2ec
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
278
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // TestSoftwareEncrypt.pch 将成为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 //引用任何所需的附加头文件,而不是在此文件中引用
[ [ [ 1, 8 ] ] ]
08b37ece009142a63d1b3925a9c2c0e7eafb58f3
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Models/SIZEDST1/sqszbase.h
8b2f2a09dfb40082fb3eb1b48affba4e4fbb09a8
[]
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
28,619
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __SQSZBASE_H #define __SQSZBASE_H #ifndef __SC_DEFS_H #include "sc_defs.h" #endif #ifndef __2D_FN_H #include "2d_fn.h" #endif #ifndef __SCDARRAY_H #include "scdarray.h" #endif #ifndef __DATAATTR_H #include "dataattr.h" #endif #ifndef __SP_CONT_H #include "sp_cont.h" #endif #ifndef __SFE_INIT_H #include "sfe_init.h" #endif #ifdef __SQSZBASE_CPP #define DllImportExport DllExport #elif !defined(SizeDst1) #define DllImportExport DllImport #else #define DllImportExport #endif // ========================================================================== // // // // ========================================================================== class SQSzDist1; class SQSzDist1Edt1; class SzPartCrv1; class SzSelBrk1; // ========================================================================== #define UseExtraColumns 1 // CNM & KGA restored on 29/06/2007 - for QAL //kga: 16/10/02 : Removed seldom used columns, //this has memory/speed/etc savings for project mith large number of ore types #if UseExtraColumns #define UseAllColumns 0 //kga:if 1 include SumG, xxxG columns (doubt we will ever need these) #else #define UseAllColumns 0 #endif const dword SzDSlct_Fp = 0x00000001; const dword SzDSlct_Qm = 0x00000002; const dword SzDSlct_M = 0x00000004; const dword SzDSlct_NFp = 0x00000008; const dword SzDSlct_Qn = 0x00000010; const dword SzDSlct_N = 0x00000020; const dword SzDSlct_NpM = 0x00000040; const dword SzDSlct_Cum = 0x00010000; #if UseAllColumns const dword SzDSlct_CumG = 0x00020000; #endif #if UseAllColumns const int DI_MFp = 0; // Mass Related const int DI_Qm = 1; const int DI_M = 2; const int DI_MFpCum = 3; const int DI_QmCum = 4; const int DI_MCum = 5; const int DI_MFpCumG = 6; const int DI_QmCumG = 7; const int DI_MCumG = 8; const int DI_NFp = 9; // Count Related const int DI_Qn = 10; const int DI_N = 11; const int DI_NFpCum = 12; const int DI_QnCum = 13; const int DI_NCum = 14; const int DI_NFpCumG = 15; const int DI_QnCumG = 16; const int DI_NCumG = 17; const int DI_NpM = 18; // Specific Count const int DI_NpMCum = 19; const int DI_NpMCumG = 20; const int DI_Xtra = 21; #else #if UseExtraColumns const int DI_MFp = 0; // Mass Related const int DI_Qm = 1; const int DI_M = 2; const int DI_MFpCum = 3; const int DI_QmCum = 4; const int DI_MCum = 5; const int DI_NFp = 6; // Count Related const int DI_Qn = 7; const int DI_N = 8; const int DI_NFpCum = 9; const int DI_QnCum = 10; const int DI_NCum = 11; const int DI_NpM = 12; // Specific Count const int DI_NpMCum = 13; const int DI_Xtra = 14; #else const int DI_MFp = 0; // Mass Related const int DI_Qm = 1; const int DI_M = 2; const int DI_MFpCum = 3; const int DI_QmCum = 4; //const int DI_MCum = 5;//maybe include this? const int DI_Xtra = 5; #endif #endif // =========================================================================== // // // // =========================================================================== enum SeriesDataType { e_Manual, e_Q , e_Sqrt , e_Ratio , e_Arithmetic }; class CSieveSeriesHelper { public: CSieveSeriesHelper() { pCnv=NULL; Precision=-1; m_SeriesDataType = e_Ratio; m_Data=sqrt(2.0); m_DataMin=0.1; m_DataMax=500.0; m_bQMidPt=1; }; CSieveSeriesHelper(char* pName, char* pUnits) { m_Name=pName; Units=pUnits; pCnv=NULL; Precision=-1; m_SeriesDataType = e_Q; m_Data=0.0; m_DataMin=0.5; m_DataMax=490.0; m_bQMidPt=1; }; void SortSizes(); flag ChangeUnits(char* pNewCnvTxt); void CalcDisplayPrecision(); void FormatSize(double d, CString& S); void CreateSeriesFromQ(); void CreateSeriesSQRT(); void CreateSeriesFromRatio(); void CreateSeriesArithmetic(); void CreateSeriesFromData(); // Calls one of the above depending on m_SeriesDataType public: Strng m_Name; Strng Units; SeriesDataType m_SeriesDataType; //double m_Q; //double m_QMin; //double m_QMax; //bool m_bQMidPt; double m_Data; // Data has different meaning for differnet SeriesDataType double m_DataMin; double m_DataMax; bool m_bQMidPt; //CArray <double, double> Sizes; CArray <double, double> CalculatedSizes; CArray <double, double> ManualSizes; //CDVector Sizes; CDataCnv* pCnv; int Precision; double Q() { return m_Data; }; // double Ratio() { return m_Data>0 ? pow(2.0, 1.0/(3.0*m_Data)) : -1; }; // }; class CSizeDistHelper { public: CSizeDistHelper() { dTopSize = 1e-3; dBottomSize = 1e-6; dTopSizeDisplay = 1e-3; dBottomSizeDisplay = 1e-6; }; CSizeDistHelper(char* pName, char* pSieveSeriesName) { Name=pName; SieveSeriesName=pSieveSeriesName; }; void SetDefaultTopBottom(CSieveSeriesHelper* pSeries); public: Strng Name; Strng SieveSeriesName; double dTopSize; double dBottomSize; double dTopSizeDisplay; double dBottomSizeDisplay; Strng DefaultSpecie; CArray <Strng, Strng&> Species; }; _FWDDEF(CSD_Measurement) class CDistMeasHelper { public: CDistMeasHelper() {}; public: CArray <CSD_Measurement, CSD_Measurement> Measurements; }; typedef CSieveSeriesHelper* pCSieveSeriesHelper; typedef CSizeDistHelper* pCSizeDistHelper; typedef CDistMeasHelper* pCDistMeasHelper; class CSD_CfgHelper { public: ~CSD_CfgHelper(); CSieveSeriesHelper* FindSieveSeries(char* pSeriesName); CSizeDistHelper* FindDistribution(char* pDistName); void Load(CProfINIFile & CfgPF); void Save(CProfINIFile & CfgPF); int CreateDefaultSD(); int CreateDefaultSS(); int CreateDefaultMeasurement(); void RemoveDistribution(int index); void RemoveSieveSeries(int index); CArray <pCSieveSeriesHelper, pCSieveSeriesHelper&> SSs; CArray <pCSizeDistHelper, pCSizeDistHelper&> SDs; CArray <pCDistMeasHelper, pCDistMeasHelper&> SDsMeas; }; // =========================================================================== class CSD_Intervals; class CSD_Distribution; class CSD_DistDefn; // ========================================================================== #ifdef OLD class DllImportExport CSD_Intervals : public CDArray { friend class SfeSD_Defn; protected: Strng m_sName; double m_Q; // From Aust CSIRO docs for QAL 3rd Page public: CSD_Intervals() { m_Q=0; }; // Copy Constructor. CSD_Intervals(CSD_Intervals & Copy) { m_sName=Copy.m_sName; m_Q=Copy.m_Q; }; char * Name() { return m_sName(); }; int NameLength() { return m_sName.Length(); }; void SetQ(double d) { m_Q=d; }; // double Q() { return m_Q; }; // double Ratio() { return m_Q>0 ? pow(2.0, 1.0/(3.0*m_Q)) : -1; }; // }; #endif class DllImportExport CSD_Intervals : public CDArray { friend class SfeSD_Defn; protected: Strng m_sName; //double m_Q; // From Aust CSIRO docs for QAL 3rd Page double m_Data; // m_Data replaces m_Q as can have different types // of Series SeriesDataType m_SeriesDataType; public: CSD_Intervals() { m_SeriesDataType = e_Manual; m_Data=0; }; // Copy Constructor. CSD_Intervals(CSD_Intervals & Copy) { m_sName=Copy.m_sName; m_Data=Copy.m_Data; }; char * Name() { return m_sName(); }; int NameLength() { return m_sName.Length(); }; // // // void SetSeriesType(SeriesDataType iSeriesDataType ) { m_SeriesDataType = iSeriesDataType; }; SeriesDataType GetSeriesType(void) { return m_SeriesDataType; }; // // Q Series Methods - Should we throw an exception if the // SeriesDataType is not a Q type? // void SetQ(double d) { m_Data=d; }; // double Q() { return m_Data; }; // double Ratio() { return m_Data>0 ? pow(2.0, 1.0/(3.0*m_Data)) : -1; }; // }; // ========================================================================== struct ColumnInitInfo { char * Name; flag fFileIt; flag fOn; flag fForFlow; flag fForMass; flag fForCum; dword m_dwVarSlct; int iDataId; CnvAttribute *pCnv; FmtAttribute *pFmt; flag fEditable; flag fGrfOn; dword dwSaveFlags; flag fDone; }; class DllImportExport CSD_Column { public: //const int MaxSelectCols=4; CSD_Column(); CSD_Column(ColumnInitInfo & CI, char * SpName, int Xid, int SpId, flag SimpleNames); // char* DispName() { return (fSimpleNames ? sName() : sFullName()); }; char* DispName() { return (fSimpleNames ? sName() : sFullNameColon()); }; // CNM void SetOn(flag On) { fOn=On; }; flag On() { return fOn; }; void SetForFlow(flag ForFlow) { fForFlow=ForFlow; }; flag ForFlow() { return fForFlow; }; void SetForMass(flag ForMass) { fForMass=ForMass; }; flag ForMass() { return fForMass; }; flag ForCum() { return fForCum; }; flag Editable() { return fEditable; }; flag SimpleNames() { return fSimpleNames; }; void SetGrfOn(flag GrfOn) { fGrfOn=GrfOn; }; flag GrfOn() { return fGrfOn; }; flag Avail(SpModel &p) { return ((sm_VarSlctMask & m_dwVarSlct)==m_dwVarSlct) && (fForFlow==p.UseAsFlow() || fForMass==!p.UseAsFlow()) ; }; flag Reqd(SpModel &p) { return fOn && Avail(p); }; public: Strng sFullName, sFullNameColon, sName, sSpName; int iSpId, iDataId, iXid; double dDispMin, dFDispMax; CnvAttribute *pCnv; FmtAttribute *pFmt; dword dwSaveFlags; int iColWidth; dword m_dwVarSlct; static dword sm_VarSlctMask; protected: flag fOn; flag fForFlow:1, fForMass:1, fEditable:1, fForCum:1, fSimpleNames:1, fGrfOn:1; }; class DllImportExport CSD_ColumnArray : public CArray <CSD_Column, CSD_Column&> {}; // ========================================================================== class DllImportExport CSD_ColumnOpt { public: Strng sName; int iOpt; }; class DllImportExport CSD_ColumnOptArray : public CArray <CSD_ColumnOpt, CSD_ColumnOpt&> {}; // ========================================================================== const int MaxCSDMeasurements=40; enum eSDMeasTypes { eSDMT_Null, eSDMT_SizePassFrac, eSDMT_FracPassSize, eSDMT_PPG, eSDMT_SAM, eSDMT_SAL, eSDMT_Text }; class DllImportExport CSD_Measurement { public: eSDMeasTypes m_eType; // Measurement Type double m_dValue; // Value for measurment if required Strng m_sName; // Measurement Name CnvAttribute ValCnv; // Value Conversion Attribute CnvAttribute Cnv; // Result Conversion Attribute FmtAttribute Fmt; CSD_Measurement() { m_eType = eSDMT_Null; m_dValue = 0; }; CSD_Measurement& operator=(const CSD_Measurement &M) { m_eType = M.m_eType; m_dValue = M.m_dValue; m_sName = M.m_sName; Cnv = M.Cnv; ValCnv = M.ValCnv; Fmt = M.Fmt; return *this; } // // short m_iCnv; // Strng m_sCnv; }; class DllImportExport CSD_MeasurementArray : public CArray <CSD_Measurement, CSD_Measurement&> {}; // ========================================================================== class DllImportExport CSD_DistDefn { friend class CSD_Distribution; friend class SfeSD_Defn; friend class SQSzDist1; friend class SQSzDist1Edt; friend class CSzSSA; protected: Strng sName; int iDefaultDist; // Set to index where all unrefd solids are to be CSMatrx sSzNames; CIMatrx iSzIds; // Grade CSArray GrdNames; CLVector GrdIds; double dBottomSize, dTopSize; double dBottomSizeDisp, dTopSizeDisp; double dSzDispMin; double dSzDispMax; flag fAutoScale:1, fDispRetained:1, fXLog:1, fYLog:1; //fViewIsMass:1; public: CSD_Intervals Intervals; // Actual Intervals; //CDArray BondWIInit; // N+1 Individual Bond Work Indices. CSD_ColumnOptArray ColumnOpts; CSD_MeasurementArray Measurements; CSD_ColumnArray Columns; CArray <int, int> FileColIndices; CArray <int, int> DispColIndices; public: CSD_DistDefn() { iDefaultDist=-1; dBottomSize=1.0e-8; dBottomSizeDisp=1.0e-8; dTopSize=10.0; dTopSizeDisp=10.0; fAutoScale=true; //fCumulativeOn=true; //fFractionalOn=true; fDispRetained=true; fXLog=true; fYLog=false; dSzDispMin=0.0001; dSzDispMax=1; } char * Name() { return sName(); }; int NameLength() { return sName.Length(); }; double BottomSize() { return dBottomSize; }; double TopSize() { return dTopSize; }; double BottomSizeDisp() { return dBottomSizeDisp; }; double TopSizeDisp() { return dTopSizeDisp; }; int NIntervals() { return Intervals.GetSize();}; int NGrades() { return GrdNames.GetSize();}; double GeometricMean(int iInt) { return iInt==0 ? sqrt(Intervals[iInt] * dBottomSize) : sqrt(Intervals[iInt] * Intervals[iInt-1]); }; // { return iInt==0 ? 0.0 : sqrt(Intervals[iInt] * Intervals[iInt-1]); }; // { return iInt==0 ? sqrt(Intervals[iInt]) : sqrt(Intervals[iInt] * Intervals[iInt-1]); }; double MeanPartDiam(int iInt) { if (iInt==0) return Intervals[iInt]*0.5; if (iInt==NIntervals()-1) return ((Intervals[iInt-1]+Intervals[iInt])*0.5)*Intervals[iInt]/Intervals[iInt-1]; return (Intervals[iInt-1]+Intervals[iInt])*0.5; }; // { return iInt==0 ? (Intervals[iInt]+dBottomSize)*0.5 : (Intervals[iInt-1]+Intervals[iInt])*0.5; }; int NPriIds() { return iSzIds.GetSize(); }; int NSecIds(int i) { return iSzIds[i].GetSize(); }; int SzId(int i, int j) { return iSzIds[i][j]; }; //return SpecieId int PriSzId(int i) { return iSzIds[i][0]; }; //return Pri SpecieId int FindPriSzIdIndex(int SpecieId) { for (int i=0; i<iSzIds.GetSize(); i++) if (iSzIds[i].GetSize()>0 && iSzIds[i][0]==SpecieId) return i; return -1; }; int NColumnOpts() { return ColumnOpts.GetSize(); }; int NColumns() { return Columns.GetSize(); }; }; // ========================================================================== class DllImportExport CSD_SpDist { friend class SfeSD_Defn; friend class SQSzDist1; friend class SQSzDist1Edt; friend class CSD_Distribution; friend class CSD_SpDistArray; friend class CSzSSA; public: CDArray FracPass; // Ni Fractions Passing Interval size //CDArray BondWI; // Ni Individual Bond Work Indices. //CDMatrx Grade; // Ng by Ni Grades of M Species CDArray WorkFrac; // Ni Fractions Passing Interval size public: CSD_SpDist(); CSD_SpDist(const CSD_SpDist & Other); CSD_SpDist & operator=(const CSD_SpDist & Other); virtual ~CSD_SpDist(); DEFINE_SPARES(CSD_SpDist) }; // ========================================================================== typedef CSmartPtrAllocate<CSD_SpDist> CSPASD_SpDist; class DllImportExport CSD_SpDistArray : public CArray <CSPASD_SpDist, CSPASD_SpDist&> {}; // ========================================================================== extern DllImportExport double gs_CountFactor; class DllImportExport CSD_Distribution { friend class SfeSD_Defn; friend class SQSzDist1; friend class SQSzDist1Edt; friend class CSzSSA; protected: CSD_DistDefn & rDefn; CSD_Intervals & rIntervals; // Reference to Actual Intervals; int iCurrentDataId; int iCurrentSpId; CDArray SpMass; CDArray SpDensity; CDArray WorkSpace; CDArray WorkSpace1; //CDArray TempMass; CDArray *pResults; public: CSD_SpDistArray PriSp; int NIntervals() { return rIntervals.GetSize();}; int NGrades() { return rDefn.GrdNames.GetSize();}; double BottomSize() { return rDefn.dBottomSize; }; double TopSize() { return rDefn.dTopSize; }; double BottomSizeDisp() { return rDefn.dBottomSizeDisp; }; double TopSizeDisp() { return rDefn.dTopSizeDisp; }; CSD_Intervals & Intervals() { return rIntervals;}; int NPriIds() { return rDefn.iSzIds.GetSize(); }; int NSecIds(int i) { return rDefn.iSzIds[i].GetSize(); }; int SzId(int i, int j) { return rDefn.iSzIds[i][j]; }; int PriSzId(int i) { return rDefn.iSzIds[i][0]; }; int FindPriSzIdIndex(int SpecieId) { return rDefn.FindPriSzIdIndex(SpecieId); }; double GeometricMean(int iInt) { return rDefn.GeometricMean(iInt); }; double MeanPartDiam(int iInt) { return rDefn.MeanPartDiam(iInt); }; double MeanPartMass(int iInt, double MeanDens) { //double R=MeanPartDiam(iInt)/2; //return 4/3*PI*(R*R*R)*MeanDens; //return 4.0/3.0*PI*(R*R*R)*MeanDens; const double D = MeanPartDiam(iInt); return PI*(D*D*D)*MeanDens/6.0; }; double PartCount(int iInt, double Mass, double MeanDens) { return Mass/GTZ(MeanPartMass(iInt, MeanDens))*gs_CountFactor; }; double PartDensity(int iInt, double MeanDens) { return 1.0/GTZ(MeanPartMass(iInt, MeanDens)); }; double SpecificSurfaceAreaM(double T, double P, SpPropOveride * pOvr, double *M) { double TotalF=0.0; double TotalA=0.0; double TotalM=0.0; for (int s=0; s<NPriIds(); s++) TotalM+=M[PriSzId(s)]; TotalM=GTZ(TotalM); CDensityInfo C(SpModel::Fidelity(), SMO_DensNone/*SpModel::DensityMethod()*/, T, P, pOvr, M); for (int s=0; s<NPriIds(); s++) { if (SDB[PriSzId(s)].DensityX(C)) { double SolDens=C.Density(); CSD_SpDist & S=*PriSp[s]; double Mult=C.Mass()/TotalM; for (int i=0; i<NIntervals(); i++) { const double D=MeanPartDiam(i); const double Y=3.0/GTZ(0.5*SolDens*D); // m^2/kg TotalF+=Mult*S.FracPass[i]; TotalA+=Mult*Y*S.FracPass[i]; } } } return 0.001*TotalA/GTZ(TotalF); } double SpecificSurfaceAreaV(double T, double P, SpPropOveride * pOvr, double *M, double LiqVol) { CDensityInfo C(SpModel::Fidelity(), SMO_DensNone/*SpModel::DensityMethod()*/, T, P, pOvr, M); double TotalF=0.0; double TotalA=0.0; for (int s=0; s<NPriIds(); s++) { if (SDB[PriSzId(s)].DensityX(C)) { double SolDens=C.Density(); CSD_SpDist & S=*PriSp[s]; for (int i=0; i<NIntervals(); i++) { const double D=MeanPartDiam(i); const double Y=3.0/GTZ(0.5*SolDens*D); // m^2/kg TotalA+=C.Mass()*Y*S.FracPass[i]; } } } return TotalA/GTZ(LiqVol); } double SolidsMass(double T, double P, SpPropOveride * pOvr, double *M) { double TotalM=0.0; for (int s=0; s<NPriIds(); s++) TotalM+=M[PriSzId(s)]; return TotalM; } /*double SolidsDensity(double T, double P, SpPropOveride * pOvr, double *M) { //double TotalM=0; //double TotalV=0; //for (int s=0; s<NPriIds(); s++) // TotalM+=M[PriSzId(s)]; //TotalM=GTZ(TotalM); //for (int s=0; s<NPriIds(); s++) // { // CSD_SpDist & S=*PriSp[s]; // //double Mult=M[PriSzId(s)]/TotalM; // //double Volume=M[PriSzId(s)]/ // for (int i=0; i<NIntervals(); i++) // { // double D=MeanPartDiam(i); // double Y=3.0/GTZ(0.5*MeanDens*D); // m^2/kg // TotalF+=Mult*S.FracPass[i]; // TotalA+=Mult*Y*S.FracPass[i]; // }; // }; //return TotalA/GTZ(TotalF); return 2420; // return TotalM; }*/ CSD_DistDefn & Defn() { return rDefn; }; char* Name() { return rDefn.sName(); }; int NameLength() { return rDefn.sName.Length(); }; CSD_Distribution(CSD_DistDefn* pDefn); CSD_Distribution(const CSD_Distribution & Other); CSD_Distribution& operator=(const CSD_Distribution & Other); virtual ~CSD_Distribution(); flag ValidateData(ValidateDataBlk & VDB); void ZeroMass(); void AddMassF(CSysVector &M1, double M1Mult, CSD_Distribution *pD2, CSysVector &M2, double M2Mult); double Crush0(C2DFn & PartFn); double Crush1(int s, C2DFn & PartFn); double Crush0(SzPartCrv1 & PartFn, int CurveNo); double Crush1(int s, SzPartCrv1 & PartFn, int CurveNo); double Break0(SzSelBrk1 & PartFn); double CrushExt0(SzPartCrv1 &Extents, CSD_Distribution &FdD, int CurveNo); double CrushExt1(int s, SzPartCrv1 &Extents, CSD_Distribution &FdD, int CurveNo); protected: void ClearWorkSpace(); void ClearWorkSpace1(); CDArray & Results() { return *pResults; }; void SetResults(CDArray & Results) { pResults=&Results; }; void DistTotals(SpPropOveride *Ovr, CSysVector &M1, int iSpPriId, double &Mass, double &Volume); void CalcDensity(SpPropOveride *Ovr, CSysVector &M1, int iSpId); double GetMass(SpPropOveride *Ovr, CSysVector &M1, int iSpId); double GetMassFrac(SpPropOveride *Ovr, CSysVector &M1, int iSpId); void GetSpCount(SpPropOveride *Ovr, CSysVector &M1, int iSpId); void GetCount(SpPropOveride *Ovr, CSysVector &M1, int iSpId); void GetCountFrac(SpPropOveride *Ovr, CSysVector &M1, int iSpId); void SetCountFrac(SpPropOveride *Ovr, CSysVector &M1, int iSpId, int iInt, double Val); void SetSpCount(SpPropOveride *Ovr, CSysVector &M1, int iSpId, int iInt, double Val); flag CalculateResults(SpPropOveride *Ovr, CSysVector &M1, int DataId, int SpId); DEFINE_SPARES(CSD_Distribution) }; // ========================================================================== // // // // ========================================================================== enum SzLabelStyles { LS_Full, LS_Short }; class DllImportExport SfeSD_Defn : public SfeInitClass, public CMdlGeneralInfo { public: SfeSD_Defn(); virtual ~SfeSD_Defn(); virtual void Clear(); virtual flag LoadConfiguration(CProfINIFile & CfgPF); virtual flag Initialise(); virtual flag Terminate(); SzLabelStyles LabelStyle() { return LblStyle; }; int NIntervals() { return Intervals.GetSize(); }; //return number of defined sieve series CSD_Intervals * GetIntervals(int i) { return Intervals[i]; }; int NDistributions() { return Distributions.GetSize(); }; //return number of defined distributions flag DistExists(int i) { return (i<Distributions.GetSize() && Distributions[i]!=NULL); }; CSD_DistDefn * GetDist(int i) { return Distributions[i]; }; int NPriIds(int i) { return (DistExists(i) ? Distributions[i]->NPriIds() : 0); }; //return number of species used in this distribution int FindIndex(int i, int SpecieId) { return (DistExists(i) ? Distributions[i]->FindPriSzIdIndex(SpecieId) : -1); }; CSD_DistDefn * FindDistributionFor(int SpecieId); virtual bool GetInfo(); CnvAttribute XCnv, YFCnv, YQmCnv, YMCnv, YNFCnv, YQnCnv, YNCnv, YNpMCnv; FmtAttribute XFmt, YFFmt, YQmFmt, YMFmt, YNFFmt, YQnFmt, YNFmt, YNpMFmt; CnvAttribute TBCnv; //top/bottom size FmtAttribute TBFmt; //top/bottom size protected: CArray <CSD_Intervals*, CSD_Intervals*> Intervals; CArray <CSD_DistDefn*, CSD_DistDefn*> Distributions; SzLabelStyles LblStyle; void ParseSeries(Strng & CurTkn, CTokenFile &Tkns); void ParseTyler(Strng & CurTkn, CTokenFile &Tkns); void ParseDistribution(Strng & CurTkn, CTokenFile &Tkns); }; // ========================================================================== extern DllImportExport SfeSD_Defn SD_Defn; //global pointer for size distribution management extern flag DllImportExport fSzAscend; // ========================================================================== // // // // ========================================================================== class DllImportExport SQSzDist1TagObjClass : public SQTagObjClass { protected: CnvAttribute FCnv; FmtAttribute FFmt; public: SQSzDist1TagObjClass(pchar pClassName, pchar pGroup_, pchar pClassId_, pchar SubClassId, pchar pVersion_, pchar pDrwGroup_, pchar pDefTag_, dword dwCat, pchar ShortDesc, pchar pDesc, DWORD SelectMask); virtual int NTearVariables(); virtual int DefineTearVariables(TearVarArray & TV, int n); }; // ========================================================================== // // // // ========================================================================== #undef DllImportExport #endif
[ [ [ 1, 47 ], [ 58, 66 ], [ 68, 68 ], [ 70, 70 ], [ 72, 96 ], [ 127, 139 ], [ 141, 180 ], [ 188, 389 ], [ 391, 574 ], [ 576, 616 ], [ 629, 631 ], [ 635, 637 ], [ 639, 640 ], [ 642, 642 ], [ 655, 658 ], [ 662, 663 ], [ 665, 665 ], [ 676, 679 ], [ 681, 684 ], [ 686, 709 ], [ 711, 841 ] ], [ [ 48, 50 ], [ 140, 140 ], [ 181, 187 ], [ 390, 390 ], [ 575, 575 ], [ 617, 628 ], [ 632, 634 ], [ 638, 638 ], [ 641, 641 ], [ 643, 654 ], [ 659, 661 ], [ 664, 664 ], [ 666, 675 ], [ 680, 680 ], [ 685, 685 ], [ 710, 710 ] ], [ [ 51, 57 ], [ 67, 67 ], [ 69, 69 ], [ 71, 71 ], [ 97, 126 ] ] ]
57d798ca09aa66ad78dd3cbed5b7cc22fce6b830
93eac58e092f4e2a34034b8f14dcf847496d8a94
/ncl30-cpp/ncl30-generator/src/CausalLinkGenerator.cpp
4fe9a3184062f2b854290ca6627021eaa922d803
[]
no_license
lince/ginga-srpp
f8154049c7e287573f10c472944315c1c7e9f378
5dce1f7cded43ef8486d2d1a71ab7878c8f120b4
refs/heads/master
2020-05-27T07:54:24.324156
2011-10-17T13:59:11
2011-10-17T13:59:11
2,576,332
0
0
null
null
null
null
UTF-8
C++
false
false
4,095
cpp
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file CausalLinkGenerator.cpp * @author Caio Viel * @date 29-01-10 */ #include "../include/generables/CausalLinkGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generator { string CausalLinkGenerator::generateCode(ConnectorBase* connectorBase) { HLoggerPtr logger = LoggerUtil::getLogger("br.ufscar.lince.ncl.generate.CausalLinkGenerator"); string ret = "<link "; string id = this->getId(); if (id!= "") { ret += "id=\"" + id + "\" "; } Connector* connector = this->getConnector(); ret += "xconnector=\""; if (!connectorBase->containsConnector(connector)) { vector<Base*>* bases = connectorBase->getBases(); if (bases != NULL) { bool find = false; for (int i=0; i < bases->size(); i++) { ConnectorBase* connectorBaseAux = (ConnectorBase*)(*bases)[i]; if (connectorBaseAux->containsConnector(connector)) { ret += connectorBase->getBaseAlias((*bases)[i]) + "#"; find = true; break; } } if (!find) { LoggerUtil_error(logger, "Connector não encontrado em nenhuma base!"); } } else { LoggerUtil_error(logger, "Connector não encontrado em nenhuma base!"); } } ret += connector->getId() + "\" >"; vector<Parameter*>* parameters = this->getParameters(); if (parameters != NULL) { vector<Parameter*>::iterator itParam; itParam = parameters->begin(); while (itParam != parameters->end()) { Parameter* parameter = *itParam; ret += static_cast<ParameterGenerator*>(parameter)->generateCode("linkParam", "value"); itParam++; } } vector<Bind*>* binds = this->getBinds(); vector<Bind*>::iterator itBind; itBind = binds->begin(); while (itBind != binds->end()) { Bind* bind = *itBind; ret += (static_cast<BindGenerator*>(bind))->generateCode() + "\n"; itBind++; } ret += "</link>\n"; return ret; } } } } } }
[ [ [ 1, 120 ] ] ]
5fc26e55ab3d129010535be62496550ae123f2bf
27687dfacdfa03f7a1f509e36e848fa1767f47b3
/Addonissimo2/main.cpp
ad5a66fc2d8ab91d66059c7aba4dcc8183275064
[]
no_license
Gbps/gmod
7f11a79e439c2c63233ad9dcc2e3c32e6c8ceb95
125f7c94e5732abc4dac441181bc3bad51c7aa23
refs/heads/master
2022-06-20T18:36:45.742134
2011-08-04T03:08:58
2011-08-04T03:08:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,817
cpp
#define GMOD_MODULE_PRINTINFO #define GMOD_MODULE_AUTHOR "Gbps" #define GMOD_MODULE_NAME "gm_addonissimo" #define GMOD_MODULE_VERSION "1.0" #include "includes/GmodModuleConfig.h" #include <string.h> #include <iostream> #include "includes/csimpledetour.h" #include "includes/csimplescan.h" #include "includes/cdetour.h" #include "eiface.h" #pragma warning (disable : 4099 4075 4996) using namespace std; // Yeah yeah ////////////////////////////////////////////////////////////////////////// // Addon Loading Detours // ////////////////////////////////////////////////////////////////////////// bool _AddonLoadDetour(const char* sScriptLoadPath, const char* sScriptSideIdent){ string path (sScriptLoadPath); size_t AddonPos = path.find("addons/"); if (AddonPos == string::npos) return true; // Not loading an addon, so go ahead and load whatever it is... string SubStrCheck = path.substr(path.length()-4); if (SubStrCheck.compare("/lua") != 0) return true; // This should never really happen... string FolderName = path.substr(AddonPos+7,(path.length()-4)-(AddonPos+7)); // Extract the folder name ILuaObject *hookT = gLua->GetGlobal("hook"); ILuaObject *callM = hookT->GetMember("Call"); gLua->Push(callM); gLua->Push("ShouldLoadAddon"); gLua->PushNil(); gLua->Push(FolderName.c_str()); gLua->Push(sScriptSideIdent); callM->UnReference(); hookT->UnReference(); gLua->Call(4, 1); ILuaObject *retL = gLua->GetReturn(0); bool bState = (retL->isNil() || retL->GetBool()); retL->UnReference(); return bState; } ILuaShared* oILuaShared = NULL; typedef void (__stdcall * MountLuaAdd_t) (const char * sPath, const char* pathID); MountLuaAdd_t MountLuaAdd_o = NULL; typedef DWORD (__cdecl * GetILuaShared_t)(); GetILuaShared_t GetILuaShared = NULL; void __stdcall MountLuaAdd_d(const char * sPath, const char* pathID){ void * pThis = NULL; __asm mov pThis, ecx if (_AddonLoadDetour(sPath, pathID)){ __asm { push pathID push sPath mov ecx, pThis call MountLuaAdd_o; } } } LUA_FUNCTION (ReloadAddonList){ int* AddonNumber = reinterpret_cast<int*>(((PBYTE)oILuaShared)+0x802C); if (AddonNumber == NULL) { Warning("Addon number was 0 or NULL?\n"); return 0; } (*AddonNumber) = 0; // Basically we're forcing the size to 0. Not a very good way of doing it tbh, but it works. // It's probably a std::map, which means it will grow to the maximum size it needs. // Even if there were old entries, it should overwrite them, so it shouldn't be too horribly bad :F // But memory leaks... who knows :( oILuaShared->MountAddons(); return 0; } CSimpleScan Scanner("lua_shared.dll"); CSimpleScan ScannerCl("client.dll"); //////////////////////////////////////////////////////////////////////////// // End Addon Loading Detours // ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // Begin Command Hooking // ////////////////////////////////////////////////////////////////////////// IVEngineServer* g_Engine = NULL; typedef void (__cdecl * ExecuteCmdString_t)(const char* cmdStr); PBYTE pb_orig_ExecuteString = NULL; ExecuteCmdString_t tramp_ExecuteString = NULL; void __stdcall ExecuteCmdString_d(const char* cmdStr){ void* retAddr = NULL; void* pThis = NULL; __asm mov pThis, ecx ILuaObject *hookT = gLua->GetGlobal("hook"); ILuaObject *callM = hookT->GetMember("Call"); gLua->Push(callM); gLua->Push("OnCommandRan"); gLua->PushNil(); gLua->Push(cmdStr); callM->UnReference(); hookT->UnReference(); gLua->Call(3, 1); ILuaObject *retL = gLua->GetReturn(0); bool bState = (retL->isNil() || retL->GetBool()); retL->UnReference(); if (bState){ __asm{ MOV ECX,pThis PUSH cmdStr CALL tramp_ExecuteString } } } LUA_FUNCTION (ExecuteCmdString){ gLua = Lua(); gLua->CheckType(1,GLua::TYPE_STRING); g_Engine->ServerCommand(gLua->GetString()); return 0; } CSimpleScan EngineScanner("engine.dll"); //////////////////////////////////////////////////////////////////////////// // End Command Hooking // ////////////////////////////////////////////////////////////////////////// CDetour cdetours; int Init(lua_State* L) { gLua = Lua(); GMOD_MODULE_PRINTAUTHOR(); g_Engine = ( IVEngineServer* ) Sys_GetFactory("engine.dll")( INTERFACEVERSION_VENGINESERVER, NULL ); ILuaObject* tbl = gLua->GetGlobal("Addonissimo"); tbl->SetMember("ExecuteClientCmd",ExecuteCmdString); tbl->SetMember("ReloadAddonList",ReloadAddonList); tbl->UnReference(); PBYTE luaSharedCallAddr = (PBYTE)ScannerCl.FindPointer("\xE8\x48\xD8\xFF\xFF\x8B\x0D\x9C\xFD\x4D\x18\x83\x79\x14\x01\x8D\x4C\x24\x03\x51\x0F\x9F\xC2\x88\x54\x24\x08\x8B\x4C\x24\x08\x8B","x????xx????xxxxxxxxxxxxxxx?xxx?x"); if (luaSharedCallAddr == NULL){ gLua->Error("*********************************************************\n"); gLua->Error("* Vtable signature failed... Post about it! *\n"); gLua->Error("*********************************************************\n"); return 1; } int luaSharedOffset = *(reinterpret_cast<int*>(luaSharedCallAddr+1)); PBYTE luaSharedFuncAddr = luaSharedCallAddr + luaSharedOffset + 5; GetILuaShared = (GetILuaShared_t)luaSharedFuncAddr; DWORD ILuaSharedAddr = GetILuaShared(); oILuaShared = reinterpret_cast<ILuaShared*>(ILuaSharedAddr); void*** ILuaSharedVTable = (void***)ILuaSharedAddr; void* MountLuaAdd_a = (*ILuaSharedVTable)[16]; pb_orig_ExecuteString = (PBYTE)EngineScanner.FindPointer("\x8B\x44\x24\x04\x50\xE8\x56\x6C\xF5\xFF\x68\x04\x8C\x2D\x10\xE8\x4C\x6C\xF5\xFF\x83\xC4\x08\xC2\x04\x00","x?xx?x????x????x????xx?xxx"); if (pb_orig_ExecuteString == NULL){ gLua->Msg("**** Addonissimo failed to load command hooking interface... Functionality has been disabled!\n"); }else{ tramp_ExecuteString = (ExecuteCmdString_t)cdetours.Create((PBYTE)pb_orig_ExecuteString, (PBYTE)&ExecuteCmdString_d, DETOUR_TYPE_JMP); } if (MountLuaAdd_a != NULL){ MountLuaAdd_o = (MountLuaAdd_t)cdetours.Create((PBYTE)MountLuaAdd_a, (PBYTE)&MountLuaAdd_d, DETOUR_TYPE_JMP); }else{ gLua->Msg("*********************************************************\n"); gLua->Msg("* LoadAddon function failed... Post about it! *\n"); gLua->Msg("*********************************************************\n"); return 1; } return 0; } int Shutdown(lua_State* L) { return 0; }
[ "cowmonkey111@ea4bc6c7-d654-2506-312e-aa9fc04bc719" ]
[ [ [ 1, 210 ] ] ]
1c992afa9ddab5840ac3f01764744900aef1269b
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Common/Internal/GeometryProcessing/Topology/hkgpTopology.inl
478190b28fc155e3a0d9dc29b0a6f63572469d2c
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,464
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. * */ TOPOLOGY_HDR HK_FORCE_INLINE unsigned TOPOLOGY_TYP::ip1mod3(unsigned i) { HK_ASSERT(0x23be31ed, i<3); #ifdef HK_ARCH_PPC // Variable shifts are slow on PowerPC consoles. // The ternary op should be pretty easy to optimize, however const unsigned mod3 = (i==2) ? 0 : i+1; return mod3; #else return((0x09>>(i<<1))&3); #endif } TOPOLOGY_HDR HK_FORCE_INLINE unsigned TOPOLOGY_TYP::ip2mod3(unsigned i) { HK_ASSERT(0x23be31ed, i<3); #ifdef HK_ARCH_PPC unsigned mod3 = (i==0) ? 2 : i-1; return mod3; #else return((0x12>>(i<<1))&3); #endif } // TOPOLOGY_HDR HK_FORCE_INLINE void TOPOLOGY_TYP::bind(const Edge& edge) const { #if defined(HK_DEBUG) if(!canBind(edge)) { bool found=false; for(int i=2,j=0;j<3;i=j++) { if(edge.triangle()->vertex(i)==end() && edge.triangle()->vertex(j)==start()) { HK_REPORT("Edge index should be "<<i<<" instead of "<<edge.index()); found=true;break; } } if(!found) HK_REPORT("Incorrect triangle bind"); } #endif HK_ASSERT2(0x9801541,canBind(edge),"Incorrect edge bind"); m_triangle->link(m_index)=edge.uid(); if(edge.isValid()) edge.m_triangle->link(edge.m_index)=uid(); } // TOPOLOGY_HDR HK_FORCE_INLINE void TOPOLOGY_TYP::bindSides() const { EDGE n=next().link(),p=prev().link(); if(p.isValid()) { EDGE t=n;n=p;p=t; } if(n.isValid()) { n.bind(p); next().bind(null()); prev().bind(null()); } } // TOPOLOGY_HDR HK_FORCE_INLINE void TOPOLOGY_TYP::unbind() const { if(!isNaked()) { EDGE l=link(); l.m_triangle->link(l.m_index)=0; } m_triangle->link(m_index)=0; } // TOPOLOGY_HDR HK_FORCE_INLINE EDGE TOPOLOGY_TYP::flip() const { const Edge lk=link(); const Edge ep=prev(); const Edge lp=lk.prev(); start()=lp.start(); lk.start()=ep.start(); lk.bind(ep.link()); bind(lp.link()); ep.bind(lp); return(prev()); } // TOPOLOGY_HDR template <typename FNC> HK_FORCE_INLINE void TOPOLOGY_TYP::applyFan(FNC& fnc) const { EDGE base(self()); EDGE curr(base); do { if(fnc(curr)) curr=curr.turnCw(); else return; } while(curr.isValid() && (curr!=base)); if(!curr.isValid()) { curr=base.turnCcw(); while(curr.isValid()) { if(fnc(curr)) curr=curr.turnCcw(); else return; } } } /* * 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, 131 ] ] ]
52a5e37af30808acd5cf4a9f68b2bc4f1847c17c
cfa667b1f83649600e78ea53363ee71dfb684d81
/code/render/input/win32/win32inputdisplayeventhandler.cc
f86ccd03bf054011f12b3b298d452119ea03bcdd
[]
no_license
zhouxh1023/nebuladevice3
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
refs/heads/master
2021-01-23T08:56:15.823698
2011-08-26T02:22:25
2011-08-26T02:22:25
32,018,644
0
1
null
null
null
null
UTF-8
C++
false
false
4,167
cc
//------------------------------------------------------------------------------ // win32inputdisplayeventhandler.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "input/win32/win32inputdisplayeventhandler.h" #include "input/inputserver.h" #include "input/inputevent.h" namespace Win32 { __ImplementClass(Win32::Win32InputDisplayEventHandler, 'WIEH', CoreGraphics::ThreadSafeDisplayEventHandler); using namespace Input; using namespace CoreGraphics; //------------------------------------------------------------------------------ /** */ bool Win32InputDisplayEventHandler::HandleEvent(const DisplayEvent& displayEvent) { InputEvent inputEvent; InputServer* inputServer = InputServer::Instance(); switch (displayEvent.GetEventCode()) { case DisplayEvent::CloseRequested: inputServer->SetQuitRequested(true); break; case DisplayEvent::DisplayMinimized: case DisplayEvent::KillFocus: inputEvent.SetType(InputEvent::AppLoseFocus); inputServer->PutEvent(inputEvent); XInputEnable(false); return true; case DisplayEvent::DisplayRestored: case DisplayEvent::SetFocus: inputEvent.SetType(InputEvent::AppObtainFocus); inputServer->PutEvent(inputEvent); XInputEnable(true); return true; case DisplayEvent::KeyDown: inputEvent.SetType(InputEvent::KeyDown); inputEvent.SetKey(displayEvent.GetKey()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::KeyUp: inputEvent.SetType(InputEvent::KeyUp); inputEvent.SetKey(displayEvent.GetKey()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::Character: inputEvent.SetType(InputEvent::Character); inputEvent.SetChar(displayEvent.GetChar()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::MouseButtonDown: inputEvent.SetType(InputEvent::MouseButtonDown); inputEvent.SetMouseButton(displayEvent.GetMouseButton()); inputEvent.SetAbsMousePos(displayEvent.GetAbsMousePos()); inputEvent.SetNormMousePos(displayEvent.GetNormMousePos()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::MouseButtonUp: inputEvent.SetType(InputEvent::MouseButtonUp); inputEvent.SetMouseButton(displayEvent.GetMouseButton()); inputEvent.SetAbsMousePos(displayEvent.GetAbsMousePos()); inputEvent.SetNormMousePos(displayEvent.GetNormMousePos()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::MouseButtonDoubleClick: inputEvent.SetType(InputEvent::MouseButtonDoubleClick); inputEvent.SetMouseButton(displayEvent.GetMouseButton()); inputEvent.SetAbsMousePos(displayEvent.GetAbsMousePos()); inputEvent.SetNormMousePos(displayEvent.GetNormMousePos()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::MouseMove: inputEvent.SetType(InputEvent::MouseMove); inputEvent.SetAbsMousePos(displayEvent.GetAbsMousePos()); inputEvent.SetNormMousePos(displayEvent.GetNormMousePos()); inputEvent.SetDragging(displayEvent.Dragging()); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::MouseWheelForward: inputEvent.SetType(InputEvent::MouseWheelForward); inputServer->PutEvent(inputEvent); return true; case DisplayEvent::MouseWheelBackward: inputEvent.SetType(InputEvent::MouseWheelBackward); inputServer->PutEvent(inputEvent); return true; } return false; } } // namespace Win32
[ [ [ 1, 108 ] ] ]
3c8741af5f0b5ac7e1185263431bec7aee4460e3
83c85d3cae31e27285ca07e192cc9bbad8081736
/SetArea.cpp
704ea0cc24f977c0d0e54cb925e0eba25cf6cefa
[]
no_license
yjfcool/poitool
0768d7299a453335cbd1ae1045440285b3295801
1068837ab32dbb9c6df18bbab1ea64bc70942cbf
refs/heads/master
2016-09-05T11:37:18.585724
2010-04-09T06:16:14
2010-04-09T06:16:14
42,576,080
0
0
null
null
null
null
GB18030
C++
false
false
4,431
cpp
// SetArea.cpp : implementation file // #include "stdafx.h" #include "poiview.h" #include "SetArea.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSetArea dialog CSetArea::CSetArea(CWnd* pParent /*=NULL*/) : CDialog(CSetArea::IDD, pParent) { //{{AFX_DATA_INIT(CSetArea) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } void CSetArea::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSetArea) DDX_Control(pDX, IDC_CBCITY, m_cbCity); DDX_Control(pDX, IDC_CBCOUNTRY, m_cbCountry); DDX_Control(pDX, IDC_CBPROVINCE, m_cbProvince); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSetArea, CDialog) //{{AFX_MSG_MAP(CSetArea) ON_CBN_SELCHANGE(IDC_CBPROVINCE, OnSelchangeCbprovince) ON_CBN_SELCHANGE(IDC_CBCOUNTRY, OnSelchangeCbcountry) ON_CBN_SELCHANGE(IDC_CBCITY, OnSelchangeCbcity) ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSetArea message handlers void CSetArea::OnOK() { // TODO: Add extra validation here m_ipro = m_cbProvince.GetCurSel(); m_icity = m_cbCity.GetCurSel(); m_icountry = m_cbCountry.GetCurSel(); CDialog::OnOK(); } void CSetArea::rebulid(const pod_vector<Lemon<zone>*>* province, const pod_vector<Lemon<zone>*>* city, const pod_vector<Lemon<zone>*>* country) { CString xx; unsigned i = 0; char str[50] = {0}; m_p_province = (pod_vector<Lemon<zone>*>*)province; m_p_city = (pod_vector<Lemon<zone>*>*)city; m_p_country = (pod_vector<Lemon<zone>*>*)country; m_ipro = -1; m_icity = -1; m_icountry = -1; m_iCityBegin = 0; m_iCountryBegin = 0; m_cbProvince.ResetContent(); for(i = 0; i < (*province).size(); i++) { b_char_mem str; (*m_p_province)[i]->m_Kernel.name(str); m_cbProvince.AddString((char*)str.m_buf); } m_cbProvince.SetCurSel(0); UpdateAdmin(0,0,0); UpdateData(FALSE); } //pro,city,country全部为相对索引 void CSetArea::UpdateAdmin(int pro, int city, int country) { m_iCityBegin = 0; m_iCountryBegin = 0; int cur_country = country; int i = 0; b_char_mem str; m_cbCity.ResetContent(); m_cbCountry.ResetContent(); if (pro >= 0 && pro < (*m_p_province).size()) { Lemon<zone>* p = (*m_p_province)[pro]; m_cbProvince.SetCurSel(pro); for(i = 0; i < p->child_num(); i++) { p->child[i].m_Kernel.name(str); m_cbCity.AddString((char*)str.m_buf); } for(i = 0; i < pro; i++) m_iCityBegin += (*m_p_province)[i]->child_num(); if (city >= 0 && city < p->child_num()) { m_cbCity.SetCurSel(city); if (cur_country >= 0) { p = (*m_p_city)[city+m_iCityBegin]; for(i = 0; i < p->child_num(); i++) { p->child[i].m_Kernel.name(str); m_cbCountry.AddString((char*)str.m_buf); } for(i = 0; i < city+m_iCityBegin; i++) m_iCountryBegin += (*m_p_city)[i]->child_num(); if (country >= 0 && country < p->child_num()) m_cbCountry.SetCurSel(country); } } } UpdateData(FALSE); } void CSetArea::get_admin(int& pro, int& city, int& county) { if (m_ipro == -1 || m_icity == -1) { m_ipro = 0; m_icity = 0; } pro = m_ipro; city = m_icity + m_iCityBegin; county = m_icountry + m_iCountryBegin; } void CSetArea::OnSelchangeCbprovince() { // TODO: Add your control notification handler code here UpdateData(); int cur_pro = m_cbProvince.GetCurSel(); UpdateAdmin(cur_pro, 0, 0); } void CSetArea::OnSelchangeCbcountry() { // TODO: Add your control notification handler code here } void CSetArea::OnSelchangeCbcity() { // TODO: Add your control notification handler code here UpdateData(); int cur_pro = m_cbProvince.GetCurSel(); int cur_city = m_cbCity.GetCurSel(); UpdateAdmin(cur_pro, cur_city, 0); } int CSetArea::DoModal() { return CDialog::DoModal(); } int CSetArea::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here m_ipro = -1; m_icity = -1; m_icountry = -1; m_iCityBegin = 0; m_iCountryBegin = 0; return 0; }
[ "dulton@370d939e-410d-02cf-1e1d-9a5f4ca5de21" ]
[ [ [ 1, 196 ] ] ]
33536d908eadb204888a8a686c32b992e73f8587
8ad5d6836fe4ad3349929802513272db86d15bc3
/lib/Spin/Exceptions/HTTP/UnsupportedProtocol.h
127b6cc86f5e8fe398888ce407c1e8ff66e36b05
[]
no_license
blytkerchan/arachnida
90a72c27f0c650a6fbde497896ef32186c0219e5
468f4ef6c35452de3ca026af42b8eedcef6e4756
refs/heads/master
2021-01-10T21:43:51.505486
2010-03-12T04:02:19
2010-03-12T04:02:42
2,203,393
0
1
null
null
null
null
UTF-8
C++
false
false
2,045
h
#ifndef _spin_exceptions_http_unsupportedprotocol_h #define _spin_exceptions_http_unsupportedprotocol_h #include <algorithm> #include <iterator> namespace Spin { namespace Exceptions { namespace HTTP { //! Thrown when an unsupported protocol and/or protocol version is used struct SPIN_API UnsupportedProtocol : public HTTPProtocolError { enum { max_protocol_size__ = 96 ///< Maximum expected size of a protocol name }; //! Construct from a range of chars containing the protocol name template < typename Iterator > UnsupportedProtocol(Iterator begin, Iterator end) : HTTPProtocolError("Unsupported protocol."), what_(0) { Iterator where(end); if (std::distance(begin, where) > max_protocol_size__) { where = begin; std::advance(where, static_cast< typename std::iterator_traits< Iterator >::difference_type >(max_protocol_size__)); } else { /* all is well */ } char * start(std::copy(begin, where, protocol_)); *start = 0; } //! Copy-constructor UnsupportedProtocol(const UnsupportedProtocol & e) : HTTPProtocolError(e), what_(e.what_) { std::copy(e.protocol_, e.protocol_ + max_protocol_size__, protocol_); e.what_ = 0; } //! No-fail destructor ~UnsupportedProtocol() throw() { delete[] what_; // Assuming what_ was created with new[] } //! Assignment operator UnsupportedProtocol & operator=(UnsupportedProtocol e) { return swap(e); } //! no-fail swap UnsupportedProtocol & swap(UnsupportedProtocol & e) throw() { std::swap_ranges(e.protocol_, e.protocol_ + max_protocol_size__, protocol_); std::swap(what_, e.what_); return *this; } //! No-fail what, returns a default string if anything does fail virtual const char * what() const throw(); char protocol_[max_protocol_size__ + 1]; mutable char * what_; }; } } } #endif
[ [ [ 1, 4 ], [ 6, 13 ], [ 15, 15 ], [ 19, 19 ], [ 21, 22 ], [ 25, 29 ], [ 31, 37 ], [ 39, 39 ], [ 42, 46 ], [ 49, 52 ], [ 54, 56 ], [ 58, 64 ], [ 66, 75 ] ], [ [ 5, 5 ], [ 14, 14 ], [ 16, 18 ], [ 20, 20 ], [ 23, 24 ], [ 30, 30 ], [ 38, 38 ], [ 40, 41 ], [ 47, 48 ], [ 53, 53 ], [ 57, 57 ], [ 65, 65 ] ] ]
3bee4a1d2bf1ff3d3b4b9e9ac5204c945cb6b72b
ee065463a247fda9a1927e978143186204fefa23
/Src/Engine/Player/Agent.h
311cfe5121d54cd986c5ed559a6905abad754209
[]
no_license
ptrefall/hinsimviz
32e9a679170eda9e552d69db6578369a3065f863
9caaacd39bf04bbe13ee1288d8578ece7949518f
refs/heads/master
2021-01-22T09:03:52.503587
2010-09-26T17:29:20
2010-09-26T17:29:20
32,448,374
1
0
null
null
null
null
UTF-8
C++
false
false
950
h
#pragma once #include "IPlayer.h" #include <vector> namespace Engine { namespace Player { class Agent : public IPlayer { public: Agent(unsigned int id, const CL_String &name, Core::CoreManager *coreMgr); virtual ~Agent(); virtual unsigned int getId() { return id; } virtual const CL_String &getName() { return name; } virtual void addGO(Scene::Object *go); virtual void removeGO(Scene::Object *go); virtual Scene::Object *getGO(unsigned int i); virtual unsigned int getGOCount() const; virtual void sendCommand(const CL_String &command); virtual void sendEvent(const Events::IEvent &event); virtual void hover(const CL_Vec3i &abs, const CL_Vec3i &rel) {} virtual CL_Vec3f getFocusPoint() { return CL_Vec3f(); } virtual CL_Vec3f getRelativeFocus() { return CL_Vec3f(); } private: Core::CoreManager *coreMgr; unsigned int id; CL_String name; std::vector<Scene::Object*> gos; }; } }
[ "[email protected]@28a56cb3-1e7c-bc60-7718-65c159e1d2df" ]
[ [ [ 1, 42 ] ] ]
7be6edda74f5a7913fae142dd5f03482d2718984
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/extensions/PythonBindings/common/src/Export.cpp
e30f3ab77622b73d69511df0ad83cc8c572bbd3a
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
139
cpp
#include "stdafx.h" #include "PyContainers.h" #include <boost/python.hpp> BOOST_PYTHON_MODULE(common) { exportContainers(); }
[ "devnull@localhost" ]
[ [ [ 1, 8 ] ] ]
7cd9e4ec2abab47785b202e4b481a9030dde9ff8
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthread.cpp
c07475e39060c711c7ffd1821bee06c6d78bc62c
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
cpp
/* * Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: POSIX implementation of pthread on Symbian * */ #include <stddef.h> #include <limits.h> #include <e32def.h> #include <e32std.h> #include <stdlib.h> #include <errno.h> #include "pthread.h" #ifdef __SYMBIAN_COMPILE_UNUSED__ int pthread_cancel (pthread_t /*thread*/) { return ENOSYS; } int pthread_setcancelstate (int /*state*/, int* /*oldstate*/) { return ENOSYS; } int pthread_setcanceltype (int /*type*/, int* /*oldtype*/) { return ENOSYS; } #endif void pthread_testcancel (void) { return; } // End of File
[ "none@none" ]
[ [ [ 1, 50 ] ] ]
e7c9fdc7f4d8436c6402bedb9fbcc597a3d8e4ad
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/SRC/Model/AppModel.cpp
ffff7b3d6405c50d3778963408238022e133ef29
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
GB18030
C++
false
false
5,526
cpp
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: #include "AppModel.h" AppModel::AppModel(void) //描述:构造函数,空 { SetLastError(ERROR_MODEL_SUCCESS); } AppModel::AppModel(string StrScriptCache):bprivateCache(true) //根据ConfigCachePath路径构造配置缓存,指针赋给pConfigCache { CFileScript *f = new CFileScript(StrScriptCache); if (!f->LoadFile()) { cout << f->GetLastError()<<":"<<f->GetLastErrorIdentify()<<":"<< f->GetLastErrorEx()<<"\n"<<endl; } else { pScriptCache = f; } SetLastError(ERROR_MODEL_SUCCESS); } AppModel::~AppModel(void) //描述:析构函数 { if (bprivateCache)//类内部创建的配置缓存对象,应销毁 { //销毁pConfigCache delete pScriptCache; } } void AppModel::AttachNode(Node *n) /* 描述:将结点与模型对象和相关的自定义部件进行绑定, 备注:所有继承该方法的子类应先调用这个方法 */ { node = n; //遍历ElementIndex中需要绑定结点的自定义部件 //绑定到和结点相关的自定义部件上 map<int, ElementStruct>::iterator it = ElementIndex.begin(); while(it != ElementIndex.end()) { if ((it->second).RevelantToNode)//需要绑定结点到自定义部件 { (it->second).thisElement.AttachNode(n); } ++it; } } Size_t AppModel::AddElement(int id, bool revelantToNode, string strSectionName) //描述:增加一个自定义部件到ElementIndex,返回当前ElementIndex中剩余的Element个数 { //首先看该id是否已存在 if (ElementIndex.count(id)) { SetLastError(ERROR_MODEL_INSERT_EXIST); return ElementIndex.size(); } CElementCustom ce; if(!pScriptCache->InitCustomElementBySectionName(strSectionName, ce)) { SetLastError(ERROR_MODEL_WHEN_INIT_CUSTOMELEMENT); return ElementIndex.size(); } ElementStruct eStruct; eStruct.ID = id; eStruct.RevelantToNode = revelantToNode; eStruct.thisElement = ce; ElementIndex.insert(make_pair(id, eStruct)); return ElementIndex.size(); } Size_t AppModel::DeleteElement(int id) //描述:删除ID为id的自定义部件,返回当前ElementIndex中剩余的Element个数 { int flag = ElementIndex.erase(id); if (!flag) SetLastError(ERROR_MODEL_DELETE_NOT_EXIST); return ElementIndex.size(); } double AppModel::GetElementValueById(int id) //描述:调用自定义部件类的相关方法,获得ID为id的自定义部件的值,并返回 { map<int, ElementStruct>::iterator it = ElementIndex.find(id); if (it != ElementIndex.end()) { return it->second.thisElement.GetValue(); } else { SetLastError(ERROR_MODEL_GET_NOT_EXIST); return -1; } } string AppModel::GetLastErrorEx() /* #define ERROR_MODEL_SUCCESS ERROR_NO_ERROR #define ERROR_MODEL_INSERT_EXIST 0x00050201 #define ERROR_MODEL_DELETE_NOT_EXIST 0x00050202 #define ERROR_MODEL_GET_NOT_EXIST 0x00050203 */ { switch (GetLastError()) { case ERROR_MODEL_SUCCESS: return "Model successfully"; case ERROR_MODEL_INSERT_EXIST: return "When insert by id, this element_id already exist"; case ERROR_MODEL_DELETE_NOT_EXIST: return "When delete by id, this element_id does not exist"; case ERROR_MODEL_GET_NOT_EXIST: return "When get by id, this element_id does not exist"; case ERROR_MODEL_WHEN_INIT_CUSTOMELEMENT: return "Error when init custom element"; default: return "UNKNOWN"; } }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 191 ] ] ]
a504a1231a1bff742feddd24fefc68b4c061e331
6baa03d2d25d4685cd94265bd0b5033ef185c2c9
/TGL/src/objects/TGLobject_ship.cpp
022c65c5a2833f182ee065496f3ce4a144f935d4
[]
no_license
neiderm/transball
6ac83b8dd230569d45a40f1bd0085bebdc4a5b94
458dd1a903ea4fad582fb494c6fd773e3ab8dfd2
refs/heads/master
2021-01-10T07:01:43.565438
2011-12-12T23:53:54
2011-12-12T23:53:54
55,928,360
0
0
null
null
null
null
UTF-8
C++
false
false
2,646
cpp
#ifdef KITSCHY_DEBUG_MEMORY #include "debug_memorymanager.h" #endif #ifdef _WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include "math.h" #include "string.h" #include "gl.h" #include "glu.h" #include "SDL.h" #include "SDL_mixer.h" #include "SDL_ttf.h" #include "List.h" #include "Symbol.h" #include "2DCMC.h" #include "auxiliar.h" #include "GLTile.h" #include "2DCMC.h" #include "sound.h" #include "keyboardstate.h" #include "randomc.h" #include "VirtualController.h" #include "GLTManager.h" #include "SFXManager.h" #include "TGLobject.h" #include "TGLobject_ship.h" #include "TGLmap.h" #include "debug.h" TGLobject_ship::TGLobject_ship(float x,float y,int initial_fuel) : TGLobject(x,y,0) { m_speed_x=0; m_speed_y=0; m_thrust_channel=-1; m_fuel_channel=-1; m_fuel=(initial_fuel/2)*64; m_fuel_recharging_timmer=0; } /* TGLobject_ship::TGLobject_ship */ TGLobject_ship::~TGLobject_ship() { if (m_thrust_channel!=-1) { Mix_HaltChannel(m_thrust_channel); m_thrust_channel=-1; } // if if (m_fuel_channel!=-1) { Mix_HaltChannel(m_fuel_channel); m_fuel_channel=-1; } // if } /* TGLobject_ship::~TGLobject_ship */ void TGLobject_ship::draw(GLTManager *GLTM) { } /* TGLobject_ship::draw */ bool TGLobject_ship::is_a(Symbol *c) { if (c->cmp("TGLobject_ship")) return true; return TGLobject::is_a(c); } /* TGLobject_ship::is_a */ bool TGLobject_ship::is_a(char *c) { bool retval; Symbol *s=new Symbol(c); retval=is_a(s); delete s; return retval; } /* TGLobject_ship::is_a */ const char *TGLobject_ship::get_class(void) { return "TGLobject_ship"; } /* TGLobject_ship:get_class */ int TGLobject_ship::get_fuel(void) { return m_fuel; } /* TGLobject_ship::get_fuel */ void TGLobject_ship::recharge_fuel(SFXManager *SFXM,int sfx_volume) { if (m_fuel<m_max_fuel) { m_fuel+=8; if (m_fuel>m_max_fuel) m_fuel=m_max_fuel; if (m_fuel_channel==-1) { m_fuel_channel=Sound_play_continuous(SFXM->get("sfx/fuel"),sfx_volume); } // if m_fuel_recharging_timmer=2; } // if } /* TGLobject_ship::recharge_fuel */ float TGLobject_ship::get_speedx(void) { return m_speed_x; } /* TGLobject_ship::get_speedx */ float TGLobject_ship::get_speedy(void) { return m_speed_y; } /* TGLobject_ship::get_speedy */ void TGLobject_ship::set_speedx(float speedx) { m_speed_x=speedx; } /* TGLobject_ship::set_speedx */ void TGLobject_ship::set_speedy(float speedy) { m_speed_y=speedy; } /* TGLobject_ship::set_speedy */
[ "santi.ontanon@535450eb-5f2b-0410-a0e9-a13dc2d1f197" ]
[ [ [ 1, 142 ] ] ]
34bdab6235b2f72978899194bed46ff68a776cff
61352a7371397524fe7dcfab838de40d502c3c9a
/server/Sources/Observers/IRemoteObserver.cpp
20cffc417844a3e28db81a6d3434a321e6232253
[]
no_license
ustronieteam/emmanuelle
fec6b6ccfa1a9a6029d8c3bb5ee2b9134fccd004
68d639091a781795d2e8ce95c3806ce6ae9f36f6
refs/heads/master
2021-01-21T13:04:29.965061
2009-01-28T04:07:01
2009-01-28T04:07:01
32,144,524
2
0
null
null
null
null
UTF-8
C++
false
false
131
cpp
#include "Observers/IRemoteObserver.h" IRemoteObserver::IRemoteObserver() { } IRemoteObserver::~IRemoteObserver() { }
[ "coutoPL@c118a9a8-d993-11dd-9042-6d746b85d38b" ]
[ [ [ 1, 9 ] ] ]
a91abd19900f496a5c480ffef13934398e3d0821
27c6eed99799f8398fe4c30df2088f30ae317aff
/rtt-tool/qdoc3/cppcodemarker.cpp
ea6d90f44e88fd849387f82f9cf8ff4b14370478
[]
no_license
lit-uriy/ysoft
ae67cd174861e610f7e1519236e94ffb4d350249
6c3f077ff00c8332b162b4e82229879475fc8f97
refs/heads/master
2021-01-10T08:16:45.115964
2009-07-16T00:27:01
2009-07-16T00:27:01
51,699,806
0
0
null
null
null
null
UTF-8
C++
false
false
35,772
cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ /* cppcodemarker.cpp */ #include "atom.h" #include "cppcodemarker.h" #include "node.h" #include "text.h" #include "tree.h" QT_BEGIN_NAMESPACE static int insertTagAround(QString &result, int pos, int len, const QString &tagName, const QString &attributes = QString()) { QString s; //s.reserve(result.size() + tagName.size() * 2 + attributes.size() + 20); s += result.midRef(0, pos); s += QLatin1Char('<'); s += tagName; if (!attributes.isEmpty()) { s += QLatin1Char(' '); s += attributes; } s += QLatin1Char('>'); s += result.midRef(pos, len); s += QLatin1String("</"); s += tagName; s += QLatin1Char('>'); s += result.midRef(pos + len); int diff = s.length() - result.length(); result = s; return diff; } /*! The constructor does nothing. */ CppCodeMarker::CppCodeMarker() { // nothing. } /*! The destructor does nothing. */ CppCodeMarker::~CppCodeMarker() { // nothing. } /*! Returns true. */ bool CppCodeMarker::recognizeCode(const QString & /* code */) { return true; } /*! Returns true if \a ext is any of a list of file extensions for the C++ language. */ bool CppCodeMarker::recognizeExtension(const QString& ext) { return ext == "c" || ext == "c++" || ext == "cc" || ext == "cpp" || ext == "cxx" || ext == "ch" || ext == "h" || ext == "h++" || ext == "hh" || ext == "hpp" || ext == "hxx"; } /*! Returns true if \a lang is either "C" or "Cpp". */ bool CppCodeMarker::recognizeLanguage(const QString &lang) { return lang == "C" || lang == "Cpp"; } /*! Returns the \a node name, or "()" if \a node is a Node::Function node. */ QString CppCodeMarker::plainName(const Node *node) { QString name = node->name(); if (node->type() == Node::Function) name += "()"; return name; } QString CppCodeMarker::plainFullName(const Node *node, const Node *relative) { if (node->name().isEmpty()) { return "global"; } else { QString fullName; for (;;) { fullName.prepend(plainName(node)); if (node->parent() == relative || node->parent()->name().isEmpty()) break; fullName.prepend("::"); node = node->parent(); } return fullName; } } QString CppCodeMarker::markedUpCode(const QString &code, const Node *relative, const QString &dirPath) { return addMarkUp(protect(code), relative, dirPath); } QString CppCodeMarker::markedUpSynopsis(const Node *node, const Node * /* relative */, SynopsisStyle style) { const int MaxEnumValues = 6; const FunctionNode *func; const PropertyNode *property; const VariableNode *variable; const EnumNode *enume; const TypedefNode *typedeff; QString synopsis; QString extra; QString name; name = taggedNode(node); if (style != Detailed) name = linkTag(node, name); name = "<@name>" + name + "</@name>"; if (style == Detailed && !node->parent()->name().isEmpty() && node->type() != Node::Property) name.prepend(taggedNode(node->parent()) + "::"); switch (node->type()) { case Node::Namespace: synopsis = "namespace " + name; break; case Node::Class: synopsis = "class " + name; break; case Node::Function: func = (const FunctionNode *) node; if (style != SeparateList && !func->returnType().isEmpty()) synopsis = typified(func->returnType()) + " "; synopsis += name; if (func->metaness() != FunctionNode::MacroWithoutParams) { synopsis += " ("; if (!func->parameters().isEmpty()) { synopsis += " "; QList<Parameter>::ConstIterator p = func->parameters().begin(); while (p != func->parameters().end()) { if (p != func->parameters().begin()) synopsis += ", "; synopsis += typified((*p).leftType()); if (style != SeparateList && !(*p).name().isEmpty()) synopsis += " <@param>" + protect((*p).name()) + "</@param>"; synopsis += protect((*p).rightType()); if (style != SeparateList && !(*p).defaultValue().isEmpty()) synopsis += " = " + protect((*p).defaultValue()); ++p; } synopsis += " "; } synopsis += ")"; } if (func->isConst()) synopsis += " const"; if (style == Summary || style == Accessors) { if (func->virtualness() != FunctionNode::NonVirtual) synopsis.prepend("virtual "); if (func->virtualness() == FunctionNode::PureVirtual) synopsis.append(" = 0"); } else if (style == SeparateList) { if (!func->returnType().isEmpty() && func->returnType() != "void") synopsis += " : " + typified(func->returnType()); } else { QStringList bracketed; if (func->isStatic()) { bracketed += "static"; } else if (func->virtualness() != FunctionNode::NonVirtual) { if (func->virtualness() == FunctionNode::PureVirtual) bracketed += "pure"; bracketed += "virtual"; } if (func->access() == Node::Protected) { bracketed += "protected"; } else if (func->access() == Node::Private) { bracketed += "private"; } if (func->metaness() == FunctionNode::Signal) { bracketed += "signal"; } else if (func->metaness() == FunctionNode::Slot) { bracketed += "slot"; } if (!bracketed.isEmpty()) extra += " [" + bracketed.join(" ") + "]"; } break; case Node::Enum: enume = static_cast<const EnumNode *>(node); synopsis = "enum " + name; if (style == Summary) { synopsis += " { "; QStringList documentedItems = enume->doc().enumItemNames(); if (documentedItems.isEmpty()) { foreach (const EnumItem &item, enume->items()) documentedItems << item.name(); } QStringList omitItems = enume->doc().omitEnumItemNames(); foreach (const QString &item, omitItems) documentedItems.removeAll(item); if (documentedItems.size() <= MaxEnumValues) { for (int i = 0; i < documentedItems.size(); ++i) { if (i != 0) synopsis += ", "; synopsis += documentedItems.at(i); } } else { for (int i = 0; i < documentedItems.size(); ++i) { if (i < MaxEnumValues - 2 || i == documentedItems.size() - 1) { if (i != 0) synopsis += ", "; synopsis += documentedItems.at(i); } else if (i == MaxEnumValues - 1) { synopsis += ", ..."; } } } if (!documentedItems.isEmpty()) synopsis += " "; synopsis += "}"; } break; case Node::Typedef: typedeff = static_cast<const TypedefNode *>(node); if (typedeff->associatedEnum()) { synopsis = "flags " + name; } else { synopsis = "typedef " + name; } break; case Node::Property: property = static_cast<const PropertyNode *>(node); synopsis = name + " : " + typified(property->qualifiedDataType()); break; case Node::Variable: variable = static_cast<const VariableNode *>(node); if (style == SeparateList) { synopsis = name + " : " + typified(variable->dataType()); } else { synopsis = typified(variable->leftType()) + " " + name + protect(variable->rightType()); } break; default: synopsis = name; } if (style == Summary) { if (node->status() == Node::Preliminary) { extra += " (preliminary)"; } else if (node->status() == Node::Deprecated) { extra += " (deprecated)"; } else if (node->status() == Node::Obsolete) { extra += " (obsolete)"; } } if (!extra.isEmpty()) { extra.prepend("<@extra>"); extra.append("</@extra>"); } return synopsis + extra; } QString CppCodeMarker::markedUpName(const Node *node) { QString name = linkTag(node, taggedNode(node)); if (node->type() == Node::Function) name += "()"; return name; } QString CppCodeMarker::markedUpFullName(const Node *node, const Node *relative) { if (node->name().isEmpty()) { return "global"; } else { QString fullName; for (;;) { fullName.prepend(markedUpName(node)); if (node->parent() == relative || node->parent()->name().isEmpty()) break; fullName.prepend("<@op>::</@op>"); node = node->parent(); } return fullName; } } QString CppCodeMarker::markedUpEnumValue(const QString &enumValue, const Node *relative) { const Node *node = relative->parent(); QString fullName; while (node->parent()) { fullName.prepend(markedUpName(node)); if (node->parent() == relative || node->parent()->name().isEmpty()) break; fullName.prepend("<@op>::</@op>"); node = node->parent(); } if (!fullName.isEmpty()) fullName.append("<@op>::</@op>"); fullName.append(enumValue); return fullName; } QString CppCodeMarker::markedUpIncludes(const QStringList& includes) { QString code; QStringList::ConstIterator inc = includes.begin(); while (inc != includes.end()) { code += "#include &lt;<@headerfile>" + *inc + "</@headerfile>&gt;\n"; ++inc; } return addMarkUp(code, 0, ""); } QString CppCodeMarker::functionBeginRegExp(const QString& funcName) { return "^" + QRegExp::escape(funcName) + "$"; } QString CppCodeMarker::functionEndRegExp(const QString& /* funcName */) { return "^\\}$"; } QList<Section> CppCodeMarker::sections(const InnerNode *inner, SynopsisStyle style, Status status) { QList<Section> sections; if (inner->type() == Node::Class) { const ClassNode *classe = static_cast<const ClassNode *>(inner); if (style == Summary) { FastSection privateFunctions(classe, "Private Functions", "private function", "private functions"); FastSection privateSlots(classe, "Private Slots", "private slot", "private slots"); FastSection privateTypes(classe, "Private Types", "private type", "private types"); FastSection protectedFunctions(classe, "Protected Functions", "protected function", "protected functions"); FastSection protectedSlots(classe, "Protected Slots", "protected slot", "protected slots"); FastSection protectedTypes(classe, "Protected Types", "protected type", "protected types"); FastSection protectedVariables(classe, "Protected Variables", "protected type", "protected variables"); FastSection publicFunctions(classe, "Public Functions", "public function", "public functions"); FastSection publicSignals(classe, "Signals", "signal", "signals"); FastSection publicSlots(classe, "Public Slots", "public slot", "public slots"); FastSection publicTypes(classe, "Public Types", "public type", "public types"); FastSection publicVariables(classe, "Public Variables", "public type", "public variables"); FastSection properties(classe, "Properties", "property", "properties"); FastSection relatedNonMembers(classe, "Related Non-Members", "related non-member", "related non-members"); FastSection staticPrivateMembers(classe, "Static Private Members", "static private member", "static private members"); FastSection staticProtectedMembers(classe, "Static Protected Members", "static protected member", "static protected members"); FastSection staticPublicMembers(classe, "Static Public Members", "static public member", "static public members"); FastSection macros(inner, "Macros", "macro", "macros"); NodeList::ConstIterator r = classe->relatedNodes().begin(); while (r != classe->relatedNodes().end()) { if ((*r)->type() == Node::Function) { FunctionNode *func = static_cast<FunctionNode *>(*r); if (func->isMacro()) insert(macros, *r, style, status); else insert(relatedNonMembers, *r, style, status); } else { insert(relatedNonMembers, *r, style, status); } ++r; } QStack<const ClassNode *> stack; stack.push(classe); while (!stack.isEmpty()) { const ClassNode *ancestorClass = stack.pop(); NodeList::ConstIterator c = ancestorClass->childNodes().begin(); while (c != ancestorClass->childNodes().end()) { bool isSlot = false; bool isSignal = false; bool isStatic = false; if ((*c)->type() == Node::Function) { const FunctionNode *func = (const FunctionNode *) *c; isSlot = (func->metaness() == FunctionNode::Slot); isSignal = (func->metaness() == FunctionNode::Signal); isStatic = func->isStatic(); } else if ((*c)->type() == Node::Variable) { const VariableNode *var = static_cast<const VariableNode *>(*c); isStatic = var->isStatic(); } switch ((*c)->access()) { case Node::Public: if (isSlot) { insert(publicSlots, *c, style, status); } else if (isSignal) { insert(publicSignals, *c, style, status); } else if (isStatic) { if ((*c)->type() != Node::Variable || !(*c)->doc().isEmpty()) insert(staticPublicMembers, *c, style, status); } else if ((*c)->type() == Node::Property) { insert(properties, *c, style, status); } else if ((*c)->type() == Node::Variable) { if (!(*c)->doc().isEmpty()) insert(publicVariables, *c, style, status); } else if ((*c)->type() == Node::Function) { insert(publicFunctions, *c, style, status); } else { insert(publicTypes, *c, style, status); } break; case Node::Protected: if (isSlot) { insert(protectedSlots, *c, style, status); } else if (isStatic) { if ((*c)->type() != Node::Variable || !(*c)->doc().isEmpty()) insert(staticProtectedMembers, *c, style, status); } else if ((*c)->type() == Node::Variable) { if (!(*c)->doc().isEmpty()) insert(protectedVariables, *c, style, status); } else if ((*c)->type() == Node::Function) { insert(protectedFunctions, *c, style, status); } else { insert(protectedTypes, *c, style, status); } break; case Node::Private: if (isSlot) { insert(privateSlots, *c, style, status); } else if (isStatic) { if ((*c)->type() != Node::Variable || !(*c)->doc().isEmpty()) insert(staticPrivateMembers, *c, style, status); } else if ((*c)->type() == Node::Function) { insert(privateFunctions, *c, style, status); } else { insert(privateTypes, *c, style, status); } } ++c; } QList<RelatedClass>::ConstIterator r = ancestorClass->baseClasses().begin(); while (r != ancestorClass->baseClasses().end()) { stack.prepend((*r).node); ++r; } } append(sections, publicTypes); append(sections, properties); append(sections, publicFunctions); append(sections, publicSlots); append(sections, publicSignals); append(sections, publicVariables); append(sections, staticPublicMembers); append(sections, protectedTypes); append(sections, protectedFunctions); append(sections, protectedSlots); append(sections, protectedVariables); append(sections, staticProtectedMembers); append(sections, privateTypes); append(sections, privateFunctions); append(sections, privateSlots); append(sections, staticPrivateMembers); append(sections, relatedNonMembers); append(sections, macros); } else if (style == Detailed) { FastSection memberFunctions(classe,"Member Function Documentation"); FastSection memberTypes(classe,"Member Type Documentation"); FastSection memberVariables(classe,"Member Variable Documentation"); FastSection properties(classe,"Property Documentation"); FastSection relatedNonMembers(classe,"Related Non-Members"); FastSection macros(classe,"Macro Documentation"); NodeList::ConstIterator r = classe->relatedNodes().begin(); while (r != classe->relatedNodes().end()) { if ((*r)->type() == Node::Function) { FunctionNode *func = static_cast<FunctionNode *>(*r); if (func->isMacro()) insert(macros, *r, style, status); else insert(relatedNonMembers, *r, style, status); } else { insert(relatedNonMembers, *r, style, status); } ++r; } NodeList::ConstIterator c = classe->childNodes().begin(); while (c != classe->childNodes().end()) { if ((*c)->type() == Node::Enum || (*c)->type() == Node::Typedef) { insert(memberTypes, *c, style, status); } else if ((*c)->type() == Node::Property) { insert(properties, *c, style, status); } else if ((*c)->type() == Node::Variable) { if (!(*c)->doc().isEmpty()) insert(memberVariables, *c, style, status); } else if ((*c)->type() == Node::Function) { FunctionNode *function = static_cast<FunctionNode *>(*c); if (!function->associatedProperty()) insert(memberFunctions, function, style, status); } ++c; } append(sections, memberTypes); append(sections, properties); append(sections, memberFunctions); append(sections, memberVariables); append(sections, relatedNonMembers); append(sections, macros); } else { FastSection all(classe); QStack<const ClassNode *> stack; stack.push(classe); while (!stack.isEmpty()) { const ClassNode *ancestorClass = stack.pop(); NodeList::ConstIterator c = ancestorClass->childNodes().begin(); while (c != ancestorClass->childNodes().end()) { if ((*c)->access() != Node::Private && (*c)->type() != Node::Property) insert(all, *c, style, status); ++c; } QList<RelatedClass>::ConstIterator r = ancestorClass->baseClasses().begin(); while (r != ancestorClass->baseClasses().end()) { stack.prepend((*r).node); ++r; } } append(sections, all); } } else { if (style == Summary || style == Detailed) { FastSection namespaces(inner, "Namespaces", "namespace", "namespaces"); FastSection classes(inner, "Classes", "class", "classes"); FastSection types(inner, style == Summary ? "Types" : "Type Documentation", "type", "types"); FastSection functions(inner, style == Summary ? "Functions" : "Function Documentation", "function", "functions"); FastSection macros(inner, style == Summary ? "Macros" : "Macro Documentation", "macro", "macros"); NodeList nodeList = inner->childNodes(); nodeList += inner->relatedNodes(); NodeList::ConstIterator n = nodeList.begin(); while (n != nodeList.end()) { switch ((*n)->type()) { case Node::Namespace: insert(namespaces, *n, style, status); break; case Node::Class: insert(classes, *n, style, status); break; case Node::Enum: case Node::Typedef: insert(types, *n, style, status); break; case Node::Function: { FunctionNode *func = static_cast<FunctionNode *>(*n); if (func->isMacro()) insert(macros, *n, style, status); else insert(functions, *n, style, status); } break; default: ; } ++n; } append(sections, namespaces); append(sections, classes); append(sections, types); append(sections, functions); append(sections, macros); } } return sections; } const Node *CppCodeMarker::resolveTarget(const QString &target, const Tree *tree, const Node *relative) { if (target.endsWith("()")) { const FunctionNode *func; QString funcName = target; funcName.chop(2); QStringList path = funcName.split("::"); if ((func = tree->findFunctionNode(path, relative, Tree::SearchBaseClasses)) && func->metaness() != FunctionNode::MacroWithoutParams) return func; } else if (target.contains("#")) { // ### this doesn't belong here; get rid of TargetNode hack int hashAt = target.indexOf("#"); QString link = target.left(hashAt); QString ref = target.mid(hashAt + 1); const Node *node; if (link.isEmpty()) { node = relative; } else { QStringList path(link); node = tree->findNode(path, tree->root(), Tree::SearchBaseClasses); } if (node && node->isInnerNode()) { const Atom *atom = node->doc().body().firstAtom(); while (atom) { if (atom->type() == Atom::Target && atom->string() == ref) { Node *parentNode = const_cast<Node *>(node); return new TargetNode(static_cast<InnerNode*>(parentNode), ref); } atom = atom->next(); } } } else { QStringList path = target.split("::"); const Node *node; if ((node = tree->findNode(path, relative, Tree::SearchBaseClasses | Tree::SearchEnumValues | Tree::NonFunction))) return node; } return 0; } QString CppCodeMarker::addMarkUp(const QString& protectedCode, const Node * /* relative */, const QString& /* dirPath */) { static QRegExp globalInclude("#include +&lt;([^<>&]+)&gt;"); static QRegExp yHasTypeX("(?:^|\n *)([a-zA-Z_][a-zA-Z_0-9]*)" "(?:&lt;[^;{}]+&gt;)?(?: *(?:\\*|&amp;) *| +)" "([a-zA-Z_][a-zA-Z_0-9]*)? *[,;()=]"); static QRegExp xNewY("([a-zA-Z_][a-zA-Z_0-9]*) *= *new +([a-zA-Z_0-9]+)"); static QRegExp xDotY("\\b([a-zA-Z_][a-zA-Z_0-9]*) *(?:\\.|-&gt;|,[ \n]*S(?:IGNAL|LOT)\\() *" "([a-zA-Z_][a-zA-Z_0-9]*)(?= *\\()"); static QRegExp xIsStaticZOfY("[\n:;{(=] *(([a-zA-Z_0-9]+)::([a-zA-Z_0-9]+))(?= *\\()"); static QRegExp classX("[:,][ \n]*(?:p(?:ublic|r(?:otected|ivate))[ \n]+)?" "([a-zA-Z_][a-zA-Z_0-9]*)"); static QRegExp globalX("[\n{()=] *([a-zA-Z_][a-zA-Z_0-9]*)[ \n]*\\("); static QRegExp multiLineComment("/(?:( )?\\*(?:[^*]+|\\*(?! /))*\\*\\1/)"); multiLineComment.setMinimal(true); static QRegExp singleLineComment("//(?!!)[^!\n]*"); static QRegExp preprocessor("(?:^|\n)(#[ \t]*(?:include|if|elif|endif|error|pragma|define" "|warning)(?:(?:\\\\\n|\\n#)[^\n]*)*)"); static QRegExp literals("&quot;(?:[^\\\\&]|\\\\[^\n]|&(?!quot;))*&quot;" "|'(?:[^\\\\]|\\\\(?:[^x0-9']|x[0-9a-f]{1,4}|[0-9]{1,3}))'"); QString result = protectedCode; int pos; if (!hurryUp()) { /* Mark global includes. For example: #include &lt;<@headerfile>QString</@headerfile> */ pos = 0; while ((pos = result.indexOf(globalInclude, pos)) != -1) pos += globalInclude.matchedLength() + insertTagAround(result, globalInclude.pos(1), globalInclude.cap(1).length(), "@headerfile"); /* Look for variable definitions and similar constructs, mark the data type, and remember the type of the variable. */ QMap<QString, QSet<QString> > typesForVariable; pos = 0; while ((pos = yHasTypeX.indexIn(result, pos)) != -1) { QString x = yHasTypeX.cap(1); QString y = yHasTypeX.cap(2); if (!y.isEmpty()) typesForVariable[y].insert(x); /* Without the minus one at the end, 'void member(Class var)' would give 'member' as a variable of type 'void', but would ignore 'Class var'. (### Is that true?) */ pos += yHasTypeX.matchedLength() + insertTagAround(result, yHasTypeX.pos(1), x.length(), "@type") - 1; } /* Do syntax highlighting of preprocessor directives. */ pos = 0; while ((pos = preprocessor.indexIn(result, pos)) != -1) pos += preprocessor.matchedLength() + insertTagAround(result, preprocessor.pos(1), preprocessor.cap(1).length(), "@preprocessor"); /* Deal with string and character literals. */ pos = 0; while ((pos = literals.indexIn(result, pos)) != -1) pos += literals.matchedLength() + insertTagAround(result, pos, literals.matchedLength(), result.at(pos) == QLatin1Char(' ') ? "@string" : "@char"); /* Look for 'var = new Class'. */ pos = 0; while ((pos = xNewY.indexIn(result, pos)) != -1) { QString x = xNewY.cap(1); QString y = xNewY.cap(2); typesForVariable[x].insert(y); pos += xNewY.matchedLength() + insertTagAround(result, xNewY.pos(2), y.length(), "@type"); } /* Insert some stuff that cannot harm. */ typesForVariable["qApp"].insert("QApplication"); /* Add link to ': Class'. */ pos = 0; while ((pos = classX.indexIn(result, pos)) != -1) pos += classX.matchedLength() + insertTagAround(result, classX.pos(1), classX.cap(1).length(), "@type") - 1; /* Find use of any of var.method() var->method() var, SIGNAL(method()) var, SLOT(method()). */ pos = 0; while ((pos = xDotY.indexIn(result, pos)) != -1) { QString x = xDotY.cap(1); QString y = xDotY.cap(2); QSet<QString> types = typesForVariable.value(x); pos += xDotY.matchedLength() + insertTagAround(result, xDotY.pos(2), xDotY.cap(2).length(), "@func", (types.count() == 1) ? "target=\"" + protect(*types.begin() + "::" + y) + "()\"" : QString()); } /* Add link to 'Class::method()'. */ pos = 0; while ((pos = xIsStaticZOfY.indexIn(result, pos)) != -1) { QString x = xIsStaticZOfY.cap(1); QString z = xIsStaticZOfY.cap(3); pos += insertTagAround(result, xIsStaticZOfY.pos(3), z.length(), "@func", "target=\"" + protect(x) + "()\""); pos += insertTagAround(result, xIsStaticZOfY.pos(2), xIsStaticZOfY.cap(2).length(), "@type"); pos += xIsStaticZOfY.matchedLength() - 1; } /* Add link to 'globalFunction()'. */ pos = 0; while ((pos = globalX.indexIn(result, pos)) != -1) { QString x = globalX.cap(1); if (x != "QT_FORWARD_DECLARE_CLASS") { pos += globalX.matchedLength() + insertTagAround(result, globalX.pos(1), x.length(), "@func", "target=\"" + protect(x) + "()\"") - 1; } else pos += globalX.matchedLength(); } } /* Do syntax highlighting of comments. Also alter the code in a minor way, so that we can include comments in documentation comments. */ pos = 0; while (pos != -1) { int mlpos; int slpos; int len; slpos = singleLineComment.indexIn(result, pos); mlpos = multiLineComment.indexIn(result, pos); if (slpos == -1 && mlpos == -1) break; if (slpos == -1) { pos = mlpos; len = multiLineComment.matchedLength(); } else if (mlpos == -1) { pos = slpos; len = singleLineComment.matchedLength(); } else { if (slpos < mlpos) { pos = slpos; len = singleLineComment.matchedLength(); } else { pos = mlpos; len = multiLineComment.matchedLength(); } } if (result.at(pos + 1) == QLatin1Char(' ')) { result.remove(pos + len - 2, 1); result.remove(pos + 1, 1); len -= 2; forever { int endcodePos = result.indexOf("\\ endcode", pos); if (endcodePos == -1 || endcodePos >= pos + len) break; result.remove(endcodePos + 1, 1); len -= 1; } } pos += len + insertTagAround(result, pos, len, "@comment"); } return result; } QT_END_NAMESPACE
[ "lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330" ]
[ [ [ 1, 1009 ] ] ]
6cccb203ae600be1b24cf339b737b4681aacebab
f177993b13e97f9fecfc0e751602153824dfef7e
/ImPro/OtherLib/OpenCV2.1/vs2008/include/opencv2/video/background_segm.hpp
67110689cffbdabf2fd4c1a47973b162db386886
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
16,383
hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_BACKGROUND_SEGM_HPP__ #define __OPENCV_BACKGROUND_SEGM_HPP__ #include "opencv2/core/core.hpp" #ifdef __cplusplus extern "C" { #endif /****************************************************************************************\ * Background/foreground segmentation * \****************************************************************************************/ /* We discriminate between foreground and background pixels * by building and maintaining a model of the background. * Any pixel which does not fit this model is then deemed * to be foreground. * * At present we support two core background models, * one of which has two variations: * * o CV_BG_MODEL_FGD: latest and greatest algorithm, described in * * Foreground Object Detection from Videos Containing Complex Background. * Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian. * ACM MM2003 9p * * o CV_BG_MODEL_FGD_SIMPLE: * A code comment describes this as a simplified version of the above, * but the code is in fact currently identical * * o CV_BG_MODEL_MOG: "Mixture of Gaussians", older algorithm, described in * * Moving target classification and tracking from real-time video. * A Lipton, H Fujijoshi, R Patil * Proceedings IEEE Workshop on Application of Computer Vision pp 8-14 1998 * * Learning patterns of activity using real-time tracking * C Stauffer and W Grimson August 2000 * IEEE Transactions on Pattern Analysis and Machine Intelligence 22(8):747-757 */ #define CV_BG_MODEL_FGD 0 #define CV_BG_MODEL_MOG 1 /* "Mixture of Gaussians". */ #define CV_BG_MODEL_FGD_SIMPLE 2 struct CvBGStatModel; typedef void (CV_CDECL * CvReleaseBGStatModel)( struct CvBGStatModel** bg_model ); typedef int (CV_CDECL * CvUpdateBGStatModel)( IplImage* curr_frame, struct CvBGStatModel* bg_model, double learningRate ); #define CV_BG_STAT_MODEL_FIELDS() \ int type; /*type of BG model*/ \ CvReleaseBGStatModel release; \ CvUpdateBGStatModel update; \ IplImage* background; /*8UC3 reference background image*/ \ IplImage* foreground; /*8UC1 foreground image*/ \ IplImage** layers; /*8UC3 reference background image, can be null */ \ int layer_count; /* can be zero */ \ CvMemStorage* storage; /*storage for foreground_regions*/ \ CvSeq* foreground_regions /*foreground object contours*/ typedef struct CvBGStatModel { CV_BG_STAT_MODEL_FIELDS(); } CvBGStatModel; // // Releases memory used by BGStatModel CV_INLINE void cvReleaseBGStatModel( CvBGStatModel** bg_model ) { if( bg_model && *bg_model && (*bg_model)->release ) (*bg_model)->release( bg_model ); } // Updates statistical model and returns number of found foreground regions CV_INLINE int cvUpdateBGStatModel( IplImage* current_frame, CvBGStatModel* bg_model, double learningRate CV_DEFAULT(-1)) { return bg_model && bg_model->update ? bg_model->update( current_frame, bg_model, learningRate ) : 0; } // Performs FG post-processing using segmentation // (all pixels of a region will be classified as foreground if majority of pixels of the region are FG). // parameters: // segments - pointer to result of segmentation (for example MeanShiftSegmentation) // bg_model - pointer to CvBGStatModel structure CVAPI(void) cvRefineForegroundMaskBySegm( CvSeq* segments, CvBGStatModel* bg_model ); /* Common use change detection function */ CVAPI(int) cvChangeDetection( IplImage* prev_frame, IplImage* curr_frame, IplImage* change_mask ); /* Interface of ACM MM2003 algorithm */ /* Default parameters of foreground detection algorithm: */ #define CV_BGFG_FGD_LC 128 #define CV_BGFG_FGD_N1C 15 #define CV_BGFG_FGD_N2C 25 #define CV_BGFG_FGD_LCC 64 #define CV_BGFG_FGD_N1CC 25 #define CV_BGFG_FGD_N2CC 40 /* Background reference image update parameter: */ #define CV_BGFG_FGD_ALPHA_1 0.1f /* stat model update parameter * 0.002f ~ 1K frame(~45sec), 0.005 ~ 18sec (if 25fps and absolutely static BG) */ #define CV_BGFG_FGD_ALPHA_2 0.005f /* start value for alpha parameter (to fast initiate statistic model) */ #define CV_BGFG_FGD_ALPHA_3 0.1f #define CV_BGFG_FGD_DELTA 2 #define CV_BGFG_FGD_T 0.9f #define CV_BGFG_FGD_MINAREA 15.f #define CV_BGFG_FGD_BG_UPDATE_TRESH 0.5f /* See the above-referenced Li/Huang/Gu/Tian paper * for a full description of these background-model * tuning parameters. * * Nomenclature: 'c' == "color", a three-component red/green/blue vector. * We use histograms of these to model the range of * colors we've seen at a given background pixel. * * 'cc' == "color co-occurrence", a six-component vector giving * RGB color for both this frame and preceding frame. * We use histograms of these to model the range of * color CHANGES we've seen at a given background pixel. */ typedef struct CvFGDStatModelParams { int Lc; /* Quantized levels per 'color' component. Power of two, typically 32, 64 or 128. */ int N1c; /* Number of color vectors used to model normal background color variation at a given pixel. */ int N2c; /* Number of color vectors retained at given pixel. Must be > N1c, typically ~ 5/3 of N1c. */ /* Used to allow the first N1c vectors to adapt over time to changing background. */ int Lcc; /* Quantized levels per 'color co-occurrence' component. Power of two, typically 16, 32 or 64. */ int N1cc; /* Number of color co-occurrence vectors used to model normal background color variation at a given pixel. */ int N2cc; /* Number of color co-occurrence vectors retained at given pixel. Must be > N1cc, typically ~ 5/3 of N1cc. */ /* Used to allow the first N1cc vectors to adapt over time to changing background. */ int is_obj_without_holes;/* If TRUE we ignore holes within foreground blobs. Defaults to TRUE. */ int perform_morphing; /* Number of erode-dilate-erode foreground-blob cleanup iterations. */ /* These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1. */ float alpha1; /* How quickly we forget old background pixel values seen. Typically set to 0.1 */ float alpha2; /* "Controls speed of feature learning". Depends on T. Typical value circa 0.005. */ float alpha3; /* Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1. */ float delta; /* Affects color and color co-occurrence quantization, typically set to 2. */ float T; /* "A percentage value which determines when new features can be recognized as new background." (Typically 0.9).*/ float minArea; /* Discard foreground blobs whose bounding box is smaller than this threshold. */ } CvFGDStatModelParams; typedef struct CvBGPixelCStatTable { float Pv, Pvb; uchar v[3]; } CvBGPixelCStatTable; typedef struct CvBGPixelCCStatTable { float Pv, Pvb; uchar v[6]; } CvBGPixelCCStatTable; typedef struct CvBGPixelStat { float Pbc; float Pbcc; CvBGPixelCStatTable* ctable; CvBGPixelCCStatTable* cctable; uchar is_trained_st_model; uchar is_trained_dyn_model; } CvBGPixelStat; typedef struct CvFGDStatModel { CV_BG_STAT_MODEL_FIELDS(); CvBGPixelStat* pixel_stat; IplImage* Ftd; IplImage* Fbd; IplImage* prev_frame; CvFGDStatModelParams params; } CvFGDStatModel; /* Creates FGD model */ CVAPI(CvBGStatModel*) cvCreateFGDStatModel( IplImage* first_frame, CvFGDStatModelParams* parameters CV_DEFAULT(NULL)); /* Interface of Gaussian mixture algorithm "An improved adaptive background mixture model for real-time tracking with shadow detection" P. KadewTraKuPong and R. Bowden, Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001." http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf */ /* Note: "MOG" == "Mixture Of Gaussians": */ #define CV_BGFG_MOG_MAX_NGAUSSIANS 500 /* default parameters of gaussian background detection algorithm */ #define CV_BGFG_MOG_BACKGROUND_THRESHOLD 0.7 /* threshold sum of weights for background test */ #define CV_BGFG_MOG_STD_THRESHOLD 2.5 /* lambda=2.5 is 99% */ #define CV_BGFG_MOG_WINDOW_SIZE 200 /* Learning rate; alpha = 1/CV_GBG_WINDOW_SIZE */ #define CV_BGFG_MOG_NGAUSSIANS 5 /* = K = number of Gaussians in mixture */ #define CV_BGFG_MOG_WEIGHT_INIT 0.05 #define CV_BGFG_MOG_SIGMA_INIT 30 #define CV_BGFG_MOG_MINAREA 15.f #define CV_BGFG_MOG_NCOLORS 3 typedef struct CvGaussBGStatModelParams { int win_size; /* = 1/alpha */ int n_gauss; double bg_threshold, std_threshold, minArea; double weight_init, variance_init; }CvGaussBGStatModelParams; typedef struct CvGaussBGValues { int match_sum; double weight; double variance[CV_BGFG_MOG_NCOLORS]; double mean[CV_BGFG_MOG_NCOLORS]; } CvGaussBGValues; typedef struct CvGaussBGPoint { CvGaussBGValues* g_values; } CvGaussBGPoint; typedef struct CvGaussBGModel { CV_BG_STAT_MODEL_FIELDS(); CvGaussBGStatModelParams params; CvGaussBGPoint* g_point; int countFrames; } CvGaussBGModel; /* Creates Gaussian mixture background model */ CVAPI(CvBGStatModel*) cvCreateGaussianBGModel( IplImage* first_frame, CvGaussBGStatModelParams* parameters CV_DEFAULT(NULL)); typedef struct CvBGCodeBookElem { struct CvBGCodeBookElem* next; int tLastUpdate; int stale; uchar boxMin[3]; uchar boxMax[3]; uchar learnMin[3]; uchar learnMax[3]; } CvBGCodeBookElem; typedef struct CvBGCodeBookModel { CvSize size; int t; uchar cbBounds[3]; uchar modMin[3]; uchar modMax[3]; CvBGCodeBookElem** cbmap; CvMemStorage* storage; CvBGCodeBookElem* freeList; } CvBGCodeBookModel; CVAPI(CvBGCodeBookModel*) cvCreateBGCodeBookModel(); CVAPI(void) cvReleaseBGCodeBookModel( CvBGCodeBookModel** model ); CVAPI(void) cvBGCodeBookUpdate( CvBGCodeBookModel* model, const CvArr* image, CvRect roi CV_DEFAULT(cvRect(0,0,0,0)), const CvArr* mask CV_DEFAULT(0) ); CVAPI(int) cvBGCodeBookDiff( const CvBGCodeBookModel* model, const CvArr* image, CvArr* fgmask, CvRect roi CV_DEFAULT(cvRect(0,0,0,0)) ); CVAPI(void) cvBGCodeBookClearStale( CvBGCodeBookModel* model, int staleThresh, CvRect roi CV_DEFAULT(cvRect(0,0,0,0)), const CvArr* mask CV_DEFAULT(0) ); CVAPI(CvSeq*) cvSegmentFGMask( CvArr *fgmask, int poly1Hull0 CV_DEFAULT(1), float perimScale CV_DEFAULT(4.f), CvMemStorage* storage CV_DEFAULT(0), CvPoint offset CV_DEFAULT(cvPoint(0,0))); #ifdef __cplusplus } namespace cv { /*! The Base Class for Background/Foreground Segmentation The class is only used to define the common interface for the whole family of background/foreground segmentation algorithms. */ class CV_EXPORTS BackgroundSubtractor { public: //! the virtual destructor virtual ~BackgroundSubtractor(); //! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image. virtual void operator()(const Mat& image, Mat& fgmask, double learningRate=0); }; /*! Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm The class implements the following algorithm: "An improved adaptive background mixture model for real-time tracking with shadow detection" P. KadewTraKuPong and R. Bowden, Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001." http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf */ class CV_EXPORTS BackgroundSubtractorMOG : public BackgroundSubtractor { public: //! the default constructor BackgroundSubtractorMOG(); //! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength BackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma=0); //! the destructor virtual ~BackgroundSubtractorMOG(); //! the update operator virtual void operator()(const Mat& image, Mat& fgmask, double learningRate=0); //! re-initiaization method virtual void initialize(Size frameSize, int frameType); Size frameSize; int frameType; Mat bgmodel; int nframes; int history; int nmixtures; double varThreshold; double backgroundRatio; double noiseSigma; }; } #endif #endif
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 411 ] ] ]
dbba300c9213a3631e23386e649dab1c2d267424
36809be8f4e66fa2a3794776772584273853fede
/Config.h
fbb3958d0d8978e7cff1c0a2a27a54aa014b166e
[]
no_license
ktd2004/mygdb
dbaa0ebd0a3e6958dec8e80248cb8e12a92548bd
016405acfe3d548d9333155b316f4d16cb3baebc
refs/heads/master
2020-04-29T00:31:39.201731
2010-11-16T03:18:50
2010-11-16T03:18:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
717
h
// vim: set fdm=marker ts=4 sw=4: #ifndef _CONFIG_H_ #define _CONFIG_H_ class Config { public: wxXmlDocument* xml; wxXmlNode* root; public: Config(); ~Config(); wxString fileName; wxString sXml; wxString backup; bool Open(void); void Save (void); void New (void); wxString Read(wxString fileName); bool Changed(void); void Backup(void); void Restore(void); wxXmlNode* SetNode(wxString nodePath); bool SetProperty(wxString nodePath, wxString property, wxString value); wxString GetProperty(wxString nodePath, wxString name); bool GetPropertyBool(wxString nodePath, wxString property); long GetPropertyInt(wxString nodePath, wxString property); }; #endif
[ [ [ 1, 36 ] ] ]
07635d87a78aa5bb4bde3f5c20ae3cf682c92b8c
4b111d57027ac3a21af503aa5344a2e9f7e09746
/ndefnfcmimevcardrecord.cpp
698193723edf89fafcece2586bc7359474d36d2b
[]
no_license
ginggs/nfcwriter
8d713da10041a6bb8c8cbc178081083807ba3e28
6b59ab5348c34c5b05da70f1561610e9ac17d86a
refs/heads/master
2020-12-24T22:59:03.309554
2011-11-21T21:19:07
2011-11-21T21:19:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,063
cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Andreas Jakl ([email protected]) ** ** This file is part of an NFC example for Qt Mobility. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "ndefnfcmimevcardrecord.h" /*! \brief Return a list of all the contacts contained in the vCard record. In case the contents of the payload can not be parsed into valid QContact instances, an empty list is returned. You can then retrieve the error message through error(). */ QList<QContact> NdefNfcMimeVcardRecord::contacts() { QByteArray p = payload(); // Is the payload empty? if (p.isEmpty()) return QList<QContact>(); // Create a buffer so that the versit reader can read from the byte array QBuffer buffer(&p); // compiler warning: taking address of temporary buffer.open(QBuffer::ReadOnly); // Read the versit document synchronously - for NFC, we will usually only // have one contact with as few details as possible. QVersitReader reader; reader.setDevice(&buffer); reader.startReading(); // Remember to check the return value reader.waitForFinished(); // As a final step, use the contact importer to create a list of // QContact instances based on the versit documents. QList<QVersitDocument> inputDocuments = reader.results(); QVersitContactImporter importer; if (importer.importDocuments(inputDocuments)) { // Successful - return the list of contacts return importer.contacts(); } else { // Error converting the versit documents into QContact instances. // Assemble the error message. QString errorMessage; QMap<int, QVersitContactImporter::Error>::const_iterator iterator = importer.errorMap().constBegin(); while(iterator != importer.errorMap().constEnd()){ switch (iterator.value()){ case QVersitContactImporter::InvalidDocumentError: errorMessage += QString("Index %1:").arg(iterator.key()); errorMessage += "One of the documents is not a vCard"; break; case QVersitContactImporter::EmptyDocumentError: errorMessage += QString("Index %1:").arg(iterator.key()); errorMessage += "One of the documents is empty"; break; default: errorMessage += QString("Index %1:").arg(iterator.key()); errorMessage += "Unknown error"; } ++iterator; } cachedErrorText = "Error while reading vCard: " + errorMessage; qDebug() << cachedErrorText; return QList<QContact>(); } } /*! \brief Convenience function if only one contact should be stored in the message. \see setContact() */ bool NdefNfcMimeVcardRecord::setContact(const QContact &contact, QVersitDocument::VersitType versitType) { return setContact(QList<QContact>() << contact, versitType); } /*! \brief Store the list of contacts into the payload of the vCard record. In case there is an error while creating versit documents based on the QContact instances, the method will return false and you can retrieve the error message through error(). \param contacts a list of contacts to be stored as a vCard. \param versitType version of the versit document to be created. Defaults to v3. \return true if the payload was successfully set. */ bool NdefNfcMimeVcardRecord::setContact(const QList<QContact> contacts, QVersitDocument::VersitType versitType) { // Export the contacts into a versit document QVersitContactExporter contactExporter; if (!contactExporter.exportContacts(contacts, versitType)) { // Error exporting - create an error message and return false. QString errorMessage; QMap<int, QVersitContactExporter::Error>::const_iterator iterator = contactExporter.errorMap().constBegin(); while(iterator != contactExporter.errorMap().constEnd()){ switch (iterator.value()){ case QVersitContactExporter::EmptyContactError: errorMessage += QString("Index %1:").arg(iterator.key()); errorMessage += "One of the contacts was empty"; break; case QVersitContactExporter::NoNameError: errorMessage += QString("Index %1:").arg(iterator.key()); errorMessage += "One of the contacts has no QContactName field"; break; default: errorMessage += QString("Index %1:%2 ").arg(iterator.key()) .arg("Unknown error"); } ++iterator; } cachedErrorText = "Error while writing vCard: " + errorMessage; qDebug() << cachedErrorText; return false; } // Exporting the contacts to a versit document was successful. // Retrieve the versit documents. QList<QVersitDocument> versitDocuments = contactExporter.documents(); // Create an array to store the payload. QByteArray p; QBuffer buffer(&p); buffer.open(QIODevice::WriteOnly); // Create a versit writer which will serialize the versit document // into our byte array. QVersitWriter writer; writer.setDevice(&buffer); // Handle the writing synchronously - for NFC, we will usually only // have one contact with as few details as possible. writer.startWriting(versitDocuments); writer.waitForFinished(); // Check if there was an error writing the contact. const QVersitWriter::Error writeError = writer.error(); if (writeError == QVersitWriter::NoError) { // No error - commit the byte array to the payload of the base record class. setPayload(p); } else { // Error - create the error message. QString errorMessage; switch (writeError) { case QVersitWriter::UnspecifiedError: errorMessage += "The most recent operation failed for an undocumented reason"; break; case QVersitWriter::IOError: errorMessage += "The most recent operation failed because of a problem with the device"; break; case QVersitWriter::OutOfMemoryError: errorMessage += "The most recent operation failed due to running out of memory"; break; case QVersitWriter::NotReadyError: errorMessage += "The most recent operation failed because there is an operation in progress"; break; default: errorMessage += "Unknown error"; break; } cachedErrorText = "Error while serializing vCard: " + errorMessage; qDebug() << cachedErrorText; return false; } return true; } /*! \brief Returns the error message in case there was a problem parsing the record into a QContact or assembling the payload. */ QString NdefNfcMimeVcardRecord::error() { return cachedErrorText; }
[ [ [ 1, 224 ] ] ]
1ebc8bab6c1213cb39098fb94742a21cd401a02a
4497c10f3b01b7ff259f3eb45d0c094c81337db6
/Retargeting/Shifmap/Version01/HorizontalScaleSM.cpp
7c8efcdebc8dfe2e317476a501030daa017f45ed
[]
no_license
liuguoyou/retarget-toolkit
ebda70ad13ab03a003b52bddce0313f0feb4b0d6
d2d94653b66ea3d4fa4861e1bd8313b93cf4877a
refs/heads/master
2020-12-28T21:39:38.350998
2010-12-23T16:16:59
2010-12-23T16:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,465
cpp
#include "StdAfx.h" #include "HorizontalScaleSM.h" HorizontalScaleSM::HorizontalScaleSM(void) { } HorizontalScaleSM::~HorizontalScaleSM(void) { } void HorizontalScaleSM::SetScaleSetting(int scaleCount, double scaleStep) { _scaleCount = scaleCount; _scaleStep = scaleStep; } void HorizontalScaleSM::SetShiftRange(int shiftRange) { _shiftRange = shiftRange; } void HorizontalScaleSM::ComputeOptimalRetargetMapping(IplImage* image, IplImage* saliency, CvSize outputSize) { _input = image; _outputSize = outputSize; _energyFunction = new HorizontalScaleEnergyFunction(); IplImage* gradient = cvCloneImage(image); cvSobel(image, gradient, 1, 1); HorizontalScaleLabelMapping* labelMapping = new HorizontalScaleLabelMapping(); labelMapping->InitScaleRange(image->width, outputSize.width, _scaleCount, _scaleStep); labelMapping->InitShiftRange(_shiftRange); _labelMapping = labelMapping; Mapping2D* mapping2D = new Mapping2D(); mapping2D->InitializeMapping(outputSize.width, outputSize.height); mapping2D->IsShift(false); _mapping2D = mapping2D; _energyFunction->SetInput(image, gradient, saliency); _energyFunction->SetRetargetSize(cvSize(image->width, image->height), outputSize); _energyFunction->SetLabelMapping(labelMapping); _energyFunction->SetMapping2D(mapping2D); GCScaleImage* gc = new GCScaleImage(); gc->Initialize(outputSize.width, outputSize.height, labelMapping->GetLabelCount()); gc->SetEnergyFunction(_energyFunction); gc->ComputeGC(); _gc = gc; } CvScalar HorizontalScaleSM::GetInterpolatedValue(double x1, int y, IplImage* image) { int x1Int = (int)floor(x1); double weight = x1 - x1Int; if(weight == 0) { return cvGet2D(image, y, x1Int); } else { CvScalar value1 = cvGet2D(image, y, x1Int); CvScalar value2 = cvGet2D(image, y, x1Int + 1); CvScalar value; for(int i = 0; i < 4; i++) { value.val[i] = value1.val[i] * (1-weight) + value1.val[i] * weight; } return value; } } // should call only after compute optimal mapping IplImage* HorizontalScaleSM::RenderRetargetImage() { IplImage* image = cvCreateImage(_outputSize, IPL_DEPTH_8U, 3); GCoptimization* gc = _gc->GetGCoptimization(); int nodeCount = _outputSize.width * _outputSize.height; for(int i = 0; i < nodeCount; i++) { int label = gc->whatLabel(i); CvPoint point = _mapping2D->GetMappedPoint(i); double mappedX = _labelMapping->GetMappedPoint(label, point.x); if(mappedX >= _input->width || mappedX < 0) { printf("Map outside"); cvSet2D(image, point.y, point.x, cvScalar(255)); } else { CvScalar value = GetInterpolatedValue(mappedX, point.y, _input); cvSet2D(image, point.y, point.x, value); } } //DisplayImage(image, "TEST"); return image; } // render a stack map for visualization of which pixel is mapped to which layer in stack IplImage* HorizontalScaleSM::RenderStackMapVisualisation() { IplImage* image = cvCreateImage(_outputSize, IPL_DEPTH_8U, 3); GCoptimization* gc = _gc->GetGCoptimization(); int nodeCount = _gc->GetSitesCount(); int scaleCount = _labelMapping->GetScaleCount(); for(int i = 0; i < nodeCount; i++) { int label = gc->whatLabel(i); CvPoint point = _mapping2D->GetMappedPoint(i); int scaleId = _labelMapping->GetScaleId(label); int shiftId = _labelMapping->GetShiftId(label); double value = scaleId * 255 / scaleCount ; double shiftValue = shiftId * 10; cvSet2D(image, point.y, point.x, cvScalar(value,0,0)); } //DisplayImage(image, "TEST"); return image; } IplImage* HorizontalScaleSM::RenderSmoothCostMapVisualisation() { IplImage* image = cvCreateImage(_outputSize, IPL_DEPTH_8U, 3); for(int i = 0; i < _outputSize.width-1; i++) for(int j = 0; j < _outputSize.height; j++) { cvSet2D(image, j, i, cvScalar(0,0,0)); } GCoptimization* gc = _gc->GetGCoptimization(); int nodeCount = _gc->GetSitesCount(); int scaleCount = _labelMapping->GetScaleCount(); // vertical for(int i = 0; i < _outputSize.width-1; i++) for(int j = 0; j < _outputSize.height; j++) { int id1 = _mapping2D->GetPointId(cvPoint(i,j)); int id2 = _mapping2D->GetPointId(cvPoint(i+1,j)); CvPoint ponit1 = _mapping2D->GetMappedPoint(id1); CvPoint ponit2 = _mapping2D->GetMappedPoint(id2); int label1 = gc->whatLabel(id1); int label2 = gc->whatLabel(id2); int smoothCost = _energyFunction->GetSmoothCost(label1, label2, id1, id2); cvSet2D(image, j, i, cvScalar(smoothCost)); } // horizontal for(int i = 0; i < _outputSize.width; i++) for(int j = 0; j < _outputSize.height - 1; j++) { int id1 = _mapping2D->GetPointId(cvPoint(i,j)); int id2 = _mapping2D->GetPointId(cvPoint(i,j + 1)); int label1 = gc->whatLabel(id1); int label2 = gc->whatLabel(id2); int smoothCost = _energyFunction->GetSmoothCost(label1, label2, id1, id2); CvScalar value = cvGet2D(image, j, i); CvScalar cost; for(int i = 0; i < 4; i++) cost.val[i] = value.val[i] + smoothCost; cvSet2D(image, j, i, cost); } //DisplayImage(image, "TEST"); return image; } string HorizontalScaleSM::GetCost() { string result = ""; char b[100]; sprintf(b, "Data-%i", _gc->GetDataEnergy()); result += b; sprintf(b, "Smooth-%i", _gc->GetSmoothEnergy()); result += b; return result; }
[ "kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a" ]
[ [ [ 1, 188 ] ] ]
e15330bbdc33d9240624db434dac3f84ef1770e5
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Tools/LayoutEditor/DialogManager.cpp
37f8e752faaddb58f85a6db0b49870cad0f96a7e
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
/*! @file @author Albert Semenov @date 08/2010 */ #include "precompiled.h" #include "DialogManager.h" template <> tools::DialogManager* MyGUI::Singleton<tools::DialogManager>::msInstance = nullptr; template <> const char* MyGUI::Singleton<tools::DialogManager>::mClassTypeName("DialogManager"); namespace tools { DialogManager::DialogManager() { } DialogManager::~DialogManager() { } void DialogManager::initialise() { } void DialogManager::shutdown() { } bool DialogManager::getAnyDialog() { return !mDialogs.empty(); } void DialogManager::endTopDialog(bool _result) { if (!mDialogs.empty()) { Dialog* item = mDialogs.back(); item->eventEndDialog(item, _result); } } void DialogManager::_addDialog(Dialog* _modal) { mDialogs.push_back(_modal); } void DialogManager::_removeDialog(Dialog* _modal) { VectorDialog::iterator item = std::find(mDialogs.begin(), mDialogs.end(), _modal); mDialogs.erase(item); } } // namespace tools
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 55 ] ] ]
ddf86a7dd32e01db5bd1573571d72298b7961703
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/test/src/cpp_main.cpp
9209c91c999861cf9b1fb384319d4bb309e911f9
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
3,685
cpp
// (C) Copyright Gennadiy Rozental 2001-2004. // (C) Copyright Beman Dawes 1995-2001. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile: cpp_main.cpp,v $ // // Version : $Revision: 1.15 $ // // Description : main function implementation for Program Executon Monitor // *************************************************************************** // Boost.Test #include <boost/test/execution_monitor.hpp> #include <boost/test/detail/unit_test_config.hpp> // BOOST #include <boost/cstdlib.hpp> #include <boost/config.hpp> // STL #include <iostream> #include <cstring> #ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::getenv; using ::strcmp; } #endif int cpp_main( int argc, char* argv[] ); // prototype for user's cpp_main() namespace { class cpp_main_caller : public boost::execution_monitor { public: cpp_main_caller( int argc, char** argv ) : m_argc( argc ), m_argv( argv ) {} int function() { return cpp_main( m_argc, m_argv ); } private: int m_argc; char** m_argv; }; } // ************************************************************************** // // ************** cpp main ************** // // ************************************************************************** // int main( int argc, char* argv[] ) { cpp_main_caller caller( argc, argv ); int result; boost::unit_test::const_string p( std::getenv( "BOOST_TEST_CATCH_SYSTEM_ERRORS" ) ); bool catch_system_errors = p != "no"; try { result = caller.execute( catch_system_errors ); if( result == 0 ) result = boost::exit_success; else if( result != boost::exit_success ) { std::cout << "\n**** error return code: " << result << std::endl; result = boost::exit_failure; } } catch( boost::execution_exception const& exex ) { std::cout << "\n**** exception(" << exex.code() << "): " << exex.what() << std::endl; result = boost::exit_exception_failure; } if( result != boost::exit_success ) { std::cerr << "******** errors detected; see standard output for details ********" << std::endl; } else { // Some prefer a confirming message when all is well, while others don't // like the clutter. Use an environment variable to avoid command // line argument modifications; for use in production programs // that's a no-no in some organizations. boost::unit_test::const_string p( std::getenv( "BOOST_PRG_MON_CONFIRM" ) ); if( p != "no" ) { std::cerr << std::flush << "no errors detected" << std::endl; } } return result; } //____________________________________________________________________________// // *************************************************************************** // Revision History : // // $Log: cpp_main.cpp,v $ // Revision 1.15 2004/05/21 06:26:09 rogeeff // licence update // // Revision 1.14 2004/05/11 11:04:44 rogeeff // basic_cstring introduced and used everywhere // class properties reworked // namespace names shortened // // Revision 1.13 2003/12/01 00:42:37 rogeeff // prerelease cleaning // // *************************************************************************** // EOF
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 116 ] ] ]
227503c13afcd421410ab09a5f0f09bfd40e8d88
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/TEST_MyGUI_Source/LayoutEditor/BasisManager.cpp
c4ff2f214eb8365087d059b82cb36e0695ad5815
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
WINDOWS-1251
C++
false
false
11,182
cpp
#include <Ogre.h> #include <OgreLogManager.h> #include "BasisManager.h" #include <OgreException.h> #include <OgrePanelOverlayElement.h> #ifdef WIN32 #include <windows.h> #include "resource.h" void g_setMainWindowInfo(char *strWindowCaption, unsigned int uIconResourceID) { HWND hWnd = ::FindWindow("OgreD3D9Wnd", "MyGUI Layout Editor"); if (!::IsWindow(hWnd)) hWnd = ::FindWindow("OgreGLWindow", "MyGUI Layout Editor"); if (::IsWindow(hWnd)) { if (strWindowCaption) ::SetWindowText(hWnd, strWindowCaption); // берем имя нашего экзешника char buf[1024]; ::GetModuleFileName(0, (LPCH)&buf, 1024); // берем инстанс нашего модуля HINSTANCE instance = ::GetModuleHandle(buf); // побыстрому грузим иконку HICON hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(uIconResourceID)); if (hIcon) { ::SendMessage(hWnd, WM_SETICON, 1, (LPARAM)hIcon); ::SendMessage(hWnd, WM_SETICON, 0, (LPARAM)hIcon); } } } #endif BasisManager::BasisManager() : mInputManager(0), mMouse(0), mKeyboard(0), mRoot(0), mCamera(0), mSceneMgr(0), mWindow(0), m_exit(false) { #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE mResourcePath = macBundlePath() + "/Contents/Resources/"; #else mResourcePath = ""; #endif } void BasisManager::createInput() // создаем систему ввода { Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***"); OIS::ParamList pl; size_t windowHnd = 0; std::ostringstream windowHndStr; mWindow->getCustomAttribute("WINDOW", &windowHnd); windowHndStr << windowHnd; pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); #ifdef NO_EXCLUSIVE_INPUT #if defined OIS_WIN32_PLATFORM pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND" ))); pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE"))); pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND"))); pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE"))); #elif defined OIS_LINUX_PLATFORM pl.insert(std::make_pair(std::string("x11_mouse_grab"), std::string("false"))); pl.insert(std::make_pair(std::string("x11_mouse_hide"), std::string("false"))); pl.insert(std::make_pair(std::string("x11_keyboard_grab"), std::string("false"))); pl.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true"))); #endif #endif mInputManager = OIS::InputManager::createInputSystem( pl ); mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true )); mKeyboard->setEventCallback(this); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true )); mMouse->setEventCallback(this); mRoot->addFrameListener(this); windowResized(mWindow); // инициализация Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("wallpaper"); if (false == material.isNull()) { /*Ogre::OverlayManager & manager = Ogre::OverlayManager::getSingleton(); Ogre::Overlay * overlay = manager.create("wallpaper"); overlay->setZOrder(0); overlay->show(); Ogre::PanelOverlayElement * panel = static_cast<Ogre::PanelOverlayElement*>(manager.createOverlayElement("Panel", "wallpaper")); panel->setDimensions(1, 1);*/ /*Ogre::FontPtr mpFont = Ogre::FontManager::getSingleton().getByName("MyGUI_font"); mpFont->load(); if (!mpFont.isNull()) { const Ogre::MaterialPtr & material2 = mpFont->getMaterial(); panel->setMaterialName(material2->getName()); }*/ /*panel->setMaterialName(material->getName()); overlay->add2D(panel);*/ } } void BasisManager::destroyInput() // удаляем систему ввода { if( mInputManager ) { Ogre::LogManager::getSingletonPtr()->logMessage("*** Destroy OIS ***"); if (mMouse) { mInputManager->destroyInputObject( mMouse ); mMouse = 0; } if (mKeyboard) { mInputManager->destroyInputObject( mKeyboard ); mKeyboard = 0; } OIS::InputManager::destroyInputSystem(mInputManager); mInputManager = 0; } } void BasisManager::createBasisManager(void) // создаем начальную точки каркаса приложения { Ogre::String pluginsPath; // only use plugins.cfg if not static #ifndef OGRE_STATIC_LIB pluginsPath = mResourcePath + "plugins.cfg"; #endif mRoot = new Ogre::Root(pluginsPath, mResourcePath + "ogre.cfg", mResourcePath + "Ogre.log"); setupResources(); if (!mRoot->restoreConfig()) { // попробуем завестись на дефолтных if (!mRoot->showConfigDialog()) return; // ничего не получилось, покажем диалог } mWindow = mRoot->initialise(true, "MyGUI Layout Editor"); mWidth = mWindow->getWidth(); mHeight = mWindow->getHeight(); #ifdef WIN32 g_setMainWindowInfo("MyGUI Layout Editor", IDI_ICON); #endif mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC, "BasisSceneManager"); mCamera = mSceneMgr->createCamera("BasisCamera"); mCamera->setNearClipDistance(5); mCamera->setPosition(Ogre::Vector3(200, 200, 200)); mCamera->lookAt(Ogre::Vector3(0.0, 0.0, 0.0)); // Create one viewport, entire window Ogre::Viewport * vp = mWindow->addViewport(mCamera); // Alter the camera aspect ratio to match the viewport mCamera->setAspectRatio(Ogre::Real(mWidth) / Ogre::Real(mHeight)); // Set default mipmap level (NB some APIs ignore this) Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); Ogre::Light* mLight = mSceneMgr->createLight("BasisLight"); mLight->setDiffuseColour(Ogre::ColourValue::White); mLight->setSpecularColour(Ogre::ColourValue::White); mLight->setAttenuation(8000,1,0.0005,0); // Load resources Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); createInput(); changeState(&mEditor); mRoot->startRendering(); } void BasisManager::destroyBasisManager() // очищаем все параметры каркаса приложения { // очищаем состояния while (!mStates.empty()) { mStates.back()->exit(); mStates.pop_back(); } // очищаем сцену if (mSceneMgr) { mSceneMgr->clearScene(); mSceneMgr->destroyAllCameras(); mSceneMgr = 0; } destroyInput(); // удаляем ввод if (mWindow) { mWindow->destroy(); mWindow = 0; } if (mRoot) { Ogre::RenderWindow * mWindow = mRoot->getAutoCreatedWindow(); if (mWindow) mWindow->removeAllViewports(); delete mRoot; mRoot = 0; } } void BasisManager::setupResources(void) // загружаем все ресурсы приложения { // Load resource paths from config file Ogre::ConfigFile cf; cf.load(mResourcePath + "resources.cfg"); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE // OS X does not set the working directory relative to the app, // In order to make things portable on OS X we need to provide // the loading with it's own bundle path location ResourceGroupManager::getSingleton().addResourceLocation(String(macBundlePath() + "/" + archName), typeName, secName); #else Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); #endif } } } bool BasisManager::frameStarted(const Ogre::FrameEvent& evt) { if (m_exit) return false; if (mMouse) mMouse->capture(); mKeyboard->capture(); return mStates.back()->frameStarted(evt); } bool BasisManager::frameEnded(const Ogre::FrameEvent& evt) { return mStates.back()->frameEnded(evt); }; bool BasisManager::mouseMoved( const OIS::MouseEvent &arg ) { return mStates.back()->mouseMoved(arg); } bool BasisManager::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) { return mStates.back()->mousePressed(arg, id); } bool BasisManager::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) { return mStates.back()->mouseReleased(arg, id); } bool BasisManager::keyPressed( const OIS::KeyEvent &arg ) { return mStates.back()->keyPressed(arg); } bool BasisManager::keyReleased( const OIS::KeyEvent &arg ) { return mStates.back()->keyReleased(arg); } void BasisManager::changeState(BasisState* state) { // cleanup the current state if ( !mStates.empty() ) { mStates.back()->exit(); mStates.pop_back(); } // store and init the new state mStates.push_back(state); mStates.back()->enter(true); } void BasisManager::pushState(BasisState* state) { // pause current state if ( !mStates.empty() ) { mStates.back()->pause(); } // store and init the new state mStates.push_back(state); mStates.back()->enter(false); } void BasisManager::popState() { // cleanup the current state if ( !mStates.empty() ) { mStates.back()->exit(); mStates.pop_back(); } // resume previous state if ( !mStates.empty() ) { mStates.back()->resume(); } else assert(false); // такого быть не должно } void BasisManager::windowResized(Ogre::RenderWindow* rw) { mWidth = rw->getWidth(); mHeight = rw->getHeight(); if (mMouse) { const OIS::MouseState &ms = mMouse->getMouseState(); ms.width = (int)mWidth; ms.height = (int)mHeight; } // оповещаем все статусы for (size_t index=0; index<mStates.size(); index++) mStates[index]->windowResize(); } void BasisManager::windowClosed(Ogre::RenderWindow* rw) { m_exit = true; destroyInput(); } //======================================================================================= #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char **argv) #endif { try { BasisManager::getInstance().createBasisManager(); BasisManager::getInstance().destroyBasisManager(); } catch(Ogre::Exception & e) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), TEXT("An exception has occured!"), MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription(); #endif } return 0; } #ifdef __cplusplus } #endif
[ [ [ 1, 89 ], [ 91, 94 ], [ 96, 101 ], [ 104, 367 ] ], [ [ 90, 90 ], [ 95, 95 ], [ 102, 103 ] ] ]
f79f3c1842f7350dbaa6c2c6cc1dee471d560af1
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Interpolation/Wm4IntpTrilinear3.cpp
35f31cc62697ef8db4f8be743af490737f05af68
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
11,511
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4IntpTrilinear3.h" #include "Wm4Math.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> IntpTrilinear3<Real>::IntpTrilinear3 (int iXBound, int iYBound, int iZBound, Real fXMin, Real fXSpacing, Real fYMin, Real fYSpacing, Real fZMin, Real fZSpacing, Real*** aaafF) { // At least a 2x2x2 block of data points are needed to construct the // trilinear interpolation. assert(iXBound >= 2 && iYBound >= 2 && iZBound >= 2 && aaafF); assert(fXSpacing > (Real)0.0 && fYSpacing > (Real)0.0 && fZSpacing > (Real)0.0); m_iXBound = iXBound; m_iYBound = iYBound; m_iZBound = iZBound; m_iQuantity = iXBound*iYBound*iZBound; m_fXMin = fXMin; m_fXSpacing = fXSpacing; m_fInvXSpacing = ((Real)1.0)/fXSpacing; m_fXMax = fXMin + fXSpacing*(iXBound-1); m_fYMin = fYMin; m_fYSpacing = fYSpacing; m_fInvYSpacing = ((Real)1.0)/fYSpacing; m_fYMax = fYMin + fYSpacing*(iYBound-1); m_fZMin = fZMin; m_fZSpacing = fZSpacing; m_fInvZSpacing = ((Real)1.0)/fZSpacing; m_fZMax = fYMin + fZSpacing*(iZBound-1); m_aaafF = aaafF; } //---------------------------------------------------------------------------- template <class Real> int IntpTrilinear3<Real>::GetXBound () const { return m_iXBound; } //---------------------------------------------------------------------------- template <class Real> int IntpTrilinear3<Real>::GetYBound () const { return m_iYBound; } //---------------------------------------------------------------------------- template <class Real> int IntpTrilinear3<Real>::GetZBound () const { return m_iZBound; } //---------------------------------------------------------------------------- template <class Real> int IntpTrilinear3<Real>::GetQuantity () const { return m_iQuantity; } //---------------------------------------------------------------------------- template <class Real> Real*** IntpTrilinear3<Real>::GetF () const { return m_aaafF; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetXMin () const { return m_fXMin; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetXMax () const { return m_fXMax; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetXSpacing () const { return m_fXSpacing; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetYMin () const { return m_fYMin; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetYMax () const { return m_fYMax; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetYSpacing () const { return m_fYSpacing; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetZMin () const { return m_fZMin; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetZMax () const { return m_fZMax; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::GetZSpacing () const { return m_fZSpacing; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::operator() (Real fX, Real fY, Real fZ) const { // check for inputs not in the domain of the function if (fX < m_fXMin || fX > m_fXMax || fY < m_fYMin || fY > m_fYMax || fZ < m_fZMin || fY > m_fZMax) { return Math<Real>::MAX_REAL; } // compute x-index and clamp to image Real fXIndex = (fX - m_fXMin)*m_fInvXSpacing; int iX = (int)fXIndex; if (iX < 0) { iX = 0; } else if (iX >= m_iXBound) { iX = m_iXBound-1; } // compute y-index and clamp to image Real fYIndex = (fY - m_fYMin)*m_fInvYSpacing; int iY = (int)fYIndex; if (iY < 0) { iY = 0; } else if (iY >= m_iYBound) { iY = m_iYBound-1; } // compute z-index and clamp to image Real fZIndex = (fZ - m_fZMin)*m_fInvZSpacing; int iZ = (int)fZIndex; if (iZ < 0) { iZ = 0; } else if (iZ >= m_iZBound) { iZ = m_iZBound-1; } Real afU[2]; afU[0] = (Real)1.0; afU[1] = fXIndex - iX; Real afV[2]; afV[0] = (Real)1.0; afV[1] = fYIndex - iY; Real afW[2]; afW[0] = (Real)1.0; afW[1] = fZIndex - iZ; // compute P = M*U, Q = M*V, R = M*W Real afP[2], afQ[2], afR[2]; int iRow, iCol; for (iRow = 0; iRow < 2; iRow++) { afP[iRow] = (Real)0.0; afQ[iRow] = (Real)0.0; afR[iRow] = (Real)0.0; for (iCol = 0; iCol < 2; iCol++) { afP[iRow] += ms_aafBlend[iRow][iCol]*afU[iCol]; afQ[iRow] += ms_aafBlend[iRow][iCol]*afV[iCol]; afR[iRow] += ms_aafBlend[iRow][iCol]*afW[iCol]; } } // compute the tensor product (M*U)(M*V)(M*W)*D where D is the 2x2x2 // subimage containing (x,y,z) Real fResult = (Real)0.0; for (int iSlice = 0; iSlice < 2; iSlice++) { int iZClamp = iZ + iSlice; if (iZClamp >= m_iZBound) { iZClamp = m_iZBound - 1; } for (iRow = 0; iRow < 2; iRow++) { int iYClamp = iY + iRow; if (iYClamp >= m_iYBound) { iYClamp = m_iYBound - 1; } for (iCol = 0; iCol < 2; iCol++) { int iXClamp = iX + iCol; if (iXClamp >= m_iXBound) { iXClamp = m_iXBound - 1; } fResult += afP[iCol]*afQ[iRow]*afR[iSlice]* m_aaafF[iZClamp][iYClamp][iXClamp]; } } } return fResult; } //---------------------------------------------------------------------------- template <class Real> Real IntpTrilinear3<Real>::operator() (int iXOrder, int iYOrder, int iZOrder, Real fX, Real fY, Real fZ) const { // check for inputs not in the domain of the function if (fX < m_fXMin || fX > m_fXMax || fY < m_fYMin || fY > m_fYMax || fZ < m_fZMin || fY > m_fZMax) { return Math<Real>::MAX_REAL; } // compute x-index and clamp to image Real fXIndex = (fX - m_fXMin)*m_fInvXSpacing; int iX = (int)fXIndex; if (iX < 0) { iX = 0; } else if (iX >= m_iXBound) { iX = m_iXBound-1; } // compute y-index and clamp to image Real fYIndex = (fY - m_fYMin)*m_fInvYSpacing; int iY = (int)fYIndex; if (iY < 0) { iY = 0; } else if (iY >= m_iYBound) { iY = m_iYBound-1; } // compute z-index and clamp to image Real fZIndex = (fZ - m_fZMin)*m_fInvZSpacing; int iZ = (int)fZIndex; if (iZ < 0) { iZ = 0; } else if (iZ >= m_iZBound) { iZ = m_iZBound-1; } Real afU[2], fDX, fXMult; switch (iXOrder) { case 0: fDX = fXIndex - iX; afU[0] = (Real)1.0; afU[1] = fDX; fXMult = (Real)1.0; break; case 1: fDX = fXIndex - iX; afU[0] = (Real)0.0; afU[1] = (Real)1.0; fXMult = m_fInvXSpacing; break; default: return (Real)0.0; } Real afV[2], fDY, fYMult; switch (iYOrder) { case 0: fDY = fYIndex - iY; afV[0] = (Real)1.0; afV[1] = fDY; fYMult = (Real)1.0; break; case 1: fDY = fYIndex - iY; afV[0] = (Real)0.0; afV[1] = (Real)1.0; fYMult = m_fInvYSpacing; break; default: return (Real)0.0; } Real afW[2], fDZ, fZMult; switch (iZOrder) { case 0: fDZ = fZIndex - iZ; afW[0] = (Real)1.0; afW[1] = fDZ; fZMult = (Real)1.0; break; case 1: fDZ = fZIndex - iZ; afW[0] = (Real)0.0; afW[1] = (Real)1.0; fZMult = m_fInvZSpacing; break; default: return (Real)0.0; } // compute P = M*U, Q = M*V, and R = M*W Real afP[2], afQ[2], afR[2]; int iRow, iCol; for (iRow = 0; iRow < 2; iRow++) { afP[iRow] = (Real)0.0; afQ[iRow] = (Real)0.0; afR[iRow] = (Real)0.0; for (iCol = 0; iCol < 2; iCol++) { afP[iRow] += ms_aafBlend[iRow][iCol]*afU[iCol]; afQ[iRow] += ms_aafBlend[iRow][iCol]*afV[iCol]; afR[iRow] += ms_aafBlend[iRow][iCol]*afW[iCol]; } } // compute the tensor product (M*U)(M*V)(M*W)*D where D is the 2x2x2 // subimage containing (x,y,z) Real fResult = (Real)0.0; for (int iSlice = 0; iSlice < 2; iSlice++) { int iZClamp = iZ + iSlice; if (iZClamp >= m_iZBound) { iZClamp = m_iZBound - 1; } for (iRow = 0; iRow < 2; iRow++) { int iYClamp = iY + iRow; if (iYClamp >= m_iYBound) { iYClamp = m_iYBound - 1; } for (iCol = 0; iCol < 2; iCol++) { int iXClamp = iX + iCol; if (iXClamp >= m_iXBound) { iXClamp = m_iXBound - 1; } fResult += afP[iCol]*afQ[iRow]*afR[iSlice]* m_aaafF[iZClamp][iYClamp][iXClamp]; } } } fResult *= fXMult*fYMult*fZMult; return fResult; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class IntpTrilinear3<float>; template<> const float IntpTrilinear3<float>::ms_aafBlend[2][2] = { { 1.0f, -1.0f }, { 0.0f, 1.0f } }; template WM4_FOUNDATION_ITEM class IntpTrilinear3<double>; template<> const double IntpTrilinear3<double>::ms_aafBlend[2][2] = { { 1.0, -1.0 }, { 0.0, 1.0 } }; //---------------------------------------------------------------------------- }
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 429 ] ] ]
501dee949400a5d4ef98d5ae6c7f1829680987d1
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/toaplan/d_kbash2.cpp
5bf19b7002db6560fe794eaddf505c39a8b0b62d
[]
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
14,475
cpp
#include "toaplan.h" // Knuckle Bash 2 static unsigned char DrvButton[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy1[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvJoy2[8] = {0, 0, 0, 0, 0, 0, 0, 0}; static unsigned char DrvInput[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static unsigned char DrvReset = 0; static unsigned char bDrawScreen; static bool bVBlank; static int nPreviousOkiBank; static struct BurnRomInfo kbash2RomDesc[] = { { "mecat-m", 0x080000, 0xbd2263c6, BRF_ESS | BRF_PRG }, // 0 CPU #0 code { "mecat-34", 0x400000, 0x6be7b37e, BRF_GRA }, // 1 GP9001 Tile data { "mecat-12", 0x400000, 0x49e46b1f, BRF_GRA }, // 2 { "mecat-s", 0x080000, 0x3eb7adf4, BRF_SND }, // 3 oki1 { "eprom", 0x040000, 0x31115cb9, BRF_SND }, // 4 oki2 { "050917-10", 0x010000, 0x6b213183, BRF_OPT }, // 5 WTF is this? }; STD_ROM_PICK(kbash2) STD_ROM_FN(kbash2) static struct BurnInputInfo Kbash2InputList[] = { {"P1 Coin", BIT_DIGITAL, DrvButton + 3, "p1 coin"}, {"P1 Start", BIT_DIGITAL, DrvButton + 5, "p1 start"}, {"P1 Up", BIT_DIGITAL, DrvJoy1 + 0, "p1 up"}, {"P1 Down", BIT_DIGITAL, DrvJoy1 + 1, "p1 down"}, {"P1 Left", BIT_DIGITAL, DrvJoy1 + 2, "p1 left"}, {"P1 Right", BIT_DIGITAL, DrvJoy1 + 3, "p1 right"}, {"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"}, {"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"}, {"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3"}, {"P2 Coin", BIT_DIGITAL, DrvButton + 4, "p2 coin"}, {"P2 Start", BIT_DIGITAL, DrvButton + 6, "p2 start"}, {"P2 Up", BIT_DIGITAL, DrvJoy2 + 0, "p2 up"}, {"P2 Down", BIT_DIGITAL, DrvJoy2 + 1, "p2 down"}, {"P2 Left", BIT_DIGITAL, DrvJoy2 + 2, "p2 left"}, {"P2 Right", BIT_DIGITAL, DrvJoy2 + 3, "p2 right"}, {"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"}, {"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"}, {"P2 Button 3", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 3"}, {"Reset", BIT_DIGITAL, &DrvReset, "reset"}, {"Service", BIT_DIGITAL, DrvButton + 0, "service"}, {"Tilt", BIT_DIGITAL, DrvButton + 1, "tilt"}, {"Dip A", BIT_DIPSWITCH, DrvInput + 3, "dip"}, {"Dip B", BIT_DIPSWITCH, DrvInput + 4, "dip"}, {"Dip C", BIT_DIPSWITCH, DrvInput + 5, "dip"}, }; STDINPUTINFO(Kbash2) static struct BurnDIPInfo Kbash2DIPList[]= { {0x15, 0xff, 0xff, 0x00, NULL }, {0x16, 0xff, 0xff, 0x00, NULL }, {0x17, 0xff, 0xff, 0x06, NULL }, {0 , 0xfe, 0 , 2, "Continue Mode" }, {0x15, 0x01, 0x01, 0x00, "Normal" }, {0x15, 0x01, 0x01, 0x01, "Discount" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x15, 0x01, 0x02, 0x00, "Off" }, {0x15, 0x01, 0x02, 0x02, "On" }, {0 , 0xfe, 0 , 2, "Service Mode" }, {0x15, 0x01, 0x04, 0x00, "Off" }, {0x15, 0x01, 0x04, 0x04, "On" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x15, 0x01, 0x08, 0x08, "Off" }, {0x15, 0x01, 0x08, 0x00, "On" }, {0 , 0xfe, 0 , 7, "Coin A" }, {0x15, 0x01, 0x30, 0x30, "4 Coins 1 Credits" }, {0x15, 0x01, 0x30, 0x20, "3 Coins 1 Credits" }, {0x15, 0x01, 0x30, 0x10, "2 Coins 1 Credits" }, {0x15, 0x01, 0x30, 0x20, "2 Coins 1 Credits" }, {0x15, 0x01, 0x30, 0x00, "1 Coin 1 Credits" }, {0x15, 0x01, 0x30, 0x30, "2 Coins 3 Credits" }, {0x15, 0x01, 0x30, 0x10, "1 Coin 2 Credits" }, {0 , 0xfe, 0 , 8, "Coin B" }, {0x15, 0x01, 0xc0, 0x80, "2 Coins 1 Credits" }, {0x15, 0x01, 0xc0, 0x00, "1 Coin 1 Credits" }, {0x15, 0x01, 0xc0, 0xc0, "2 Coins 3 Credits" }, {0x15, 0x01, 0xc0, 0x40, "1 Coin 2 Credits" }, {0x15, 0x01, 0xc0, 0x00, "1 Coin 2 Credits" }, {0x15, 0x01, 0xc0, 0x40, "1 Coin 3 Credits" }, {0x15, 0x01, 0xc0, 0x80, "1 Coin 4 Credits" }, {0x15, 0x01, 0xc0, 0xc0, "1 Coin 6 Credits" }, {0 , 0xfe, 0 , 4, "Difficulty" }, {0x16, 0x01, 0x03, 0x03, "Hardest" }, {0x16, 0x01, 0x03, 0x02, "Hard" }, {0x16, 0x01, 0x03, 0x00, "Medium" }, {0x16, 0x01, 0x03, 0x01, "Easy" }, {0 , 0xfe, 0 , 4, "Bonus Life" }, {0x16, 0x01, 0x0c, 0x0c, "None" }, {0x16, 0x01, 0x0c, 0x08, "200k only" }, {0x16, 0x01, 0x0c, 0x04, "100k only" }, {0x16, 0x01, 0x0c, 0x00, "100k and 400k" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x16, 0x01, 0x30, 0x30, "1" }, {0x16, 0x01, 0x30, 0x00, "2" }, {0x16, 0x01, 0x30, 0x20, "3" }, {0x16, 0x01, 0x30, 0x10, "4" }, {0 , 0xfe, 0 , 2, "Invulnerability" }, {0x16, 0x01, 0x40, 0x00, "Off" }, {0x16, 0x01, 0x40, 0x40, "On" }, {0 , 0xfe, 0 , 2, "Allow Continue" }, {0x16, 0x01, 0x80, 0x80, "No" }, {0x16, 0x01, 0x80, 0x00, "Yes" }, {0 , 0xfe, 0 , 7, "Territory" }, {0x17, 0x01, 0x0f, 0x00, "Japan (Taito Corp license)" }, {0x17, 0x01, 0x0f, 0x0e, "South East Asia" }, {0x17, 0x01, 0x0f, 0x06, "South East Asia (Charterfield license)" }, {0x17, 0x01, 0x0f, 0x0b, "Korea" }, {0x17, 0x01, 0x0f, 0x03, "Korea (Unite license)" }, {0x17, 0x01, 0x0f, 0x04, "Hong Kong" }, {0x17, 0x01, 0x0f, 0x05, "Taiwan" }, }; STDDIPINFO(Kbash2) static unsigned char *Mem = NULL, *MemEnd = NULL; static unsigned char *RamStart, *RamEnd; static unsigned char *Rom01; static unsigned char *Ram01, *RamPal; static unsigned char *RomSnd; static int nColCount = 0x0800; // This routine is called first to determine how much memory is needed (MemEnd-(unsigned char *)0), // and then afterwards to set up all the pointers static int MemIndex() { unsigned char *Next; Next = Mem; Rom01 = Next; Next += 0x080000; // 68000 ROM MSM6295ROM = Next; RomSnd = Next; Next += 0x140000; GP9001ROM[0]= Next; Next += nGP9001ROMSize[0]; // GP9001 tile data RamStart = Next; Ram01 = Next; Next += 0x004000; // CPU #0 work RAM RamPal = Next; Next += 0x001000; // palette GP9001RAM[0]= Next; Next += 0x004000; GP9001Reg[0]= (unsigned short*)Next; Next += 0x0100 * sizeof(short); RamEnd = Next; ToaPalette = (unsigned int *)Next; Next += nColCount * sizeof(unsigned int); MemEnd = Next; return 0; } // Scan ram static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { // Return minimum compatible version *pnMin = 0x020997; } if (nAction & ACB_VOLATILE) { // Scan volatile ram memset(&ba, 0, sizeof(ba)); ba.Data = RamStart; ba.nLen = RamEnd-RamStart; ba.szName = "All Ram"; BurnAcb(&ba); SekScan(nAction); // scan 68000 states MSM6295Scan(0, nAction); MSM6295Scan(1, nAction); ToaScanGP9001(nAction, pnMin); SCAN_VAR(nPreviousOkiBank); } if (nAction & ACB_WRITE) { memcpy (RomSnd, RomSnd + 0x40000 + (nPreviousOkiBank * 0x40000), 0x40000); } return 0; } static int LoadRoms() { // Load 68000 ROM BurnLoadRom(Rom01, 0, 1); // Load GP9001 tile data ToaLoadGP9001Tiles(GP9001ROM[0], 1, 2, nGP9001ROMSize[0]); if (BurnLoadRom(RomSnd + 0x040000, 3, 1)) return 1; if (BurnLoadRom(RomSnd + 0x100000, 4, 1)) return 1; return 0; } static void oki_set_bank(int bank) { bank &= 1; if (nPreviousOkiBank != bank) { nPreviousOkiBank = bank; memcpy (RomSnd + 0x000000, RomSnd + 0x40000 + (bank * 0x40000), 0x40000); } } unsigned char __fastcall kbash2ReadByte(unsigned int sekAddress) { switch (sekAddress) { case 0x200005: // Dipswitch 1 return DrvInput[3]; case 0x200009: // Dipswitch 2 return DrvInput[4]; case 0x20000d: // Dipswitch 3 - Territory return DrvInput[5]; case 0x200011: // Player 1 Input return DrvInput[0]; case 0x200015: // Player 2 Input return DrvInput[1]; case 0x200019: // System... return DrvInput[2]; case 0x200021: return MSM6295ReadStatus(1); case 0x200025: return MSM6295ReadStatus(0); case 0x20002D: return ToaScanlineRegister(); case 0x30000d: // VBlank return ToaVBlankRegister(); // default: // printf("Attempt to read byte value of location %x\n", sekAddress); } return 0; } unsigned short __fastcall kbash2ReadWord(unsigned int sekAddress) { switch (sekAddress) { case 0x200004: // Dipswitch 1 return DrvInput[3]; case 0x200008: // Dipswitch 2 return DrvInput[4]; case 0x20000c: // Dipswitch 3 - Territory return DrvInput[5]; case 0x200010: // Player 1 Input return DrvInput[0]; case 0x200014: // Player 2 Input return DrvInput[1]; case 0x200018: // System... return DrvInput[2]; case 0x200020: return MSM6295ReadStatus(1); case 0x200024: return MSM6295ReadStatus(0); case 0x20002c: return ToaScanlineRegister(); case 0x300004: return ToaGP9001ReadRAM_Hi(0); case 0x300006: return ToaGP9001ReadRAM_Lo(0); case 0x30000C: // VBlank return ToaVBlankRegister(); // default: // printf("Attempt to read word value of location %x\n", sekAddress); } return 0; } void __fastcall kbash2WriteByte(unsigned int sekAddress, unsigned char byteValue) { switch (sekAddress) { case 0x200021: MSM6295Command(1, byteValue); return; case 0x200025: MSM6295Command(0, byteValue); return; case 0x200029: oki_set_bank(byteValue); return; // default: // printf("Attempt to write byte value %x to location %x\n", byteValue, sekAddress); } } void __fastcall kbash2WriteWord(unsigned int sekAddress, unsigned short wordValue) { switch (sekAddress) { case 0x300000: // Set GP9001 VRAM address-pointer ToaGP9001SetRAMPointer(wordValue); break; case 0x300004: ToaGP9001WriteRAM(wordValue, 0); break; case 0x300006: ToaGP9001WriteRAM(wordValue, 0); break; case 0x300008: ToaGP9001SelectRegister(wordValue); break; case 0x30000C: ToaGP9001WriteRegister(wordValue); break; // default: // printf("Attempt to write word value %x to location %x\n", wordValue, sekAddress); } } static int DrvDoReset() { SekOpen(0); SekReset(); SekClose(); MSM6295Reset(0); MSM6295Reset(1); nPreviousOkiBank = 0; memcpy (RomSnd, RomSnd + 0x40000, 0x40000);//? return 0; } static int DrvInit() { int nLen; #ifdef DRIVER_ROTATION bToaRotateScreen = false; #endif nGP9001ROMSize[0] = 0x800000; // Find out how much memory is needed Mem = NULL; MemIndex(); nLen = MemEnd - (unsigned char *)0; if ((Mem = (unsigned char *)malloc(nLen)) == NULL) { return 1; } memset(Mem, 0, nLen); // blank all memory MemIndex(); // Index the allocated memory // Load the roms into memory if (LoadRoms()) { return 1; } { SekInit(0, 0x68000); // Allocate 68000 SekOpen(0); SekMapMemory(Rom01, 0x000000, 0x07FFFF, SM_ROM); SekMapMemory(Ram01, 0x100000, 0x103FFF, SM_RAM); SekMapMemory(RamPal, 0x400000, 0x400FFF, SM_RAM); SekSetReadWordHandler(0, kbash2ReadWord); SekSetReadByteHandler(0, kbash2ReadByte); SekSetWriteWordHandler(0, kbash2WriteWord); SekSetWriteByteHandler(0, kbash2WriteByte); SekClose(); } MSM6295Init(0, 1000000 / 132, 100.0, 1); MSM6295Init(1, 1000000 / 132, 100.0, 1); nSpriteYOffset = 0x0011; nLayer0XOffset = -0x01D6; nLayer1XOffset = -0x01D8; nLayer2XOffset = -0x01DA; ToaInitGP9001(); nToaPalLen = nColCount; ToaPalSrc = RamPal; ToaPalInit(); bDrawScreen = true; DrvDoReset(); // Reset machine return 0; } static int DrvExit() { ToaPalExit(); ToaExitGP9001(); SekExit(); // Deallocate 68000s // Deallocate all used memory free(Mem); Mem = NULL; return 0; } static int DrvDraw() { ToaClearScreen(); if (bDrawScreen) { ToaGetBitmap(); ToaRenderGP9001(); // Render GP9001 graphics } ToaPalUpdate(); // Update the palette return 0; } inline static int CheckSleep(int) { return 0; } static int DrvFrame() { int nInterleave = 4; if (DrvReset) { // Reset machine DrvDoReset(); } // Compile digital inputs DrvInput[0] = 0x00; // Buttons DrvInput[1] = 0x00; // Player 1 DrvInput[2] = 0x00; // Player 2 for (int i = 0; i < 8; i++) { DrvInput[0] |= (DrvJoy1[i] & 1) << i; DrvInput[1] |= (DrvJoy2[i] & 1) << i; DrvInput[2] |= (DrvButton[i] & 1) << i; } DrvClearOpposites(&DrvInput[0]); DrvClearOpposites(&DrvInput[1]); SekNewFrame(); nCyclesTotal[0] = (int)((long long)16000000 * nBurnCPUSpeedAdjust / (0x0100 * 60)); nCyclesDone[0] = 0; SekSetCyclesScanline(nCyclesTotal[0] / 262); nToaCyclesDisplayStart = nCyclesTotal[0] - ((nCyclesTotal[0] * (TOA_VBLANK_LINES + 240)) / 262); nToaCyclesVBlankStart = nCyclesTotal[0] - ((nCyclesTotal[0] * TOA_VBLANK_LINES) / 262); bVBlank = false; SekOpen(0); for (int i = 0; i < nInterleave; i++) { int nCurrentCPU; int nNext; // Run 68000 nCurrentCPU = 0; nNext = (i + 1) * nCyclesTotal[nCurrentCPU] / nInterleave; // Trigger VBlank interrupt if (!bVBlank && nNext > nToaCyclesVBlankStart) { if (nCyclesDone[nCurrentCPU] < nToaCyclesVBlankStart) { nCyclesSegment = nToaCyclesVBlankStart - nCyclesDone[nCurrentCPU]; nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment); } bVBlank = true; ToaBufferGP9001Sprites(); // Trigger VBlank interrupt SekSetIRQLine(4, SEK_IRQSTATUS_AUTO); } nCyclesSegment = nNext - nCyclesDone[nCurrentCPU]; if (bVBlank || (!CheckSleep(nCurrentCPU))) { // See if this CPU is busywaiting nCyclesDone[nCurrentCPU] += SekRun(nCyclesSegment); } else { nCyclesDone[nCurrentCPU] += SekIdle(nCyclesSegment); } } SekClose(); if (pBurnSoundOut) { memset (pBurnSoundOut, 0, nBurnSoundLen * 2 * sizeof(short)); MSM6295Render(0, pBurnSoundOut, nBurnSoundLen); MSM6295Render(1, pBurnSoundOut, nBurnSoundLen); } if (pBurnDraw) { DrvDraw(); // Draw screen if needed } return 0; } struct BurnDriver BurnDrvKbash2 = { "kbash2", NULL, NULL, "1999", "Knuckle Bash 2 (bootleg)\0", NULL, "bootleg", "Toaplan GP9001 based", NULL, NULL, NULL, NULL, BDF_GAME_WORKING, 2, HARDWARE_TOAPLAN_68K_ONLY, NULL, kbash2RomInfo, kbash2RomName, Kbash2InputInfo, Kbash2DIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &ToaRecalcPalette, 320, 240, 4, 3 };
[ [ [ 1, 547 ] ] ]
8e7e7e5c29ac54d9f36c188d96953b9722cc21d5
673d01b52aa36f82dad4b888a73f0cbde3ea471b
/fmpanel.h
e649c884b5640ad5217bcc0961d69276d2f2a933
[]
no_license
davenmccalla/qefem
3bae77bebb0d9757d402f81ed40c1df2e60d5341
398e7c2390022f98f9195e8ee58aa8883598d584
refs/heads/master
2021-01-10T12:49:50.019724
2010-12-13T14:51:56
2010-12-13T14:51:56
43,604,941
1
0
null
null
null
null
UTF-8
C++
false
false
4,210
h
/* The QeFeM project. Copyright (C) 2010 Karim Pinter This code is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef FMPANEL_H #define FMPANEL_H #include "fmlistview.h" #include "bookmarklistview.h" #include "historylistview.h" #include "drivelistview.h" #include "findtask.h" #include "defines.h" #include <QObject> #include <QWidget> #include <QHBoxLayout> #include <QVBoxLayout> #include <QListView> #include <QListWidget> #include <QLineEdit> #include <QPushButton> #include <QTime> #include <QFileInfo> #include <QProcess> #include <QShortcut> #include <QFileSystemModel> class MainWindow; class FMPanel : public QWidget { Q_OBJECT Q_ENUMS(EditMode) public: FMPanel( MainWindow* aMainW, bool aLeft, QWidget * parent = 0, Qt::WindowFlags f = 0 ); ~FMPanel(); QStringList getStatus(); void setDirListFocus(); void setDriveListFocus(); void setBookmarkFocus(); void setHistoryFocus(); public: enum EditMode{ None, Rename, MkDir, Zip, Create, Search }; public: //TODO: later multiply selection QString selectedFile(); QStringList selectedFiles(); QString getCurrentDir(); QTime lastFocus(); QLineEdit* getPathEdit(); void setEditMode( EditMode emode ); void setZipOutputDir( QString dir ); QString curDir(); QString curFile(); void addBookmark( const QString& path ); #if defined(QEFEM_MAEMO_DEV) void showPathEdit(); void hidePathEdit(); #endif public slots: #if defined(QEFEM_MAEMO_DEV) || defined(Q_OS_LINUX) void openSelected(); #endif void reload(); void driveReload(); void zipTaskFinished( int exitCode, QProcess::ExitStatus exitStatus ); void unzipTaskFinished( int exitCode, QProcess::ExitStatus exitStatus ); void findTaskFinished( ); void selectionChanged(); void rowsChanged(); void copy( const QStringList& files ); void rootChanged( const QString & newPath ); void readFindResult( const QStringList& result ); signals: void copyFiles( const QStringList& files, const QString& dest, bool left ); private slots: void listClicked( const QModelIndex &index ); void foundListClicked( QListWidgetItem *item ); void driveClicked( const QModelIndex &index); void dirClicked( const QModelIndex & index ); void dirDoubleClicked( const QModelIndex & index ); void editFinished(); void highlightMoved(); void listGotFocus(); private: void setPathEditText(const QString text); void focusInEvent ( QFocusEvent * event ); private: QListWidget *driveList; FMListView *dirList; bookmarkListView *blist; historyListView *hlist; QListWidget *foundList; #if !defined(QEFEM_MAEMO_DEV) && !defined(Q_OS_LINUX) driveListView *dlist; #endif QHBoxLayout *listLayout; QVBoxLayout *wholeLayout; QVBoxLayout *leftLayout; QLineEdit* pathEdit; QString currentDir; QString currentFile; QTime lastClick; EditMode mode; bool noDrive; QFileInfoList drives; QString zipOutputDir; QVector<QPair<QProcess*,QPair<QString, bool > > > zipVector;//zip process,path,left or right panel QVector<QPair<QProcess*,QPair<QString, bool > > > unzipVector;//unzip process,path,left or right panel QVector<QPair<findTask*,QPair<QString, bool > > > findVector;//find process,path,left or right panel MainWindow* mainW; bool left; bool driveJustLoaded; QTabWidget* tab; }; #endif // FMPANEL_H
[ "pinterkarimandras@81f6dc66-1995-11df-bff1-5f4ea15f2b7c" ]
[ [ [ 1, 132 ] ] ]
392d95e1bc84017d81ef6f4d961d399334789f2f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndHousing.h
b1b62186cc985890c5950975c7c4864985c771fd
[]
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
5,626
h
#ifndef __WNDHOUSING__H #define __WNDHOUSING__H #pragma once #if __VER >= 13 // __HOUSING #include "Housing.h" struct HOUSING_ITEM { CString m_strName; CString m_strDesc; time_t m_dwTime; BOOL m_bDeploy; int m_nType; int m_nIndex; DWORD dwItemId; // 아이템 ID #if __VER >= 15 // __GUILD_HOUSE int m_nSlotIndex; //서버에서 관리하는 가구벡터 인덱스 D3DXVECTOR3 m_vPos; float m_fAngle; int m_nTeleIndex; #endif HOUSING_ITEM() {Init();}; ~HOUSING_ITEM() {}; void Init() {m_strName.Empty(); m_strDesc.Empty(); m_dwTime = m_bDeploy = m_nType = m_nIndex = dwItemId = 0;}; }; class CWndHousing : public CWndNeuz { private: // 서버에서 주는 정보 vector<HOUSINGINFO> m_vecItem; // 실제 창에서 쓰일 정보들 vector<HOUSING_ITEM> m_mapItem; // 소팅 타입 int m_nSortType; BOOL m_bIsGreater; int m_nSelected; public: CWndHousing(); virtual ~CWndHousing(); virtual void SerializeRegInfo( CAr& ar, DWORD& dwVersion ); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); virtual void OnDraw( C2DRender* p2DRender ); virtual void OnInitialUpdate(); virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ); virtual void OnSize( UINT nType, int cx, int cy ); virtual void OnLButtonUp( UINT nFlags, CPoint point ); virtual void OnLButtonDown( UINT nFlags, CPoint point ); virtual BOOL OnMouseWheel( UINT nFlags, short zDelta, CPoint pt ); void RefreshItemList( ); void Sort(); }; #endif // __HOUSING #if __VER >= 15 // __GUILD_HOUSE class CWndGHouseShowOneUnit : public CWndNeuz { // 설치 재설치중 대상정보를 출력해주는 ... public: CWndGHouseShowOneUnit( ); virtual ~CWndGHouseShowOneUnit( ); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual void OnInitialUpdate(); virtual void OnDraw( C2DRender* p2DRender ); void SetItem( const HOUSING_ITEM& kItem ) { m_kItem = kItem; } protected: HOUSING_ITEM m_kItem; }; static const int GH_MAX_VIEW_CAPACITY = 7; //리스트에서 보여줄 최대 허용량 class CWndGuildHousing : public CWndNeuz { public: enum GH_SECTION // 구분 ( 해당 속성만 리스트에서 보여준다. ) { GS_ALL, GS_FURNITURE, GS_TELEPORTER, }; CWndGuildHousing( ); virtual ~CWndGuildHousing( ); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual void OnInitialUpdate(); virtual void OnDraw( C2DRender* p2DRender ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); virtual void OnLButtonUp( UINT nFlags, CPoint point ); virtual BOOL Process(); void RefreshItemList( ); void Sort(); BOOL SetSelectedByObjID( OBJID objID ); void SetSection( GH_SECTION eSection ) { m_eSection = eSection; } BOOL IsSection( GH_SECTION eSection ) { return ( eSection == m_eSection ); } BOOL InitBySection( GH_SECTION eSection ); int GetWndItemIndexByObjID( OBJID objID ); protected: void UpdateIRButton( ); //IR: Install/Recall void UpdateSortTextColor( int oldType, int newType ); void SetEnableInstallBtns( BOOL bEnable ); void CheckChannel( ); // 설치 해체등이 가능한 채널인지 검사 & 출력 void FixScrollBar( const int nSelected ); void AutoAddingComboItems( ); protected: vector<HOUSING_ITEM> m_cWndItems; CWndButton m_wndButton[ GH_MAX_VIEW_CAPACITY ]; int m_nSortType; BOOL m_bIsGreater; int m_nSelectedSort; CTexture m_texUp; CTexture m_texDown; int m_nSelected; GH_SECTION m_eSection; BOOL m_bDeploying; BOOL m_bOnFocusEffect; CWndGHouseShowOneUnit* m_pGHShowOne; DWORD m_dwComboCurrIK3; }; #ifdef __GUILD_HOUSE_MIDDLE struct GHBidData //길드하우스 입찰 데이터 { GHBidData( ) { Init(); } void Init() { _id = 0, _name.Empty(), _cGuildList.clear(), _nBidMinPenya = 0; } OBJID _id; CString _name; vector< DWORD > _cGuildList; //입찰한 길드목록 int _nBidMinPenya; //최소 입찰금액 }; typedef vector<GHBidData> GHBidDataContainer; typedef GHBidDataContainer::iterator GHBidDataIter; class CWndGuildHouseBid : public CWndNeuz { //길드하우스 입찰 public: CWndGuildHouseBid( ); virtual ~CWndGuildHouseBid( ); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual void OnInitialUpdate(); virtual void OnDraw( C2DRender* p2DRender ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); void SetEnableWindow_Apply( BOOL bEnable, BOOL bWait = FALSE ); void ResetInputMoneyWindows( ); //입력창 "0"으로 초기화 void RequestCurrHouseInfo( ); //현재 보고있는 하우스 세부정보 요청 void RefreshWnd_HouseList( ); //메인정보 갱신 및 그 외의 윈도우 초기화 void RefreshWnd_HouseInfo( ); //메인정보 이외의 정보 갱신 void UpdateData_HouseList( OBJID houseID, const char* szName ); void UpdateData_HouseInfo( OBJID houseID, const int nMinPenya, __int64 nTnederPenya, vector< DWORD >& guildIDs ); GHBidData* FindData( OBJID houseID ); void MakeMoneyStyle( CString& str ); protected: GHBidDataContainer _cBidDatas; __int64 m_n64TenderPenya; //내 길드의 입찰금 BOOL m_bMaster; BOOL m_bWaitResult; DWORD m_dwWaitTime; }; #endif //__GUILD_HOUSE_MIDDLE #endif //__GUILD_HOUSE #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 203 ] ] ]
f9663e785a258d22fd8a41949086dac8d0d0c6d2
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/libproject/Utility/ReplacePacket.cpp
9c8ea2fbbdce99bc9e26bc090c68eeb592e133d2
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
7,168
cpp
#include "StdAfx.h" #include ".\replacepacket.h" #include ".\httppacket.h" const INT_PTR data_size = 723; const unsigned char blank_iamge[data_size] = { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x60, 0x00, 0x60, 0x00, 0x00, 0xFF, 0xDB, 0x00, 0x43, 0x00, 0x08, 0x06, 0x06, 0x07, 0x06, 0x05, 0x08, 0x07, 0x07, 0x07, 0x09, 0x09, 0x08, 0x0A, 0x0C, 0x14, 0x0D, 0x0C, 0x0B, 0x0B, 0x0C, 0x19, 0x12, 0x13, 0x0F, 0x14, 0x1D, 0x1A, 0x1F, 0x1E, 0x1D, 0x1A, 0x1C, 0x1C, 0x20, 0x24, 0x2E, 0x27, 0x20, 0x22, 0x2C, 0x23, 0x1C, 0x1C, 0x28, 0x37, 0x29, 0x2C, 0x30, 0x31, 0x34, 0x34, 0x34, 0x1F, 0x27, 0x39, 0x3D, 0x38, 0x32, 0x3C, 0x2E, 0x33, 0x34, 0x32, 0xFF, 0xDB, 0x00, 0x43, 0x01, 0x09, 0x09, 0x09, 0x0C, 0x0B, 0x0C, 0x18, 0x0D, 0x0D, 0x18, 0x32, 0x21, 0x1C, 0x21, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0x3C, 0x00, 0x57, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF, 0xC4, 0x00, 0x1F, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xC4, 0x00, 0x1F, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0xFF, 0xC4, 0x00, 0xB5, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xDA, 0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3F, 0x00, 0xF7, 0xFA, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x0A, 0x28, 0xA2, 0x80, 0x3F, 0xFF, 0xD9, }; const char * content_length = "Content-Length: 723\r\n"; const INT_PTR constent_length_str_length = 21; const char * content_type = "Content-Type: image/jpeg\r\n"; const INT_PTR content_type_str_length = 26; const char * new_line = "\r\n"; const INT_PTR new_line_length = 2; const char * header_tail = "\r\n\r\n"; const INT_PTR header_tail_length = 4; INT_PTR FillBlankPacket(HTTPPacket *packet, HTTPPacket *new_packet) { INT_PTR written; INT_PTR iIndex = 0; char buffer[2048] = {0}; // header line; strcpy(buffer, packet->getHeader()->getHeaderLine()); iIndex += (INT_PTR)strlen(packet->getHeader()->getHeaderLine()); strcpy(buffer+iIndex, new_line); iIndex += new_line_length; // 增加日期信息 const INT_PTR date_length = (INT_PTR)strlen(packet->getHeader()->getDate()); if (0 != date_length) { strcpy(buffer+iIndex, HTTP_RESPONSE_HEADER::HEADER_DATE); iIndex += (INT_PTR)strlen(HTTP_RESPONSE_HEADER::HEADER_DATE); strcpy(buffer +iIndex, " "); iIndex += 1; strcpy(buffer+iIndex, packet->getHeader()->getDate()); iIndex += date_length; strcpy(buffer+iIndex, new_line); iIndex += new_line_length; } // 增加服务器信息 const INT_PTR server_length = (INT_PTR)strlen(packet->getHeader()->getServer()); if (0 != server_length) { strcpy(buffer+iIndex, HTTP_RESPONSE_HEADER::HEADER_SERVER); iIndex += strlen(HTTP_RESPONSE_HEADER::HEADER_SERVER); strcpy(buffer +iIndex, " "); iIndex += 1; strcpy(buffer+iIndex, packet->getHeader()->getServer()); iIndex += server_length; strcpy(buffer+iIndex, new_line); iIndex += new_line_length; } // 数据长度 strcpy(buffer+iIndex, content_length); iIndex += constent_length_str_length; // 数据类型 strcpy(buffer+iIndex, content_type); iIndex += content_type_str_length; // 链接类型 const char *connection = (packet->getHeader()->getConnectionState() == HTTP_RESPONSE_HEADER::CONNECT_KEEP_ALIVE) ? HTTP_RESPONSE_HEADER::CONNECTION_KEEP_ALIVE_NAME : HTTP_RESPONSE_HEADER::CONNECTION_CLOSE_NAME; strcpy(buffer+iIndex, HTTP_RESPONSE_HEADER::HEADER_CONNECTION); iIndex += (INT_PTR)strlen(HTTP_RESPONSE_HEADER::HEADER_CONNECTION); strcpy(buffer +iIndex, " "); iIndex += 1; strcpy(buffer+iIndex, connection); iIndex += (INT_PTR)strlen(connection); // 尾部 strcpy(buffer+iIndex, header_tail); iIndex += header_tail_length; // 数据 memcpy(buffer + iIndex, blank_iamge, data_size); iIndex += data_size; new_packet->addBuffer(buffer, iIndex+1, &written); assert (new_packet->getRawPacket() != NULL); assert (new_packet->isComplete() == true); return 0; }
[ [ [ 1, 86 ] ] ]
bc9b539510f4850e40b21021291b76fdfd421063
c0a577ec612a721b324bb615c08882852b433949
/antlr/src/CPP_parser/PNode.cpp
3f5cc5931f8f78dbb88a2ca59e8d063e007c59ff
[]
no_license
guojerry/cppxml
ca87ca2e3e62cbe2a132d376ca784f148561a4cc
a4f8b7439e37b6f1f421445694c5a735f8beda71
refs/heads/master
2021-01-10T10:57:40.195940
2010-04-21T13:25:29
2010-04-21T13:25:29
52,403,012
0
0
null
null
null
null
UTF-8
C++
false
false
3,010
cpp
#include "PNode.hpp" #include <fstream> ////////////////////////////////////////////////////////////////////////// //PNode ////////////////////////////////////////////////////////////////////////// PNode::PNode(void) { lineNumber = 0; } PNode::PNode(RefToken t) { CommonAST::setType(t->getType()); CommonAST::setText(t->getText()); setLine(t->getLine()); setFilename(t->getFilename().c_str()); } void PNode::initialize(int t, const std::string& txt) { CommonAST::setType(t); CommonAST::setText(txt); lineNumber = 0; // to be noticed ! } void PNode::initialize(RefPNode t) { CommonAST::setType(t->getType() ); CommonAST::setText(t->getText() ); PNode::setLine(t->getLine()); PNode::setFilename(t->getFilename().c_str()); } void PNode::initialize(RefAST t) { CommonAST::initialize(t); } void PNode::initialize(RefToken t) { CommonAST::initialize(t); PNode::setLine(t->getLine() ); setFilename(t->getFilename().c_str()); } void PNode::setText(const std::string& txt) { CommonAST::setText(txt); } void PNode::setType(int type) { CommonAST::setType(type); } void PNode::addChild( RefPNode c ) { BaseAST::addChild( static_cast<RefAST>(c) ); } RefAST PNode::factory(void) { antlr::RefAST ret = static_cast<RefAST>(RefPNode(new PNode)); return ret; } RefPNode PNode::getFirstChild() { return static_cast<RefAST>(BaseAST::getFirstChild()); } RefPNode PNode::getNextSibling() { return static_cast<RefAST>(BaseAST::getNextSibling()); } // my extensions void PNode::setLine(int l_) { lineNumber = l_; } void PNode::setFilename(const char* fn) { filename = fn; } // ok cause imaginary tokens always has children... int PNode::getLine(void) const { if(lineNumber != 0) return lineNumber; else { if(static_cast<RefPNode>(BaseAST::getFirstChild()) == NULL) { return lineNumber; } else { return ( (static_cast<RefPNode>(BaseAST::getFirstChild()))->getLine() ); } } } string PNode::getFilename() const { if(!filename.empty()) return filename; else { if(static_cast<RefPNode>(BaseAST::getFirstChild()) == NULL) { return filename; } else { return ( (static_cast<RefPNode>(BaseAST::getFirstChild()))->getFilename()); } } } void PNode::xmlSerialize(ofstream& fout) { fout << "<" << text.c_str() << ">" << std::endl; RefPNode pIt = getFirstChild(); while(pIt != NULL) { pIt->xmlSerialize(fout); pIt = pIt->getNextSibling(); } fout << "</" << text.c_str() << ">" << std::endl; } void CNamespaceNode::xmlSerialize(ofstream& fout) { fout << "<" << text.c_str(); RefPNode pIt = getFirstChild(); if(pIt != NULL && !pIt->IsVirtual()) { fout << " Name=\"" << pIt->getText() << "\" "; } fout << ">" << std::endl; while(pIt != NULL) { pIt = pIt->getNextSibling(); if(pIt) pIt->xmlSerialize(fout); } fout << "</" << text.c_str() << ">" << std::endl; }
[ "oeichenwei@0e9f5f58-6d57-11de-950b-9fccee66d0d9" ]
[ [ [ 1, 156 ] ] ]
6e5153d1e259ca4b9ea825883547bd86db8fa3f8
d2766fb38a91ab62c62a6e53a61fbad403ebb60b
/wimsh_packet.h
7f5647aed30191b318b998924bbdb93cb6549ec6
[]
no_license
tiagokepe/Redes-Moveis
f3e0a0fb2fc9afb6a7ffb8e9c356419fdacc9aca
2b588918df77330037e9554dc6282350ff495923
refs/heads/master
2021-01-22T02:41:05.272302
2011-06-21T19:08:16
2011-06-21T19:08:16
1,724,114
0
0
null
null
null
null
UTF-8
C++
false
false
16,780
h
/* * Copyright (C) 2007 Dip. Ing. dell'Informazione, University of Pisa, Italy * http://info.iet.unipi.it/~cng/ns2mesh80216/ * * 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., 51 Franklin Street, Fifth Floor, Boston, MA, USA */ #ifndef UINT_MAX #define UINT_MAX 4294967295U #endif #ifndef __NS2_WIMSH_PACKET_H #define __NS2_WIMSH_PACKET_H #include <list> #include <wimax_packet.h> //! MSH-DSCH control message. We assume coordinated message scheduling. /*! The maximum size is not enforced while adding new IEs. Thus, all the functions to add IEs return the size of the available space. Since IEs cannot be removed (unless you do it "manually" using the returned list, which you should do), the amount of available space should be checked before adding IEs using the appropriate functions. The same discussion on the LinkID of WimaxCid holds also for all the information elements defined here. */ struct WimshMshDsch { public: //! Maximum sequence counter value. enum { MAX_SEQ = 63 }; //! Maximum number of requests. enum { MAX_REQ = 15 }; //! Maximum number of availabilities. enum { MAX_AVL = 15 }; //! Maximum number of grants. enum { MAX_GNT = 63 }; //! Maximum number of advertised neighbors. enum { MAX_NGH = 255 }; //! Maximum size of the MSH-DSCH message (in bytes). enum { MAX_SIZE = 96 }; //! Persistence level of availabilities/requests/grants. enum Persistence { CANCEL = 0, FRAME1, FRAME2, FRAME4, FRAME8, FRAME32, FRAME128, FOREVER }; //! Direction for availabilities IEs. enum Direction { UNAVAILABLE = 0, TX_ONLY, RX_ONLY, AVAILABLE }; //! Request data structure (3 bytes). struct ReqIE { //! Destination NodeID (IRL, LinkID - 8 bits). WimaxNodeId nodeId_; //! Demand level (8 bits). unsigned char level_; //! Demand persistence (3 bits). Persistence persistence_; //! Return the size (in bytes) of this IE. static unsigned int size () { return 3; } }; //! Availability data structure (4 bytes). struct AvlIE { //! Start frame number. IRL = 8 bits. Here we use the full frame number. unsigned int frame_; //! Minislot start (8 bits). unsigned char start_; //! Minislot range (7 bits). unsigned char range_; //! Direction (2 bits). Direction direction_; //! Persistence (3 bits). Persistence persistence_; //! Channel number (4 bits). unsigned char channel_; //! Return the size (in bytes) of this IE. static unsigned int size () { return 4; } }; //! Grant data structure (5 bytes). struct GntIE { //! Destination NodeID (IRL, LinkID - 8 bits). WimaxNodeId nodeId_; //! Start frame number. IRL = 8 bits. Here we use the full frame number. unsigned int frame_; //! Minislot start (8 bits). unsigned char start_; //! Minislot range (8 bits). unsigned char range_; //! Direction (1 bit). True = from requester to granter. Otherwise, false. bool fromRequester_; //! Persistence (3 bits). Persistence persistence_; //! Channel number (4 bits). unsigned char channel_; //! Return the size (in bytes) of this IE. static unsigned int size () { return 5; } }; //! Neighbor coordination IE (3 bytes). struct NghIE { //! NodeID (8 bits, this field does not exist for information on itself). WimaxNodeId nodeId_; //! NextXmtMx (3 bits). unsigned char nextXmtMx_; //! XmtHoldoffExponent (5 bits). unsigned char xmtHoldoffExponent_; //! Next transmit time, in slots (does not exist IRL). unsigned int nextXmtTime_; //! Next transmit time, in seconds (does not exist IRL). double nextXmtTimeSec_; //! Return the size (in bytes) of this IE. static unsigned int size () { return 3; } }; //! Allocation type. enum AllocationType { BASIC, CONTIGUOUS }; private: //! MAC header (always present). MSH-DSCH messages are never fragmented. WimaxMacHeader hdr_; //! Mesh subheader = transmitter NodeId (16 bits). WimaxNodeId src_; //! Sequence counter (6 bits). unsigned int nseq_; //! Number of requests (4 bits). unsigned int nreq_; //! Number of availabilities (4 bits). unsigned int navl_; //! Number of grants (6 bits). unsigned int ngnt_; //! Number of advertised neighbors (8 bits) not including itself. unsigned int nngh_; //! List of availabilities. std::list<AvlIE> avl_; //! List of requests. std::list<ReqIE> req_; //! List of grants. std::list<GntIE> gnt_; //! List of neighbors. std::list<NghIE> ngh_; //! Information on myself, about the distributed election mechanism. NghIE myself_; //! Allocation type. Changed via allocationType(). Default = BASIC. static AllocationType allocationType_; public: //! Create an empty MSH-DSCH message. WimshMshDsch () { hdr_.crc() = true; hdr_.fragmentation() = false; hdr_.length() = 15; // includes fixed fields // the hdr_.cid() is set to management values by default nseq_ = 0; nreq_ = 0; navl_ = 0; ngnt_ = 0; nngh_ = 0; } //! Return the current message size (in bytes). unsigned int size () { return hdr_.length(); } //! Return the available space (in bytes). unsigned int remaining () { return MAX_SIZE - size(); } //! Return the MAC header. WimaxMacHeader hdr () { return hdr_; } //! Return the transmitter NodeID (in the mesh subheader). WimaxNodeId& src () { return src_; } //! Add an availabilities IE. Return the available space (in bytes). unsigned int add (AvlIE x) { if ( allocationType_ == BASIC ) { hdr_.length() += AvlIE::size(); avl_.push_front(x); } else if ( allocationType_ == CONTIGUOUS ) addContiguous (x); return remaining(); } //! Add a request IE. Return the available space (in bytes). unsigned int add (ReqIE x) { hdr_.length() += ReqIE::size(); req_.push_front(x); return remaining(); } //! Add a grants IE. Return the available space (in bytes). unsigned int add (GntIE x) { if ( allocationType_ == BASIC ) { hdr_.length() += GntIE::size(); gnt_.push_front(x); } else if ( allocationType_ == CONTIGUOUS ) addContiguous (x); return remaining(); } //! Add a neighbors IE. Return the available space (in bytes). unsigned int add (NghIE x) { hdr_.length() += NghIE::size(); ngh_.push_front(x); return remaining(); } //! Get the distribute election information on myself. NghIE& myself () { return myself_; } //! Get the list of availabilities IEs. std::list<AvlIE>& avl () { return avl_; } //! Get the list of requests IEs. std::list<ReqIE>& req () { return req_; } //! Get the list of grants IEs. std::list<GntIE>& gnt () { return gnt_; } //! Get the list of neighbors IEs. std::list<NghIE>& ngh () { return ngh_; } //! Convert a number of minislots into a pair <level, persistence> for req. static void slots2level (unsigned int N, unsigned int minislots, unsigned char& level, Persistence& persistence); //! Get/set the allocation type. static AllocationType& allocationType () { return allocationType_; } //! Convert the persistence into a number of frames (except FOREVER). static unsigned int pers2frames (Persistence p) { return ( p == CANCEL ) ? 0 : ( p == FRAME1 ) ? 1 : ( p == FRAME2 ) ? 2 : ( p == FRAME4 ) ? 4 : ( p == FRAME8 ) ? 8 : ( p == FRAME32 ) ? 32 : ( p == FRAME128 ) ? 128 : UINT_MAX; } protected: //! Add a grant IE with contiguous allocation. void addContiguous (GntIE& x); //! Add an availability IE with contiguous allocation. void addContiguous (AvlIE& x); }; //! MSH-NCFG control message. We assume coordinated message scheduling. struct WimshMshNcfg { public: //! Maximum number of advertised neighbors. enum { MAX_NGH = 255 }; //! Maximum size of the MSH-NCFG message (in bytes). enum { MAX_SIZE = 96 }; //! MSH-NCFG message types. /*! * The following MSH-NCFG message types are implemented: * - The NET_ENTRY_OPEN message is sent by the sponsor node in * response to an MSH-NENT REQUEST message. * - The CHALLENGE message is sent by the new node to a neighbor * with which it is trying to establish a logical link. * - The RESPONSE message is sent by the neighbor in response to * an MSH-NCFG CHALLENGE message. * - The ACK message is sent by the new node to a neighbor with which * it is trying to establish a logical link to complete the procedure. */ enum Type { NET_ENTRY_OPEN, CHALLENGE, RESPONSE, ACK }; //! Neighbor coordination IE (3 bytes). struct NghIE { //! NodeID (8 bits, this field does not exist for information on itself). WimaxNodeId nodeId_; //! NextXmtMx (3 bits). unsigned char nextXmtMx_; //! XmtHoldoffExponent (5 bits). unsigned char xmtHoldoffExponent_; //! Next transmit time (does not exist IRL). unsigned int nextXmtTime_; //! Return the size (in bytes) of this IE. static unsigned int size () { return 3; } }; private: //! MAC header (always present). MSH-NCFG messages are never fragmented. WimaxMacHeader hdr_; //! Mesh subheader = transmitter NodeId (16 bits). WimaxNodeId src_; //! Number of advertised neighbors (8 bits) not including itself. unsigned int nngh_; //! List of neighbors. std::list<NghIE> ngh_; //! Information on myself, about the distributed election mechanism. NghIE myself_; // MSH-NCFG message type. Type type_; public: //! Create an empty MSH-NCFG message. WimshMshNcfg () { hdr_.crc() = true; hdr_.fragmentation() = false; hdr_.length() = 20; // includes fixed fields :XXX: fix to the real value // the hdr_.cid() is set to management values by default nngh_ = 0; type_ = NET_ENTRY_OPEN; } //! Return the current message size (in bytes). unsigned int size () { return hdr_.length(); } //! Return the available space (in bytes). unsigned int remaining () { return MAX_SIZE - size(); } //! Return the MAC header. WimaxMacHeader& hdr () { return hdr_; } //! Return the transmitter NodeID (in the mesh subheader). WimaxNodeId& src () { return src_; } //! Get/set the message type. Type& type () { return type_; } //! Add a neighbors IE. Return the available space (in bytes). unsigned int add (NghIE x) { hdr_.length() += NghIE::size(); ngh_.push_front(x); return remaining(); } //! Get the distribute election information on myself. NghIE& myself () { return myself_; } //! Get the list of neighbors IEs. std::list<NghIE>& ngh () { return ngh_; } }; //! MSH-NENT control message. We assume coordinated message scheduling. struct WimshMshNent { public: //! MSH-NENT message types. /*! * The following MSH-NENT message types are implemented: * - The REQUEST message is sent by a new node to its sponsor node to * open a sponsor channel. * - The ACK message is sent by a new node to complete the sponsor channel * open procedure. */ enum Type { REQUEST, ACK }; //! Maximum size of the MSH-NENT message (in bytes). enum { MAX_SIZE = 96 }; private: //! MAC header (always present). MSH-NENT messages are never fragmented. WimaxMacHeader hdr_; //! Mesh subheader = transmitter NodeId (16 bits). WimaxNodeId src_; //! MSH-NENT message type. Type type_; public: //! Create an empty MSH-NENT message. WimshMshNent () { hdr_.crc() = true; hdr_.fragmentation() = false; hdr_.length() = 20; // includes fixed fields :XXX: fix to the real value // the hdr_.cid() is set to management values by default type_ = REQUEST; } //! Return the current message size (in bytes). unsigned int size () { return hdr_.length(); } //! Return the available space (in bytes). unsigned int remaining () { return MAX_SIZE - size(); } //! Return the MAC header. WimaxMacHeader& hdr () { return hdr_; } //! Return the transmitter NodeID (in the mesh subheader). WimaxNodeId& src () { return src_; } //! Get/set the MSH-NENT message type. Type& type () { return type_; } }; //! WiMAX mesh burst of MAC PDUs. /*! A burst of PDUs is either a list of MAC PDUs, or a container for one MSH-DSCH message, according to the burst type. If you want to copy a burst, then use the copy() function. On the other hand, the destructor can be used safely to delete a burst. In any case, the ns2 packets, nor the MSH-DSCH message, are *not* copied. If you really want to deallocate the ns2 packets, which are encapsulated into each SDU, you have to do it manually. The rationale behind this is that we want only *one* copy of each ns2 packet to travel from the source node to the destination, to save both memory (a packet) and time (copying a packet). However, care must be taken to destroy these objects. We assume that only the final recipient of the communication destroys ns2 packets, which should be safe enough with unicast communications. */ struct WimshBurst { public: typedef std::list<WimaxPdu*> List; private: //--------------------------------------------------------// //-- Payload of the burst, depending on the burst type. --// //--------------------------------------------------------// //! List of PDUs (if type == wimax::DATA). List pdus_; //! Pointer to the MSH-DSCH message (if type == wimax::MSHDSCH). WimshMshDsch* mshDsch_; //! Pointer to the MSH-DSCH message (if type == wimax::MSHNCFG). WimshMshNcfg* mshNcfg_; //! Pointer to the MSH-DSCH message (if type == wimax::MSHNENT). WimshMshNent* mshNent_; //------------------// //-- Other fields --// //------------------// //! Transmission time of this burst (in seconds, including preambles). double txtime_; //! True if the whole burst is corrupt. bool error_; //! Burst profile. wimax::BurstProfile profile_; //! PDU burst type. wimax::BurstType type_; //! Size, in bytes. unsigned int size_; //! Source node ID. WimaxNodeId src_; public: //! Build an empty burst of PDUs. WimshBurst () { error_ = false; size_ = 0; mshDsch_ = 0; mshNcfg_ = 0; mshNent_ = 0; profile_ = wimax::QPSK_1_2; type_ = wimax::DATA; } //! Destroy everything ;) ~WimshBurst (); //! Allocate a copy of this burst and return a pointer to it. /*! The ns2 packets (ie. the SDUs' payload) are *not* copied. On the other hand, the MSH-DSCH message, if any, is copied. */ WimshBurst (const WimshBurst& obj); //! Add a PDU to the burst. void addData (WimaxPdu* pdu, bool tail = true ) { if ( tail ) pdus_.push_back (pdu); else pdus_.push_front (pdu); size_ += pdu->size(); } //! Remove a PDU from the burst. The PDU must be freed afterwards. WimaxPdu* pdu () { if ( pdus_.empty() ) return 0; WimaxPdu* tmp = pdus_.front(); pdus_.pop_front(); return tmp; } //! Return the list of PDUs. List& pdus () { return pdus_; } //! Return the number of PDUs in the burst. unsigned int npdus () { return pdus_.size(); } //! Get a pointer to the MSH-DSCH message, if any. WimshMshDsch*& mshDsch () { return mshDsch_; } //! Add an MSH-DSCH message to the burst. void addMshDsch (WimshMshDsch* m); //! Get a pointer to the MSH-NCFG message, if any. WimshMshNcfg*& mshNcfg () { return mshNcfg_; } //! Add an MSH-NCFG message to the burst. void addMshNcfg (WimshMshNcfg* m); //! Get a pointer to the MSH-NENT message, if any. WimshMshNent*& mshNent () { return mshNent_; } //! Add an MSH-NENT message to the burst. void addMshNent (WimshMshNent* m); //! Get/set the transmission time (in seconds, including preambles). double& txtime () { return txtime_; } //! Get/set the error status of the whole burst. bool& error () { return error_; } //! Get/set the burst profile. wimax::BurstProfile& profile () { return profile_; } //! Get the burst type. wimax::BurstType& type () { return type_; } //! Get the burst size (in bytes). unsigned int size () { return size_; } //! Get/set the source node. WimaxNodeId& source () { return src_; } private: void operator= (const WimshBurst&); }; #endif /* __NS2_WIMSH_PACKET_H */
[ "[email protected]", "antonio@antonio-desktop.(none)" ]
[ [ [ 1, 18 ], [ 22, 491 ] ], [ [ 19, 21 ] ] ]
72100c4cb9e9f01e55b6767a0e972200aca0ad0c
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/q3header.h
0e2b908c4e9b1f4c61213bd01c55d4d01752b8f6
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,642
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the Qt3Support module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef Q3HEADER_H #define Q3HEADER_H #include <QtGui/qicon.h> #include <QtGui/qwidget.h> #include <QtCore/qstring.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Qt3SupportLight) #ifndef QT_NO_HEADER class QShowEvent; class Q3HeaderData; class Q3Table; class Q3ListView; class Q_COMPAT_EXPORT Q3Header : public QWidget { friend class Q3Table; friend class Q3TableHeader; friend class Q3ListView; Q_OBJECT Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) Q_PROPERTY(bool tracking READ tracking WRITE setTracking) Q_PROPERTY(int count READ count) Q_PROPERTY(int offset READ offset WRITE setOffset) Q_PROPERTY(bool moving READ isMovingEnabled WRITE setMovingEnabled) Q_PROPERTY(bool stretching READ isStretchEnabled WRITE setStretchEnabled) public: Q3Header(QWidget* parent=0, const char* name=0); Q3Header(int, QWidget* parent=0, const char* name=0); ~Q3Header(); int addLabel(const QString &, int size = -1); int addLabel(const QIcon&, const QString &, int size = -1); void removeLabel(int section); virtual void setLabel(int, const QString &, int size = -1); virtual void setLabel(int, const QIcon&, const QString &, int size = -1); QString label(int section) const; QIcon* iconSet(int section) const; virtual void setOrientation(Qt::Orientation); Qt::Orientation orientation() const; virtual void setTracking(bool enable); bool tracking() const; virtual void setClickEnabled(bool, int section = -1); virtual void setResizeEnabled(bool, int section = -1); virtual void setMovingEnabled(bool); virtual void setStretchEnabled(bool b, int section); void setStretchEnabled(bool b) { setStretchEnabled(b, -1); } bool isClickEnabled(int section = -1) const; bool isResizeEnabled(int section = -1) const; bool isMovingEnabled() const; bool isStretchEnabled() const; bool isStretchEnabled(int section) const; void resizeSection(int section, int s); int sectionSize(int section) const; int sectionPos(int section) const; int sectionAt(int pos) const; int count() const; int headerWidth() const; QRect sectionRect(int section) const; virtual void setCellSize(int , int); // obsolete, do not use int cellSize(int i) const { return sectionSize(mapToSection(i)); } // obsolete, do not use int cellPos(int) const; // obsolete, do not use int cellAt(int pos) const { return mapToIndex(sectionAt(pos + offset())); } // obsolete, do not use int offset() const; QSize sizeHint() const; int mapToSection(int index) const; int mapToIndex(int section) const; int mapToLogical(int) const; // obsolete, do not use int mapToActual(int) const; // obsolete, do not use void moveSection(int section, int toIndex); virtual void moveCell(int, int); // obsolete, do not use void setSortIndicator(int section, bool ascending = true); // obsolete, do not use inline void setSortIndicator(int section, Qt::SortOrder order) { setSortIndicator(section, (order == Qt::AscendingOrder)); } int sortIndicatorSection() const; Qt::SortOrder sortIndicatorOrder() const; void adjustHeaderSize() { adjustHeaderSize(-1); } public Q_SLOTS: void setUpdatesEnabled(bool enable); virtual void setOffset(int pos); Q_SIGNALS: void clicked(int section); void pressed(int section); void released(int section); void sizeChange(int section, int oldSize, int newSize); void indexChange(int section, int fromIndex, int toIndex); void sectionClicked(int); // obsolete, do not use void moved(int, int); // obsolete, do not use void sectionHandleDoubleClicked(int section); protected: void paintEvent(QPaintEvent *); void showEvent(QShowEvent *e); void resizeEvent(QResizeEvent *e); QRect sRect(int index); virtual void paintSection(QPainter *p, int index, const QRect& fr); virtual void paintSectionLabel(QPainter* p, int index, const QRect& fr); void changeEvent(QEvent *); void mousePressEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void mouseDoubleClickEvent(QMouseEvent *); void keyPressEvent(QKeyEvent *); void keyReleaseEvent(QKeyEvent *); private: void handleColumnMove(int fromIdx, int toIdx); void adjustHeaderSize(int diff); void init(int); void paintRect(int p, int s); void markLine(int idx); void unMarkLine(int idx); int pPos(int i) const; int pSize(int i) const; int findLine(int); int handleAt(int p); bool reverse() const; void calculatePositions(bool onlyVisible = false, int start = 0); void handleColumnResize(int, int, bool, bool = true); QSize sectionSizeHint(int section, const QFontMetrics& fm) const; void setSectionSizeAndHeight(int section, int size); void resizeArrays(int size); void setIsATableHeader(bool b); int offs; int handleIdx; int oldHIdxSize; int moveToIdx; enum State { Idle, Sliding, Pressed, Moving, Blocked }; State state; int clickPos; bool trackingIsOn; int oldHandleIdx; int cachedPos; // not used Qt::Orientation orient; Q3HeaderData *d; private: Q_DISABLE_COPY(Q3Header) }; inline Qt::Orientation Q3Header::orientation() const { return orient; } inline void Q3Header::setTracking(bool enable) { trackingIsOn = enable; } inline bool Q3Header::tracking() const { return trackingIsOn; } extern Q_COMPAT_EXPORT bool qt_qheader_label_return_null_strings; // needed for professional edition #endif // QT_NO_HEADER QT_END_NAMESPACE QT_END_HEADER #endif // Q3HEADER_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 225 ] ] ]
1613ccc3acf6844974c848593675a2351a0e172c
d6a28d9d845a20463704afe8ebe644a241dc1a46
/source/Irrlicht/CImageWriterPNG.cpp
9c78d6410ebb1f0a4f1639017aefcde4e6bb1916
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
marky0720/irrlicht-android
6932058563bf4150cd7090d1dc09466132df5448
86512d871eeb55dfaae2d2bf327299348cc5202c
refs/heads/master
2021-04-30T08:19:25.297407
2010-10-08T08:27:33
2010-10-08T08:27:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,857
cpp
// Copyright (C) 2002-2009 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CImageWriterPNG.h" #ifdef _IRR_COMPILE_WITH_PNG_WRITER_ #include "CImageLoaderPNG.h" #include "CColorConverter.h" #include "IWriteFile.h" #include "irrString.h" #include "os.h" // for logging #ifdef _IRR_COMPILE_WITH_LIBPNG_ #ifndef _IRR_USE_NON_SYSTEM_LIB_PNG_ #include <png.h> // use system lib png #else // _IRR_USE_NON_SYSTEM_LIB_PNG_ #include "libpng/png.h" // use irrlicht included lib png #endif // _IRR_USE_NON_SYSTEM_LIB_PNG_ #endif // _IRR_COMPILE_WITH_LIBPNG_ namespace irr { namespace video { IImageWriter* createImageWriterPNG() { return new CImageWriterPNG; } #ifdef _IRR_COMPILE_WITH_LIBPNG_ // PNG function for error handling static void png_cpexcept_error(png_structp png_ptr, png_const_charp msg) { os::Printer::log("PNG fatal error", msg, ELL_ERROR); longjmp(png_jmpbuf(png_ptr), 1); } // PNG function for warning handling static void png_cpexcept_warning(png_structp png_ptr, png_const_charp msg) { os::Printer::log("PNG warning", msg, ELL_WARNING); } // PNG function for file writing void PNGAPI user_write_data_fcn(png_structp png_ptr, png_bytep data, png_size_t length) { png_size_t check; io::IWriteFile* file=(io::IWriteFile*)png_get_io_ptr(png_ptr); check=(png_size_t) file->write((const void*)data,(u32)length); if (check != length) png_error(png_ptr, "Write Error"); } #endif // _IRR_COMPILE_WITH_LIBPNG_ CImageWriterPNG::CImageWriterPNG() { #ifdef _DEBUG setDebugName("CImageWriterPNG"); #endif } bool CImageWriterPNG::isAWriteableFileExtension(const io::path& filename) const { #ifdef _IRR_COMPILE_WITH_LIBPNG_ return core::hasFileExtension ( filename, "png" ); #else return false; #endif } bool CImageWriterPNG::writeImage(io::IWriteFile* file, IImage* image,u32 param) const { #ifdef _IRR_COMPILE_WITH_LIBPNG_ if (!file || !image) return false; // Allocate the png write struct png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, (png_error_ptr)png_cpexcept_error, (png_error_ptr)png_cpexcept_warning); if (!png_ptr) { os::Printer::log("PNGWriter: Internal PNG create write struct failure\n", file->getFileName(), ELL_ERROR); return false; } // Allocate the png info struct png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { os::Printer::log("PNGWriter: Internal PNG create info struct failure\n", file->getFileName(), ELL_ERROR); png_destroy_write_struct(&png_ptr, NULL); return false; } // for proper error handling if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); return false; } png_set_write_fn(png_ptr, file, user_write_data_fcn, NULL); // Set info switch(image->getColorFormat()) { case ECF_A8R8G8B8: case ECF_A1R5G5B5: png_set_IHDR(png_ptr, info_ptr, image->getDimension().Width, image->getDimension().Height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); break; default: png_set_IHDR(png_ptr, info_ptr, image->getDimension().Width, image->getDimension().Height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); } s32 lineWidth=image->getDimension().Width; switch(image->getColorFormat()) { case ECF_R8G8B8: case ECF_R5G6B5: lineWidth*=3; break; case ECF_A8R8G8B8: case ECF_A1R5G5B5: lineWidth*=4; break; } u8* tmpImage = new u8[image->getDimension().Height*lineWidth]; if (!tmpImage) { os::Printer::log("PNGWriter: Internal PNG create image failure\n", file->getFileName(), ELL_ERROR); png_destroy_write_struct(&png_ptr, &info_ptr); return false; } u8* data = (u8*)image->lock(); switch(image->getColorFormat()) { case ECF_R8G8B8: CColorConverter::convert_R8G8B8toR8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); break; case ECF_A8R8G8B8: CColorConverter::convert_A8R8G8B8toA8R8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); break; case ECF_R5G6B5: CColorConverter::convert_R5G6B5toR8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); break; case ECF_A1R5G5B5: CColorConverter::convert_A1R5G5B5toA8R8G8B8(data,image->getDimension().Height*image->getDimension().Width,tmpImage); break; } image->unlock(); // Create array of pointers to rows in image data //Used to point to image rows u8** RowPointers = new png_bytep[image->getDimension().Height]; if (!RowPointers) { os::Printer::log("PNGWriter: Internal PNG create row pointers failure\n", file->getFileName(), ELL_ERROR); png_destroy_write_struct(&png_ptr, &info_ptr); delete [] tmpImage; return false; } data=tmpImage; // Fill array of pointers to rows in image data for (u32 i=0; i<image->getDimension().Height; ++i) { RowPointers[i]=data; data += lineWidth; } // for proper error handling if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); delete [] RowPointers; delete [] tmpImage; return false; } png_set_rows(png_ptr, info_ptr, RowPointers); if (image->getColorFormat()==ECF_A8R8G8B8 || image->getColorFormat()==ECF_A1R5G5B5) png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL); else { png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); } delete [] RowPointers; delete [] tmpImage; png_destroy_write_struct(&png_ptr, &info_ptr); return true; #else return false; #endif } } // namespace video } // namespace irr #endif
[ "hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475", "bitplane@dfc29bdd-3216-0410-991c-e03cc46cb475", "engineer_apple@dfc29bdd-3216-0410-991c-e03cc46cb475", "Rogerborg@dfc29bdd-3216-0410-991c-e03cc46cb475" ]
[ [ [ 1, 3 ], [ 6, 8 ], [ 37, 44 ], [ 52, 53 ], [ 67, 67 ], [ 76, 76 ], [ 84, 84 ], [ 87, 87 ], [ 95, 95 ], [ 110, 124 ], [ 141, 141 ], [ 163, 163 ], [ 165, 167 ], [ 170, 170 ], [ 212, 214 ] ], [ [ 4, 5 ], [ 9, 36 ], [ 45, 51 ], [ 54, 66 ], [ 68, 69 ], [ 71, 75 ], [ 77, 83 ], [ 85, 86 ], [ 88, 94 ], [ 96, 109 ], [ 125, 140 ], [ 142, 162 ], [ 164, 164 ], [ 168, 169 ], [ 171, 177 ], [ 179, 211 ] ], [ [ 70, 70 ] ], [ [ 178, 178 ] ] ]
b5a937cceb7a1e76713e7665e7c2bb366a24deea
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/InformationProviders/DirImageInfoProvider/DirImageInfoProvider.cpp
146991199a3989a39610d1ef474e0aecd0a74453
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
10,220
cpp
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #include "stdafx.h" #include "DirImageInfoProvider.h" #include "cStringUtils.h" #ifdef _UNITTESTING //#define UNITTESTNOSQLMANAGER LPCTSTR GetFirstFileByArtistAlbumResult = NULL; const int lastSizeOf = 120; BOOL DirImageInfoProvider::UnitTest() { if (lastSizeOf != sizeof(DirImageInfoProvider)) TRACE(_T("TestDirImageInfoProvider. Object Size Changed. Was: %d - Is: %d\r\n"), lastSizeOf, sizeof(DirImageInfoProvider)); DirImageInfoProvider ip; #ifdef UNITTESTNOSQLMANAGER GetFirstFileByArtistAlbumResult = _T("D:\\Music\\Nick Cave\\1984 - From Her To Eternity\\"); #endif Request req(IInfoProvider::SRV_AlbumImage); req.artist = _T("Nick Cave"); req.album = _T("From Her To Eternity"); if (ip.OpenRequest(req)) { Result res; DWORD resNum = 0; while (ip.GetNextResult(res)) { UNITTEST(res.IsValid()); TRACE(_T("Result %d. %s\r\n"), resNum++, res.main); } } #ifdef UNITTESTNOSQLMANAGER GetFirstFileByArtistAlbumResult = _T("D:\\Musi0\\90s\\sublime-second-hand_smoke-1997-jayms\\"); #endif req.artist = _T("Sublime"); req.album = _T("Second Hand Smoke"); if (ip.OpenRequest(req)) { Result res; DWORD resNum = 0; while (ip.GetNextResult(res)) { UNITTEST(res.IsValid()); TRACE(_T("Result %d. %s\r\n"), resNum++, res.main); } } return TRUE; } #endif #ifndef UNITTESTNOSQLMANAGER #include <SQLManager.h> #endif DirImageInfoProvider::DirImageInfoProvider(): m_pSQLManager(NULL), m_curResult(-1), m_StrictCriteriaMaxFilesNum(25), m_StrictCriteriaMaxFilesSize(500000), m_request(SRV_First) { } DirImageInfoProvider::~DirImageInfoProvider() { } IInfoProvider* DirImageInfoProvider::Clone() const { DirImageInfoProvider* pIP = new DirImageInfoProvider; pIP->SetInternetHandle(GetInternetHandle()); IConfigurableHelper::TransferConfiguration(*this, *pIP); pIP->SetSQLManager(m_pSQLManager); return pIP; } BOOL DirImageInfoProvider::OpenRequest(const Request& request) { ASSERT(request.IsValid()); if (!request.IsValid()) return FALSE; #ifndef UNITTESTNOSQLMANAGER ASSERT(m_pSQLManager != NULL); if (m_pSQLManager == NULL) return FALSE; #endif if (request.service != SRV_AlbumImage) return FALSE; m_Artist = request.artist; m_Album = request.album; m_request.artist = m_Artist.c_str(); m_request.album = m_Album.c_str(); m_request.service = request.service; m_results.clear(); m_curResult = -1; return TRUE; } BOOL DirImageInfoProvider::GetFirstFileByArtistAlbum(LPTSTR path, LPCTSTR artist, LPCTSTR album) { ASSERT(path != NULL && artist != NULL && album != NULL); #ifdef UNITTESTNOSQLMANAGER _tcscpy(path, GetFirstFileByArtistAlbumResult); return TRUE; #else ASSERT(m_pSQLManager != NULL); if (m_pSQLManager == NULL) return FALSE; TracksFilter tf; tf.Album.val = album; tf.Album.match = TXTM_Exact; tf.Artist.val = artist; tf.Artist.match = TXTM_Exact; FullTrackRecordCollection col; if (m_pSQLManager->GetFullTrackRecordCollectionByTracksFilter(col, tf, 1)) { if (col.size() > 0) { _tcsncpy(path, col[0]->track.location.c_str(), MAX_PATH); TCHAR* pos = _tcsrchr(path, '\\'); if (pos != NULL) { pos++; *pos = 0; return TRUE; } } } #endif return FALSE; } BOOL DirImageInfoProvider::GetNextResult(Result& result) { if (m_curResult == -1) { TCHAR path[MAX_PATH]; if (GetFirstFileByArtistAlbum(path, m_Artist.c_str(), m_Album.c_str())) { BOOL bStrictSearch = HasMoreThanXFilesWithMinSizeY(path, m_StrictCriteriaMaxFilesNum, m_StrictCriteriaMaxFilesSize); WIN32_FIND_DATA dta; TCHAR wildCard[MAX_PATH]; _sntprintf(wildCard, MAX_PATH, _T("%s*.jpg"), path); HANDLE hFileFinder = FindFirstFile(wildCard, &dta); if (hFileFinder != INVALID_HANDLE_VALUE) { do { TCHAR bf[MAX_PATH]; _sntprintf(bf, MAX_PATH, _T("%s%s"), path, dta.cFileName); if (IsLegalPicture(bf, m_Album.c_str(), bStrictSearch)) { m_results.push_back(bf); } } while (FindNextFile(hFileFinder, &dta)); FindClose(hFileFinder); //===This code promotes the "front" image to be the first result if (m_results.size() > 1) { INT foundFront = -1; for (size_t i = 0; i < m_results.size(); i++) { if (_tcsistr(m_results[i].c_str(), _T("front")) != NULL) { foundFront = i; break; } } if (foundFront > 0) { std::tstring tmp = m_results[0]; m_results[0] = m_results[foundFront]; m_results[foundFront] = tmp; } } //===End } } } m_curResult++; if (m_curResult >= 0 && m_curResult < (INT)m_results.size()) { result.service = m_request.service; result.main = m_results[m_curResult].c_str(); result.additionalInfo = _T("(local)"); return TRUE; } return FALSE; } BOOL DirImageInfoProvider::CanHandle(ServiceEnum service) const { switch (service) { case IInfoProvider::SRV_AlbumImage: return TRUE; } return FALSE; } LPCTSTR DirImageInfoProvider::GetModuleInfo(ModuleInfo mi) const { switch (mi) { case IPI_UniqueID: return _T("FOLD"); case IPI_Name: return _T("Folder Images"); case IPI_Author: return _T("Alex Economou"); case IPI_VersionStr: return _T("1"); case IPI_VersionNum: return _T("1"); case IPI_Description: return _T("Images from the tracks folder"); case IPI_HomePage: return _T("http://teenspirit.artificialspirit.com"); case IPI_Email: return _T("[email protected]"); } return NULL; } //Strings WILL be Modified. (in order to avoid more memory allocations) BOOL DirImageInfoProvider::IsIncluded(LPCTSTR strMain, LPCTSTR strFind, BOOL bIgnoreCase, LPCTSTR excludedCharacters) { ASSERT(strMain != NULL && strFind != NULL); size_t strMainLen = _tcslen(strMain); if (strMainLen == 0) return FALSE; size_t strFindLen = _tcslen(strFind); if (strFindLen == 0) return FALSE; TCHAR sMain[MAX_PATH]; TCHAR sFind[MAX_PATH]; _tcscpy(sMain, strMain); _tcscpy(sFind, strFind); if (bIgnoreCase) { _tcslwr(sMain); _tcslwr(sFind); } if (excludedCharacters != NULL) { for (UINT i = 0; i < _tcslen(excludedCharacters); i++) { TCHAR strCh[2]; strCh[1] = 0; strCh[0] = excludedCharacters[i]; _tcsReplaceInl(sMain, strMainLen, strCh, _T("")); _tcsReplaceInl(sFind, strFindLen, strCh, _T("")); } } return _tcsstr(strMain, strFind) != NULL; } BOOL DirImageInfoProvider::HasMoreThanXFilesWithMinSizeY(LPCTSTR path, UINT maxNumFiles, UINT minFileSize) { TCHAR dir[MAX_PATH]; _tcsncpy(dir, path, MAX_PATH); TCHAR* pos = _tcsrchr(dir, '\\'); if (pos != NULL) { pos++; *pos = 0; _tcscat(dir, _T("*.*")); WIN32_FIND_DATA fda; HANDLE f = FindFirstFile(dir, &fda); BOOL bRet = TRUE; UINT numFiles = 0; while (f != INVALID_HANDLE_VALUE && bRet) { if (fda.nFileSizeLow > minFileSize) { numFiles++; if (numFiles >= maxNumFiles) { FindClose(f); return TRUE; } } bRet = FindNextFile(f, &fda); } if (f != INVALID_HANDLE_VALUE) FindClose(f); } return FALSE; } BOOL DirImageInfoProvider::IsLegalPicture(LPCTSTR path, LPCTSTR albumName, BOOL bStrict) { ASSERT(path != NULL); ASSERT(albumName != NULL); #ifdef _DEBUG TRACE(_T("DirImageInfoProvider::IsLegalPicture. StrictSearch: %d\r\n"), bStrict); if (!bStrict && !IsIncluded(path, albumName, TRUE, _T("._ -'!?"))) TRACE(_T("DirImageInfoProvider::IsLegalPicture. Strict wuld have failed (%s)!!!\r\n"), path); #endif if (bStrict && !IsIncluded(path, albumName, TRUE, _T("._ -'!?"))) return FALSE; if (_tcsstr(path, _T("AlbumArtSmall.jpg")) != NULL) return FALSE; if (_tcsstr(path, _T("}_Small.jpg")) != NULL) return FALSE; return TRUE; } LPCTSTR cDirImageSettings[] = { _T("Strict Max Files Count"), _T("Strict Max Files Size"), NULL }; INT m_StrictCriteriaMaxFilesNum; INT m_StrictCriteriaMaxFilesSize; BOOL DirImageInfoProvider::GetSettingInfo(INT settingIndex, IConfigurable::SettingInfo& setting) const { setting = IConfigurable::SettingInfo(); if (settingIndex < sizeof(cDirImageSettings) / sizeof(LPCTSTR) - 1) setting.name = cDirImageSettings[settingIndex]; switch (settingIndex) { case 0: case 1: setting.type = IConfigurable::COVT_Int; return TRUE; } return FALSE; } INT DirImageInfoProvider::GetIntSetting(INT settingIndex) const { switch (settingIndex) { case 0: return m_StrictCriteriaMaxFilesNum; case 1: return m_StrictCriteriaMaxFilesSize; } ASSERT(0); return 0; } void DirImageInfoProvider::SetIntSetting(INT settingIndex, INT intVal) { switch (settingIndex) { case 0: if (intVal < 1) m_StrictCriteriaMaxFilesNum = 1; else if (intVal > 100) m_StrictCriteriaMaxFilesNum = 100; else m_StrictCriteriaMaxFilesNum = intVal; break; case 1: if (intVal < 50000) m_StrictCriteriaMaxFilesSize = 50000; else if (intVal > 10000000) m_StrictCriteriaMaxFilesSize = 10000000; else m_StrictCriteriaMaxFilesSize = intVal; break; default: ASSERT(0); } }
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 392 ] ] ]
2c4244f02bc9e60696103b1a207d07c7b6dc038b
b738fc6ffa2205ea210d10c395ae47b25ba26078
/udt4/src/api.cpp
500be36e1e7bf21b7692a65ebce526303d308804
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RallyWRT/ppsocket
d8609233df9bba8d316a85a3d96919b8618ea4b6
b4b0b16e2ceffe8a697905b1ef1aeb227595b110
refs/heads/master
2021-01-19T16:23:26.812183
2009-09-23T06:57:58
2009-09-23T06:57:58
35,471,076
0
0
null
null
null
null
GB18030
C++
false
false
59,976
cpp
/***************************************************************************** Copyright (c) 2001 - 2009, The Board of Trustees of the University of Illinois. 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 University of Illinois 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. *****************************************************************************/ /***************************************************************************** written by Yunhong Gu, last updated 07/10/2009 *****************************************************************************/ #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #ifdef LEGACY_WIN32 #include <wspiapi.h> #endif #else #include <unistd.h> #endif #include <cstring> #include "api.h" #include "core.h" #include "debug.h" using namespace std; CUDTSocket::CUDTSocket(): m_Status(INIT), m_TimeStamp(0), m_iIPversion(0), m_pSelfAddr(NULL), m_pPeerAddr(NULL), m_SocketID(0), m_ListenSocket(0), m_PeerID(0), m_iISN(0), m_pUDT(NULL), m_pQueuedSockets(NULL), m_pAcceptSockets(NULL), m_AcceptCond(), m_AcceptLock(), m_uiBackLog(0) { #ifndef WIN32 pthread_mutex_init(&m_AcceptLock, NULL); pthread_cond_init(&m_AcceptCond, NULL); #else m_AcceptLock = CreateMutex(NULL, false, NULL); m_AcceptCond = CreateEvent(NULL, false, false, NULL); #endif } CUDTSocket::~CUDTSocket() { if (AF_INET == m_iIPversion) { delete (sockaddr_in*)m_pSelfAddr; delete (sockaddr_in*)m_pPeerAddr; } else { delete (sockaddr_in6*)m_pSelfAddr; delete (sockaddr_in6*)m_pPeerAddr; } delete m_pUDT; delete m_pQueuedSockets; delete m_pAcceptSockets; #ifndef WIN32 pthread_mutex_destroy(&m_AcceptLock); pthread_cond_destroy(&m_AcceptCond); #else CloseHandle(m_AcceptLock); CloseHandle(m_AcceptCond); #endif } //////////////////////////////////////////////////////////////////////////////// CUDTUnited::CUDTUnited(): m_Sockets(), m_ControlLock(), m_IDLock(), m_SocketID(0), m_TLSError(), m_vMultiplexer(), m_MultiplexerLock(), m_pCache(NULL), m_bClosing(false), m_GCStopLock(), m_GCStopCond(), m_InitLock(), m_bGCStatus(false), m_GCThread(), m_ClosedSockets() { srand((unsigned int)CTimer::getTime()); m_SocketID = 1 + (int)((1 << 30) * (double(rand()) / RAND_MAX)); #ifndef WIN32 pthread_mutex_init(&m_ControlLock, NULL); pthread_mutex_init(&m_IDLock, NULL); pthread_mutex_init(&m_InitLock, NULL); #else m_ControlLock = CreateMutex(NULL, false, NULL); m_IDLock = CreateMutex(NULL, false, NULL); m_InitLock = CreateMutex(NULL, false, NULL); #endif #ifndef WIN32 pthread_key_create(&m_TLSError, TLSDestroy); #else m_TLSError = TlsAlloc(); m_TLSLock = CreateMutex(NULL, false, NULL); #endif // Global initialization code #ifdef WIN32 WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); if (0 != WSAStartup(wVersionRequested, &wsaData)) throw CUDTException(1, 0, WSAGetLastError()); #endif m_pCache = new CCache; } CUDTUnited::~CUDTUnited() { #ifndef WIN32 pthread_mutex_destroy(&m_ControlLock); pthread_mutex_destroy(&m_IDLock); pthread_mutex_destroy(&m_InitLock); #else CloseHandle(m_ControlLock); CloseHandle(m_IDLock); CloseHandle(m_InitLock); #endif #ifndef WIN32 pthread_key_delete(m_TLSError); #else TlsFree(m_TLSError); CloseHandle(m_TLSLock); #endif delete m_pCache; // Global destruction code #ifdef WIN32 WSACleanup(); #endif } int CUDTUnited::startup() { CGuard gcinit(m_InitLock); if (m_bGCStatus) return true; m_bClosing = false; #ifndef WIN32 pthread_mutex_init(&m_GCStopLock, NULL); pthread_cond_init(&m_GCStopCond, NULL); pthread_create(&m_GCThread, NULL, garbageCollect, this); #else m_GCStopLock = CreateMutex(NULL, false, NULL); m_MultiplexerLock = CreateMutex(NULL, false, NULL); m_GCStopCond = CreateEvent(NULL, false, false, NULL); DWORD ThreadID; m_GCThread = CreateThread(NULL, 0, garbageCollect, this, NULL, &ThreadID); #endif m_bGCStatus = true; return 0; } int CUDTUnited::cleanup() { CGuard gcinit(m_InitLock); if (!m_bGCStatus) return 0; m_bClosing = true; #ifndef WIN32 pthread_cond_signal(&m_GCStopCond); pthread_join(m_GCThread, NULL); pthread_mutex_destroy(&m_GCStopLock); pthread_cond_destroy(&m_GCStopCond); #else SetEvent(m_GCStopCond); WaitForSingleObject(m_GCThread, INFINITE); //WaitForSingleObject(m_GCThread, 2000);//tianzuo,advoid dead waiting. CloseHandle(m_GCThread); CloseHandle(m_GCStopLock); CloseHandle(m_GCStopCond); CloseHandle(m_MultiplexerLock); #endif //tianzuo,2009-9-12 CloseHandle(CTimer::m_EventCond); CloseHandle(CTimer::m_EventLock); m_bGCStatus = false; return 0; } UDTSOCKET CUDTUnited::newSocket(const int& af, const int& type) { if ((type != SOCK_STREAM) && (type != SOCK_DGRAM)) throw CUDTException(5, 3, 0); CUDTSocket* ns = NULL; try { ns = new CUDTSocket; ns->m_pUDT = new CUDT; if (AF_INET == af) { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in); ((sockaddr_in*)(ns->m_pSelfAddr))->sin_port = 0; } else { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in6); ((sockaddr_in6*)(ns->m_pSelfAddr))->sin6_port = 0; } } catch (...) { delete ns; throw CUDTException(3, 2, 0); } CGuard::enterCS(m_IDLock); ns->m_SocketID = -- m_SocketID; CGuard::leaveCS(m_IDLock); ns->m_Status = CUDTSocket::INIT; ns->m_ListenSocket = 0; ns->m_pUDT->m_SocketID = ns->m_SocketID; ns->m_pUDT->m_iSockType = (SOCK_STREAM == type) ? UDT_STREAM : UDT_DGRAM; ns->m_pUDT->m_iIPversion = ns->m_iIPversion = af; ns->m_pUDT->m_pCache = m_pCache; // protect the m_Sockets structure. //CGuard::enterCS(m_ControlLock); try { CGuard cg(m_ControlLock); m_Sockets[ns->m_SocketID] = ns; } catch (...) { //failure and rollback delete ns; ns = NULL; } //CGuard::leaveCS(m_ControlLock); if (NULL == ns) throw CUDTException(3, 2, 0); return ns->m_SocketID; } //tianzuo,2009-8-7, a group of function to replace unsafe "locate" function. void CUDTUnited::LocateEraseSocket(UDTSOCKET uListen, UDTSOCKET idSocket) { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(uListen); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); return ; } CUDTSocket* ls = i->second; if (NULL == ls) { //ATLASSERT(FALSE); return ; } //CGuard::enterCS(ls->m_AcceptLock); CGuard accept_accept(ls->m_AcceptLock); ls->m_pQueuedSockets->erase(idSocket); ls->m_pAcceptSockets->erase(idSocket); //CGuard::leaveCS(ls->m_AcceptLock); } bool CUDTUnited::LocateIsQueueEmpty(UDTSOCKET uListen) const { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(uListen); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); return true; } CUDTSocket* ls = i->second; if (NULL == ls) { //ATLASSERT(FALSE); return true; } return ls->m_pQueuedSockets->empty(); } bool CUDTUnited::LocateIsQueueFull(UDTSOCKET uListen) const { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(uListen); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); return true; } CUDTSocket* ls = i->second; if (NULL == ls) { //ATLASSERT(FALSE); return true; } return ls->m_pQueuedSockets->size() >= ls->m_uiBackLog; } void CUDTUnited::LocateSetBackLog(UDTSOCKET uListen,const int& backlog) { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(uListen); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); return ; } CUDTSocket* ls = i->second; if (NULL == ls) { //ATLASSERT(FALSE); return ; } ls->m_uiBackLog = backlog; } int CUDTUnited::newConnection(const UDTSOCKET listen, const sockaddr* peer, CHandShake* hs) { //CGuard cg(m_ControlLock); //map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(listen); //if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) //{ // //ATLASSERT(FALSE); // throw CUDTException(5, 4, 0); //} //CUDTSocket* ls = i->second; { CUDTSocket* ls = locate(listen); if (NULL == ls) return -1; } // if this connection has already been processed CUDTSocket* ns = NULL; if (NULL != (ns = locate(listen, peer, hs->m_iID, hs->m_iISN))) { if (ns->m_pUDT->m_bBroken) { // last connection from the "peer" address has been broken ns->m_Status = CUDTSocket::CLOSED; ns->m_TimeStamp = CTimer::getTime(); //CGuard::enterCS(ls->m_AcceptLock); //ls->m_pQueuedSockets->erase(ns->m_SocketID); //ls->m_pAcceptSockets->erase(ns->m_SocketID); //CGuard::leaveCS(ls->m_AcceptLock); LocateEraseSocket(listen,ns->m_SocketID); } else { // connection already exist, this is a repeated connection request // respond with existing HS information hs->m_iISN = ns->m_pUDT->m_iISN; hs->m_iMSS = ns->m_pUDT->m_iMSS; hs->m_iFlightFlagSize = ns->m_pUDT->m_iFlightFlagSize; hs->m_iReqType = -1; hs->m_iID = ns->m_SocketID; return 0; //except for this situation a new connection should be started } } // exceeding backlog, refuse the connection request //if (ls->m_pQueuedSockets->size() >= ls->m_uiBackLog) if(LocateIsQueueFull(listen)) return -1; try { CUDTSocket* ls = locate(listen); if (NULL == ls) return -1; ns = new CUDTSocket; ns->m_pUDT = new CUDT(*(ls->m_pUDT)); if (AF_INET == ls->m_iIPversion) { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in); ((sockaddr_in*)(ns->m_pSelfAddr))->sin_port = 0; ns->m_pPeerAddr = (sockaddr*)(new sockaddr_in); memcpy(ns->m_pPeerAddr, peer, sizeof(sockaddr_in)); } else { ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in6); ((sockaddr_in6*)(ns->m_pSelfAddr))->sin6_port = 0; ns->m_pPeerAddr = (sockaddr*)(new sockaddr_in6); memcpy(ns->m_pPeerAddr, peer, sizeof(sockaddr_in6)); } } catch (...) { delete ns; return -1; } CGuard::enterCS(m_IDLock); ns->m_SocketID = -- m_SocketID; CGuard::leaveCS(m_IDLock); ns->m_ListenSocket = listen; { CUDTSocket* ls = locate(listen); if (NULL == ls) return -1; ns->m_iIPversion = ls->m_iIPversion; } ns->m_pUDT->m_SocketID = ns->m_SocketID; ns->m_PeerID = hs->m_iID; ns->m_iISN = hs->m_iISN; int error = 0; try { // bind to the same addr of listening socket ns->m_pUDT->open(); { CUDTSocket* ls = locate(listen); if (NULL == ls) return -1; updateMux(ns->m_pUDT, ls); } ns->m_pUDT->connect(peer, hs); } catch (...) { error = 1; goto ERR_ROLLBACK; } ns->m_Status = CUDTSocket::CONNECTED; // copy address information of local node ns->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(ns->m_pSelfAddr); CIPAddress::pton(ns->m_pSelfAddr, ns->m_pUDT->m_piSelfIP, ns->m_iIPversion); // protect the m_Sockets structure. //CGuard::enterCS(m_ControlLock); try { CGuard cg(m_ControlLock); m_Sockets[ns->m_SocketID] = ns; } catch (...) { error = 2; } //CGuard::leaveCS(m_ControlLock); //CGuard::enterCS(ls->m_AcceptLock); { CUDTSocket* ls = locate(listen); if (NULL == ls) return -1; CGuard cg(ls->m_AcceptLock); try { ls->m_pQueuedSockets->insert(ns->m_SocketID); } catch (...) { error = 3; } } //CGuard::leaveCS(ls->m_AcceptLock); CTimer::triggerEvent(); ERR_ROLLBACK: if (error > 0) { ns->m_pUDT->close(); ns->m_Status = CUDTSocket::CLOSED; ns->m_TimeStamp = CTimer::getTime(); return -1; } CUDTSocket* ls = locate(listen); if (NULL == ls) return -1; // wake up a waiting accept() call #ifndef WIN32 pthread_mutex_lock(&(ls->m_AcceptLock)); pthread_cond_signal(&(ls->m_AcceptCond)); pthread_mutex_unlock(&(ls->m_AcceptLock)); #else SetEvent(ls->m_AcceptCond); #endif return 1; } CUDT* CUDTUnited::lookup(const UDTSOCKET u) { // protects the m_Sockets structure CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::iterator i = m_Sockets.find(u); if ((i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) throw CUDTException(5, 4, 0); return i->second->m_pUDT; } CUDTSocket::UDTSTATUS CUDTUnited::getStatus(const UDTSOCKET u) const { // protects the m_Sockets structure CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if (i == m_Sockets.end()) return CUDTSocket::INIT; if (i->second->m_pUDT->m_bBroken) return CUDTSocket::BROKEN; return i->second->m_Status; } int CUDTUnited::bind(const UDTSOCKET u, const sockaddr* name, const int& namelen) { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* s = i->second; if (NULL == s) throw CUDTException(5, 4, 0); // cannot bind a socket more than once if (CUDTSocket::INIT != s->m_Status) throw CUDTException(5, 0, 0); // check the size of SOCKADDR structure if (AF_INET == s->m_iIPversion) { if (namelen != sizeof(sockaddr_in)) throw CUDTException(5, 3, 0); } else { if (namelen != sizeof(sockaddr_in6)) throw CUDTException(5, 3, 0); } s->m_pUDT->open(); updateMux(s->m_pUDT, name); s->m_Status = CUDTSocket::OPENED; // copy address information of local node s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr); return 0; } int CUDTUnited::bind(UDTSOCKET u, UDPSOCKET udpsock) { //CUDTSocket* s = locate(u); CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* s = i->second; if (NULL == s) throw CUDTException(5, 4, 0); // cannot bind a socket more than once if (CUDTSocket::INIT != s->m_Status) throw CUDTException(5, 0, 0); sockaddr_in name4; sockaddr_in6 name6; sockaddr* name; socklen_t namelen; if (AF_INET == s->m_iIPversion) { namelen = sizeof(sockaddr_in); name = (sockaddr*)&name4; } else { namelen = sizeof(sockaddr_in6); name = (sockaddr*)&name6; } if (-1 == ::getsockname(udpsock, name, &namelen)) throw CUDTException(5, 3); s->m_pUDT->open(); updateMux(s->m_pUDT, name, &udpsock); s->m_Status = CUDTSocket::OPENED; // copy address information of local node s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr); return 0; } int CUDTUnited::listen(const UDTSOCKET u, const int& backlog) { { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* s = i->second; if (NULL == s) throw CUDTException(5, 4, 0); // do nothing if the socket is already listening if (CUDTSocket::LISTENING == s->m_Status) return 0; // a socket can listen only if is in OPENED status if (CUDTSocket::OPENED != s->m_Status) throw CUDTException(5, 5, 0); // listen is not supported in rendezvous connection setup if (s->m_pUDT->m_bRendezvous) throw CUDTException(5, 7, 0); if (backlog <= 0) throw CUDTException(5, 3, 0); } //s->m_uiBackLog = backlog; LocateSetBackLog(u,backlog); try { CUDTSocket* s = locate(u); if(!s) { throw CUDTException(5, 4, 0); } s->m_pQueuedSockets = new set<UDTSOCKET>; s->m_pAcceptSockets = new set<UDTSOCKET>; } catch (...) { //delete s->m_pQueuedSockets; throw CUDTException(3, 2, 0); } CUDTSocket* s = locate(u); if(!s) { throw CUDTException(5, 4, 0); } s->m_pUDT->listen(); s->m_Status = CUDTSocket::LISTENING; return 0; } UDTSOCKET CUDTUnited::accept(const UDTSOCKET listen, sockaddr* addr, int* addrlen) { if ((NULL != addr) && (NULL == addrlen)) throw CUDTException(5, 3, 0); { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(listen); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* ls = i->second; if (ls == NULL) throw CUDTException(5, 4, 0); // the "listen" socket must be in LISTENING status if (CUDTSocket::LISTENING != ls->m_Status) throw CUDTException(5, 6, 0); // no "accept" in rendezvous connection setup if (ls->m_pUDT->m_bRendezvous) throw CUDTException(5, 7, 0); } UDTSOCKET u = CUDT::INVALID_SOCK; bool accepted = false; //// !!only one conection can be set up each time!! //#ifndef WIN32 // while (!accepted) // { // pthread_mutex_lock(&(ls->m_AcceptLock)); // if (!LocateIsQueueEmpty(listen)) // { // u = *(ls->m_pQueuedSockets->begin()); // ls->m_pAcceptSockets->insert(ls->m_pAcceptSockets->end(), u); // ls->m_pQueuedSockets->erase(ls->m_pQueuedSockets->begin()); // accepted = true; // } // else if (!ls->m_pUDT->m_bSynRecving) // accepted = true; // else if (CUDTSocket::LISTENING == ls->m_Status) // pthread_cond_wait(&(ls->m_AcceptCond), &(ls->m_AcceptLock)); // if (CUDTSocket::LISTENING != ls->m_Status) // accepted = true; // pthread_mutex_unlock(&(ls->m_AcceptLock)); // } //#else while (!accepted) { for(int i=0;i<3;i++) { { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(listen); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* ls = i->second; if (ls == NULL) throw CUDTException(5, 4, 0); // the "listen" socket must be in LISTENING status if (CUDTSocket::LISTENING != ls->m_Status) throw CUDTException(5, 6, 0); // no "accept" in rendezvous connection setup if (ls->m_pUDT->m_bRendezvous) throw CUDTException(5, 7, 0); //WaitForSingleObject(ls->m_AcceptLock, INFINITE); CGuard accept_accept(ls->m_AcceptLock); if (!LocateIsQueueEmpty(listen)) { u = *(ls->m_pQueuedSockets->begin()); ls->m_pAcceptSockets->insert(ls->m_pAcceptSockets->end(), u); ls->m_pQueuedSockets->erase(ls->m_pQueuedSockets->begin()); accepted = true; //ReleaseMutex(ls->m_AcceptLock); break; } //ReleaseMutex(ls->m_AcceptLock); } Sleep(100); } break; //WaitForSingleObject(ls->m_AcceptLock, INFINITE); //if (ls->m_pQueuedSockets->size() > 0) //{ // u = *(ls->m_pQueuedSockets->begin()); // ls->m_pAcceptSockets->insert(ls->m_pAcceptSockets->end(), u); // ls->m_pQueuedSockets->erase(ls->m_pQueuedSockets->begin()); // accepted = true; //} //else if (!ls->m_pUDT->m_bSynRecving) // accepted = true; //ReleaseMutex(ls->m_AcceptLock); //if (!accepted & (CUDTSocket::LISTENING == ls->m_Status)) // WaitForSingleObject(ls->m_AcceptCond, INFINITE); //if (CUDTSocket::LISTENING != ls->m_Status) //{ // SetEvent(ls->m_AcceptCond); // accepted = true; //} } //#endif if (u == CUDT::INVALID_SOCK) { return u; //CGuard cg(m_ControlLock); //map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(listen); //if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) //{ // //ATLASSERT(FALSE); // throw CUDTException(5, 4, 0); //} //CUDTSocket* ls = i->second; //// non-blocking receiving, no connection available //if (!ls->m_pUDT->m_bSynRecving) // throw CUDTException(6, 2, 0); //// listening socket is closed //throw CUDTException(5, 6, 0); } if (AF_INET == locate(u)->m_iIPversion) *addrlen = sizeof(sockaddr_in); else *addrlen = sizeof(sockaddr_in6); // copy address information of peer node memcpy(addr, locate(u)->m_pPeerAddr, *addrlen); return u; } int CUDTUnited::connect(const UDTSOCKET u, const sockaddr* name, const int& namelen) { //CGuard cg(m_ControlLock); CUDTSocket* s = locate(u); if (NULL == s) throw CUDTException(5, 4, 0); // check the size of SOCKADDR structure if (AF_INET == s->m_iIPversion) { if (namelen != sizeof(sockaddr_in)) throw CUDTException(5, 3, 0); } else { if (namelen != sizeof(sockaddr_in6)) throw CUDTException(5, 3, 0); } // a socket can "connect" only if it is in INIT or OPENED status if (CUDTSocket::INIT == s->m_Status) { if (!s->m_pUDT->m_bRendezvous) { s->m_pUDT->open(); updateMux(s->m_pUDT); s->m_Status = CUDTSocket::OPENED; } else throw CUDTException(5, 8, 0); } else if (CUDTSocket::OPENED != s->m_Status) throw CUDTException(5, 2, 0); s->m_pUDT->connect(name); //tianzuo,2009-8-10,connect是耗时连接,操作完检查一下连接还在不在 if (NULL==locate(u)) { throw CUDTException(5, 3, 0); } s->m_Status = CUDTSocket::CONNECTED; // copy address information of local node s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr); CIPAddress::pton(s->m_pSelfAddr, s->m_pUDT->m_piSelfIP, s->m_iIPversion); // record peer address if (AF_INET == s->m_iIPversion) { s->m_pPeerAddr = (sockaddr*)(new sockaddr_in); memcpy(s->m_pPeerAddr, name, sizeof(sockaddr_in)); } else { s->m_pPeerAddr = (sockaddr*)(new sockaddr_in6); memcpy(s->m_pPeerAddr, name, sizeof(sockaddr_in6)); } return 0; } int CUDTUnited::close(const UDTSOCKET u) { CUDT* pUDT = NULL; CUDTSocket* s = NULL; { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } s = i->second; // silently drop a request to close an invalid ID, rather than return error if (NULL == s) return 0; pUDT = s->m_pUDT; } //close函数是耗时操作,不能锁 pUDT->close(); CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } s = i->second; // silently drop a request to close an invalid ID, rather than return error if (NULL == s) return 0; // a socket will not be immediated removed when it is closed // in order to prevent other methods from accessing invalid address // a timer is started and the socket will be removed after approximately 1 second s->m_TimeStamp = CTimer::getTime(); CUDTSocket::UDTSTATUS os = s->m_Status; // synchronize with garbage collection. //CGuard::enterCS(m_ControlLock); { CGuard cg(m_ControlLock); s->m_Status = CUDTSocket::CLOSED; m_Sockets.erase(s->m_SocketID); m_ClosedSockets[s->m_SocketID] = s; if (0 != s->m_ListenSocket) { // if it is an accepted socket, remove it from the listener's queue map<UDTSOCKET, CUDTSocket*>::iterator ls = m_Sockets.find(s->m_ListenSocket); if (ls != m_Sockets.end()) { CGuard cg(ls->second->m_AcceptLock); //CGuard::enterCS(ls->second->m_AcceptLock); ls->second->m_pAcceptSockets->erase(s->m_SocketID); //CGuard::leaveCS(ls->second->m_AcceptLock); } } } //CGuard::leaveCS(m_ControlLock); // broadcast all "accept" waiting if (CUDTSocket::LISTENING == os) { #ifndef WIN32 pthread_mutex_lock(&(s->m_AcceptLock)); pthread_mutex_unlock(&(s->m_AcceptLock)); pthread_cond_broadcast(&(s->m_AcceptCond)); #else SetEvent(s->m_AcceptCond); #endif } CTimer::triggerEvent(); return 0; } int CUDTUnited::getpeername(const UDTSOCKET u, sockaddr* name, int* namelen) { if (CUDTSocket::CONNECTED != getStatus(u)) throw CUDTException(2, 2, 0); CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* s = i->second; if (NULL == s) throw CUDTException(5, 4, 0); if (!s->m_pUDT->m_bConnected || s->m_pUDT->m_bBroken) throw CUDTException(2, 2, 0); if (AF_INET == s->m_iIPversion) *namelen = sizeof(sockaddr_in); else *namelen = sizeof(sockaddr_in6); // copy address information of peer node memcpy(name, s->m_pPeerAddr, *namelen); return 0; } int CUDTUnited::getsockname(const UDTSOCKET u, sockaddr* name, int* namelen) { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) { //ATLASSERT(FALSE); throw CUDTException(5, 4, 0); } CUDTSocket* s = i->second; if (NULL == s) throw CUDTException(5, 4, 0); if (CUDTSocket::INIT == s->m_Status) throw CUDTException(2, 2, 0); if (AF_INET == s->m_iIPversion) *namelen = sizeof(sockaddr_in); else *namelen = sizeof(sockaddr_in6); // copy address information of local node memcpy(name, s->m_pSelfAddr, *namelen); return 0; } int CUDTUnited::select(ud_set* readfds, ud_set* writefds, ud_set* exceptfds, const timeval* timeout) const { uint64_t entertime = CTimer::getTime(); uint64_t to; if (NULL == timeout) to = 0xFFFFFFFFFFFFFFFFULL; else to = timeout->tv_sec * 1000000 + timeout->tv_usec; // initialize results int count = 0; set<UDTSOCKET> rs, ws, es; // retrieve related UDT sockets vector<const CUDTSocket*> ru, wu, eu; const CUDTSocket* s; if (NULL != readfds) for (set<UDTSOCKET>::const_iterator i1 = readfds->begin(); i1 != readfds->end(); ++ i1) { if (CUDTSocket::BROKEN == getStatus(*i1)) { rs.insert(*i1); ++ count; } else if (NULL == (s = locate(*i1))) throw CUDTException(5, 4, 0); else ru.insert(ru.end(), s); } if (NULL != writefds) for (set<UDTSOCKET>::const_iterator i2 = writefds->begin(); i2 != writefds->end(); ++ i2) { if (CUDTSocket::BROKEN == getStatus(*i2)) { ws.insert(*i2); ++ count; } else if (NULL == (s = locate(*i2))) throw CUDTException(5, 4, 0); else wu.insert(wu.end(), s); } if (NULL != exceptfds) for (set<UDTSOCKET>::const_iterator i3 = exceptfds->begin(); i3 != exceptfds->end(); ++ i3) { if (CUDTSocket::BROKEN == getStatus(*i3)) { es.insert(*i3); ++ count; } else if (NULL == (s = locate(*i3))) throw CUDTException(5, 4, 0); else eu.insert(eu.end(), s); } do { // query read sockets for (vector<const CUDTSocket*>::iterator j1 = ru.begin(); j1 != ru.end(); ++ j1) { s = *j1; if ((s->m_pUDT->m_bConnected && (s->m_pUDT->m_pRcvBuffer->getRcvDataSize() > 0) && ((s->m_pUDT->m_iSockType == UDT_STREAM) || (s->m_pUDT->m_pRcvBuffer->getRcvMsgNum() > 0))) || (!s->m_pUDT->m_bListening && (s->m_pUDT->m_bBroken || !s->m_pUDT->m_bConnected)) || (s->m_pUDT->m_bListening && (s->m_pQueuedSockets->size() > 0)) || (s->m_Status == CUDTSocket::CLOSED)) { rs.insert(s->m_SocketID); ++ count; } } // query write sockets for (vector<const CUDTSocket*>::iterator j2 = wu.begin(); j2 != wu.end(); ++ j2) { s = *j2; if ((s->m_pUDT->m_bConnected && (s->m_pUDT->m_pSndBuffer->getCurrBufSize() < s->m_pUDT->m_iSndBufSize)) || s->m_pUDT->m_bBroken || !s->m_pUDT->m_bConnected || (s->m_Status == CUDTSocket::CLOSED)) { ws.insert(s->m_SocketID); ++ count; } } // query exceptions on sockets for (vector<const CUDTSocket*>::iterator j3 = eu.begin(); j3 != eu.end(); ++ j3) { // check connection request status, not supported now } if (0 < count) break; CTimer::waitForEvent(); } while (to > CTimer::getTime() - entertime); if (NULL != readfds) *readfds = rs; if (NULL != writefds) *writefds = ws; if (NULL != exceptfds) *exceptfds = es; return count; } //2009-7-10,modified by tianzuo //the variable "fds_u" is removed, so that we can save more CPU, especially in case when fds is very large. int CUDTUnited::selectEx(const set<UDTSOCKET>& fds, vector<UDTSOCKET>* readfds, vector<UDTSOCKET>* writefds, vector<UDTSOCKET>* exceptfds, int64_t msTimeOut) const { //if (fds.empty()) //{ // return selectEx(readfds,writefds,exceptfds,msTimeOut); //} uint64_t entertime = CTimer::getTime(); uint64_t to; if (msTimeOut >= 0) to = msTimeOut; else to = 0xFFFFFFFFFFFFFFFFULL; // initialize results int count = 0; if (NULL != readfds) readfds->clear(); if (NULL != writefds) writefds->clear(); if (NULL != exceptfds) exceptfds->clear(); do { { CGuard cg(m_ControlLock); for (set<UDTSOCKET>::const_iterator i = fds.begin(); i != fds.end(); ++ i) { UDTSOCKET u = *i; const CUDTSocket* s = NULL; map<UDTSOCKET, CUDTSocket*>::const_iterator itSocket = m_Sockets.find(u); if (m_Sockets.end()!=itSocket) { s = (*itSocket).second; } //if s not exist, simply added it to the exceptfds, so that user can find out which socket is error. if (!s || s->m_pUDT->m_bBroken || !s->m_pUDT->m_bConnected || (s->m_Status == CUDTSocket::CLOSED)) { if (NULL != exceptfds) { exceptfds->push_back(u); ++ count; } continue; } if (NULL != readfds) { if ((s->m_pUDT->m_bConnected && (s->m_pUDT->m_pRcvBuffer->getRcvDataSize() > 0) && ((s->m_pUDT->m_iSockType == UDT_STREAM) || (s->m_pUDT->m_pRcvBuffer->getRcvMsgNum() > 0))) || (s->m_pUDT->m_bListening && (s->m_pQueuedSockets->size() > 0))) { readfds->push_back(u); ++ count; } } if (NULL != writefds) { if (s->m_pUDT->m_bConnected && (s->m_pUDT->m_pSndBuffer->getCurrBufSize() < s->m_pUDT->m_iSndBufSize)) { writefds->push_back(u); ++ count; } } } } if (count > 0) break; CTimer::waitForEvent(); } while (to > CTimer::getTime() - entertime); return count; } CUDTSocket* CUDTUnited::locate(const UDTSOCKET u) const { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); if ( (i == m_Sockets.end()) || (i->second->m_Status == CUDTSocket::CLOSED)) return NULL; return i->second; } CUDTSocket* CUDTUnited::locate(const UDTSOCKET u, const sockaddr* peer, const UDTSOCKET& id, const int32_t& isn) const { CGuard cg(m_ControlLock); map<UDTSOCKET, CUDTSocket*>::const_iterator i = m_Sockets.find(u); CGuard ag(i->second->m_AcceptLock); // look up the "peer" address in queued sockets set for (set<UDTSOCKET>::iterator j1 = i->second->m_pQueuedSockets->begin(); j1 != i->second->m_pQueuedSockets->end(); ++ j1) { map<UDTSOCKET, CUDTSocket*>::const_iterator k1 = m_Sockets.find(*j1); // this socket might have been closed and moved m_ClosedSockets if (k1 == m_Sockets.end()) continue; if (CIPAddress::ipcmp(peer, k1->second->m_pPeerAddr, i->second->m_iIPversion)) { if ((id == k1->second->m_PeerID) && (isn == k1->second->m_iISN)) return k1->second; } } // look up the "peer" address in accept sockets set for (set<UDTSOCKET>::iterator j2 = i->second->m_pAcceptSockets->begin(); j2 != i->second->m_pAcceptSockets->end(); ++ j2) { map<UDTSOCKET, CUDTSocket*>::const_iterator k2 = m_Sockets.find(*j2); // this socket might have been closed and moved m_ClosedSockets if (k2 == m_Sockets.end()) continue; if (CIPAddress::ipcmp(peer, k2->second->m_pPeerAddr, i->second->m_iIPversion)) { if ((id == k2->second->m_PeerID) && (isn == k2->second->m_iISN)) return k2->second; } } return NULL; } void CUDTUnited::checkBrokenSockets() { CGuard cg(m_ControlLock); // set of sockets To Be Closed and To Be Removed set<UDTSOCKET> tbc; set<UDTSOCKET> tbr; for (map<UDTSOCKET, CUDTSocket*>::iterator i = m_Sockets.begin(); i != m_Sockets.end(); ++ i) { // check broken connection if (i->second->m_pUDT->m_bBroken) { // if there is still data in the receiver buffer, wait longer if ((i->second->m_pUDT->m_pRcvBuffer->getRcvDataSize() > 0) && (i->second->m_pUDT->m_iBrokenCounter -- > 0)) continue; //close broken connections and start removal timer i->second->m_Status = CUDTSocket::CLOSED; i->second->m_TimeStamp = CTimer::getTime(); tbc.insert(i->first); m_ClosedSockets[i->first] = i->second; // remove from listener's queue map<UDTSOCKET, CUDTSocket*>::const_iterator ls = m_Sockets.find(i->second->m_ListenSocket); if (ls != m_Sockets.end()) { CGuard guard_accept(ls->second->m_AcceptLock); //CGuard::enterCS(ls->second->m_AcceptLock); ls->second->m_pQueuedSockets->erase(i->second->m_SocketID); ls->second->m_pAcceptSockets->erase(i->second->m_SocketID); //CGuard::leaveCS(ls->second->m_AcceptLock); } } } for (map<UDTSOCKET, CUDTSocket*>::iterator j = m_ClosedSockets.begin(); j != m_ClosedSockets.end(); ++ j) { // timeout 1 second to destroy a socket AND it has been removed from RcvUList if ((CTimer::getTime() - j->second->m_TimeStamp > 1000000) && ((NULL == j->second->m_pUDT->m_pRNode) || !j->second->m_pUDT->m_pRNode->m_bOnList)) tbr.insert(j->first); // sockets cannot be removed here because it will invalidate the map iterator } // move closed sockets to the ClosedSockets structure for (set<UDTSOCKET>::iterator k = tbc.begin(); k != tbc.end(); ++ k) m_Sockets.erase(*k); // remove those timeout sockets for (set<UDTSOCKET>::iterator l = tbr.begin(); l != tbr.end(); ++ l) removeSocket(*l); } void CUDTUnited::removeSocket(const UDTSOCKET u) { map<UDTSOCKET, CUDTSocket*>::iterator itDeleting = m_ClosedSockets.find(u); // invalid socket ID if (itDeleting == m_ClosedSockets.end()) return; //后面再使用itDeleting必然后导致迭代子失效! //UDTSOCKET uDeleting = (*itDeleting).first; CUDTSocket *pSockDeleting = (*itDeleting).second; // decrease multiplexer reference count, and remove it if necessary int port; if (AF_INET == pSockDeleting->m_iIPversion) port = ntohs(((sockaddr_in*)(pSockDeleting->m_pSelfAddr))->sin_port); else port = ntohs(((sockaddr_in6*)(pSockDeleting->m_pSelfAddr))->sin6_port); CGuard multiplexer_lock(m_MultiplexerLock); vector<CMultiplexer>::iterator m; for (m = m_vMultiplexer.begin(); m != m_vMultiplexer.end(); ++ m) if (port == m->m_iPort) break; if (NULL != pSockDeleting->m_pQueuedSockets) { CGuard guard_accept(pSockDeleting->m_AcceptLock); //CGuard::enterCS(pSockDeleting->m_AcceptLock); // if it is a listener, close all un-accepted sockets in its queue and remove them later set<UDTSOCKET> tbc; set<UDTSOCKET> tmpQueuedSockets = *pSockDeleting->m_pQueuedSockets; for (set<UDTSOCKET>::iterator q = tmpQueuedSockets.begin(); q != tmpQueuedSockets.end(); ++ q) { UDTSOCKET uQueue = *q; CGuard cg(m_ControlLock); CUDTSocket *pSocket = m_Sockets[uQueue]; if(NULL==pSocket) { //ATLASSERT(FALSE); ATLTRACE("CUDTSocket is NULL, but UDTSOCKET=%d\n",uQueue); continue; } pSocket->m_pUDT->close(); pSocket->m_TimeStamp = CTimer::getTime(); pSocket->m_Status = CUDTSocket::CLOSED; tbc.insert(uQueue); m_ClosedSockets[uQueue] = pSocket; } CGuard cg(m_ControlLock); for (set<UDTSOCKET>::iterator c = tbc.begin(); c != tbc.end(); ++ c) m_Sockets.erase(*c); //CGuard::leaveCS(pSockDeleting->m_AcceptLock); } // delete this one pSockDeleting->m_pUDT->close(); delete m_ClosedSockets[u]; m_ClosedSockets.erase(u); if (m == m_vMultiplexer.end()) return; m->m_iRefCount --; if (0 == m->m_iRefCount) { m->m_pChannel->close(); delete m->m_pSndQueue; delete m->m_pRcvQueue; delete m->m_pTimer; delete m->m_pChannel; m_vMultiplexer.erase(m); } } void CUDTUnited::setError(CUDTException* e) { #ifndef WIN32 delete (CUDTException*)pthread_getspecific(m_TLSError); pthread_setspecific(m_TLSError, e); #else CGuard tg(m_TLSLock); delete (CUDTException*)TlsGetValue(m_TLSError); TlsSetValue(m_TLSError, e); m_mTLSRecord[GetCurrentThreadId()] = e; #endif } CUDTException* CUDTUnited::getError() { #ifndef WIN32 if(NULL == pthread_getspecific(m_TLSError)) pthread_setspecific(m_TLSError, new CUDTException); return (CUDTException*)pthread_getspecific(m_TLSError); #else CGuard tg(m_TLSLock); if(NULL == TlsGetValue(m_TLSError)) { CUDTException* e = new CUDTException; TlsSetValue(m_TLSError, e); m_mTLSRecord[GetCurrentThreadId()] = e; } return (CUDTException*)TlsGetValue(m_TLSError); #endif } #ifdef WIN32 void CUDTUnited::checkTLSValue() { CGuard tg(m_TLSLock); vector<DWORD> tbr; for (map<DWORD, CUDTException*>::iterator i = m_mTLSRecord.begin(); i != m_mTLSRecord.end(); ++ i) { HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, i->first); if (NULL == h) { tbr.insert(tbr.end(), i->first); break; } if (WAIT_OBJECT_0 == WaitForSingleObject(h, 0)) { delete i->second; tbr.insert(tbr.end(), i->first); } CloseHandle(h); } for (vector<DWORD>::iterator j = tbr.begin(); j != tbr.end(); ++ j) m_mTLSRecord.erase(*j); } #endif void CUDTUnited::updateMux(CUDT* u, const sockaddr* addr, const UDPSOCKET* udpsock) { CGuard cg(m_ControlLock); if ((u->m_bReuseAddr) && (NULL != addr)) { int port = (AF_INET == u->m_iIPversion) ? ntohs(((sockaddr_in*)addr)->sin_port) : ntohs(((sockaddr_in6*)addr)->sin6_port); CGuard multiplexer_lock(m_MultiplexerLock); // find a reusable address for (vector<CMultiplexer>::iterator i = m_vMultiplexer.begin(); i != m_vMultiplexer.end(); ++ i) { if ((i->m_iIPversion == u->m_iIPversion) && (i->m_iMSS == u->m_iMSS) && i->m_bReusable) { if (i->m_iPort == port) { // reuse the existing multiplexer ++ i->m_iRefCount; u->m_pSndQueue = i->m_pSndQueue; u->m_pRcvQueue = i->m_pRcvQueue; return; } } } } // a new multiplexer is needed CMultiplexer m; m.m_iMSS = u->m_iMSS; m.m_iIPversion = u->m_iIPversion; m.m_iRefCount = 1; m.m_bReusable = u->m_bReuseAddr; m.m_pChannel = new CChannel(u->m_iIPversion); m.m_pChannel->setSndBufSize(u->m_iUDPSndBufSize); m.m_pChannel->setRcvBufSize(u->m_iUDPRcvBufSize); try { if (NULL != udpsock) m.m_pChannel->open(*udpsock); else m.m_pChannel->open(addr); } catch (CUDTException& e) { m.m_pChannel->close(); delete m.m_pChannel; throw e; } sockaddr* sa = (AF_INET == u->m_iIPversion) ? (sockaddr*) new sockaddr_in : (sockaddr*) new sockaddr_in6; m.m_pChannel->getSockAddr(sa); m.m_iPort = (AF_INET == u->m_iIPversion) ? ntohs(((sockaddr_in*)sa)->sin_port) : ntohs(((sockaddr_in6*)sa)->sin6_port); if (AF_INET == u->m_iIPversion) delete (sockaddr_in*)sa; else delete (sockaddr_in6*)sa; m.m_pTimer = new CTimer; m.m_pSndQueue = new CSndQueue; m.m_pSndQueue->init(m.m_pChannel, m.m_pTimer); m.m_pRcvQueue = new CRcvQueue; m.m_pRcvQueue->init(32, u->m_iPayloadSize, m.m_iIPversion, 1024, m.m_pChannel, m.m_pTimer); CGuard multiplexer_lock(m_MultiplexerLock); m_vMultiplexer.insert(m_vMultiplexer.end(), m); u->m_pSndQueue = m.m_pSndQueue; u->m_pRcvQueue = m.m_pRcvQueue; } void CUDTUnited::updateMux(CUDT* u, const CUDTSocket* ls) { //CGuard cg(m_ControlLock); int port = (AF_INET == ls->m_iIPversion) ? ntohs(((sockaddr_in*)ls->m_pSelfAddr)->sin_port) : ntohs(((sockaddr_in6*)ls->m_pSelfAddr)->sin6_port); CGuard multiplexer_lock(m_MultiplexerLock); // find the listener's address for (vector<CMultiplexer>::iterator i = m_vMultiplexer.begin(); i != m_vMultiplexer.end(); ++ i) { if (i->m_iPort == port) { // reuse the existing multiplexer ++ i->m_iRefCount; u->m_pSndQueue = i->m_pSndQueue; u->m_pRcvQueue = i->m_pRcvQueue; return; } } } // //#ifndef WIN32 // void* CUDTUnited::garbageCollect(void* p) //#else // DWORD WINAPI CUDTUnited::garbageCollect(LPVOID p) //#endif //{ // CUDTUnited* self = (CUDTUnited*)p; // // CGuard gcguard(self->m_GCStopLock); // // while (!self->m_bClosing) // { // self->checkBrokenSockets(); // // #ifdef WIN32 // self->checkTLSValue(); // #endif // // #ifndef WIN32 // timeval now; // timespec timeout; // gettimeofday(&now, 0); // timeout.tv_sec = now.tv_sec + 1; // timeout.tv_nsec = now.tv_usec * 1000; // // pthread_cond_timedwait(&self->m_GCStopCond, &self->m_GCStopLock, &timeout); // #else // WaitForSingleObject(self->m_GCStopCond, 1000); // #endif // } // // { // //分两步来关闭CMultiplexer。先close,等m_ClosedSockets全关掉后,再delete。 // CGuard multiplexer_lock(self->m_MultiplexerLock); // vector<CMultiplexer> tmpMlitiplexer = self->m_vMultiplexer; // for (vector<CMultiplexer>::iterator m = tmpMlitiplexer.begin(); m != tmpMlitiplexer.end(); ++ m) // { // m->m_pChannel->close(); // m->m_pRcvQueue->close(); // m->m_pSndQueue->CloseSndQueue(); // } // //self->m_vMultiplexer.clear(); // } // // // remove all sockets and multiplexers // { // CGuard cg(self->m_ControlLock); // map<UDTSOCKET, CUDTSocket*> tmpSockets = self->m_Sockets; // for (map<UDTSOCKET, CUDTSocket*>::iterator i = tmpSockets.begin(); i != tmpSockets.end(); ++ i) // { // i->second->m_pUDT->close(); // i->second->m_Status = CUDTSocket::CLOSED; // i->second->m_TimeStamp = 0; // self->m_ClosedSockets[i->first] = i->second; // } // self->m_Sockets.clear(); // } // self->checkBrokenSockets(); // // std::map<UDTSOCKET, CUDTSocket*> tmpCloseSockets = self->m_ClosedSockets; //advoid iterator crash. // for (map<UDTSOCKET, CUDTSocket*>::iterator c = tmpCloseSockets.begin(); // c != tmpCloseSockets.end(); // ++ c) // { // CUDTSocket* pSocket = c->second; // if(NULL==pSocket) // { // ATLTRACE("ERROR:CUDTSocket IS NULL!\n"); // continue; // } // delete pSocket; // } // self->m_ClosedSockets.clear(); // // { // CGuard multiplexer_lock(self->m_MultiplexerLock); // vector<CMultiplexer> tmpMlitiplexer = self->m_vMultiplexer; // for (vector<CMultiplexer>::iterator m = tmpMlitiplexer.begin(); m != tmpMlitiplexer.end(); ++ m) // { // delete m->m_pSndQueue; // delete m->m_pRcvQueue; // delete m->m_pTimer; // delete m->m_pChannel; // } // self->m_vMultiplexer.clear(); // } // // // ATLTRACE("CUDTUnited::garbageCollect EXITED\n"); // // #ifndef WIN32 // return NULL; // #else // return 0; // #endif //} //最新版的垃圾回收函数 #ifndef WIN32 void* CUDTUnited::garbageCollect(void* p) #else DWORD WINAPI CUDTUnited::garbageCollect(LPVOID p) #endif { CUDTUnited* self = (CUDTUnited*)p; CGuard gcguard(self->m_GCStopLock); while (!self->m_bClosing) { self->checkBrokenSockets(); #ifdef WIN32 self->checkTLSValue(); #endif #ifndef WIN32 timeval now; timespec timeout; gettimeofday(&now, 0); timeout.tv_sec = now.tv_sec + 1; timeout.tv_nsec = now.tv_usec * 1000; pthread_cond_timedwait(&self->m_GCStopCond, &self->m_GCStopLock, &timeout); #else WaitForSingleObject(self->m_GCStopCond, 1000); #endif } // remove all sockets and multiplexers for (map<UDTSOCKET, CUDTSocket*>::iterator i = self->m_Sockets.begin(); i != self->m_Sockets.end(); ++ i) { i->second->m_pUDT->close(); i->second->m_Status = CUDTSocket::CLOSED; i->second->m_TimeStamp = CTimer::getTime(); self->m_ClosedSockets[i->first] = i->second; } self->m_Sockets.clear(); while (!self->m_ClosedSockets.empty()) { #ifndef WIN32 usleep(1000); #else Sleep(1); #endif self->checkBrokenSockets(); } #ifndef WIN32 return NULL; #else return 0; #endif } //////////////////////////////////////////////////////////////////////////////// int CUDT::startup() { return s_UDTUnited.startup(); } int CUDT::cleanup() { return s_UDTUnited.cleanup(); } UDTSOCKET CUDT::socket(int af, int type, int) { if (!s_UDTUnited.m_bGCStatus) s_UDTUnited.startup(); try { return s_UDTUnited.newSocket(af, type); } catch (CUDTException& e) { s_UDTUnited.setError(new CUDTException(e)); return INVALID_SOCK; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return INVALID_SOCK; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return INVALID_SOCK; } } int CUDT::bind(UDTSOCKET u, const sockaddr* name, int namelen) { try { return s_UDTUnited.bind(u, name, namelen); } catch (CUDTException& e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::bind(UDTSOCKET u, UDPSOCKET udpsock) { try { return s_UDTUnited.bind(u, udpsock); } catch (CUDTException& e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::listen(UDTSOCKET u, int backlog) { try { return s_UDTUnited.listen(u, backlog); } catch (CUDTException& e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } UDTSOCKET CUDT::accept(UDTSOCKET u, sockaddr* addr, int* addrlen) { try { return s_UDTUnited.accept(u, addr, addrlen); } catch (CUDTException& e) { s_UDTUnited.setError(new CUDTException(e)); return INVALID_SOCK; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return INVALID_SOCK; } } int CUDT::connect(UDTSOCKET u, const sockaddr* name, int namelen) { try { return s_UDTUnited.connect(u, name, namelen); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::close(UDTSOCKET u) { try { return s_UDTUnited.close(u); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::getpeername(UDTSOCKET u, sockaddr* name, int* namelen) { try { return s_UDTUnited.getpeername(u, name, namelen); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::getsockname(UDTSOCKET u, sockaddr* name, int* namelen) { try { return s_UDTUnited.getsockname(u, name, namelen);; } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::getsockopt(UDTSOCKET u, int, UDTOpt optname, void* optval, int* optlen) { try { CUDT* udt = s_UDTUnited.lookup(u); udt->getOpt(optname, optval, *optlen); return 0; } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::setsockopt(UDTSOCKET u, int, UDTOpt optname, const void* optval, int optlen) { try { CUDT* udt = s_UDTUnited.lookup(u); udt->setOpt(optname, optval, optlen); return 0; } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::send(UDTSOCKET u, const char* buf, int len, int) { try { CUDT* udt = s_UDTUnited.lookup(u); return udt->send((char*)buf, len); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::recv(UDTSOCKET u, char* buf, int len, int) { try { CUDT* udt = s_UDTUnited.lookup(u); return udt->recv(buf, len); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::sendmsg(UDTSOCKET u, const char* buf, int len, int ttl, bool inorder) { try { CUDT* udt = s_UDTUnited.lookup(u); return udt->sendmsg((char*)buf, len, ttl, inorder); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::recvmsg(UDTSOCKET u, char* buf, int len) { try { CUDT* udt = s_UDTUnited.lookup(u); return udt->recvmsg(buf, len); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int64_t CUDT::sendfile(UDTSOCKET u, fstream& ifs, const int64_t& offset, const int64_t& size, const int& block) { try { CUDT* udt = s_UDTUnited.lookup(u); return udt->sendfile(ifs, offset, size, block); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int64_t CUDT::recvfile(UDTSOCKET u, fstream& ofs, const int64_t& offset, const int64_t& size, const int& block) { try { CUDT* udt = s_UDTUnited.lookup(u); return udt->recvfile(ofs, offset, size, block); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::select(int, ud_set* readfds, ud_set* writefds, ud_set* exceptfds, const timeval* timeout) { if ((NULL == readfds) && (NULL == writefds) && (NULL == exceptfds)) { s_UDTUnited.setError(new CUDTException(5, 3, 0)); return ERROR; } try { return s_UDTUnited.select(readfds, writefds, exceptfds, timeout); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } int CUDT::selectEx(const set<UDTSOCKET>& fds, vector<UDTSOCKET>* readfds, vector<UDTSOCKET>* writefds, vector<UDTSOCKET>* exceptfds, int64_t msTimeOut) { if ((NULL == readfds) && (NULL == writefds)) { s_UDTUnited.setError(new CUDTException(5, 3, 0)); return ERROR; } try { return s_UDTUnited.selectEx(fds, readfds, writefds, exceptfds, msTimeOut); } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (bad_alloc&) { s_UDTUnited.setError(new CUDTException(3, 2, 0)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } CUDTException& CUDT::getlasterror() { return *s_UDTUnited.getError(); } int CUDT::perfmon(UDTSOCKET u, CPerfMon* perf, bool clear) { try { CUDT* udt = s_UDTUnited.lookup(u); udt->sample(perf, clear); return 0; } catch (CUDTException e) { s_UDTUnited.setError(new CUDTException(e)); return ERROR; } catch (...) { s_UDTUnited.setError(new CUDTException(-1, 0, 0)); return ERROR; } } CUDT* CUDT::getUDTHandle(UDTSOCKET u) { try { return s_UDTUnited.lookup(u); } catch (...) { return NULL; } } //////////////////////////////////////////////////////////////////////////////// namespace UDT { int startup() { return CUDT::startup(); } int cleanup() { return CUDT::cleanup(); } UDTSOCKET socket(int af, int type, int protocol) { return CUDT::socket(af, type, protocol); } int bind(UDTSOCKET u, const struct sockaddr* name, int namelen) { return CUDT::bind(u, name, namelen); } int bind(UDTSOCKET u, UDPSOCKET udpsock) { return CUDT::bind(u, udpsock); } int listen(UDTSOCKET u, int backlog) { return CUDT::listen(u, backlog); } UDTSOCKET accept(UDTSOCKET u, struct sockaddr* addr, int* addrlen) { return CUDT::accept(u, addr, addrlen); } int connect(UDTSOCKET u, const struct sockaddr* name, int namelen) { return CUDT::connect(u, name, namelen); } int close(UDTSOCKET u) { return CUDT::close(u); } int getpeername(UDTSOCKET u, struct sockaddr* name, int* namelen) { return CUDT::getpeername(u, name, namelen); } int getsockname(UDTSOCKET u, struct sockaddr* name, int* namelen) { return CUDT::getsockname(u, name, namelen); } int getsockopt(UDTSOCKET u, int level, SOCKOPT optname, void* optval, int* optlen) { return CUDT::getsockopt(u, level, optname, optval, optlen); } int setsockopt(UDTSOCKET u, int level, SOCKOPT optname, const void* optval, int optlen) { return CUDT::setsockopt(u, level, optname, optval, optlen); } int send(UDTSOCKET u, const char* buf, int len, int flags) { return CUDT::send(u, buf, len, flags); } int recv(UDTSOCKET u, char* buf, int len, int flags) { return CUDT::recv(u, buf, len, flags); } int sendmsg(UDTSOCKET u, const char* buf, int len, int ttl, bool inorder) { return CUDT::sendmsg(u, buf, len, ttl, inorder); } int recvmsg(UDTSOCKET u, char* buf, int len) { return CUDT::recvmsg(u, buf, len); } int64_t sendfile(UDTSOCKET u, fstream& ifs, int64_t offset, int64_t size, int block) { return CUDT::sendfile(u, ifs, offset, size, block); } int64_t recvfile(UDTSOCKET u, fstream& ofs, int64_t offset, int64_t size, int block) { return CUDT::recvfile(u, ofs, offset, size, block); } int select(int nfds, UDSET* readfds, UDSET* writefds, UDSET* exceptfds, const struct timeval* timeout) { return CUDT::select(nfds, readfds, writefds, exceptfds, timeout); } int selectEx(const set<UDTSOCKET>& fds, vector<UDTSOCKET>* readfds, vector<UDTSOCKET>* writefds, vector<UDTSOCKET>* exceptfds, int64_t msTimeOut) { return CUDT::selectEx(fds, readfds, writefds, exceptfds, msTimeOut); } ERRORINFO& getlasterror() { return CUDT::getlasterror(); } int perfmon(UDTSOCKET u, TRACEINFO* perf, bool clear) { return CUDT::perfmon(u, perf, clear); } }
[ "tantianzuo@159e4f46-9839-11de-8efd-97b2a7529d09" ]
[ [ [ 1, 2381 ] ] ]
29b5e1b4224008891e456610b7f533b3d4aecb01
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/zFileManager/ZFileDlg.h
29056a728af06578a856ae1597ce5bb6f1f52bb6
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
7,575
h
// // C++ Interface: ZFileDlg // // Description: // // // Author: root <root@andLinux>, (C) 2008 // // Copyright: See COPYING file that comes with this distribution // // #ifndef ZFILEDLG_H #define ZFILEDLG_H #include "BaseDlg.h" #include "ZFileBrowser.h" #include <ZMultiLineEdit.h> #include <ZMessageDlg.h> #include "resources.h" #include <ZOptionsMenu.h> #include <ZKbMainWidget.h> #include <ZListBox.h> #include <ZPressButton.h> class FileBrowser; class ZFileOpenDialog : public MyBaseDlg { Q_OBJECT public: ZFileOpenDialog(bool onlyDirs); ~ZFileOpenDialog(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void slot_paste(); void selectItem(int); void slot_makedir(); private: QString fileName; QString basePath; FileBrowser* fb; ZOptionsMenu * menuPaste; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZFileSaveDialog : public MyBaseDlg { Q_OBJECT public: ZFileSaveDialog(const QString &curPath = "/", const QString &originName = ""); ~ZFileSaveDialog(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); private: ZMultiLineEdit *zmle; QString fileName; QString basePath; FileBrowser* fb; protected: virtual void keyPressEvent( QKeyEvent* e); virtual void accept(); }; class ZIconSelect : public MyBaseDlg { Q_OBJECT public: ZIconSelect(); ~ZIconSelect(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void selectItem(int); void brClicked(); private: QString fileName; QString basePath; ZListBox* browser; ZOptionsMenu * menuPaste; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZOpenWith : public MyBaseDlg { Q_OBJECT public: ZOpenWith(); ~ZOpenWith(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void selectItem(int); void brClicked(); private: QString fileName; QString basePath; ZListBox* browser; ZOptionsMenu * menuPaste; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZFolderSelect2 : public MyBaseDlg { Q_OBJECT public: ZFolderSelect2(bool onlyDirs, QString path = "/"); ~ZFolderSelect2(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void slot_paste(); void selectItem(int); private: QString fileName; QString basePath; FileBrowser* fb; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZFolderSelect : public MyBaseDlg { Q_OBJECT public: ZFolderSelect(bool onlyDirs, QString path = "/"); ~ZFolderSelect(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void slot_paste(); void selectItem(int); void slot_makedir(); private: QString fileName; QString basePath; FileBrowser* fb; ZOptionsMenu * menuPaste; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZAdminFav : public MyBaseDlg { Q_OBJECT public: ZAdminFav(); ~ZAdminFav(); //int exec(); //int result() const ; QString getFileName() { return fileName; } QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void selectItem(int); void EditarFav(); void BorrarFav(); void CargarFavs(); void brClicked(); private: QString fileName; QString basePath; ZListBox* browser; ZOptionsMenu * menuMain; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZSettings : public MyBaseDlg { Q_OBJECT public: ZSettings(); ~ZSettings(); QString getFileName(const QString &AFileName); QString getFilePath() { return basePath; } QString texto(const char*xString); public slots: void slot_cancel(); void selectItem(int); void CargarSettings(); void setClicked(); void MostrarOcultos(); void Miniaturas(); void VerLista(); void VerDetalle(); void VerGrandes(); void EditarHome(); void CambiarVista(); void FontSize(); void TextEditor(); private: QString fileName; QString basePath; ZListBox* browser; protected: virtual void accept(); // virtual void keyPressEvent(QKeyEvent* e); }; class ZClipboard : public MyBaseDlg { Q_OBJECT public: ZClipboard(); ~ZClipboard(); //int exec(); //int result() const ; QString getFileName(const QString &AFileName); QString getFilePath(const QString &AFileName); QString texto(const char*xString); bool PasteFiles(const QString &ASourse, const QString &ADest, bool remove = false); bool CopyFile ( QString ASourceName, QString ADestName ); int GetFolderSize ( const QString &path ); int GetFilesCountInFolder ( const QString &path ); QStringList GetFilesInFolder(const QString &path); ZAppInfoArea *pAIA; public slots: void slot_cancel(); void Borrar(); void Vaciar(); void brClicked(); void CargarFavs(); private: QString fileName; QString basePath; ZListBox* browser; ZOptionsMenu * menuMain; protected: virtual void accept(); }; class myButton : public ZPressButton { Q_OBJECT public: myButton(QWidget*, char const*, ZSkinService::WidgetClsID = ZSkinService::clsZPressButton); ~myButton(); protected: virtual void keyPressEvent(QKeyEvent* k); }; class ZSearch : public MyBaseDlg { Q_OBJECT public: ZSearch(); ~ZSearch(); QString texto(const char*xString); public slots: void slot_cancel(); void slot_search(); private: ZListBox* browser; myButton* buttonDir; ZLineEdit* lineEdit; protected: //virtual void keyPressEvent(QKeyEvent* e); }; class ZSearchRes : public MyBaseDlg { Q_OBJECT public: ZSearchRes(); ~ZSearchRes(); //int exec(); //int result() const ; QString getFileName(const QString &AFileName); QString getFilePath(const QString &AFileName); QString texto(const char*xString); public slots: void slot_cancel(); void brClicked(); void CargarFavs(); private: QString fileName; QString basePath; ZListBox* browser; protected: virtual void accept(); virtual void keyPressEvent(QKeyEvent* e); }; #endif
[ [ [ 1, 362 ] ] ]
92b3c0378cbba7c4db9f8629e5e88a49b139ddc0
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/set/aux_/value_type_impl.hpp
eef03e973ee5ebff460f06b327a5e74da2b579db
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
927
hpp
#ifndef BOOST_MPL_SET_AUX_VALUE_TYPE_IMPL_HPP_INCLUDED #define BOOST_MPL_SET_AUX_VALUE_TYPE_IMPL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/set/aux_/value_type_impl.hpp,v $ // $Date: 2006/04/17 23:49:41 $ // $Revision: 1.1 $ #include <boost/mpl/value_type_fwd.hpp> #include <boost/mpl/set/aux_/tag.hpp> namespace boost { namespace mpl { template<> struct value_type_impl< aux::set_tag > { template< typename Set, typename T > struct apply { typedef T type; }; }; }} #endif // BOOST_MPL_SET_AUX_VALUE_TYPE_IMPL_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 34 ] ] ]
9dd003faf1f54e6b7a39e40fa64c6a06230705cb
4a2b2d6d07714e82ecf94397ea6227edbd7893ad
/Curl/CurlTest/mjpegtojpeg.cpp
44d93c0a52255c0a040c5067e426ef10eb60093b
[]
no_license
intere/tmee
8b0a6dd4651987a580e3194377cfb999e9615758
327fed841df6351dc302071614a9600e2fa67f5f
refs/heads/master
2021-01-25T07:28:47.788280
2011-07-21T04:24:31
2011-07-21T04:24:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,544
cpp
//#include "mjpegtojpeg.h" /** * bool mjpeg2Jpeg(const char *fileName, const byte *buffer, const int size) { HANDLE file_ = CreateFile(fileName, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS, 0, NULL); if (file_ == INVALID_HANDLE_VALUE) { return false; } byte jpgHdr[] = { 0xff,0xd8, // SOI 0xff,0xe0, // APP0 0x00,0x10, // APP0 Hdr size 0x4a,0x46,0x49,0x46,0x00, // ID string 0x01,0x01, // Version 0x00, // Bits per type 0x00, 0x00, // X density 0x00, 0x00, // Y density 0x00, // X Thumbnail size 0x00 // Y Thumbnail size }; unsigned long wrote = 0; //write header if (!WriteFile(file_, jpgHdr, sizeof (jpgHdr), &wrote, NULL)) { CloseHandle(file_); return false; } byte MJPGDHTSeg[0x1A4] = { // JPEG DHT Segment for YCrCb omitted from MJPG data 0xFF,0xC4,0x01,0xA2, 0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00, 0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61, 0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24, 0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34, 0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56, 0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78, 0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99, 0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9, 0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9, 0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7, 0xF8,0xF9,0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01, 0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71, 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0,0x15,0x62, 0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A, 0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56, 0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78, 0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98, 0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8, 0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8, 0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8, 0xF9,0xFA }; //Write DHT color segment if (!WriteFile (file_, MJPGDHTSeg, sizeof (MJPGDHTSeg), &wrote, NULL)) { CloseHandle(file_); return false; } //removing avi header int tmp = *(buffer + 4); tmp <<= 8; tmp += *(buffer + 5) + 4; //write frame if (!WriteFile (file_, buffer + tmp, size - tmp, &wrote, NULL)) { CloseHandle(file_); return false; } CloseHandle(file_); return true; } */
[ "intere@8c6822e2-464b-4b1f-8ae9-3c1f0a8e8225" ]
[ [ [ 1, 94 ] ] ]
e298aab79c4177f953b836f42c1cabfb4719a5d0
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/fonttexturemanager.cpp
a09291603e452a4d9b1402a68b76bc8cb73aa12b
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
6,080
cpp
#include"fonttexturemanager.h" #include"../auxiliary/debug/assert.h" #include"../auxiliary/debug/warning.h" #include"../auxiliary/string.h" #include"transiter.h" namespace Maid { /*! @class FontTexture fonttexturecache.h @brief FontTextureCache 内で管理されるテクスチャ */ void FontTexture::Load( const Surface& surf ) { GraphicsCore* pCore = GlobalPointer<GraphicsCore>::Get(); Destroy(); Graphics::SPTEXTURE2D pTexture; Graphics::CREATERETEXTURE2DPARAM tex; Graphics::CREATEMATERIALPARAM mat; const PIXELFORMAT DstFormat = pCore->FindFormatTexture2D( surf.GetPixelFormat(), false ); // フォントは縮小しなくてもいいと思う const SIZE2DI ImgSize = surf.GetSize(); const SIZE2DI TexSize = pCore->CalcTextureSize( ImgSize ); { tex.Size = TexSize; tex.MipLevels = 1; tex.ArraySize = 1; tex.Format = DstFormat; tex.Usage = Graphics::RESOURCEUSAGE_DEFAULT; tex.BindFlags = Graphics::RESOURCEBINDFLAG_MATERIAL; SurfaceInstance tmp; { tmp.Create( tex.Size, tex.Format ); const RECT2DI src_rc( POINT2DI(0,0), ImgSize ); const RECT2DI dst_rc( POINT2DI(0,0), ImgSize ); Transiter::Copy(surf, src_rc, tmp, dst_rc); } Graphics::SUBRESOURCE Data; Data.pData = const_cast<SurfaceInstance&>(tmp).GetPlanePTR(); Data.Pitch = const_cast<SurfaceInstance&>(tmp).GetPitch(); pTexture = pCore->GetDevice()->CreateTexture2D( tex, &Data ); } if( pTexture.get()==NULL ) { MAID_WARNING( MAIDTEXT("テクスチャの作成に失敗 ") ); return ; } Graphics::SPMATERIAL pMaterial; { mat.Format = DstFormat; mat.Dimension = Graphics::CREATEMATERIALPARAM::DIMENSION_TEXTURE2D; pMaterial = pCore->GetDevice()->CreateMaterial( pTexture, NULL ); } Setup( pTexture, pMaterial, ImgSize, ImgSize, surf.GetPixelFormat() ); } void FontTexture::Destroy() { IMaterial::Clear(); } /*! @class FontTextureManager fonttexturecache.h @brief FontTexture の管理クラス \n こいつがうまくやりくりする */ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! コンストラクタ /*! */ FontTextureManager::FontTextureManager() { } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! デストラクタ /*! */ FontTextureManager::~FontTextureManager() { } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! フォントテクスチャの取得 /*! この関数を呼び出すだけで自動的に、キャッシュの破棄、作成、更新 \n を行ってくれます @param pFont [i ] 取得したいフォント @param FontCode [i ] 取得したいフォントコード */ const FontTexture& FontTextureManager::GetTexture( const Font& f, unt32 FontCode ) { const CACHEKEY MapKey(f,FontCode); if( m_CacheTable.IsExist(MapKey) ) { return m_CacheTable.GetData(MapKey); } SurfaceInstance surf; // フォントとして使うデータ f.Rasterize( FontCode, surf ); FontTexture tex; tex.Load( surf ); m_CacheTable.Register( MapKey, tex ); return m_CacheTable.GetData(MapKey); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! キャッシュをすべてクリアする /*! */ void FontTextureManager::ClearCache() { m_CacheTable.ClearAll(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! キャッシュとして保持する数を変更する /*! @param Size [i ] 最低限キャッシュしておく数 */ void FontTextureManager::SetCacheSize( int Size ) { m_CacheTable.SetCacheSize(Size); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! キャッシュの掃除 /*! @_CacheMax 個まで減少させます */ void FontTextureManager::Garbage() { m_CacheTable.Garbage(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*/ //! 初期化 /*! */ void FontTextureManager::Initialize() { m_CacheTable.SetCacheSize( 200 ); m_CacheTable.SetGarbageState( CACHETABLE::GARBAGESTATE_MANUAL ); } void FontTextureManager::Finalize() { m_CacheTable.ClearAll(); } FontTextureManager::CACHEKEY::CACHEKEY() :Code(0) { } FontTextureManager::CACHEKEY::CACHEKEY( const CACHEKEY& rha ) :font(rha.font),Code(rha.Code) { } FontTextureManager::CACHEKEY::CACHEKEY( const Font& f, unt32 c ) :font(f),Code(c) { } bool FontTextureManager::CACHEKEY::operator < ( const CACHEKEY& rhs ) const { if( Code < rhs.Code ) { return true; } else if( Code > rhs.Code ) { return false; } if( font.GetName() < rhs.font.GetName() ) { return true; } else if( font.GetName() > rhs.font.GetName() ) { return false; } if( font.GetSize().w < rhs.font.GetSize().w ) { return true; } else if( font.GetSize().w > rhs.font.GetSize().w ) { return false; } if( font.GetSize().h < rhs.font.GetSize().h ) { return true; } else if( font.GetSize().h > rhs.font.GetSize().h ) { return false; } { const COLOR_R32G32B32A32F& t = font.GetColor(); const COLOR_R32G32B32A32F& r = rhs.font.GetColor(); if( t.GetR() < r.GetR() ) { return true; } else if( t.GetR() > r.GetR() ) { return false; } if( t.GetG() < r.GetG() ) { return true; } else if( t.GetG() > r.GetG() ) { return false; } if( t.GetB() < r.GetB() ) { return true; } else if( t.GetB() > r.GetB() ) { return false; } if( t.GetA() < r.GetA() ) { return true; } else if( t.GetA() > r.GetA() ) { return false; } } { const unt t = font.GetFilterNo(); const unt r = rhs.font.GetFilterNo(); if( t < r ) { return true; } else if( t > r ) { return false; } } if( font.IsAntiAlias() != rhs.font.IsAntiAlias() ) { return true; } return false; } }
[ [ [ 1, 246 ] ] ]
bf22ef2249d75f5b2466f1a050bb8cea25da272b
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_graphics/images/juce_Image.h
ca97f8c95e78d14d414b46ae6919f6c42d3d17f6
[]
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
21,864
h
/* ============================================================================== 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. ============================================================================== */ #ifndef __JUCE_IMAGE_JUCEHEADER__ #define __JUCE_IMAGE_JUCEHEADER__ #include "../colour/juce_Colour.h" #include "../contexts/juce_GraphicsContext.h" class ImageType; class ImagePixelData; //============================================================================== /** Holds a fixed-size bitmap. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format. To draw into an image, create a Graphics object for it. e.g. @code // create a transparent 500x500 image.. Image myImage (Image::RGB, 500, 500, true); Graphics g (myImage); g.setColour (Colours::red); g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image. @endcode Other useful ways to create an image are with the ImageCache class, or the ImageFileFormat, which provides a way to load common image files. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel */ class JUCE_API Image { public: //============================================================================== /** */ enum PixelFormat { UnknownFormat, RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */ ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */ SingleChannel /**<< each pixel is a 1-byte alpha channel value. */ }; //============================================================================== /** Creates a null image. */ Image(); /** Creates an image with a specified size and format. The image's internal type will be of the NativeImageType class - to specify a different type, use the other constructor, which takes an ImageType to use. @param format the number of colour channels in the image @param imageWidth the desired width of the image, in pixels - this value must be greater than zero (otherwise a width of 1 will be used) @param imageHeight the desired width of the image, in pixels - this value must be greater than zero (otherwise a height of 1 will be used) @param clearImage if true, the image will initially be cleared to black (if it's RGB) or transparent black (if it's ARGB). If false, the image may contain junk initially, so you need to make sure you overwrite it thoroughly. */ Image (PixelFormat format, int imageWidth, int imageHeight, bool clearImage); /** Creates an image with a specified size and format. @param format the number of colour channels in the image @param imageWidth the desired width of the image, in pixels - this value must be greater than zero (otherwise a width of 1 will be used) @param imageHeight the desired width of the image, in pixels - this value must be greater than zero (otherwise a height of 1 will be used) @param clearImage if true, the image will initially be cleared to black (if it's RGB) or transparent black (if it's ARGB). If false, the image may contain junk initially, so you need to make sure you overwrite it thoroughly. @param type the type of image - this lets you specify the internal format that will be used to allocate and manage the image data. */ Image (PixelFormat format, int imageWidth, int imageHeight, bool clearImage, const ImageType& type); /** Creates a shared reference to another image. This won't create a duplicate of the image - when Image objects are copied, they simply point to the same shared image data. To make sure that an Image object has its own unique, unshared internal data, call duplicateIfShared(). */ Image (const Image& other); /** Makes this image refer to the same underlying image as another object. This won't create a duplicate of the image - when Image objects are copied, they simply point to the same shared image data. To make sure that an Image object has its own unique, unshared internal data, call duplicateIfShared(). */ Image& operator= (const Image&); #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS Image (Image&& other) noexcept; Image& operator= (Image&&) noexcept; #endif /** Destructor. */ ~Image(); /** Returns true if the two images are referring to the same internal, shared image. */ bool operator== (const Image& other) const noexcept { return image == other.image; } /** Returns true if the two images are not referring to the same internal, shared image. */ bool operator!= (const Image& other) const noexcept { return image != other.image; } /** Returns true if this image isn't null. If you create an Image with the default constructor, it has no size or content, and is null until you reassign it to an Image which contains some actual data. The isNull() method is the opposite of isValid(). @see isNull */ inline bool isValid() const noexcept { return image != nullptr; } /** Returns true if this image is not valid. If you create an Image with the default constructor, it has no size or content, and is null until you reassign it to an Image which contains some actual data. The isNull() method is the opposite of isValid(). @see isValid */ inline bool isNull() const noexcept { return image == nullptr; } /** A null Image object that can be used when you need to return an invalid image. This object is the equivalient to an Image created with the default constructor. */ static const Image null; //============================================================================== /** Returns the image's width (in pixels). */ int getWidth() const noexcept; /** Returns the image's height (in pixels). */ int getHeight() const noexcept; /** Returns a rectangle with the same size as this image. The rectangle's origin is always (0, 0). */ Rectangle<int> getBounds() const noexcept; /** Returns the image's pixel format. */ PixelFormat getFormat() const noexcept; /** True if the image's format is ARGB. */ bool isARGB() const noexcept; /** True if the image's format is RGB. */ bool isRGB() const noexcept; /** True if the image's format is a single-channel alpha map. */ bool isSingleChannel() const noexcept; /** True if the image contains an alpha-channel. */ bool hasAlphaChannel() const noexcept; //============================================================================== /** Clears a section of the image with a given colour. This won't do any alpha-blending - it just sets all pixels in the image to the given colour (which may be non-opaque if the image has an alpha channel). */ void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000)); /** Returns a rescaled version of this image. A new image is returned which is a copy of this one, rescaled to the given size. Note that if the new size is identical to the existing image, this will just return a reference to the original image, and won't actually create a duplicate. */ Image rescaled (int newWidth, int newHeight, Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const; /** Returns a version of this image with a different image format. A new image is returned which has been converted to the specified format. Note that if the new format is no different to the current one, this will just return a reference to the original image, and won't actually create a copy. */ Image convertedToFormat (PixelFormat newFormat) const; /** Makes sure that no other Image objects share the same underlying data as this one. If no other Image objects refer to the same shared data as this one, this method has no effect. But if there are other references to the data, this will create a new copy of the data internally. Call this if you want to draw onto the image, but want to make sure that this doesn't affect any other code that may be sharing the same data. @see getReferenceCount */ void duplicateIfShared(); /** Returns an image which refers to a subsection of this image. This will not make a copy of the original - the new image will keep a reference to it, so that if the original image is changed, the contents of the subsection will also change. Likewise if you draw into the subimage, you'll also be drawing onto that area of the original image. Note that if you use operator= to make the original Image object refer to something else, the subsection image won't pick up this change, it'll remain pointing at the original. The area passed-in will be clipped to the bounds of this image, so this may return a smaller image than the area you asked for, or even a null image if the area was out-of-bounds. */ Image getClippedImage (const Rectangle<int>& area) const; //============================================================================== /** Returns the colour of one of the pixels in the image. If the co-ordinates given are beyond the image's boundaries, this will return Colours::transparentBlack. @see setPixelAt, Image::BitmapData::getPixelColour */ Colour getPixelAt (int x, int y) const; /** Sets the colour of one of the image's pixels. If the co-ordinates are beyond the image's boundaries, then nothing will happen. Note that this won't do any alpha-blending, it'll just replace the existing pixel with the given one. The colour's opacity will be ignored if this image doesn't have an alpha-channel. @see getPixelAt, Image::BitmapData::setPixelColour */ void setPixelAt (int x, int y, const Colour& colour); /** Changes the opacity of a pixel. This only has an effect if the image has an alpha channel and if the given co-ordinates are inside the image's boundary. The multiplier must be in the range 0 to 1.0, and the current alpha at the given co-ordinates will be multiplied by this value. @see setPixelAt */ void multiplyAlphaAt (int x, int y, float multiplier); /** Changes the overall opacity of the image. This will multiply the alpha value of each pixel in the image by the given amount (limiting the resulting alpha values between 0 and 255). This allows you to make an image more or less transparent. If the image doesn't have an alpha channel, this won't have any effect. */ void multiplyAllAlphas (float amountToMultiplyBy); /** Changes all the colours to be shades of grey, based on their current luminosity. */ void desaturate(); //============================================================================== /** Retrieves a section of an image as raw pixel data, so it can be read or written to. You should only use this class as a last resort - messing about with the internals of an image is only recommended for people who really know what they're doing! A BitmapData object should be used as a temporary, stack-based object. Don't keep one hanging around while the image is being used elsewhere. Depending on the way the image class is implemented, this may create a temporary buffer which is copied back to the image when the object is deleted, or it may just get a pointer directly into the image's raw data. You can use the stride and data values in this class directly, but don't alter them! The actual format of the pixel data depends on the image's format - see Image::getFormat(), and the PixelRGB, PixelARGB and PixelAlpha classes for more info. */ class BitmapData { public: enum ReadWriteMode { readOnly, writeOnly, readWrite }; BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode); BitmapData (const Image& image, int x, int y, int w, int h); BitmapData (const Image& image, ReadWriteMode mode); ~BitmapData(); /** Returns a pointer to the start of a line in the image. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make sure it's not out-of-range. */ inline uint8* getLinePointer (int y) const noexcept { return data + y * lineStride; } /** Returns a pointer to a pixel in the image. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're not out-of-range. */ inline uint8* getPixelPointer (int x, int y) const noexcept { return data + y * lineStride + x * pixelStride; } /** Returns the colour of a given pixel. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's repsonsibility to make sure they're within the image's size. */ const Colour getPixelColour (int x, int y) const noexcept; /** Sets the colour of a given pixel. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's repsonsibility to make sure they're within the image's size. */ void setPixelColour (int x, int y, const Colour& colour) const noexcept; uint8* data; PixelFormat pixelFormat; int lineStride, pixelStride, width, height; //============================================================================== /** Used internally by custom image types to manage pixel data lifetime. */ class BitmapDataReleaser { protected: BitmapDataReleaser() {} public: virtual ~BitmapDataReleaser() {} }; ScopedPointer<BitmapDataReleaser> dataReleaser; private: JUCE_DECLARE_NON_COPYABLE (BitmapData); }; //============================================================================== /** Copies a section of the image to somewhere else within itself. */ void moveImageSection (int destX, int destY, int sourceX, int sourceY, int width, int height); /** Creates a RectangleList containing rectangles for all non-transparent pixels of the image. @param result the list that will have the area added to it @param alphaThreshold for a semi-transparent image, any pixels whose alpha is above this level will be considered opaque */ void createSolidAreaMask (RectangleList& result, float alphaThreshold = 0.5f) const; //============================================================================== /** Returns a NamedValueSet that is attached to the image and which can be used for associating custom values with it. If this is a null image, this will return a null pointer. */ NamedValueSet* getProperties() const; //============================================================================== /** Creates a context suitable for drawing onto this image. Don't call this method directly! It's used internally by the Graphics class. */ LowLevelGraphicsContext* createLowLevelContext() const; /** Returns the number of Image objects which are currently referring to the same internal shared image data. @see duplicateIfShared */ int getReferenceCount() const noexcept; //============================================================================== /** @internal */ ImagePixelData* getPixelData() const noexcept { return image; } /** @internal */ explicit Image (ImagePixelData*); private: //============================================================================== ReferenceCountedObjectPtr<ImagePixelData> image; JUCE_LEAK_DETECTOR (Image); }; //============================================================================== /** This is a base class for holding image data in implementation-specific ways. You may never need to use this class directly - it's used internally by the Image class to store the actual image data. To access pixel data directly, you should use Image::BitmapData rather than this class. ImagePixelData objects are created indirectly, by subclasses of ImageType. @see Image, ImageType */ class JUCE_API ImagePixelData : public ReferenceCountedObject { public: ImagePixelData (Image::PixelFormat, int width, int height); ~ImagePixelData(); /** Creates a context that will draw into this image. */ virtual LowLevelGraphicsContext* createLowLevelContext() = 0; /** Creates a copy of this image. */ virtual ImagePixelData* clone() = 0; /** Creates an instance of the type of this image. */ virtual ImageType* createType() const = 0; /** Initialises a BitmapData object. */ virtual void initialiseBitmapData (Image::BitmapData&, int x, int y, Image::BitmapData::ReadWriteMode) = 0; /** The pixel format of the image data. */ const Image::PixelFormat pixelFormat; const int width, height; /** User-defined settings that are attached to this image. @see Image::getProperties(). */ NamedValueSet userData; private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePixelData); }; //============================================================================== /** This base class is for handlers that control a type of image manipulation format, e.g. an in-memory bitmap, an OpenGL image, CoreGraphics image, etc. @see SoftwareImageType, NativeImageType, OpenGLImageType */ class JUCE_API ImageType { public: ImageType(); virtual ~ImageType(); /** Creates a new image of this type, and the specified parameters. */ virtual ImagePixelData* create (Image::PixelFormat format, int width, int height, bool shouldClearImage) const = 0; /** Must return a unique number to identify this type. */ virtual int getTypeID() const = 0; /** Returns an image which is a copy of the source image, but using this type of storage mechanism. For example, to make sure that an image is stored in-memory, you could use: @code myImage = SoftwareImageType().convert (myImage); @endcode */ virtual Image convert (const Image& source) const; }; //============================================================================== /** An image storage type which holds the pixels in-memory as a simple block of values. @see ImageType, NativeImageType */ class JUCE_API SoftwareImageType : public ImageType { public: SoftwareImageType(); ~SoftwareImageType(); ImagePixelData* create (Image::PixelFormat, int width, int height, bool clearImage) const; int getTypeID() const; }; //============================================================================== /** An image storage type which holds the pixels using whatever is the default storage format on the current platform. @see ImageType, SoftwareImageType */ class JUCE_API NativeImageType : public ImageType { public: NativeImageType(); ~NativeImageType(); ImagePixelData* create (Image::PixelFormat, int width, int height, bool clearImage) const; int getTypeID() const; }; #endif // __JUCE_IMAGE_JUCEHEADER__
[ "ow3nskip" ]
[ [ [ 1, 511 ] ] ]
d8d8212ad27b949ff584c01d3013910403f23b9a
5095bbe94f3af8dc3b14a331519cfee887f4c07e
/Shared/Components/Data/TPercentileLineSeries.cpp
d79e6177acb775c422e5da631a67a3d02072e29f
[]
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
5,200
cpp
//--------------------------------------------------------------------------- #include <general\pch.h> #include <vcl.h> #pragma hdrstop #include "TPercentileLineSeries.h" #include <values.h> #include <math> #include <algorithm> #pragma package(smart_init) #pragma link "ErrorBar" using namespace std; // ------------------------------------------------------------------ // Short description: // constructor // Notes: // Changes: // DPH 5/2/98 // ------------------------------------------------------------------ __fastcall TPercentileLineSeries::TPercentileLineSeries(Classes::TComponent* AOwner) : TErrorBarSeries(AOwner) { doWhiskers = false; doMedian = false; } // ------------------------------------------------------------------ // Short description: // add box point data // Notes: // Changes: // DPH 5/2/98 // ------------------------------------------------------------------ void TPercentileLineSeries::addPoint (double Y1, double Y2, double Mean, double Median, const char* XLabel) { double X = y1.size()+1; x.push_back (X); xLabels.push_back (XLabel); y1.push_back (Y1); y2.push_back (Y2); mean.push_back (Mean); median.push_back (Median); AddErrorBar(X, Mean, 0, XLabel, clTeeColor); } // ------------------------------------------------------------------ // Short description: // clear all points // Notes: // Changes: // DPH 5/2/98 // ------------------------------------------------------------------ void TPercentileLineSeries::clearPoints() { Clear(); x.erase(x.begin(), x.end()); xLabels.erase(xLabels.begin(), xLabels.end()); y1.erase(y1.begin(), y1.end()); y2.erase(y2.begin(), y2.end()); mean.erase(mean.begin(), mean.end()); median.erase(median.begin(), median.end()); } // ------------------------------------------------------------------ // Short description: // first method to be called directly from chart. // Notes: // Changes: // DPH 5/2/98 // ------------------------------------------------------------------ void __fastcall TPercentileLineSeries::DrawValue(int ValueIndex) { ErrorPen->Width = 2; ErrorWidth = 50; TErrorBarSeries::DrawValue(ValueIndex); } // ------------------------------------------------------------------ // Short description: // draw the series // Notes: // Changes: // DPH 5/2/98 // ------------------------------------------------------------------ void __fastcall TPercentileLineSeries::DrawBar(int BarIndex, int StartPos, int EndPos) { ErrorPen->Visible = false; TErrorBarSeries::DrawBar(BarIndex, StartPos, EndPos); ParentChart->Canvas->Pen->Assign(ErrorPen); long Pos_y1 = CalcYPosValue(y1[BarIndex]); long Pos_y2 = CalcYPosValue(y2[BarIndex]); long Pos_median = CalcYPosValue(median[BarIndex]); long tmpWidth; long tmpBarWidth = (BarBounds.Right - BarBounds.Left); if (ErrorWidth == 0) tmpWidth = tmpBarWidth; else { if (ErrorWidthUnits == ewuPercent) tmpWidth = floor(1.0*ErrorWidth*tmpBarWidth/100.0 + 0.5); else tmpWidth = ErrorWidth; } long tmpHalfX = ((BarBounds.Right + BarBounds.Left) / 2) + (ParentChart->SeriesWidth3D / 2); Pos_y1 = Pos_y1 - (ParentChart->SeriesHeight3D / 2); // draw the bottom vertical line ParentChart->Canvas->DoVertLine(tmpHalfX, Pos_y1, Pos_y2); // draw the whiskers. if (doWhiskers) { ParentChart->Canvas->DoHorizLine(tmpHalfX-(tmpWidth / 2),tmpHalfX+(tmpWidth / 2), Pos_y1); ParentChart->Canvas->DoHorizLine(tmpHalfX-(tmpWidth / 2),tmpHalfX+(tmpWidth / 2), Pos_y2); } // draw the median line. if (doMedian) ParentChart->Canvas->DoHorizLine(tmpHalfX, tmpHalfX+10, Pos_median); } // ------------------------------------------------------------------ // Short description: // return the lowest y1 value to caller. Used by zooming/axis scaling // algorithms. // Notes: // Changes: // DPH 5/2/98 // DAH 12/9/00 - removed the call to TErrorBarSeries::MinValue() as it is // irrelevant to the absolute minimum. // ------------------------------------------------------------------ double __fastcall TPercentileLineSeries::MinYValue(void) { // double result = TErrorBarSeries::MinYValue(); double result = 0; for (unsigned int i = 0; i < y1.size(); i++) result = min(result, y2[i]); result -= 0.1 * result; return result; } // ------------------------------------------------------------------ // Short description: // return the lowest y1 value to caller. Used by zooming/axis scaling // algorithms. // Notes: // Changes: // DPH 5/2/98 // ------------------------------------------------------------------ double __fastcall TPercentileLineSeries::MaxYValue(void) { double result = 0; for (unsigned int i = 0; i < y1.size(); i++) result = max(result, y2[i]); result += 0.1 * result; return result; }
[ "devoilp@8bb03f63-af10-0410-889a-a89e84ef1bc8" ]
[ [ [ 1, 186 ] ] ]
d0a7531050c079ea13bd0a3f297c9923b9576d95
f13f46fbe8535a7573d0f399449c230a35cd2014
/HappyCooker/HappyCookerCMD/BinCooker.cpp
82a142c8847b03f5fc313173d9a8c566719ff220
[]
no_license
fangsunjian/jello-man
354f1c86edc2af55045d8d2bcb58d9cf9b26c68a
148170a4834a77a9e1549ad3bb746cb03470df8f
refs/heads/master
2020-12-24T16:42:11.511756
2011-06-14T10:16:51
2011-06-14T10:16:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,536
cpp
#include "BinCooker.h" #include "CookingStream.h" BinCooker::BinCooker(Model* pModel, const string output): m_pModel(pModel), m_OutputName(output) { } BinCooker::~BinCooker(void) { } bool BinCooker::Cook() { if (m_pModel->IsSoftBody()) return CookSB(); else return CookNSB(); } //LAYOUT BINOBJNSB ------------------------------------------------------------------------> //NxU8 : isSoftbody //DWord : #meshes //Word: nameLength //buffer: name //DWord : #vert //vector3: pos, //vector3: norm, //vector3: tan, //vector2: tex : vertex //DWord : #triangles //DWord, DWord, DWord : triangle //... bool BinCooker::CookNSB() { UserStream stream(m_OutputName.c_str(), false); //store Meshes stream.storeDword(m_pModel->GetDrawMeshes().size()); vector<ModelMesh<VertexPosNormTex>*>::const_iterator it; for_each(m_pModel->GetDrawMeshes().cbegin(), m_pModel->GetDrawMeshes().cend(), [&](ModelMesh<VertexPosNormTanTex>* mesh) { //store Name stream.storeWord(static_cast<WORD>(mesh->GetName().size())); const char* name = mesh->GetName().c_str(); stream.storeBuffer(name, mesh->GetName().size()); //store Vertices stream.storeDword(mesh->GetNumVertices()); const vector<VertexPosNormTanTex>& v = mesh->GetVertices(); for (unsigned int i = 0; i < mesh->GetNumVertices(); ++i) { stream.storeVector3(v[i].position); stream.storeVector3(v[i].normal); stream.storeVector3(v[i].tangent); stream.storeVector2(v[i].tex); } //store Indices stream.storeDword(mesh->GetNumIndices() / 3); const vector<DWORD>& ind = mesh->GetIndices(); for (DWORD i = 0; i < mesh->GetNumIndices(); ++i) { stream.storeDword(ind[i]); } }); return true; } //End <----------------------------------------------------------------------- //LAYOUT BINOBJSB --------------------------------------------------------------------------------> //Word: nameLength //buffer: name //DWord : #vert //vector3: pos, vector3: norm, vector2: tex, DWORD tetra, Vector3 barycentricCoords : vertex //DWord : #triangles //DWord, DWord, DWord : triangle //... bool BinCooker::CookSB() { UserStream stream(m_OutputName.c_str(), false); ModelMesh<VertexPNTSoftbody>* mesh = m_pModel->GetSoftbodyDrawMesh(); //store Name stream.storeWord(static_cast<WORD>(mesh->GetName().size())); const char* name = mesh->GetName().c_str(); stream.storeBuffer(name, mesh->GetName().size()); //store Vertices stream.storeDword(mesh->GetNumVertices()); const vector<VertexPNTSoftbody>& v = mesh->GetVertices(); for (unsigned int i = 0; i < mesh->GetNumVertices(); ++i) { stream.storeVector3(v[i].position); stream.storeVector3(v[i].normal); stream.storeVector2(v[i].tex); stream.storeDword(v[i].tetra); stream.storeVector3(v[i].barycentricCoords); } //store Indices stream.storeDword(mesh->GetNumIndices() / 3); const vector<DWORD>& ind = mesh->GetIndices(); for (DWORD i = 0; i < mesh->GetNumIndices(); ++i) { stream.storeDword(ind[i]); } return true; } //<-----------------------------------------------------------------------------------
[ "bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6" ]
[ [ [ 1, 113 ] ] ]
742bed5507d9b92b9e4fde7261380ab04c2e836a
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/singleplayer/utils/vgui/include/VGUI_ActionSignal.h
24579735925f5a7228d74eecb1e2948b62590892
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,444
h
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #ifndef VGUI_ACTIONSIGNAL_H #define VGUI_ACTIONSIGNAL_H #include<VGUI.h> /* TODO: maybe try something like this.. class VGUIAPI ActionSignal { }; class VGUIAPI ActionSignalSimple : public ActionSignal { public: virtual void actionPerformed(Panel* panel)=0; }; class VGUIAPI ActionSignalInt : public ActionSignal { public: virtual void actionPerformed(int value,Panel* panel)=0; }; DefaultButtonModel would implement: virtual void addActionSignal(ActionSignal* s) { if(s!=null) { _actionSignalDar.putElement(s); } } virtual void fireActionSignal() { for(int i=0;i<_actionSignalDar.getCount();i++) { ActionSignal* signal=_actionSignalDar[i]; ActionSignalSimple* ss=dynamic_cast<ActionSignalSimple*>(signal); if(ss!=null) { ss->actionPerformed(this); } ActionSignalCommand* si=dynamic_cast<ActionSignalInt*>(signal); if(si!=null) { si->actionPerformed(_intValue,this); } } } */ #include<VGUI.h> namespace vgui { class Panel; class VGUIAPI ActionSignal { public: virtual void actionPerformed(Panel* panel)=0; }; } #endif
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 84 ] ] ]
b2032bd4d6c0a81b54fcfca14bcdf5d56a478c36
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/date_time/test/posix_time/testtime_facet.cpp
4c2cff4d860ee099fd4dd0de13711608b8e3fc35
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
15,771
cpp
/* Copyright (c) 2004 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) * Author: Jeff Garland, Bart Garst * $Date: 2005/07/03 06:55:06 $ */ #include "boost/date_time/posix_time/posix_time.hpp" #include "boost/date_time/testfrmwk.hpp" #include <fstream> #include <iostream> #include <sstream> template<class temporal_type, typename charT> inline void teststreaming(std::string testname, temporal_type value, std::basic_string<charT> expected_result, const std::locale& locale = std::locale::classic()) { std::basic_stringstream<charT> ss; ss.imbue(locale); ss << value; check(testname, ss.str() == expected_result); } #if !defined(BOOST_NO_STD_WSTRING) static const wchar_t* long_month_names[] = {L"Januar",L"Februar",L"Marz",L"April",L"Mai",L"Juni",L"Juli",L"August", L"September",L"Oktober",L"November",L"Dezember"}; static const wchar_t* short_month_names[]= {L"Jan",L"Feb",L"Mar",L"Apr",L"Mai",L"Jun",L"Jul",L"Aug", L"Sep",L"Okt",L"Nov",L"Dez"}; std::vector<std::basic_string<wchar_t> > de_short_month_names; std::vector<std::basic_string<wchar_t> > de_long_month_names; #endif // int main() { using namespace boost::gregorian; using namespace boost::posix_time; try { date d(2004,Oct,13); date min_date(min_date_time); date max_date(max_date_time); date_period dp(d, d + date_duration(7)); ptime t(d, time_duration(18,01,56)); ptime tf = t + microseconds(3); time_period tp(t, tf + days(7) + time_duration(1,1,1)); time_duration td = hours(3) + minutes(2) + seconds(1) + milliseconds(9); { std::stringstream ss; ss << t; check("Stream and to_string formats match (ptime)", to_simple_string(t) == ss.str()); std::cout << t << ' ' << td << std::endl; ss.str(""); ss << tf; check("Stream and to_string formats match (ptime w/ fracsec)", to_simple_string(tf) == ss.str()); ss.str(""); ss << tp; check("Stream and to_string formats match (time_period)", to_simple_string(tp) == ss.str()); ss.str(""); ss << td; check("Stream and to_string formats match (time_duration)", to_simple_string(td) == ss.str()); std::cout << ss.str() << std::endl; time_facet* f = new time_facet(); ss.imbue(std::locale(ss.getloc(), f)); ss.str(""); f->format("%Y-%b-%d %H:%M:%S %%d"); f->time_duration_format("%H:%M:%S %%S"); ss << t; check("Literal '%' in format", ss.str() == std::string("2004-Oct-13 18:01:56 %d")); ss.str(""); ss << td; check("Literal '%' in time_duration format", ss.str() == std::string("03:02:01 %S")); ss.str(""); f->format("%Y-%b-%d %H:%M:%S %%%d"); f->time_duration_format("%H:%M:%S %%%S"); ss << t; check("Multiple literal '%'s in format", ss.str() == std::string("2004-Oct-13 18:01:56 %13")); ss.str(""); ss << td; check("Multiple literal '%'s in time_duration format", ss.str() == std::string("03:02:01 %01")); ss.str(""); } { // negative time_duration tests std::string result; std::stringstream ss; time_duration td1(2,0,0); time_duration td2(1,0,0); ss << td2 - td1; result = "-01:00:00"; check("Negative time_duration", result == ss.str()); ss.str(""); time_duration td3(0,2,0); time_duration td4(0,1,0); ss << td4 - td3; result = "-00:01:00"; check("Negative time_duration", result == ss.str()); ss.str(""); time_duration td5(0,0,2); time_duration td6(0,0,1); ss << td6 - td5; result = "-00:00:01"; check("Negative time_duration", result == ss.str()); ss.str(""); #if defined(BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG) result = "-00:00:00.000000001"; #else result = "-00:00:00.000001"; #endif time_duration td7(0,0,0,123); time_duration td8(0,0,0,122); ss << td8 - td7; check("Negative time_duration: " + ss.str(), result == ss.str()); //reset the sign to always print time_facet* f = new time_facet(); ss.imbue(std::locale(ss.getloc(), f)); f->time_duration_format("%+%H:%M:%S%F"); ss.str(""); ss << td4 - td3; result = "-00:01:00"; check("Negative time_duration sign always: " + ss.str(), result == ss.str()); ss.str(""); ss << td3 - td4; result = "+00:01:00"; check("time_duration sign always: " + ss.str(), result == ss.str()); #if defined(BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG) result = "-00:00:00.000000001"; #else result = "-00:00:00.000001"; #endif ss.str(""); ss << td8 - td7; check("Negative time_duration: " + ss.str(), result == ss.str()); #if defined(BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG) result = "+00:00:00.000000001"; #else result = "+00:00:00.000001"; #endif ss.str(""); ss << td7 - td8; check("time_duration sign bit always: " + ss.str(), result == ss.str()); f->time_duration_format("%-%H hours and %-%M minutes"); ss.str(""); ss << td4 - td3; result = "-00 hours and -01 minutes"; check("Negative time_duration two sign flags" + ss.str(), result == ss.str()); } #if !defined(BOOST_NO_STD_WSTRING) std::copy(&short_month_names[0], &short_month_names[12], std::back_inserter(de_short_month_names)); std::copy(&long_month_names[0], &long_month_names[12], std::back_inserter(de_long_month_names)); { wtime_facet *timefacet = new wtime_facet(wtime_facet::standard_format); teststreaming("widestream default classic time", t, //std::wstring(L"Wed Oct 13 18:01:56 2004"), std::wstring(L"10/13/04 18:01:56"), std::locale(std::locale::classic(), timefacet)); } { wtime_facet *timefacet = new wtime_facet(wtime_facet::standard_format); teststreaming("widestream default classic time with fractional seconds truncated", t, //std::wstring(L"Wed Oct 13 18:01:56 2004"), std::wstring(L"10/13/04 18:01:56"), std::locale(std::locale::classic(), timefacet)); } { wtime_facet *timefacet = new wtime_facet(wtime_facet::standard_format); teststreaming("widestream default time period with fractional seconds truncated", tp, //std::wstring(L"[Wed Oct 13 18:01:56 2004/Wed Oct 20 19:02:57 2004]"), std::wstring(L"[10/13/04 18:01:56/10/20/04 19:02:57]"), std::locale(std::locale::classic(), timefacet)); } { wtime_facet *timefacet = new wtime_facet(L"%Y-%b-%d %I:%M:%S %p"); teststreaming("widestream time in 12 hours format w/ (AM/PM)", tp.begin(), std::wstring(L"2004-Oct-13 06:01:56 PM"), std::locale(std::locale::classic(), timefacet)); } { wtime_facet *timefacet = new wtime_facet(wtime_facet::standard_format); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream time duration", td, std::wstring(L"03:02:01.009000000"), std::locale(std::locale::classic(), timefacet)); #else teststreaming("widestream time duration", td, std::wstring(L"03:02:01.009000"), std::locale(std::locale::classic(), timefacet)); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS } #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream time duration", td, std::wstring(L"03:02:01.009000000")); #else teststreaming("widestream time duration", td, std::wstring(L"03:02:01.009000")); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS //wtime_facet *timefacet = new wtime_facet(); //std::locale cloc = std::locale(std::locale::classic(), timefacet); //ss.imbue(cloc); // ss << L"classic date: " << d << std::endl; // ss << L"classic dateperiod: " << dp << std::endl; //ss << L"classic time: " << t << std::endl; //ss << L"classic timefrac: " << tf << std::endl; //ss << L"classic timeperiod: " << tp << std::endl; { wtime_facet* wtimefacet = new wtime_facet(L"day: %j date: %Y-%b-%d weekday: %A time: %H:%M:%s"); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream custom time facet narly format", t, std::wstring(L"day: 287 date: 2004-Oct-13 weekday: Wednesday time: 18:01:56.000000000"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream custom time facet narly format", t, std::wstring(L"day: 287 date: 2004-Oct-13 weekday: Wednesday time: 18:01:56.000000"), std::locale(std::locale::classic(), wtimefacet)); #endif } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%S,%f"); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream custom time fractional seconds: %Y-%b-%d %H:%M:%S,%f", t, std::wstring(L"2004-Oct-13 18:01:56,000000000"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream custom time fractional seconds: %Y-%b-%d %H:%M:%S,%f", t, std::wstring(L"2004-Oct-13 18:01:56,000000"), std::locale(std::locale::classic(), wtimefacet)); #endif } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%S"); teststreaming("widestream custom time no frac seconds: %Y-%b-%d %H:%M:%S", t, std::wstring(L"2004-Oct-13 18:01:56"), std::locale(std::locale::classic(), wtimefacet)); } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%S"); wtimefacet->short_month_names(de_short_month_names); teststreaming("widestream custom time no frac seconds, german months: %Y-%b-%d %H:%M:%S", t, std::wstring(L"2004-Okt-13 18:01:56"), std::locale(std::locale::classic(), wtimefacet)); } { wtime_facet* wtimefacet = new wtime_facet(); wtimefacet->format(L"%B %b %Y"); wtimefacet->short_month_names(de_short_month_names); wtimefacet->long_month_names(de_long_month_names); teststreaming("widestream custom time no frac seconds, german months: %B %b %Y", t, std::wstring(L"Oktober Okt 2004"), std::locale(std::locale::classic(), wtimefacet)); } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%S%F"); teststreaming("widestream custom time no frac seconds %F operator: %Y-%b-%d %H:%M:%S%F", t, std::wstring(L"2004-Oct-13 18:01:56"), std::locale(std::locale::classic(), wtimefacet)); } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%S%F"); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream custom time with frac seconds %F operator: %Y-%b-%d %H:%M:%S%F", tf, std::wstring(L"2004-Oct-13 18:01:56.000003000"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream custom time with frac seconds %F operator: %Y-%b-%d %H:%M:%S%F", tf, std::wstring(L"2004-Oct-13 18:01:56.000003"), std::locale(std::locale::classic(), wtimefacet)); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS } { wtime_facet* wtimefacet = new wtime_facet(); wtimefacet->set_iso_format(); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream custom time iso format", tf, std::wstring(L"20041013T180156.000003000"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream custom time iso format", tf, std::wstring(L"20041013T180156.000003"), std::locale(std::locale::classic(), wtimefacet)); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS } { wtime_facet* wtimefacet = new wtime_facet(); wtimefacet->set_iso_extended_format(); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream custom time iso extended format", tf, std::wstring(L"2004-10-13 18:01:56.000003000"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream custom time iso extended format", tf, std::wstring(L"2004-10-13 18:01:56.000003"), std::locale(std::locale::classic(), wtimefacet)); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%S%F"); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream time period frac seconds %F operator: %Y-%b-%d %H:%M:%S%F", tp, std::wstring(L"[2004-Oct-13 18:01:56/2004-Oct-20 19:02:57.000002999]"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream time period frac seconds %F operator: %Y-%b-%d %H:%M:%S%F", tp, std::wstring(L"[2004-Oct-13 18:01:56/2004-Oct-20 19:02:57.000002]"), std::locale(std::locale::classic(), wtimefacet)); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS } { wtime_facet* wtimefacet = new wtime_facet(L"%Y-%b-%d %H:%M:%s"); wperiod_formatter pf(wperiod_formatter::AS_OPEN_RANGE, L" / ", L"[ ", L" )", L" ]"); wtimefacet->period_formatter(pf); #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS teststreaming("widestream custom time : %Y-%b-%d %H:%M:%s", tp, std::wstring(L"[ 2004-Oct-13 18:01:56.000000000 / 2004-Oct-20 19:02:57.000003000 )"), std::locale(std::locale::classic(), wtimefacet)); #else teststreaming("widestream custom time : %Y-%b-%d %H:%M:%s", tp, std::wstring(L"[ 2004-Oct-13 18:01:56.000000 / 2004-Oct-20 19:02:57.000003 )"), std::locale(std::locale::classic(), wtimefacet)); #endif // BOOST_DATE_TIME_HAS_NANOSECONDS } { ptime nt(not_a_date_time); teststreaming("widestream custom time : not a datetime", nt, std::wstring(L"not-a-date-time")); } // //Denmark English has iso extended default format... // std::locale gloc("en_DK"); // ss.imbue(gloc); // ss << L"default english-denmark date: " << d << std::endl; // ss << L"default english-denmark dateperiod: " << dp << std::endl; // ss << L"default english-denmark time: " << t << std::endl; // ss << L"default english-denmark timefrac: " << tf << std::endl; // ss << L"default english-denmark timeperiod: " << tp << std::endl; #endif } catch(std::exception& e) { std::cout << "Caught std::exception: " << e.what() << std::endl; } catch(...) { std::cout << "bad exception" << std::endl; } return printTestStats(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 399 ] ] ]
4c80cb2bc33ab0cedda6899fc5b3a6efb3c0eb6e
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.6/cbear.berlios.de/windows/select.hpp
d793e3b0953bc32615c2b2886127ebbd43f508bf
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) 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 CBEAR_BERLIOS_DE_WINDOWS_SELECT_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_SELECT_HPP_INCLUDED #include <cbear.berlios.de/select/traits.hpp> #define CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, Name) \ ::cbear_berlios_de::select::get<Char>(&Name ## A, &Name ## W) #define CBEAR_BERLIOS_DE_WINDOWS_TYPE(Char, Name) \ ::cbear_berlios_de::select::traits<Char, Name ## A, Name ## W>::type #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 34 ] ] ]
a47580e7171f7de75ade98a59322cb8dac3a2e2f
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/appsupport/profiles_engine_wrapper_api/inc/CSchedulerUtility.h
7597c67baaf3a64276050c22500eaa92cd6bfc11
[]
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
2,176
h
/* * Copyright (c) 2002-2004 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: * */ #ifndef CSCHEDULERUTILITY_H #define CSCHEDULERUTILITY_H // INCLUDES #include <e32base.h> // FORWARD DECLARATIONS // CLASS DECLARATION /** * A singleton class used to handle starting and stopping a new scheduler-loop * This stops the scheduler loop if it was started by this class. * * @lib Profiles_PEC.lib * @since 3.0 */ class CSchedulerUtility : public CBase { public: // New functions /** * Create and return instance of CSchedulerUtility. * @since 3.0 * @return instance of CSchedulerUtility */ //?type ?member_function( ?type ?arg1 ); //static CSchedulerUtility* InstanceL(); /** * Two-phased constructor. */ static CSchedulerUtility* NewL(); /** * Destroys the scheduler utility instance. * @since 3.0 */ // static void Release(); /** * Starts a new scheduler loop if one isn't already started. * @since 3.0 */ void Start(); /** * Stops a scheduler loop if it was started by this class. * @since 3.0 */ void Stop(); /** * Destructor. */ virtual ~CSchedulerUtility(); private: /** * C++ default constructor. */ CSchedulerUtility(); /** * By default Symbian 2nd phase constructor is private. */ void ConstructL(); private: // Data CActiveSchedulerWait* iWait; }; #endif // CSCHEDULERUTILITY_H // End of File
[ "none@none" ]
[ [ [ 1, 96 ] ] ]
0356952fda00519186b6dde541b6f08b03c4493d
bd89d3607e32d7ebb8898f5e2d3445d524010850
/connectivitylayer/usbphonetlink/usbpnserver_exe/src/cusbpnusbsender.cpp
ab14f1453c8af0d1cc6db0287c665dbfe7c59f59
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,978
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include "cusbpnusbsender.h" #include "cusbpnpacket.h" #include "musbpnbufferlistener.h" #include "usbpndefinitions.h" // For constants #include "usbpntrace.h" #include "OstTraceDefinitions.h" #ifdef OST_TRACE_COMPILER_IN_USE #include "cusbpnusbsenderTraces.h" #endif #include <d32usbc.h> // RDevUsbcClient // LOCAL CONSTANTS AND MACROS const TInt KTotalUsbPacketCount( KPnUsbPacketCount + 1 ); // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CUsbPnUsbSender::CUsbPnUsbSender // C++ default constructor can NOT contain any code, that // might leave. // ----------------------------------------------------------------------------- // CUsbPnUsbSender::CUsbPnUsbSender( MUsbPnBufferListener& aListener, RDevUsbcClient& aLdd ) :CActive( 100 ) //ECommTransmitPriority=100 in es_prot.h ,iBufferListener( aListener ) ,iLdd( aLdd ) ,iPacketCount( NULL ) ,iPacket( NULL ) { OstTraceExt2( TRACE_NORMAL, CUSBPNUSBSENDER_CUSBPNUSBSENDER_ENTRY, "CUsbPnUsbSender::CUsbPnUsbSender;aListener=%x;aLdd=%x", ( TUint )&( aListener ), ( TUint )&( aLdd ) ); C_TRACE( ( _T( "CUsbPnUsbSender::CUsbPnUsbSender( aListener:0x%x, aLdd:0x%x )" ), &aListener, &aLdd ) ); CActiveScheduler::Add(this); OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_CUSBPNUSBSENDER_EXIT, "CUsbPnUsbSender::CUsbPnUsbSender - return" ); C_TRACE( ( _T( "CUsbPnUsbSender::CUsbPnUsbSender() - return" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::ConstructL // Symbian 2nd phase constructor can leave. // ----------------------------------------------------------------------------- // void CUsbPnUsbSender::ConstructL() { OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_CONSTRUCTL_ENTRY, "CUsbPnUsbSender::ConstructL" ); C_TRACE( ( _T( "CUsbPnUsbSender::ConstructL()" ) ) ); // Create circular buffer objects, start count in 1, otherwise one packet is not deleted in destructor for(TUint i = 1; i < KTotalUsbPacketCount; i++) { AddPacketBufferL(i); } iCurrentPacket = iPacket; OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_CONSTRUCTL_EXIT, "CUsbPnUsbSender::ConstructL - return void" ); C_TRACE( ( _T( "CUsbPnUsbSender::ConstructL() - return void" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::NewL // Two-phased constructor. // ----------------------------------------------------------------------------- // CUsbPnUsbSender* CUsbPnUsbSender::NewL( MUsbPnBufferListener& aBufferListener, RDevUsbcClient& aLdd ) { OstTraceExt2( TRACE_NORMAL, CUSBPNUSBSENDER_NEWL_ENTRY, "CUsbPnUsbSender::NewL;aBufferListener=%x;aLdd=%x", ( TUint )&( aBufferListener ), ( TUint )&( aLdd ) ); C_TRACE( ( _T( "CUsbPnUsbSender::NewL( aBufferListener:0x%x, aLdd:0x%x )" ), &aBufferListener, &aLdd ) ); CUsbPnUsbSender* self = new( ELeave ) CUsbPnUsbSender( aBufferListener, aLdd ); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop( self ); OstTrace1( TRACE_NORMAL, CUSBPNUSBSENDER_NEWL_EXIT, "CUsbPnUsbSender::NewL - return;self=%x", self ); C_TRACE( ( _T( "CUsbPnUsbSender::NewL() - return 0x%x" ), self ) ); return self; } // Destructor CUsbPnUsbSender::~CUsbPnUsbSender() { OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_CUSBPNUSBSENDER_DESTRUCTOR_ENTRY, "CUsbPnUsbSender::~CUsbPnUsbSender" ); C_TRACE( ( _T( "CUsbPnUsbSender::~CUsbPnUsbSender()" ) ) ); Cancel(); DeletePackets(); iCurrentPacket = NULL; iPacket = NULL; OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_CUSBPNUSBSENDER_DESTRUCTOR_EXIT, "CUsbPnUsbSender::~CUsbPnUsbSender - return" ); C_TRACE( ( _T( "CUsbPnUsbSender::~CUsbPnUsbSender() - return" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::DeletePackets // ----------------------------------------------------------------------------- void CUsbPnUsbSender::DeletePackets( ) { OstTrace0( TRACE_BORDER, CUSBPNUSBSENDER_DELETEPACKETS_ENTRY, "CUsbPnUsbSender::DeletePackets" ); A_TRACE( ( _T( "CUsbPnUsbSender::DeletePackets()" ) ) ); CUsbPnPacket* packet = NULL; while(iPacketCount > 0) { iPacketCount--; packet = &iPacket->NextPacket(); delete iPacket; iPacket = packet; } OstTrace0( TRACE_BORDER, CUSBPNUSBSENDER_DELETEPACKETS_EXIT, "CUsbPnUsbSender::DeletePackets - return void" ); A_TRACE( ( _T( "CUsbPnUsbSender::DeletePackets() - return void" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::AddPacketBufferL // ----------------------------------------------------------------------------- void CUsbPnUsbSender::AddPacketBufferL( const TInt aIndex ) { OstTrace1( TRACE_NORMAL, CUSBPNUSBSENDER_ADDPACKETBUFFERL_ENTRY, "CUsbPnUsbSender::AddPacketBufferL aIndex %d", aIndex ); C_TRACE((_T("CUsbPnUsbSender::AddPacketBuffer() aIndex %d"), aIndex)); if( aIndex <= KTotalUsbPacketCount ) { iPacketCount++; iPacket = CUsbPnPacket::NewL( iPacket, aIndex ); } else { TRACE_ASSERT_ALWAYS; } OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_ADDPACKETBUFFERL_EXIT, "CUsbPnUsbSender::AddPacketBufferL - return void" ); C_TRACE((_T("CUsbPnUsbSender::AddPacketBuffer - return void"))); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::GetNextPacketL // ----------------------------------------------------------------------------- CUsbPnPacket& CUsbPnUsbSender::GetNextPacketL() { OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_GETNEXTPACKETL_ENTRY, "CUsbPnUsbSender::GetNextPacketL" ); C_TRACE((_T("CUsbPnUsbSender::PacketL()"))); CUsbPnPacket& nextPacket( iPacket->NextPacket() ); TBool err = nextPacket.PacketInUse(); if (EFalse != err) { User::Leave( err ); } OstTrace1( TRACE_NORMAL, CUSBPNUSBSENDER_GETNEXTPACKETL_EXIT, "CUsbPnUsbSender::GetNextPacketL - return;packet=%d", nextPacket.PacketNumber() ); C_TRACE((_T("CUsbPnUsbSender::GetNextPacketL() - return packet:%d"), nextPacket.PacketNumber())); return nextPacket; } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::AddPacketToSendingQueue // ----------------------------------------------------------------------------- // void CUsbPnUsbSender::AddPacketToSendingQueue( CUsbPnPacket& aPacket ) { ASSERT( &aPacket ); OstTrace0( TRACE_BORDER, CUSBPNUSBSENDER_ADDPACKETTOSENDINGQUEUE_ENTRY, "CUsbPnUsbSender::AddPacketToSendingQueue" ); A_TRACE( ( _T( "CUsbPnUsbSender::Send()" ) ) ); iPacket = &iPacket->NextPacket(); OstTrace1( TRACE_INTERNALS, CUSBPNUSBSENDER_ADDPACKETTOSENDINGQUEUE, "CUsbPnUsbSender::AddPacketToSendingQueue;packet number:%d", iPacket->PacketNumber() ); E_TRACE( ( _T( "CUsbPnUsbSender::AddPacketToSendingQueue() - packet number:%d" ), iPacket->PacketNumber() ) ); TryToSendPacket( *iPacket ); OstTrace0( TRACE_BORDER, CUSBPNUSBSENDER_ADDPACKETTOSENDINGQUEUE_EXIT, "CUsbPnUsbSender::AddPacketToSendingQueue - return void" ); A_TRACE( ( _T( "CUsbPnUsbSender::AddPacketToSendingQueue() - return void" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::TryToSendPacket // ----------------------------------------------------------------------------- // void CUsbPnUsbSender::TryToSendPacket( const CUsbPnPacket& aPacket ) { ASSERT( &aPacket ); OstTraceExt2( TRACE_BORDER, CUSBPNUSBSENDER_TRYTOSENDPACKET_ENTRY, "CUsbPnUsbSender::TryToSendPacket;aPacket=0x%x;iCurrentPacket=%d", ( TUint )&( aPacket ), iCurrentPacket->PacketNumber() ); A_TRACE( ( _T( "CUsbPnUsbSender::TryToSendPacket( aPacketNumber:0x%x, iCurrentPacket:%d )" ), &aPacket, iCurrentPacket->PacketNumber( ) )); // Write message to USB if(!IsActive()) { if( &aPacket == ( &iCurrentPacket->NextPacket() ) || &aPacket == iCurrentPacket ) { OstTrace0( TRACE_INTERNALS, CUSBPNUSBSENDER_TRYTOSENDPACKET, "CUsbPnUsbSender::TryToSendPacket - Write to socket" ); E_TRACE( ( _T( "CUsbPnUsbSender::TryToSendPacket() - Write to socket"))); HBufC8& data(aPacket.Buffer()); TInt length( data.Length() ); #ifdef EXTENDED_TRACE_FLAG for(TInt i = 0; i < length; i++) { OstTraceExt2( TRACE_INTERNALS, CUSBPNUSBSENDER_TRYTOSENDPACKET_DUP1, "CUsbPnUsbSender::Send( [%d] = %x )", i, data[i] ); E_TRACE( ( _T( "CUsbPnUsbSender::Send([%d] = %x )" ), i, data[i] ) ); i++; } #endif // ZLP flag setting is optional. Could be always true as driver checks against max packet size TBool zlp( ETrue ); if( length != 0 ) { zlp = ( ( length != 0 ) && ( length % KPnPacketSize ) == 0 ); } iLdd.Write( iStatus, EEndpoint1, data, length, zlp ); SetActive(); } else { TRACE_ASSERT_ALWAYS; } } else { OstTrace0( TRACE_INTERNALS, CUSBPNUSBSENDER_TRYTOSENDPACKET_DUP2, "CUsbPnUsbSender::TryToSendPacket - Already sending" ); E_TRACE( ( _T( "CUsbPnUsbSender::TryToSendPacket() - Already sending"))); } OstTrace0( TRACE_BORDER, CUSBPNUSBSENDER_TRYTOSENDPACKET_EXIT, "CUsbPnUsbSender::TryToSendPacket - return void" ); A_TRACE( ( _T( "CUsbPnUsbSender::TryToSendPacket() - return void" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::DoCancel // ----------------------------------------------------------------------------- // void CUsbPnUsbSender::DoCancel( ) { OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_DOCANCEL_ENTRY, "CUsbPnUsbSender::DoCancel" ); C_TRACE( ( _T( "CUsbPnUsbSender::DoCancel()" ) ) ); iLdd.WriteCancel( EEndpoint1 ); OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_DOCANCEL_EXIT, "CUsbPnUsbSender::DoCancel - return void" ); C_TRACE( ( _T( "CUsbPnUsbSender::DoCancel() - return void" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::RunL // ----------------------------------------------------------------------------- // void CUsbPnUsbSender::RunL( ) { OstTrace1( TRACE_BORDER, CUSBPNUSBSENDER_RUNL_ENTRY, "CUsbPnUsbSender::RunL;iStatus:%d", iStatus.Int() ); A_TRACE( ( _T( "CUsbPnUsbSender::RunL() iStatus:%d" ), iStatus.Int() ) ); User::LeaveIfError( iStatus.Int() ); iCurrentPacket->ReleaseL(); iBufferListener.Receive( ETrue ); iCurrentPacket = &iCurrentPacket->NextPacket(); if(iCurrentPacket != iPacket) { OstTraceExt2( TRACE_INTERNALS, CUSBPNUSBSENDER_RUNL, "CUsbPnUsbSender::RunL - Write next in queue;tail=%d;head=%d", iCurrentPacket->PacketNumber(), iPacket->PacketNumber() ); E_TRACE( ( _T( "CUsbPnUsbSender::RunL() - Write next in queue tail:%d,head:%d " ), iCurrentPacket->PacketNumber(), iPacket->PacketNumber())); TryToSendPacket( iCurrentPacket->NextPacket() ); } OstTrace0( TRACE_BORDER, CUSBPNUSBSENDER_RUNL_EXIT, "CUsbPnUsbSender::RunL - return void" ); A_TRACE( ( _T( "CUsbPnUsbSender::RunL() - return void" ) ) ); } // ----------------------------------------------------------------------------- // CUsbPnUsbSender::RunError // ----------------------------------------------------------------------------- // TInt CUsbPnUsbSender::RunError( TInt aError ) { OstTrace1( TRACE_BORDER, CUSBPNUSBSENDER_RUNERROR_ENTRY, "CUsbPnUsbSender::RunError;aError=%d", aError ); A_TRACE( ( _T( "CUsbPnUsbSender::RunError(aError:%d)" ), aError ) ); switch( aError ) { case KErrUsbCableDetached: case KErrUsbDeviceBusReset: case KErrUsbInterfaceNotReady: case KErrUsbEpNotInInterface: case KErrUsbDeviceNotConfigured: case KErrUsbBadEndpoint: case KErrUsbDeviceClosing: case KErrUsbInterfaceChange: case KErrUsbEpNotReady: { OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_RUNERROR, "CUsbPnUsbSender::RunError - Cable detached!" ); C_TRACE( ( _T( "CUsbPnUsbSender::RunError - Cable detached!" ))); break; } default: { TRACE_ASSERT_ALWAYS; break; } } OstTrace0( TRACE_NORMAL, CUSBPNUSBSENDER_RUNERROR_EXIT, "CUsbPnUsbSender::RunError - return" ); C_TRACE( ( _T( "CUsbPnUsbSender::RunError() - return" ) ) ); return KErrNone; } // ========================== OTHER EXPORTED FUNCTIONS ========================= // End of File
[ "dalarub@localhost", "[email protected]", "mikaruus@localhost" ]
[ [ [ 1, 24 ], [ 26, 32 ], [ 34, 42 ], [ 45, 47 ], [ 49, 69 ], [ 72, 94 ], [ 96, 109 ], [ 114, 114 ], [ 127, 133 ], [ 137, 140 ], [ 142, 142 ], [ 155, 160 ], [ 162, 162 ], [ 164, 164 ], [ 166, 167 ], [ 170, 173 ], [ 176, 176 ], [ 178, 180 ], [ 182, 183 ], [ 185, 185 ], [ 188, 190 ], [ 193, 195 ], [ 198, 205 ], [ 209, 212 ], [ 215, 215 ], [ 217, 221 ], [ 223, 223 ], [ 225, 230 ], [ 238, 247 ], [ 249, 251 ], [ 253, 274 ], [ 276, 285 ], [ 287, 289 ], [ 291, 299 ], [ 301, 321 ], [ 323, 325 ], [ 328, 333 ] ], [ [ 25, 25 ], [ 33, 33 ], [ 43, 44 ], [ 48, 48 ], [ 70, 71 ], [ 95, 95 ], [ 110, 113 ], [ 115, 123 ], [ 125, 126 ], [ 135, 136 ], [ 141, 141 ], [ 143, 154 ], [ 161, 161 ], [ 163, 163 ], [ 165, 165 ], [ 168, 169 ], [ 174, 175 ], [ 177, 177 ], [ 181, 181 ], [ 184, 184 ], [ 186, 186 ], [ 192, 192 ], [ 197, 197 ], [ 206, 206 ], [ 208, 208 ], [ 213, 214 ], [ 222, 222 ], [ 231, 237 ], [ 322, 322 ], [ 326, 327 ] ], [ [ 124, 124 ], [ 134, 134 ], [ 187, 187 ], [ 191, 191 ], [ 196, 196 ], [ 207, 207 ], [ 216, 216 ], [ 224, 224 ], [ 248, 248 ], [ 252, 252 ], [ 275, 275 ], [ 286, 286 ], [ 290, 290 ], [ 300, 300 ] ] ]
686dc90f52d77e7ea684202bc269dc3ee2a47781
ea2ebb5e92b4391e9793c5a326d0a31758c2a0ec
/Bomberman/Bomberman/Keyboard.h
14ea16acaaf69e82277a61a372e75f16a5aac9a5
[]
no_license
weimingtom/bombman
d0f022541e9c550af7c6dbd26481771c94828460
d73ee4c680423a79826187013d343111a62f89b7
refs/heads/master
2021-01-10T01:36:39.712497
2011-05-01T07:03:16
2011-05-01T07:03:16
44,462,509
1
0
null
null
null
null
UTF-8
C++
false
false
563
h
#pragma once #define DIRECTINPUT_VERSION 0x0800 #define INITGUID #include <Guiddef.h> #include<dinput.h> #include<Windows.h> class Keyboard { public: Keyboard(LPDIRECTINPUT8 pDI, HWND hwnd); ~Keyboard(); bool KeyDown(char key) { return (m_keys[key] & 0x80) ? true : false; } bool KeyUp(char key) { return (m_keys[key] & 0x80) ? false : true; } bool Update(); void Clear() { ZeroMemory(m_keys, 256 * sizeof(char)); } bool Acquire(); bool Unacquire(); private: LPDIRECTINPUTDEVICE8 m_pDIDev; char m_keys[256]; };
[ "yvetterowe1116@d9104e88-05a6-3fce-0cda-3a6fd9c40cd8" ]
[ [ [ 1, 27 ] ] ]
4d76dd61400c758a492740c765c60f6334309f07
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/WheelAnimalController/include/Gold.h
9bcde6bbfead4c6daec2d65af9f29b39f982af41
[]
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
783
h
#ifndef __Orz_Gold_h__ #define __Orz_Gold_h__ #include "WheelAnimalControllerConfig.h" #include "WheelAnimalSceneObj.h" #include "WheelAnimalProcess.h" #include "WheelAnimalControllerConfig.h" namespace Orz { class Gold { public: Gold(Ogre::SceneNode * node); virtual ~Gold(void); void show(void); void hide(void); void update(TimeType i); void clear(void); void setNumber(int i); private: boost::shared_ptr<OSMScene> _osm; /* boost::shared_ptr<OSMScene> _osm2;*/ Ogre::SceneNode * _sn; Ogre::AnimationState* _animation; /* Ogre::AnimationState* _animation2;*/ std::vector<Ogre::MaterialPtr> _materials; boost::array<std::string, 10> _number; }; typedef boost::shared_ptr<Gold> GoldPtr; } #endif
[ [ [ 1, 41 ] ] ]
305d1cccefbbf945054aeac2a17f4f37bac34601
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
/mytesgnikrow --username hotga2801/DoAnBaoMat/Chat_Client/EditPasswdDlg.h
c77b8814dd18f72f98c1afdbbdfedbef67ac9535
[]
no_license
taicent/mytesgnikrow
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
9264faa662454484ade7137ee8a0794e00bf762f
refs/heads/master
2020-04-06T04:25:30.075548
2011-02-17T13:37:16
2011-02-17T13:37:16
34,991,750
0
0
null
null
null
null
UTF-8
C++
false
false
687
h
#pragma once #ifdef _WIN32_WCE #error "CDHtmlDialog is not supported for Windows CE." #endif // EditPasswdDlg dialog class EditPasswdDlg : public CDHtmlDialog { DECLARE_DYNCREATE(EditPasswdDlg) public: EditPasswdDlg(CWnd* pParent = NULL); // standard constructor virtual ~EditPasswdDlg(); // Overrides HRESULT OnButtonOK(IHTMLElement *pElement); HRESULT OnButtonCancel(IHTMLElement *pElement); // Dialog Data enum { IDD = IDD_DIALOGEditPasswd, IDH = IDR_HTML_EDITPASSWDDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() DECLARE_DHTML_EVENT_MAP() };
[ "hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076" ]
[ [ [ 1, 29 ] ] ]
42836fbd8c156fbc172810e674f49919179702ae
cf98fd401c09dffdd1e7b1aaa91615e9fe64961f
/tags/0.0.0/src/win/dialog.cpp
7efa28abc47a3a8916ee9482585be023ec213209
[]
no_license
BackupTheBerlios/bvr20983-svn
77f4fcc640bd092c3aa85311fecfbea1a3b7677e
4d177c13f6ec110626d26d9a2c2db8af7cb1869d
refs/heads/master
2021-01-21T13:36:43.379562
2009-10-22T00:25:39
2009-10-22T00:25:39
40,663,412
0
0
null
null
null
null
UTF-8
C++
false
false
3,891
cpp
/* * $Id$ * * windows dialog class. * * Copyright (C) 2008 Dorothea Wachmann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ #include "os.h" #include <assert.h> #include "win/dialog.h" #include "exception/windowsexception.h" #include "exception/lasterrorexception.h" using namespace bvr20983; namespace bvr20983 { namespace win { #pragma region Construction & Deconstruction /* * Dialog::Dialog * * Purpose: * Constructor. * * Parameters: * * Return: * void */ Dialog::Dialog() : Wnd(NULL) { m_hParentWnd = NULL; m_dlgName = NULL; } // of Dialog::Dialog() /* * Dialog::~Dialog * * Purpose: * Destructor. * * Parameters: * void * * Return: * void */ Dialog::~Dialog() { } #pragma endregion #pragma region Implementation /** * */ int Dialog::Show(LPCTSTR dlgName,HWND hWnd,HINSTANCE hInstance) { m_hParentWnd = hWnd; m_dlgName = dlgName; return ::DialogBoxParam(hInstance,m_dlgName,m_hParentWnd,&DlgProc,(LPARAM)this); } // of Show() /** * */ HWND Dialog::Modeless(LPCTSTR dlgName,HWND hWnd,HINSTANCE hInstance) { m_hParentWnd = hWnd; m_dlgName = dlgName; return ::CreateDialogParam(hInstance,m_dlgName,m_hParentWnd,&DlgProc,(LPARAM)this); } // of Modeless() #pragma endregion #pragma region Windows Event Handling /** * */ INT_PTR Dialog::DialogProcedure(UINT message,WPARAM wParam,LPARAM lParam) { INT_PTR result = FALSE; switch( message ) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: ::EndDialog(GetWindowHandle(),TRUE); result = TRUE; break; case IDCANCEL: ::EndDialog(GetWindowHandle(),FALSE); result = TRUE; break; default: if( OnCommand(wParam) ) result = TRUE; break; } // of switch() break; } // of switch return result; } // of Dialog::DialogProcedure() /** * */ BOOL Dialog::InitDialog() { return TRUE; } /** * */ INT_PTR CALLBACK DlgProc(HWND hDlg,UINT msg,WPARAM wParam,LPARAM lParam) { INT_PTR result = FALSE; win::Dialog* dlg = NULL; switch( msg ) { case WM_INITDIALOG: ::SetWindowLongPtr(hDlg,GWLP_USERDATA,(LONG_PTR)lParam); dlg = reinterpret_cast<win::Dialog*>(lParam); dlg->m_hWnd = hDlg; result = dlg->InitDialog(); break; default: dlg = (win::Dialog*) ::GetWindowLongPtr(hDlg,GWLP_USERDATA); if( NULL!=dlg ) { assert( dlg->GetWindowHandle()==hDlg ); result = dlg->DialogProcedure(msg,wParam,lParam); } // of if break; } // of switch return result; } // of ::DlgProc() #pragma endregion } // of namespace win } // of namespace bvr20983 /*==========================END-OF-FILE===================================*/
[ "dwachmann@01137330-e44e-0410-aa50-acf51430b3d2" ]
[ [ [ 1, 161 ] ] ]
577120b78c6d86435123e8e24666ce220c3b0ca8
2a974d418f9c9028ead477eeb10ab7174979781f
/ vitamin-engine --username xyz.cmt/V_ClientApp/V_ClientApp/Common.cpp
e7ec7d7c2e46bb28b4ab14ac4d0c13e360156a4b
[]
no_license
KiraiChang/vitamin-engine
3fc2abc2cf221a8f2444c4e66a2eb740537dae54
596c6c4844ca961306682c39284ae82e686ed385
refs/heads/master
2020-05-18T20:19:38.516987
2010-01-06T14:05:50
2010-01-06T14:05:50
32,337,252
0
0
null
null
null
null
GB18030
C++
false
false
819
cpp
#include "../Vitamin/VEngine.h" stInputInfo g_stInputInfo; //ノ办: GameApp(MainLoop) LPDIRECT3DDEVICE9 g_pD3DDevice = NULL; //ノ办: GameApp(Init~Destory) SceneEffect* g_pSceneEffect = NULL; CGameApp* g_pGameApp = NULL; //ノ办: GameApp(CONSTRUCTOR~DESTRUCTOR) CGraphics* g_pGraphics = NULL; //ノ办: GameApp(Init~Destory) CInput g_Input; //ノ办: GameApp( Init(CreateInput)~Destory(ReleaseInput) ) //GFont g_Font; //ノ办: GameApp(Init~ ) //GUIManager* g_pGUIManager = NULL; //ノ办: GameApp(Init~Destory) //CMessageManager* g_pMessageManager = NULL; // Mouse Offset long g_CursorOffsetX = 0; long g_CursorOffsetY = 0; long g_CursorOffsetZ = 0;
[ "xyz.cmt@32d5ba4e-c8fa-11de-b743-054a4f195298" ]
[ [ [ 1, 16 ] ] ]
29ac353e8413f5afe3cfc308e654fec1f19376e2
718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1
/soft micros/Codigo/codigo portable/Vista/DiagramaDeNavegacion/DiagramaNavegacionSD.hpp
a4c8e0c276667fe52c45d67066a0911c72cedd8e
[]
no_license
jonyMarino/microsdhacel
affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca
66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3
refs/heads/master
2020-05-18T19:53:51.301695
2011-05-30T20:40:24
2011-05-30T20:40:24
34,532,512
0
0
null
null
null
null
UTF-8
C++
false
false
1,230
hpp
#ifndef _DIAGRAMA_NAVEGACION_SD_HPP #define _DIAGRAMA_NAVEGACION_SD_HPP #include "OOC/util/lib_cpp/Array.h" #include "BoxList.hpp" #include "Box.hpp" #include "Timer/RlxMTimer/RlxMTimer.hpp" #include "Vista/Frente8SegTeclasYLeds/FrenteCustomSD.hpp" #include "OOC/lang/reflect/lib_cpp/Method.hpp" #include "FstBoxPointer.hpp" #pragma DATA_SEG DIAGRAMA_NAVEGACION_DATA #pragma CODE_SEG DIAGRAMA_NAVEGACION_CODE #pragma CONST_SEG DEFAULT #define _VERSION_TIME 1500 class DiagramaNavegacionSD{ public: DiagramaNavegacionSD(const struct BoxList *BoxesOp,const struct Array *accesos,FrenteCustomSD * frente); void procesar(uchar tecla); void refresh(void); private: FrenteCustomSD * frente; struct Method metodoParaTimer; RlxMTimer * timer; const struct Array *accesos; const struct BoxList * boxesOp; uchar boxListCount; uchar listCount; uchar accessCount; Box * boxActual; void goPrincipal(); struct FstBoxPointer* opgetFstBoxP(); struct FstBoxPointer* getActualFstBoxP(); static void showCompilacion(void*); static void jumpToOperador(void*); }; #pragma DATA_SEG DEFAULT #pragma CODE_SEG DEFAULT #endif
[ "nicopimen@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549" ]
[ [ [ 1, 45 ] ] ]
a272c41654baf3c9e022056aff99e615fd8a0b4c
1407d47147b871832f108a0527fedb4b3539e8f9
/threads/office.h
a7545426136274b56858fe2f94fd58be90e32394
[ "MIT-Modern-Variant" ]
permissive
mezl/csci402group5in2008sp
1a32b78a7898e2f0f26048d626e4b283c6770ae2
6ad570987dab70538b96bf9fbf1eaf1c433cbc63
refs/heads/master
2021-01-10T20:36:18.460944
2008-04-27T22:25:48
2008-04-27T22:25:48
32,116,560
0
0
null
null
null
null
UTF-8
C++
false
false
949
h
#ifndef OFFICE_H_DEFINED #define OFFICE_H_DEFINED #include "manager.cc" #include "customer.h" #include "clerk.h" #include "cline.h" #include "ctable.h" #include "copyright.h" #include "utility.h" #include "timer.h" #include "thread.h" /* class Office { public: Office(){ applicationLine = new cLine(1); pictureLine = new cLine(2); passportLine = new cLine(3); cashierLine = new cLine(4); applicationTable = new cTable(1); pictureTable = new cTable(2); passportTable = new cTable(3); cashierTable= new cTable(4); } ~Office(){} void run(); private: void Manager(int x); void myCustomerForkFunc(int x); void myClerkForkFunc(int x); cLine *applicationLine ; cLine *pictureLine ; cLine *passportLine; cLine *cashierLine; cTable *applicationTable; cTable *pictureTable ; cTable *passportTable; cTable *cashierTable; }; */ #endif
[ "mezlxx@74156adb-be44-0410-a8bd-599819d3de0a" ]
[ [ [ 1, 49 ] ] ]
a128633517fcd1d3700142244de34cd30ae5571d
0045263cdb6bb6f662607ef9034252aa80768fb2
/IrrlichtW/guielem2.cpp
74b756699433a7d350e5e7d90d660777428fafa8
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
paupawsan/irrlichtnetcp
4fcbf1d4b11f27164c02be1d102efbc3e5ed3af6
29f8ffe0113cc4bd7f131cb4d472d0c2ef255bfa
refs/heads/master
2021-05-27T00:02:20.923024
2010-01-24T23:13:32
2010-01-24T23:13:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,375
cpp
#include "guielem2.h" bool useAlphaChannel = false; bool GUIButton_GetUseAlphaChannel(IntPtr button) { _FIX_BOOL_MARSHAL_BUG(useAlphaChannel); } bool GUIButton_IsPressed(IntPtr button) { _FIX_BOOL_MARSHAL_BUG(((IGUIButton*)button)->isPressed()); } void GUIButton_SetImage(IntPtr button, IntPtr image, M_RECT pos) { ((IGUIButton*)button)->setImage((ITexture*)image, MU_RECT(pos)); } void GUIButton_SetImageA(IntPtr button, IntPtr image) { ((IGUIButton*)button)->setImage((ITexture*)image); } void GUIButton_SetIsPushButton(IntPtr button, bool ispush) { ((IGUIButton*)button)->setIsPushButton(ispush); } void GUIButton_SetOverrideFont(IntPtr button, IntPtr font) { ((IGUIButton*)button)->setOverrideFont((IGUIFont*)font); } void GUIButton_SetPressed(IntPtr button, bool pressed) { ((IGUIButton*)button)->setPressed(pressed); } void GUIButton_SetPressedImage(IntPtr button, IntPtr image, M_RECT pos) { ((IGUIButton*)button)->setPressedImage((ITexture*)image, MU_RECT(pos)); } void GUIButton_SetPressedImageA(IntPtr button, IntPtr image) { ((IGUIButton*)button)->setPressedImage((ITexture*)image); } void GUIButton_SetUseAlphaChannel(IntPtr button, bool use) { ((IGUIButton*)button)->setUseAlphaChannel(use); useAlphaChannel = use; } bool GUICheckBox_IsChecked(IntPtr checkbox) { _FIX_BOOL_MARSHAL_BUG(((IGUICheckBox*)checkbox)->isChecked()); } void GUICheckBox_SetChecked(IntPtr checkbox, bool ck) { ((IGUICheckBox*)checkbox)->setChecked(ck); } int GUIComboBox_AddItem(IntPtr combo, M_STRING text) { return ((IGUIComboBox*)combo)->addItem(MU_WCHAR(text)); } void GUIComboBox_Clear(IntPtr combo) { ((IGUIComboBox*)combo)->clear(); } M_STRING GUIComboBox_GetItem(IntPtr combo, int index) { return UM_STRING(((IGUIComboBox*)combo)->getItem(index)); } int GUIComboBox_GetItemCount(IntPtr combo) { return ((IGUIComboBox*)combo)->getItemCount(); } int GUIComboBox_GetSelected(IntPtr combo) { return ((IGUIComboBox*)combo)->getSelected(); } void GUIComboBox_SetSelected(IntPtr combo, int index) { ((IGUIComboBox*)combo)->setSelected(index); } int GUIContextMenu_AddItem(IntPtr menu, M_STRING text, int commandID, bool enabled, bool hasSubMenu) { return ((IGUIContextMenu*)menu)->addItem(MU_WCHAR(text), commandID, enabled, hasSubMenu); } void GUIContextMenu_AddSeparator(IntPtr menu) { ((IGUIContextMenu*)menu)->addSeparator(); } int GUIContextMenu_GetItemCommandID(IntPtr menu, int id) { return ((IGUIContextMenu*)menu)->getItemCommandId(id); } int GUIContextMenu_GetItemCount(IntPtr menu) { return ((IGUIContextMenu*)menu)->getItemCount(); } M_STRING GUIContextMenu_GetItemText(IntPtr menu, int index) { return UM_STRING(((IGUIContextMenu*)menu)->getItemText(index)); } int GUIContextMenu_GetSelectedItem(IntPtr menu) { return ((IGUIContextMenu*)menu)->getSelectedItem(); } IntPtr GUIContextMenu_GetSubMenu(IntPtr menu, int index) { return ((IGUIContextMenu*)menu)->getSubMenu(index); } bool GUIContextMenu_IsItemEnabled(IntPtr menu, int id) { _FIX_BOOL_MARSHAL_BUG(((IGUIContextMenu*)menu)->isItemEnabled(id)); } void GUIContextMenu_RemoveAllItems(IntPtr menu) { ((IGUIContextMenu*)menu)->removeAllItems(); } void GUIContextMenu_RemoveItem(IntPtr menu, int item) { ((IGUIContextMenu*)menu)->removeItem(item); } void GUIContextMenu_SetItemCommandID(IntPtr menu, int index, int id) { ((IGUIContextMenu*)menu)->setItemCommandId(index, id); } void GUIContextMenu_SetItemEnabled(IntPtr menu, int index, bool enabled) { ((IGUIContextMenu*)menu)->setItemEnabled(index, enabled); } void GUIContextMenu_SetItemText(IntPtr menu, int index, M_STRING text) { ((IGUIContextMenu*)menu)->setItemText(index, MU_WCHAR(text)); } void GUIEditBox_EnableOverrideColor(IntPtr edit, bool enabled) { ((IGUIEditBox*)edit)->enableOverrideColor(enabled); } int GUIEditBox_GetMax(IntPtr edit) { return ((IGUIEditBox*)edit)->getMax(); } void GUIEditBox_SetMax(IntPtr edit, int max) { ((IGUIEditBox*)edit)->setMax(max); } void GUIEditBox_SetOverrideColor(IntPtr edit, M_SCOLOR color) { ((IGUIEditBox*)edit)->setOverrideColor(MU_SCOLOR(color)); } void GUIEditBox_SetOverrideFont(IntPtr edit, IntPtr font) { ((IGUIEditBox*)edit)->setOverrideFont((IGUIFont*)font); } M_STRING GUIFileOpenDialog_GetFilename(IntPtr dialog) { return UM_STRING(((IGUIFileOpenDialog*)dialog)->getFileName()); } void GUIImage_SetImage(IntPtr image, IntPtr texture) { ((IGUIImage*)image)->setImage((ITexture*)texture); } void GUIImage_SetUseAlphaChannel(IntPtr image, bool use) { ((IGUIImage*)image)->setUseAlphaChannel(use); } void GUIFont_Draw(IntPtr font, M_STRING text, M_RECT pos, M_SCOLOR color, bool hcenter, bool vcenter, M_RECT clip) { ((IGUIFont*)font)->draw(MU_WCHAR(text), MU_RECT(pos), MU_SCOLOR(color), hcenter, vcenter, clip ? &(MU_RECT(clip)) : 0); } int GUIFont_GetCharacterFromPos(IntPtr font, M_STRING text, int pixel_x) { return ((IGUIFont*)font)->getCharacterFromPos(MU_WCHAR(text), pixel_x); } void GUIFont_GetDimension(IntPtr font, M_STRING text, M_DIM2DS dim) { UM_DIM2DS(((IGUIFont*)font)->getDimension(MU_WCHAR(text)), dim); } void GUIFader_FadeIn(IntPtr fader, unsigned int time) { ((IGUIInOutFader*)fader)->fadeIn(time); } void GUIFader_FadeOut(IntPtr fader, unsigned int time) { ((IGUIInOutFader*)fader)->fadeOut(time); } void GUIFader_GetColor(IntPtr fader, M_SCOLOR color) { UM_SCOLOR(((IGUIInOutFader*)fader)->getColor(), color); } bool GUIFader_IsReady(IntPtr fader) { _FIX_BOOL_MARSHAL_BUG(((IGUIInOutFader*)fader)->isReady()); } void GUIFader_SetColor(IntPtr fader, M_SCOLOR color) { ((IGUIInOutFader*)fader)->setColor(MU_SCOLOR(color)); } int GUIListBox_AddItem(IntPtr listb, M_STRING text, int icon) { return ((IGUIListBox*)listb)->addItem(MU_WCHAR(text), icon); } int GUIListBox_AddItemA(IntPtr listb, M_STRING text) { return ((IGUIListBox*)listb)->addItem(MU_WCHAR(text)); } void GUIListBox_Clear(IntPtr listb) { ((IGUIListBox*)listb)->clear(); } int GUIListBox_GetItemCount(IntPtr listb) { return ((IGUIListBox*)listb)->getItemCount(); } M_STRING GUIListBox_GetListItem(IntPtr listb, int id) { return UM_STRING(((IGUIListBox*)listb)->getListItem(id)); } int GUIListBox_GetSelected(IntPtr listb) { return ((IGUIListBox*)listb)->getSelected(); } /* Irrlicht 1.4 adding */ float GUISpinBox_GetMax (IntPtr spin) { return ((IGUISpinBox*)spin)->getMax(); } float GUISpinBox_GetMin(IntPtr spin) { return ((IGUISpinBox*)spin)->getMin(); } float GUISpinBox_GetStepSize (IntPtr spin) { return ((IGUISpinBox*)spin)->getStepSize(); } float GUISpinBox_GetValue (IntPtr spin) { return ((IGUISpinBox*)spin)->getValue(); } IntPtr GUISpinBox_GetEditBox (IntPtr spin) { return (IntPtr)((IGUISpinBox*)spin)->getEditBox(); } void GUISpinBox_SetRange (IntPtr spin, int min, int max) { ((IGUISpinBox*)spin)->setRange(min, max); } void GUISpinBox_SetStepSize (IntPtr spin, float step) { ((IGUISpinBox*)spin)->setStepSize (step); } void GUISpinBox_SetValue (IntPtr spin, float value) { ((IGUISpinBox*)spin)->setValue (value); } void GUISpinBox_SetDecimalPlaces (IntPtr spin, int places) { ((IGUISpinBox*)spin)->setDecimalPlaces (places); } /**/ void GUIListBox_SetSelected(IntPtr listb, int sel) { ((IGUIListBox*)listb)->setSelected(sel); } IntPtr GUIMeshViewer_GetMaterial(IntPtr meshv) { return (IntPtr)&((IGUIMeshViewer*)meshv)->getMaterial(); } void GUIMeshViewer_SetMaterial(IntPtr meshv, IntPtr mat) { ((IGUIMeshViewer*)meshv)->setMaterial(*((SMaterial*)mat)); } void GUIMeshViewer_SetMesh(IntPtr meshv, IntPtr animatedmesh) { ((IGUIMeshViewer*)meshv)->setMesh((IAnimatedMesh*)animatedmesh); } IntPtr GUIWindow_GetCloseButton(IntPtr window) { return ((IGUIWindow*)window)->getCloseButton(); } IntPtr GUIWindow_GetMaximizeButton(IntPtr window) { return ((IGUIWindow*)window)->getMaximizeButton(); } IntPtr GUIWindow_GetMinimizeButton(IntPtr window) { return ((IGUIWindow*)window)->getMinimizeButton(); } int GUIScrollBar_GetPos(IntPtr sb) { return ((IGUIScrollBar*)sb)->getPos(); } void GUIScrollBar_SetMax(IntPtr sb, int max) { ((IGUIScrollBar*)sb)->setMax(max); } void GUIScrollBar_SetPos(IntPtr sb, int pos) { ((IGUIScrollBar*)sb)->setPos(pos); } void GUIStaticText_EnableOverrideColor(IntPtr st, bool enabled) { ((IGUIStaticText*)st)->enableOverrideColor(enabled); } int GUIStaticText_GetTextHeight(IntPtr st) { return ((IGUIStaticText*)st)->getTextHeight(); } void GUIStaticText_SetOverrideColor(IntPtr st, M_SCOLOR color) { ((IGUIStaticText*)st)->setOverrideColor(MU_SCOLOR(color)); } void GUIStaticText_SetOverrideFont(IntPtr st, IntPtr font) { ((IGUIStaticText*)st)->setOverrideFont((IGUIFont*)font); } void GUIStaticText_SetWordWrap(IntPtr st, bool enabled) { ((IGUIStaticText*)st)->setWordWrap(enabled); } int GUITab_GetNumber(IntPtr tab) { return ((IGUITab*)tab)->getNumber(); } void GUITab_SetBackgroundColor(IntPtr tab, M_SCOLOR color) { ((IGUITab*)tab)->setBackgroundColor(MU_SCOLOR(color)); } void GUITab_SetDrawBackground(IntPtr tab, bool draw) { ((IGUITab*)tab)->setDrawBackground(draw); } IntPtr GUITabControl_AddTab(IntPtr tabc, M_STRING caption, int id) { return ((IGUITabControl*)tabc)->addTab(MU_WCHAR(caption), id); } int GUITabControl_GetActiveTab(IntPtr tabc) { return ((IGUITabControl*)tabc)->getActiveTab(); } IntPtr GUITabControl_GetTab(IntPtr tabc, int index) { return ((IGUITabControl*)tabc)->getTab(index); } int GUITabControl_GetTabCount(IntPtr tabc) { return ((IGUITabControl*)tabc)->getTabCount(); } bool GUITabControl_SetActiveTab(IntPtr tabc, int index) { _FIX_BOOL_MARSHAL_BUG(((IGUITabControl*)tabc)->setActiveTab(index)); } IntPtr GUIToolBar_AddButton(IntPtr toolbar, int id, M_STRING text, M_STRING tooltip, IntPtr img, IntPtr pressedimg, bool isPushButton, bool useAlphaChannel) { return ((IGUIToolBar*)toolbar)->addButton(id, MU_WCHAR(text), MU_WCHAR(tooltip), (ITexture*)img, (ITexture*)pressedimg, isPushButton, useAlphaChannel); }
[ [ [ 1, 452 ] ] ]
3e7a99ae08ec8b3bbab8881ba4d8f53e8a446cf6
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/pcbnew/ioascii.cpp
8621311c518deb00d1ba2ae4270f15035bdd3947
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-2
C++
false
false
27,667
cpp
/********************************************************************/ /* Routines de lecture et sauvegarde des structures en format ASCii */ /* Fichier common a PCBNEW et CVPCB */ /********************************************************************/ /* ioascii.cpp */ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #ifdef PCBNEW #include "pcbnew.h" #include "autorout.h" #endif #ifdef CVPCB #include "cvpcb.h" #endif #include "protos.h" /* Format des structures de sauvegarde type ASCII : Structure PAD: $PAD Sh "name" forme dimv dimH dV dH orient :forme generale dV, dH = delta dimensions Dr diam, dV dH :drill : diametre offsets de percage At type S/N layers : type standard,cms,conn,hole,meca., Stack/Normal, Hexadecimal 32 bits: occupation des couches Nm net_code netname Po posrefX posrefy : position refX,Y (= position orient 0 / ancre) $EndPAD ******** Structure module *********** $MODULE namelib Po ax ay orient layer masquelayer m_TimeCode ax ay = coord ancre (position module) orient = orient en 0.1 degre layer = numero de couche masquelayer = couche pour serigraphie m_TimeCode a usage interne (groupements) Li <namelib> Cd <text> Description du composant (Composant Doc) Kw <text> Liste des mots cle Sc schematimestamp de reference schematique Op rot90 rot180 Options de placement auto (cout rot 90, 180 ) rot90 est sur 2x4 bits: lsb = cout rot 90, msb = cout rot -90; Tn px py dimv dimh orient epaisseur miroir visible "texte" n = type (0 = ref, 1 = val, > 1 =qcq Textes POS x,y / ancre et orient module 0 dimv dimh orient epaisseur miroir (Normal/miroir) visible V/I DS ox oy fx fy w edge: segment coord ox,oy a fx,fy, relatives a l'ancre et orient 0 epaisseur w DC ox oy fx fy w descr cercle (centre, 1 point, epaisseur) $PAD $EndPAD section pads s'il y en a $EndMODULE */ extern W_PLOT * SheetList[]; /* Variables locales, utilisees pour la lecture des fichiers PCB */ int NbDraw,NbTrack,NbZone, NbMod, NbNets; /**********************************************************************/ int WinEDA_BasePcbFrame::ReadListeSegmentDescr(wxDC * DC, FILE * File, TRACK * PtSegm,int StructType, int * LineNum, int NumSegm) /**********************************************************************/ /* Lecture de la description d'une liste de segments (Tracks, zones) Retourne: si ok nombre d'items lus. si pas de fin de block ($..) - nombre. */ { int shape, width, layer, type, flags, net_code; int ii = 0, PerCent, Pas; char Line[256]; TRACK * NewTrack; PerCent = 0; Pas = NumSegm / 99; #ifdef PCBNEW switch ( StructType ) { case TYPETRACK: case TYPEVIA: DisplayActivity(PerCent, wxT("Tracks:") ); break; case TYPEZONE: DisplayActivity(PerCent, wxT("Zones:") ); break; } #endif while( GetLine(File, Line, LineNum ) ) { if(Line[0] == '$') { return(ii); /* fin de liste OK */ } switch ( StructType ) { default: case TYPETRACK: NewTrack = new TRACK( m_Pcb ); break; case TYPEVIA: NewTrack = new SEGVIA( m_Pcb ); break; case TYPEZONE: NewTrack = new SEGZONE( m_Pcb ); break; } NewTrack->Insert(m_Pcb, PtSegm); PtSegm = NewTrack; int arg_count = sscanf( Line+2," %d %d %d %d %d %d %d",&shape, &PtSegm->m_Start.x, &PtSegm->m_Start.y, &PtSegm->m_End.x, &PtSegm->m_End.y, &width, & PtSegm->m_Drill); PtSegm->m_Width = width; PtSegm->m_Shape = shape; if ( arg_count < 7 ) PtSegm->m_Drill = -1; if( GetLine(File, Line, LineNum ) == NULL ) break; if(Line[0] == '$') break; sscanf( Line+2," %d %d %d %lX %X", &layer, &type,&net_code, &PtSegm->m_TimeStamp, &flags); if ( type == 1 ) PtSegm->m_StructType = TYPEVIA; PtSegm->m_Layer = layer; PtSegm->m_NetCode = net_code; PtSegm->SetState(flags, ON); #ifdef PCBNEW PtSegm->Draw(DrawPanel, DC, GR_OR); #endif ii++; if( ( Pas && (ii % Pas ) == 0) ) { PerCent ++; #ifdef PCBNEW switch ( StructType ) { case TYPETRACK: case TYPEVIA: DisplayActivity(PerCent, wxT("Tracks:") ); break; case TYPEZONE: DisplayActivity(PerCent, wxT("Zones:") ); break; } #endif } } DisplayError(this, _("Error: Unexpected end of file !") ); return(-ii); } /**********************************************************************************/ int WinEDA_BasePcbFrame::ReadGeneralDescrPcb(wxDC * DC, FILE * File, int * LineNum) /**********************************************************************************/ { char Line[1024], *data; BASE_SCREEN * screen = m_CurrentScreen; while( GetLine(File, Line, LineNum ) != NULL ) { data = strtok(Line," =\n\r"); if(strnicmp(data,"$EndGENERAL",10) == 0) break; if( strncmp(data, "Ly", 2) == 0 ) // Old format for Layer count { int Masque_Layer = 1, ii; data = strtok(NULL," =\n\r"); sscanf(data,"%X",&Masque_Layer); // Setup layer count m_Pcb->m_BoardSettings->m_CopperLayerCount = 0; for ( ii = 0; ii < NB_COPPER_LAYERS; ii++ ) { if ( Masque_Layer & 1 ) m_Pcb->m_BoardSettings->m_CopperLayerCount++; Masque_Layer >>= 1; } continue; } if(strnicmp(data, "Links", 5) == 0) { data = strtok(NULL," =\n\r"); m_Pcb->m_NbLinks = atoi(data); continue; } if(strnicmp(data, "NoConn", 6) == 0) { data = strtok(NULL," =\n\r"); m_Pcb->m_NbNoconnect = atoi(data); continue; } if(strnicmp(data, "Di", 2) == 0) { int ii, jj, bestzoom; wxSize pcbsize, screensize; data = strtok(NULL," =\n\r"); m_Pcb->m_BoundaryBox.SetX(atoi(data)); data = strtok(NULL," =\n\r"); m_Pcb->m_BoundaryBox.SetY(atoi(data)); data = strtok(NULL," =\n\r"); m_Pcb->m_BoundaryBox.SetWidth(atoi(data) - m_Pcb->m_BoundaryBox.GetX()); data = strtok(NULL," =\n\r"); m_Pcb->m_BoundaryBox.SetHeight(atoi(data) - m_Pcb->m_BoundaryBox.GetY()); /* calcul du zoom optimal */ pcbsize = m_Pcb->m_BoundaryBox.GetSize(); screensize = DrawPanel->GetClientSize(); ii = pcbsize.x/screensize.x; jj = pcbsize.y/screensize.y; bestzoom = max(ii, jj); screen->m_Curseur = m_Pcb->m_BoundaryBox.Centre(); screen->SetZoom(bestzoom); // la position des tracés a changé: mise a jour dans le DC courant wxPoint org; DrawPanel->GetViewStart(&org.x, &org.y); DrawPanel->GetScrollPixelsPerUnit(&ii, &jj); org.x *= ii; org.y *= jj; #ifdef WX_ZOOM DC->SetUserScale(1.0/(double)screen->GetZoom(), 1.0/screen->GetZoom()); org.x *= screen->GetZoom(); org.y *= screen->GetZoom(); DC->SetDeviceOrigin(-org.x, -org.y); #endif DrawPanel->SetBoundaryBox(); Recadre_Trace(TRUE); continue; } /* Lecture du nombre de segments type DRAW , TRACT, ZONE */ if(stricmp(data, "Ndraw") == 0) { data = strtok(NULL," =\n\r"); NbDraw = atoi(data);; continue; } if(stricmp(data, "Ntrack") == 0) { data = strtok(NULL," =\n\r"); NbTrack = atoi(data); continue; } if(stricmp(data, "Nzone") == 0) { data = strtok(NULL," =\n\r"); NbZone = atoi(data); continue; } if(stricmp(data, "Nmodule") == 0) { data = strtok(NULL," =\n\r"); NbMod = atoi(data); continue; } if(stricmp(data, "Nnets") == 0) { data = strtok(NULL," =\n\r"); NbNets = atoi(data); continue; } } return(1); } /*************************************************************/ int WinEDA_BasePcbFrame::ReadSetup(FILE * File, int * LineNum) /*************************************************************/ { char Line[1024], *data; while( GetLine(File, Line, LineNum ) != NULL ) { strtok(Line," =\n\r"); data = strtok(NULL," =\n\r"); if(stricmp(Line,"$EndSETUP") == 0) { return 0; } if(stricmp(Line, "AuxiliaryAxisOrg") == 0) { int gx = 0, gy =0; gx = atoi(data); data = strtok(NULL," =\n\r"); if ( data ) gy = atoi(data); m_Auxiliary_Axe_Position.x = gx; m_Auxiliary_Axe_Position.y = gy; continue; } #ifdef PCBNEW if(stricmp(Line, "Layers") == 0) { int tmp; sscanf(data,"%d",&tmp); m_Pcb->m_BoardSettings->m_CopperLayerCount = tmp; continue; } if(stricmp(Line, "TrackWidth") == 0) { g_DesignSettings.m_CurrentTrackWidth = atoi(data); AddHistory(g_DesignSettings.m_CurrentTrackWidth, TYPETRACK); continue; } if(stricmp(Line, "TrackWidthHistory") == 0) { int tmp = atoi(data); AddHistory(tmp, TYPETRACK); continue; } if(stricmp(Line, "TrackClearence") == 0) { g_DesignSettings.m_TrackClearence = atoi(data); continue; } if(stricmp(Line, "ZoneClearence") == 0) { g_DesignSettings.m_ZoneClearence = atoi(data); continue; } if(stricmp(Line, "ZoneGridSize") == 0) { pas_route = atoi(data); continue; } if(stricmp(Line, "DrawSegmWidth") == 0) { g_DesignSettings.m_DrawSegmentWidth = atoi(data); continue; } if(stricmp(Line, "EdgeSegmWidth") == 0) { g_DesignSettings.m_EdgeSegmentWidth = atoi(data); continue; } if(stricmp(Line, "ViaSize") == 0) { g_DesignSettings.m_CurrentViaSize = atoi(data); AddHistory(g_DesignSettings.m_CurrentViaSize, TYPEVIA); continue; } if(stricmp(Line, "ViaSizeHistory") == 0) { int tmp = atoi(data); AddHistory(tmp, TYPEVIA); continue; } if(stricmp(Line, "ViaDrill") == 0) { g_DesignSettings.m_ViaDrill = atoi(data); continue; } if(stricmp(Line, "TextPcbWidth") == 0) { g_DesignSettings.m_PcbTextWidth = atoi(data); continue; } if(stricmp(Line, "TextPcbSize") == 0) { g_DesignSettings.m_PcbTextSize.x = atoi(data); data = strtok(NULL," =\n\r"); g_DesignSettings.m_PcbTextSize.y = atoi(data); continue; } if(stricmp(Line, "EdgeModWidth") == 0) { ModuleSegmentWidth = atoi(data); continue; } if(stricmp(Line, "TextModWidth") == 0) { ModuleTextWidth = atoi(data); continue; } if(stricmp(Line, "TextModSize") == 0) { ModuleTextSize.x = atoi(data); data = strtok(NULL," =\n\r"); ModuleTextSize.y = atoi(data); continue; } if(stricmp(Line, "PadSize") == 0) { g_Pad_Master.m_Size.x = atoi(data); data = strtok(NULL," =\n\r"); g_Pad_Master.m_Size.y = atoi(data); continue; } if(stricmp(Line, "PadDrill") == 0) { g_Pad_Master.m_Drill = atoi(data); continue; } if(stricmp(Line, "PadDeltaSize") == 0) { g_Pad_Master.m_DeltaSize.x = atoi(data); data = strtok(NULL," =\n\r"); g_Pad_Master.m_DeltaSize.y = atoi(data); continue; } if(stricmp(Line, "PadShapeOffset") == 0) { g_Pad_Master.m_Offset.x = atoi(data); data = strtok(NULL," =\n\r"); g_Pad_Master.m_Offset.y = atoi(data); continue; } #endif } return(1); } #ifdef PCBNEW /**********************************************************/ static int WriteSetup(FILE * File, WinEDA_DrawFrame * frame) /**********************************************************/ { char text[1024]; int ii; fprintf(File,"$SETUP\n"); sprintf(text, "InternalUnit %f INCH\n", 1.0/PCB_INTERNAL_UNIT); to_point(text); fprintf(File, text); fprintf(File, "GridSize %d %d\n", frame->GetScreen()->GetGrid().x, frame->GetScreen()->GetGrid().y); fprintf(File, "ZoneGridSize %d\n", pas_route); fprintf(File, "Layers %d\n", g_DesignSettings.m_CopperLayerCount); fprintf(File, "TrackWidth %d\n", g_DesignSettings.m_CurrentTrackWidth); for ( ii = 0; ii < HIST0RY_NUMBER; ii++) { if ( g_DesignSettings.m_TrackWidhtHistory[ii] == 0 ) break; fprintf(File, "TrackWidthHistory %d\n", g_DesignSettings.m_TrackWidhtHistory[ii]); } fprintf(File, "TrackClearence %d\n", g_DesignSettings.m_TrackClearence); fprintf(File, "ZoneClearence %d\n", g_DesignSettings.m_ZoneClearence); fprintf(File, "DrawSegmWidth %d\n", g_DesignSettings.m_DrawSegmentWidth); fprintf(File, "EdgeSegmWidth %d\n", g_DesignSettings.m_EdgeSegmentWidth); fprintf(File, "ViaSize %d\n", g_DesignSettings.m_CurrentViaSize); fprintf(File, "ViaDrill %d\n", g_DesignSettings.m_ViaDrill); for ( ii = 0; ii < HIST0RY_NUMBER; ii++) { if ( g_DesignSettings.m_ViaSizeHistory[ii] == 0 ) break; fprintf(File, "ViaSizeHistory %d\n", g_DesignSettings.m_ViaSizeHistory[ii]); } fprintf(File, "TextPcbWidth %d\n", g_DesignSettings.m_PcbTextWidth); fprintf(File, "TextPcbSize %d %d\n", g_DesignSettings.m_PcbTextSize.x, g_DesignSettings.m_PcbTextSize.y); fprintf(File, "EdgeModWidth %d\n", ModuleSegmentWidth); fprintf(File, "TextModSize %d %d\n", ModuleTextSize.x , ModuleTextSize.y); fprintf(File, "TextModWidth %d\n", ModuleTextWidth); fprintf(File, "PadSize %d %d\n", g_Pad_Master.m_Size.x, g_Pad_Master.m_Size.y); fprintf(File, "PadDrill %d\n", g_Pad_Master.m_Drill); // fprintf(File, "PadDeltaSize %d %d\n", Pad_DeltaSize.x, Pad_DeltaSize.y); // fprintf(File, "PadDrillOffset %d %d\n", Pad_OffsetSize.x, Pad_OffsetSize.y); fprintf(File, "AuxiliaryAxisOrg %d %d\n", frame->m_Auxiliary_Axe_Position.x, frame->m_Auxiliary_Axe_Position.y); fprintf(File,"$EndSETUP\n\n"); return(1); } #endif /******************************************************/ bool WinEDA_PcbFrame::WriteGeneralDescrPcb(FILE * File) /******************************************************/ { EDA_BaseStruct * PtStruct = m_Pcb->m_Modules; int NbModules, NbDrawItem, NbLayers; /* Calcul du nombre des modules */ for( NbModules = 0; PtStruct != NULL; PtStruct = PtStruct->Pnext) NbModules++; /* generation du masque des couches autorisees */ NbLayers = m_Pcb->m_BoardSettings->m_CopperLayerCount; fprintf(File,"$GENERAL\n"); fprintf(File,"LayerCount %d\n",NbLayers); // Write old format for Layer count (for compatibility with old versions of pcbnew fprintf(File,"Ly %8X\n", g_TabAllCopperLayerMask[NbLayers-1] | ALL_NO_CU_LAYERS); // For compatibility with old version of pcbnew fprintf(File,"Links %d\n",m_Pcb->m_NbLinks); fprintf(File,"NoConn %d\n",m_Pcb->m_NbNoconnect); /* Generation des coord du rectangle d'encadrement */ m_Pcb->ComputeBoundaryBox(); fprintf(File,"Di %d %d %d %d\n", m_Pcb->m_BoundaryBox.GetX(), m_Pcb->m_BoundaryBox.GetY(), m_Pcb->m_BoundaryBox.GetRight(), m_Pcb->m_BoundaryBox.GetBottom()); /* Generation du nombre de segments type DRAW , TRACT ZONE */ PtStruct = m_Pcb->m_Drawings; NbDrawItem = 0; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext) NbDrawItem++; fprintf(File,"Ndraw %d\n", NbDrawItem); fprintf(File,"Ntrack %d\n", m_Pcb->GetNumSegmTrack() ); fprintf(File,"Nzone %d\n", m_Pcb->GetNumSegmZone() ); fprintf(File,"Nmodule %d\n",NbModules ); fprintf(File,"Nnets %d\n",m_Pcb->m_NbNets ); fprintf(File,"$EndGENERAL\n\n"); return TRUE; } /******************************************************/ bool WriteSheetDescr(BASE_SCREEN * screen, FILE * File) /******************************************************/ { /* Sauvegarde des dimensions de la feuille de dessin, des textes du cartouche.. */ W_PLOT * sheet = screen->m_CurrentSheet; fprintf(File,"$SHEETDESCR\n"); fprintf(File,"Sheet %s %d %d\n", CONV_TO_UTF8(sheet->m_Name), sheet->m_Size.x,sheet->m_Size.y); fprintf(File,"Title \"%s\"\n", CONV_TO_UTF8(screen->m_Title)); fprintf(File,"Date \"%s\"\n", CONV_TO_UTF8(screen->m_Date)); fprintf(File,"Rev \"%s\"\n", CONV_TO_UTF8(screen->m_Revision)); fprintf(File,"Comp \"%s\"\n", CONV_TO_UTF8(screen->m_Company)); fprintf(File,"Comment1 \"%s\"\n", CONV_TO_UTF8(screen->m_Commentaire1)); fprintf(File,"Comment2 \"%s\"\n", CONV_TO_UTF8(screen->m_Commentaire2)); fprintf(File,"Comment3 \"%s\"\n", CONV_TO_UTF8(screen->m_Commentaire3)); fprintf(File,"Comment4 \"%s\"\n", CONV_TO_UTF8(screen->m_Commentaire4)); fprintf(File,"$EndSHEETDESCR\n\n"); return TRUE; } /***************************************************************************/ static bool ReadSheetDescr(BASE_SCREEN * screen, FILE * File, int * LineNum) /***************************************************************************/ { char Line[1024], buf[1024], * text; /* Recheche suite et fin de descr */ while( GetLine(File, Line, LineNum ) != NULL ) { if( strnicmp(Line,"$End",4) == 0 ) return TRUE; if(strnicmp(Line, "Sheet", 4) == 0) { text = strtok(Line, " \t\n\r"); text = strtok(NULL, " \t\n\r"); W_PLOT * sheet = SheetList[0]; int ii; for( ii = 0; sheet != NULL; ii++, sheet = SheetList[ii]) { if( stricmp( CONV_TO_UTF8(sheet->m_Name), text) == 0 ) { screen->m_CurrentSheet = sheet; if ( sheet == &g_Sheet_user ) { text = strtok(NULL, " \t\n\r"); if ( text ) sheet->m_Size.x = atoi(text); text = strtok(NULL, " \t\n\r"); if ( text ) sheet->m_Size.y = atoi(text); } break; } } continue; } if( strnicmp(Line,"Title",2) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Title = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Date",2) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Date = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Rev",2) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Revision = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Comp",4) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Company = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Comment1",8) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Commentaire1 = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Comment2",8) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Commentaire2 = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Comment3",8) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Commentaire3 = CONV_FROM_UTF8(buf); continue; } if( strnicmp(Line,"Comment4",8) == 0 ) { ReadDelimitedText( buf, Line, 256); screen->m_Commentaire4 = CONV_FROM_UTF8(buf); continue; } } return(FALSE); } /********************************************************************/ int WinEDA_PcbFrame::ReadPcbFile(wxDC * DC, FILE * File, bool Append) /********************************************************************/ /* Lit un fichier PCB .brd Si Append == 0: l'ancien pcb en memoire est supprime Sinon il y a ajout des elements */ { char Line[1024]; int LineNum = 0; int nbsegm, nbmod; EDA_BaseStruct * LastStructPcb = NULL, * StructPcb; MODULE * LastModule = NULL, * Module; EQUIPOT * LastEquipot = NULL, * Equipot; wxBusyCursor dummy; NbDraw = NbTrack = NbZone = NbMod = NbNets = -1; m_Pcb->m_NbNets = 0; m_Pcb->m_Status_Pcb = 0; nbmod = 0; if ( Append ) { LastModule = m_Pcb->m_Modules; for( ; LastModule != NULL; LastModule = (MODULE*) LastModule->Pnext ) { if ( LastModule->Pnext == NULL ) break; } LastStructPcb = m_Pcb->m_Drawings; for( ; LastStructPcb != NULL; LastStructPcb = LastStructPcb->Pnext ) { if ( LastStructPcb->Pnext == NULL ) break; } LastEquipot = m_Pcb->m_Equipots; for( ; LastEquipot != NULL; LastEquipot = (EQUIPOT*)LastEquipot->Pnext ) { if ( LastEquipot->Pnext == NULL ) break; } } while( GetLine(File, Line, &LineNum ) != NULL ) { if(strnicmp(Line,"$EndPCB",6) == 0) break; if( strnicmp(Line,"$GENERAL",8) == 0 ) { ReadGeneralDescrPcb(DC, File, &LineNum); continue; } if( strnicmp(Line,"$SHEETDESCR",11) == 0 ) { ReadSheetDescr(m_CurrentScreen, File, &LineNum); continue; } if( strnicmp(Line,"$SETUP",6) == 0 ) { if( ! Append) { ReadSetup(File, &LineNum); } else { while( GetLine(File, Line, &LineNum ) != NULL ) if( strnicmp(Line,"$EndSETUP",6) == 0 ) break; } continue; } if(strnicmp(Line,"$EQUIPOT",7) == 0) { Equipot = new EQUIPOT(m_Pcb); Equipot->ReadEquipotDescr(File, &LineNum); if( LastEquipot == NULL ) { m_Pcb->m_Equipots = Equipot; Equipot->Pback = m_Pcb; } else { Equipot->Pback = LastEquipot; LastEquipot->Pnext = Equipot; } LastEquipot = Equipot; m_Pcb->m_NbNets++; continue; } if(strnicmp(Line,"$MODULE",7) == 0) { float Pas; Pas = 100.0; if( NbMod > 1) Pas /= NbMod; Module = new MODULE(m_Pcb); if( Module == NULL ) continue; Module->ReadDescr(File, &LineNum); if( LastModule == NULL ) { m_Pcb->m_Modules = Module; Module->Pback = m_Pcb; } else { Module->Pback = LastModule; LastModule->Pnext = Module; } LastModule = Module; nbmod++; #ifdef PCBNEW DisplayActivity((int)( Pas * nbmod), wxT("Modules:")); #endif Module->Draw(DrawPanel, DC, wxPoint(0,0), GR_OR); continue; } if(strnicmp(Line,"$TEXTPCB",8) == 0) { TEXTE_PCB * pcbtxt = new TEXTE_PCB(m_Pcb); StructPcb = (EDA_BaseStruct*) pcbtxt; pcbtxt->ReadTextePcbDescr(File, &LineNum); if( LastStructPcb == NULL ) { m_Pcb->m_Drawings = StructPcb; StructPcb->Pback = m_Pcb; } else { StructPcb->Pback = LastStructPcb; LastStructPcb->Pnext = StructPcb; } LastStructPcb = StructPcb; #ifdef PCBNEW ((TEXTE_PCB*)StructPcb)->Draw(DrawPanel, DC, wxPoint(0, 0), GR_OR); #endif continue; } if( strnicmp(Line,"$DRAWSEGMENT",10) == 0) { DRAWSEGMENT * DrawSegm = new DRAWSEGMENT(m_Pcb); DrawSegm->ReadDrawSegmentDescr(File, &LineNum); if( LastStructPcb == NULL ) { m_Pcb->m_Drawings = DrawSegm; DrawSegm->Pback = m_Pcb; } else { DrawSegm->Pback = LastStructPcb; LastStructPcb->Pnext = DrawSegm; } LastStructPcb = DrawSegm; #ifdef PCBNEW Trace_DrawSegmentPcb(DrawPanel, DC, DrawSegm, GR_OR); #endif continue; } if( strnicmp(Line,"$COTATION",9) == 0) { COTATION * Cotation = new COTATION(m_Pcb); Cotation->ReadCotationDescr(File, &LineNum); if( LastStructPcb == NULL ) { m_Pcb->m_Drawings = Cotation; Cotation->Pback = m_Pcb; } else { Cotation->Pback = LastStructPcb; LastStructPcb->Pnext = Cotation; } LastStructPcb = Cotation; #ifdef PCBNEW Cotation->Draw(DrawPanel, DC, wxPoint(0,0), GR_OR); #endif continue; } if( strnicmp(Line,"$MIREPCB",8) == 0) { MIREPCB * Mire = new MIREPCB(m_Pcb); Mire->ReadMirePcbDescr(File, &LineNum); if( LastStructPcb == NULL ) { m_Pcb->m_Drawings = Mire; Mire->Pback = m_Pcb; } else { Mire->Pback = LastStructPcb; LastStructPcb->Pnext = Mire; } LastStructPcb = Mire; #ifdef PCBNEW Mire->Draw(DrawPanel, DC, wxPoint(0,0), GR_OR); #endif continue; } if(strnicmp(Line,"$TRACK",6) == 0) { TRACK * StartTrack = m_Pcb->m_Track; nbsegm = 0; if( Append ) { for( ;StartTrack != NULL; StartTrack = (TRACK*)StartTrack->Pnext) { if( StartTrack->Pnext == NULL ) break; } } #ifdef PCBNEW int ii = ReadListeSegmentDescr(DC, File, StartTrack, TYPETRACK, &LineNum, NbTrack); m_Pcb->m_NbSegmTrack += ii; #endif continue; } if(strnicmp(Line,"$ZONE",5) == 0) { TRACK * StartZone = m_Pcb->m_Zone; if( Append ) { for( ;StartZone != NULL; StartZone = (TRACK*)StartZone->Pnext) { if( StartZone->Pnext == NULL ) break; } } #ifdef PCBNEW int ii = ReadListeSegmentDescr(DC, File, StartZone,TYPEZONE, &LineNum, NbZone); m_Pcb->m_NbSegmZone += ii; #endif continue; } } Affiche_Message(wxEmptyString); #ifdef PCBNEW Compile_Ratsnest(DC, TRUE); #endif // Size est donnee en 1/1000 " return(1); } #ifdef PCBNEW /***************************************************/ int WinEDA_PcbFrame::SavePcbFormatAscii(FILE * File) /****************************************************/ /* Routine de sauvegarde du PCB courant sous format ASCII retourne 1 si OK 0 si sauvegarde non faite */ { int ii, NbModules, nseg; float Pas; char Line[256]; EQUIPOT * Equipot; TRACK * PtSegm; EDA_BaseStruct * PtStruct; MODULE * Module; wxBeginBusyCursor(); m_Pcb->m_Status_Pcb &= ~CONNEXION_OK; /* Calcul du nombre des modules */ PtStruct = (EDA_BaseStruct *) m_Pcb->m_Modules; NbModules = 0; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext) NbModules++; /* Ecriture de l'entete PCB : */ fprintf(File,"PCBNEW-BOARD Version %d date %s\n\n",g_CurrentVersionPCB, DateAndTime(Line) ); WriteGeneralDescrPcb(File); WriteSheetDescr(m_CurrentScreen, File); WriteSetup(File, this); /* Ecriture des donnes utiles du pcb */ Equipot = m_Pcb->m_Equipots; Pas = 100.0; if( m_Pcb->m_NbNets) Pas /= m_Pcb->m_NbNets; for(ii = 0; Equipot != NULL; ii++, Equipot = (EQUIPOT*) Equipot->Pnext) { Equipot->WriteEquipotDescr(File); DisplayActivity((int)( Pas * ii ), wxT("Equipot:") ); } Pas = 100.0; if(NbModules) Pas /= NbModules; Module = m_Pcb->m_Modules; for( ii = 1 ; Module != NULL; Module = (MODULE*)Module->Pnext, ii++) { Module->WriteDescr(File); DisplayActivity((int)(ii * Pas) , wxT("Modules:")); } /* sortie des inscriptions du PCB: */ PtStruct = m_Pcb->m_Drawings; for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext ) { switch ( PtStruct->m_StructType ) { case TYPETEXTE: ((TEXTE_PCB*)PtStruct)->WriteTextePcbDescr(File) ; break; case TYPEDRAWSEGMENT: ((DRAWSEGMENT *)PtStruct)->WriteDrawSegmentDescr(File); break; case TYPEMIRE: ((MIREPCB *) PtStruct)->WriteMirePcbDescr(File); break; case TYPECOTATION: ((COTATION *)PtStruct)->WriteCotationDescr(File); break; case TYPEMARQUEUR: /* sauvegarde inutile */ break; default: DisplayError(this, wxT("Unknown Draw Type")); break; } } Pas = 100.0; if( m_Pcb->m_NbSegmTrack) Pas /= (m_Pcb->m_NbSegmTrack); fprintf(File,"$TRACK\n"); PtSegm = m_Pcb->m_Track; DisplayActivity(0, wxT("Tracks:")); for( nseg = 0, ii = 0; PtSegm != NULL; ii++, PtSegm = (TRACK*) PtSegm->Pnext) { ((TRACK*) PtSegm)->WriteTrackDescr(File); if ( nseg != (int)( ii * Pas) ) { nseg = (int)( ii * Pas); DisplayActivity(nseg, wxT("Tracks:")); } } fprintf(File,"$EndTRACK\n"); fprintf(File,"$ZONE\n"); PtSegm = (TRACK*) m_Pcb->m_Zone; ii = m_Pcb->m_NbSegmZone; Pas = 100.0; if(ii) Pas /= ii; PtSegm = m_Pcb->m_Zone; DisplayActivity(0, wxT("Zones:")); for( nseg = 0, ii = 0; PtSegm != NULL; ii++, PtSegm = (TRACK*) PtSegm->Pnext) { ((TRACK*) PtSegm)->WriteTrackDescr(File); if ( nseg != (int)( ii * Pas) ) { nseg = (int)( ii * Pas); DisplayActivity(nseg, wxT("Zones:")); } } fprintf(File,"$EndZONE\n"); fprintf(File,"$EndBOARD\n"); wxEndBusyCursor(); Affiche_Message(wxEmptyString); return 1; } #endif
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 1058 ] ] ]
02a4f0eeaed1545e010b8259b899cf5247bac462
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGame/SanUnitTest/include/OgrePlayerUnitTest.h
e5da190a44577ce8d86d9da84fe6285727727816
[]
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,620
h
#ifndef __Orz_UnitTest_OgrePlayerUnitTest__ #define __Orz_UnitTest_OgrePlayerUnitTest__ #include "SanUnitTestConfig.h" #include "OgrePlayerComponent.h" #include "COgreResourceInterface.h" #include "COgreEntityInterface.h" #include "COgreAnimationInterface.h" /* #include "Engine.h" #include "KeyToMessage.h" #include "SingleChipToMessage.h"*/ #include <OGRE/ogre.h> BOOST_AUTO_TEST_CASE(OgrePlayerUnitTest) { using namespace Orz; ComponentPtr comp = ComponentFactories::getInstance().create("OgrePlayer"); /* COgreResourceInterface * rf = comp->queryInterface<COgreResourceInterface>(); BOOST_CHECK(rf); BOOST_CHECK(rf->createGroup("ABC")); BOOST_CHECK(rf->addLocation("../../media/san/ZhugeLiang", "FileSystem")); rf->init();*/ COgreEntityInterface * face = comp->queryInterface<COgreEntityInterface>(); BOOST_CHECK(face); Ogre::SceneManager * sm = Orz::OgreGraphicsManager::getSingleton().getSceneManager(); Ogre::SceneNode * root = sm->getRootSceneNode()->createChildSceneNode(); face->load("ms_01_4.mesh", "ms_01_4.mesh", root); //face->play(""); Ogre::SceneNode * sn = face->getSceneNode(); sn->scale(0.1f, 0.1f, 0.1f); face->printAllAnimation(); BOOST_CHECK(sn->getParentSceneNode() == root); COgreAnimationInterface * animation = comp->queryInterface< COgreAnimationInterface >(); BOOST_CHECK(animation->isExist("first")); BOOST_CHECK(animation->enable("first", 1)); while(animation->update(0.015f)) { UnitTestEnvironmen::system->run(); } UnitTestEnvironmen::system->run(); UnitTestEnvironmen::system->run(); } #endif
[ [ [ 1, 54 ] ] ]
35a5f79a9c951453b8771508c36cc50430a22565
cf579692f2e289563160b6a218fa5f1b6335d813
/xbflashlib/giants.cpp
d6951fe25e30930748da41b57ec355e841022636
[]
no_license
opcow/XBtool
a7451971de3296e1ce5632b0c9d95430f6d3b223
718a7fbf87e08c12c0c829dd2e2c0d6cee967cbe
refs/heads/master
2021-01-16T21:02:17.759102
2011-03-09T23:36:54
2011-03-09T23:36:54
1,461,420
8
2
null
null
null
null
UTF-8
C++
false
false
56,292
cpp
/************************************************************** * * giants.c * * Library for large-integer arithmetic. * * The large-gcd implementation is due to J. P. Buhler. * Special mod routines use ideas of R. McIntosh. * Contributions from G. Woltman, A. Powell acknowledged. * * Updates: * 11 Feb 03 REC R. McIntosh fixes to fermatpowermodg, mersennepowermodg * 20 Oct 01 REC R. McIntosh fixes to: mersennemod, fermatmod, fer_mod * 18 Jul 99 REC Added routine fer_mod(), for use when Fermat giant itself is available. * 17 Jul 99 REC Fixed sign bug in fermatmod() * 17 Apr 99 REC Fixed various comment/line wraps * 25 Mar 99 REC G. Woltman/A. Powell fixes Karat. routines * 05 Mar 99 REC Moved invaux, binvaux giants to stack * 05 Mar 99 REC Moved gread/gwrite giants to stack * 05 Mar 99 REC No static on cur_den, cur_recip (A. Powell) * 28 Feb 99 REC Error detection added atop newgiant(). * 27 Feb 99 REC Reduced wasted work in addsignal(). * 27 Feb 99 REC Reduced wasted work in FFTmulg(). * 19 Feb 99 REC Generalized iaddg() per R. Mcintosh. * 2 Feb 99 REC Fixed comments. * 6 Dec 98 REC Fixed yet another Karatsuba glitch. * 1 Dec 98 REC Fixed errant case of addg(). * 28 Nov 98 REC Installed A. Powell's (correct) variant of Karatsuba multiply. * 15 May 98 REC Modified gwrite() to handle huge integers. * 13 May 98 REC Changed to static stack declarations * 11 May 98 REC Installed Karatsuba multiply, to handle * medregion 'twixt grammar- and FFT-multiply. * 1 May 98 JF gshifts now handle bits < 0 correctly. * 30 Apr 98 JF 68k assembler code removed, * stack giant size now invariant and based * on first call of newgiant(), * stack memory leaks fixed. * 29 Apr 98 JF function prototyes cleaned up, * GCD no longer uses personal stack, * optimized shifts for bits%16 == 0. * 27 Apr 98 JF scratch giants now replaced with stack * 20 Apr 98 JF grammarsquareg fixed for asize == 0. * scratch giants now static. * 29 Jan 98 JF Corrected out-of-range errors in * mersennemod and fermatmod. * 23 Dec 97 REC Sped up divide routines via split-shift. * 18 Nov 97 JF Improved mersennemod, fermatmod. * 9 Nov 97 JF Sped up grammarsquareg. * 20 May 97 RDW Fixed Win32 compiler warnings. * 18 May 97 REC Installed new, fast divide. * 17 May 97 REC Reduced memory for FFT multiply. * 26 Apr 97 REC Creation. * * c. 1997,1998 Perfectly Scientific, Inc. * All Rights Reserved. * **************************************************************/ #include "stdafx.h" /* Include Files. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "giants.h" #include "xbflashlib.h" /* Compiler options. */ #ifdef _WIN32 #pragma warning( disable : 4127 4706 ) /* disable conditional is constant warning */ #endif /* Global variables. */ int error = 0; int mulmode = AUTO_MUL; int cur_prec = 0; int cur_shift = 0; static int cur_stack_size = 0; static int cur_stack_elem = 0; static int stack_glen = 0; static giant *stack; giant cur_den = NULL, cur_recip = NULL; int current_max_size = 0, cur_run = 0; double * sinCos=NULL; int checkFFTerror = 0; double maxFFTerror; static giant u0=NULL, u1=NULL, v0=NULL, v1=NULL; static double *z = NULL, *z2 = NULL; /* stack handling functions. */ static giant popg(void); static void pushg(int); /* Private function prototypes. */ int gerr(void); double gfloor(double); int radixdiv(int, int, giant); void columnwrite(FILE *, short *, char *, short, int); void normal_addg(giant, giant); void normal_subg(giant, giant); void reverse_subg(giant, giant); int binvaux(giant, giant); int invaux(giant, giant); int allzeros(int, int, giant); void auxmulg(giant a, giant b); void karatmulg(giant a, giant b); void karatsquareg(giant b); void grammarmulg(giant a, giant b); void grammarsquareg(giant b); int lpt(int, int *); void addsignal(giant, double *, int); void FFTsquareg(giant x); void FFTmulg(giant y, giant x); void scramble_real(); void fft_real_to_hermitian(double *z, int n); void fftinv_hermitian_to_real(double *z, int n); void mul_hermitian(double *a, double *b, int n); void square_hermitian(double *b, int n); void giant_to_double(giant x, int sizex, double *z, int L); void gswap(giant *, giant *); void onestep(giant, giant, gmatrix); void mulvM(gmatrix, giant, giant); void mulmM(gmatrix, gmatrix); void writeM(gmatrix); static void punch(giant, gmatrix); static void dotproduct(giant, giant, giant, giant); void fix(giant *, giant *); void hgcd(int, giant, giant, gmatrix); void shgcd(int, int, gmatrix); void * my_malloc(int nbytes) { void *p; p = malloc(nbytes); if (p) { memset(p, 0, nbytes); } return p; } /************************************************************** * * Functions * **************************************************************/ /************************************************************** * * Initialization and utility functions * **************************************************************/ double gfloor( double f ) { return floor(f); } void init_sinCos( int n ) { int j; double e = TWOPI/n; if (n<=cur_run) return; cur_run = n; if (sinCos) free(sinCos); sinCos = (double *)my_malloc(sizeof(double)*(1+(n>>2))); for (j=0;j<=(n>>2);j++) { sinCos[j] = sin(e*j); } } double s_sin( int n ) { int seg = n/(cur_run>>2); switch (seg) { case 0: return(sinCos[n]); case 1: return(sinCos[(cur_run>>1)-n]); case 2: return(-sinCos[n-(cur_run>>1)]); case 3: return(-sinCos[cur_run-n]); } return 0; } double s_cos( int n ) { int quart = (cur_run>>2); if (n < quart) return(s_sin(n+quart)); return(-s_sin(n-quart)); } int gerr(void) { return(error); } giant popg ( void ) { int i; if (current_max_size <= 0) current_max_size = MAX_SHORTS; if (cur_stack_size == 0) { /* Initialize the stack if we're just starting out. * Note that all stack giants will be whatever current_max_size is * when newgiant() is first called. */ cur_stack_size = STACK_GROW; stack = (giant *) my_malloc (cur_stack_size * sizeof(giant)); for(i = 0; i < STACK_GROW; i++) stack[i] = NULL; if (stack_glen == 0) stack_glen = current_max_size; } else if (cur_stack_elem >= cur_stack_size) { /* Expand the stack if we need to. */ i = cur_stack_size; cur_stack_size += STACK_GROW; stack = (giant *) realloc (stack,cur_stack_size * sizeof(giant)); for (; i < cur_stack_size; i++) stack[i] = NULL; } else if (cur_stack_elem < cur_stack_size - 2*STACK_GROW) { /* Prune the stack if it's too big. Disabled, so the stack can only expand */ /* cur_stack_size -= STACK_GROW; for (i = cur_stack_size - STACK_GROW; i < cur_stack_size; i++) free(stack[i]); stack = (giant *) realloc (stack,cur_stack_size * sizeof(giant)); */ } /* my_malloc our giant. */ if (stack[cur_stack_elem] == NULL) stack[cur_stack_elem] = (giant ) my_malloc(stack_glen*sizeof(short)+sizeof(int)); stack[cur_stack_elem]->sign = 0; return(stack[cur_stack_elem++]); } void pushg ( int a ) { if (a < 0) return; cur_stack_elem -= a; if (cur_stack_elem < 0) cur_stack_elem = 0; } giant newgiant( int numshorts ) { int size; giant thegiant; if (numshorts > MAX_SHORTS) { if (logFile) fprintf(logFile, "Requested giant too big.\n"); fflush(stderr); } if (numshorts<=0) numshorts = MAX_SHORTS; size = numshorts*sizeof(short)+sizeof(int); thegiant = (giant)my_malloc(size); thegiant->sign = 0; if (newmin(2*numshorts,MAX_SHORTS) > current_max_size) current_max_size = newmin(2*numshorts,MAX_SHORTS); /* If newgiant() is being called for the first time, set the * size of the stack giants. */ if (stack_glen == 0) stack_glen = current_max_size; return(thegiant); } gmatrix newgmatrix( void ) /* Allocates space for a gmatrix struct, but does not * allocate space for the giants. */ { return((gmatrix) my_malloc (4*sizeof(giant))); } int bitlen( giant n ) { int b = 16, c = 1<<15, w; if (isZero(n)) return(0); w = n->n[abs(n->sign) - 1]; while ((w&c) == 0) { b--; c >>= 1; } return (16*(abs(n->sign)-1) + b); } int bitval( giant n, int pos ) { int i = abs(pos)>>4, c = 1 << (pos&15); return (((n->n[i]) & c) != 0); } int isone( giant g ) { return((g->sign==1)&&(g->n[0]==1)); } int isZero( giant thegiant ) /* Returns TR if thegiant == 0. */ { register int count; int length = abs(thegiant->sign); register unsigned short * numpointer = thegiant->n; if (length) { for(count = 0; count<length; ++count,++numpointer) { if (*numpointer != 0 ) return(FA); } } return(TR); } void gtog( giant srcgiant, giant destgiant ) /* destgiant becomes equal to srcgiant. */ { int numbytes = sizeof(int) + abs(srcgiant->sign)*sizeof(short); memcpy((char *)destgiant,(char *)srcgiant,numbytes); } void itog( int i, giant g ) /* The giant g becomes set to the integer value i. */ { unsigned int j = abs(i); if (i==0) { g->sign = 0; g->n[0] = 0; return; } g->n[0] = (unsigned short)(j & 0xFFFF); j >>= 16; if (j) { g->n[1] = (unsigned short)j; g->sign = 2; } else { g->sign = 1; } if (i<0) g->sign = -(g->sign); } signed int gtoi( giant x ) /* Calculate the value of an int-sized giant NOT exceeding 31 bits. */ { register int size = abs(x->sign); register int sign = (x->sign < 0) ? -1 : 1; switch(size) { case 0: break; case 1: return sign * x->n[0]; case 2: return sign * (x->n[0]+((x->n[1])<<16)); default: if (logFile) fprintf(logFile,"Giant too large for gtoi\n"); break; } return 0; } int gsign( giant g ) /* Returns the sign of g. */ { if (isZero(g)) return(0); if (g->sign >0) return(1); return(-1); } int gcompg( giant a, giant b ) /* Returns -1,0,1 if a<b, a=b, a>b, respectively. */ { int sa = a->sign, j, sb = b->sign, va, vb, sgn; if(sa > sb) return(1); if(sa < sb) return(-1); if(sa < 0) { sa = -sa; /* Take absolute value of sa. */ sgn = -1; } else { sgn = 1; } for(j = sa-1; j >= 0; j--) { va = a->n[j]; vb = b->n[j]; if (va > vb) return(sgn); if (va < vb) return(-sgn); } return(0); } void setmulmode( int mode ) { mulmode = mode; } /************************************************************** * * Private I/O Functions * **************************************************************/ int radixdiv( int base, int divisor, giant thegiant ) /* Divides giant of arbitrary base by divisor. * Returns remainder. Used by idivg and gread. */ { int first = TR; int finalsize = abs(thegiant->sign); int j = finalsize-1; unsigned short *digitpointer=&thegiant->n[j]; unsigned int num,rem=0; if (divisor == 0) { error = DIVIDEBYZERO; exit(error); } while (j>=0) { num=rem*base + *digitpointer; *digitpointer = (unsigned short)(num/divisor); if (first) { if (*digitpointer == 0) --finalsize; else first = FA; } rem = num % divisor; --digitpointer; --j; } if ((divisor<0) ^ (thegiant->sign<0)) finalsize=-finalsize; thegiant->sign=finalsize; return(rem); } void columnwrite( FILE *filepointer, short *column, char *format, short arg, int newlines ) /* Used by gwriteln. */ { char outstring[10]; short i; sprintf(outstring,format,arg); for (i=0; outstring[i]!=0; ++i) { if (newlines) { if (*column >= COLUMNWIDTH) { fputs("\\\n",filepointer); *column = 0; } } fputc(outstring[i],filepointer); ++*column; } } void gwrite( giant thegiant, FILE *filepointer, int newlines ) /* Outputs thegiant to filepointer. Output is terminated by a newline. */ { short column; unsigned int i; unsigned short *numpointer; giant garbagegiant, basetengrand; basetengrand = popg(); garbagegiant = popg(); if (isZero(thegiant)) { fputs("0",filepointer); } else { numpointer = basetengrand->n; gtog(thegiant,garbagegiant); basetengrand->sign = 0; do { *numpointer = (unsigned short)idivg(10000,garbagegiant); ++numpointer; if (++basetengrand->sign >= current_max_size) { error = OVFLOW; exit(error); } } while (!isZero(garbagegiant)); if (!error) { i = basetengrand->sign-1; column = 0; if (thegiant->sign<0 && basetengrand->n[i]!=0) columnwrite(filepointer,&column,"-",0, newlines); columnwrite(filepointer,&column,"%d",basetengrand->n[i],newlines); for( ; i>0; ) { --i; columnwrite(filepointer,&column,"%04d",basetengrand->n[i],newlines); } } } pushg(2); } void gwriteln( giant theg, FILE *filepointer ) { gwrite(theg, filepointer, 1); fputc('\n',filepointer); } void gread( giant theg, FILE *filepointer ) { char currentchar; int isneg,size,backslash=FA,numdigits=0; unsigned short *numpointer; giant basetenthousand; static char *inbuf = NULL; basetenthousand = popg(); if (inbuf == NULL) inbuf = (char*)my_malloc(MAX_DIGITS); currentchar = (char)fgetc(filepointer); if (currentchar=='-') { isneg=TR; } else { isneg=FA; if (currentchar!='+') ungetc(currentchar,filepointer); } do { currentchar = (char)fgetc(filepointer); if ((currentchar>='0') && (currentchar<='9')) { inbuf[numdigits]=currentchar; if(++numdigits==MAX_DIGITS) break; backslash=FA; } else { if (currentchar=='\\') backslash=TR; } } while(((currentchar!=' ') && (currentchar!='\n') && (currentchar!='\t')) || (backslash) ); if (numdigits) { size = 0; do { inbuf[numdigits] = 0; numdigits-=4; if (numdigits<0) numdigits=0; basetenthousand->n[size] = (unsigned short)strtol(&inbuf[numdigits],NULL,10); ++size; } while (numdigits>0); basetenthousand->sign = size; theg->sign = 0; numpointer = theg->n; do { *numpointer = (unsigned short) radixdiv(10000,1<<(8*sizeof(short)),basetenthousand); ++numpointer; if (++theg->sign >= current_max_size) { error = OVFLOW; exit(error); } } while (!isZero(basetenthousand)); if (isneg) theg->sign = -theg->sign; } pushg(1); } /************************************************************** * * Private Math Functions * **************************************************************/ void negg( giant g ) /* g becomes -g. */ { g->sign = -g->sign; } void absg( giant g ) { /* g becomes the absolute value of g. */ if (g->sign <0) g->sign=-g->sign; } void iaddg( int i, giant g ) /* Giant g becomes g + (int)i. */ { int w,j=0,carry = 0, size = abs(g->sign); giant tmp; if (isZero(g)) { itog(i,g); } else if(g->sign < 0) { tmp = popg(); itog(i, tmp); addg(tmp, g); pushg(1); return; } else { w = g->n[0]+i; do { g->n[j] = (unsigned short) (w & 65535L); carry = w >> 16; w = g->n[++j]+carry; } while ((carry!=0) && (j<size)); } if (carry) { ++g->sign; g->n[size] = (unsigned short)carry; } } /* New subtract routines. The basic subtract "subg()" uses the following logic table: a b if(b > a) if(a > b) + + b := b - a b := -(a - b) - + b := b + (-a) N.A. + - N.A. b := -((-b) + a) - - b := (-a) - (-b) b := -((-b) - (-a)) The basic addition routine "addg()" uses: a b if(b > -a) if(-a > b) + + b := b + a N.A. - + b := b - (-a) b := -((-a) - b) + - b := a - (-b) b := -((-b) - a) - - N.A. b := -((-b) + (-a)) In this way, internal routines "normal_addg," "normal_subg," and "reverse_subg;" each of which assumes non-negative operands and a non-negative result, are now used for greater efficiency. */ void normal_addg( giant a, giant b ) /* b := a + b, both a,b assumed non-negative. */ { int carry = 0; int asize = a->sign, bsize = b->sign; long k; int j=0; unsigned short *aptr = a->n, *bptr = b->n; if (asize < bsize) { for (j=0; j<asize; j++) { k = *aptr++ + *bptr + carry; carry = 0; if (k >= 65536L) { k -= 65536L; ++carry; } *bptr++ = (unsigned short)k; } for (j=asize; j<bsize; j++) { k = *bptr + carry; carry = 0; if (k >= 65536L) { k -= 65536L; ++carry; } *bptr++ = (unsigned short)k; } } else { for (j=0; j<bsize; j++) { k = *aptr++ + *bptr + carry; carry = 0; if (k >= 65536L) { k -= 65536L; ++carry; } *bptr++ = (unsigned short)k; } for (j=bsize; j<asize; j++) { k = *aptr++ + carry; carry = 0; if (k >= 65536L) { k -= 65536L; ++carry; } *bptr++ = (unsigned short)k; } } if (carry) { *bptr = 1; ++j; } b->sign = j; } void normal_subg( giant a, giant b ) /* b := b - a; requires b, a non-negative and b >= a. */ { int j, size = b->sign; unsigned int k; if (a->sign == 0) return; k = 0; for (j=0; j<a->sign; ++j) { k += 0xffff - a->n[j] + b->n[j]; b->n[j] = (unsigned short)(k & 0xffff); k >>= 16; } for (j=a->sign; j<size; ++j) { k += 0xffff + b->n[j]; b->n[j] = (unsigned short)(k & 0xffff); k >>= 16; } if (b->n[0] == 0xffff) iaddg(1,b); else ++b->n[0]; while ((size-- > 0) && (b->n[size]==0)); b->sign = (b->n[size]==0) ? 0 : size+1; } void reverse_subg( giant a, giant b ) /* b := a - b; requires b, a non-negative and a >= b. */ { int j, size = a->sign; unsigned int k; k = 0; for (j=0; j<b->sign; ++j) { k += 0xffff - b->n[j] + a->n[j]; b->n[j] = (unsigned short)(k & 0xffff); k >>= 16; } for (j=b->sign; j<size; ++j) { k += 0xffff + a->n[j]; b->n[j] = (unsigned short)(k & 0xffff); k >>= 16; } b->sign = size; /* REC, 21 Apr 1996. */ if (b->n[0] == 0xffff) iaddg(1,b); else ++b->n[0]; while (!b->n[--size]); b->sign = size+1; } void addg( giant a, giant b ) /* b := b + a, any signs any result. */ { int asgn = a->sign, bsgn = b->sign; if (asgn == 0) return; if (bsgn == 0) { gtog(a,b); return; } if ((asgn < 0) == (bsgn < 0)) { if (bsgn > 0) { normal_addg(a,b); return; } absg(b); if(a != b) absg(a); normal_addg(a,b); negg(b); if(a != b) negg(a); return; } if(bsgn > 0) { negg(a); if (gcompg(b,a) >= 0) { normal_subg(a,b); negg(a); return; } reverse_subg(a,b); negg(a); negg(b); return; } negg(b); if(gcompg(b,a) < 0) { reverse_subg(a,b); return; } normal_subg(a,b); negg(b); return; } void subg( giant a, giant b ) /* b := b - a, any signs, any result. */ { int asgn = a->sign, bsgn = b->sign; if (asgn == 0) return; if (bsgn == 0) { gtog(a,b); negg(b); return; } if ((asgn < 0) != (bsgn < 0)) { if (bsgn > 0) { negg(a); normal_addg(a,b); negg(a); return; } negg(b); normal_addg(a,b); negg(b); return; } if (bsgn > 0) { if (gcompg(b,a) >= 0) { normal_subg(a,b); return; } reverse_subg(a,b); negg(b); return; } negg(a); negg(b); if (gcompg(b,a) >= 0) { normal_subg(a,b); negg(a); negg(b); return; } reverse_subg(a,b); negg(a); return; } int numtrailzeros( giant g ) /* Returns the number of trailing zero bits in g. */ { register int numshorts = abs(g->sign), j, bcount=0; register unsigned short gshort, c; for (j=0;j<numshorts;j++) { gshort = g->n[j]; c = 1; for (bcount=0;bcount<16; bcount++) { if (c & gshort) break; c <<= 1; } if (bcount<16) break; } return(bcount + 16*j); } void bdivg( giant v, giant u ) /* u becomes greatest power of two not exceeding u/v. */ { int diff = bitlen(u) - bitlen(v); giant scratch7; if (diff<0) { itog(0,u); return; } scratch7 = popg(); gtog(v, scratch7); gshiftleft(diff,scratch7); if (gcompg(u,scratch7) < 0) diff--; if (diff<0) { itog(0,u); pushg(1); return; } itog(1,u); gshiftleft(diff,u); pushg(1); } int binvaux( giant p, giant x ) /* Binary inverse method. Returns zero if no inverse exists, * in which case x becomes GCD(x,p). */ { giant scratch7, u0, u1, v0, v1; if (isone(x)) return(1); u0 = popg(); u1 = popg(); v0 = popg(); v1 = popg(); itog(1, v0); gtog(x, v1); itog(0,x); gtog(p, u1); scratch7 = popg(); while(!isZero(v1)) { gtog(u1, u0); bdivg(v1, u0); gtog(x, scratch7); gtog(v0, x); mulg(u0, v0); subg(v0,scratch7); gtog(scratch7, v0); gtog(u1, scratch7); gtog(v1, u1); mulg(u0, v1); subg(v1,scratch7); gtog(scratch7, v1); } pushg(1); if (!isone(u1)) { gtog(u1,x); if(x->sign<0) addg(p, x); pushg(4); return(0); } if(x->sign<0) addg(p, x); pushg(4); return(1); } int binvg( giant p, giant x ) { modg(p, x); return(binvaux(p,x)); } int invg( giant p, giant x ) { modg(p, x); return(invaux(p,x)); } int invaux( giant p, giant x ) /* Returns zero if no inverse exists, in which case x becomes * GCD(x,p). */ { giant scratch7, u0, u1, v0, v1; if ((x->sign==1)&&(x->n[0]==1)) return(1); u0 = popg(); u1 = popg(); v0 = popg(); v1 = popg(); itog(1,u1); gtog(p, v0); gtog(x, v1); itog(0,x); scratch7 = popg(); while (!isZero(v1)) { gtog(v0, u0); divg(v1, u0); gtog(u0, scratch7); mulg(v1, scratch7); subg(v0, scratch7); negg(scratch7); gtog(v1, v0); gtog(scratch7, v1); gtog(u1, scratch7); mulg(u0, scratch7); subg(x, scratch7); negg(scratch7); gtog(u1,x); gtog(scratch7, u1); } pushg(1); if ((v0->sign!=1)||(v0->n[0]!=1)) { gtog(v0,x); pushg(4); return(0); } if(x->sign<0) addg(p, x); pushg(4); return(1); } int mersenneinvg( int q, giant x ) { int k; giant u0, u1, v1; u0 = popg(); u1 = popg(); v1 = popg(); itog(1, u0); itog(0, u1); itog(1, v1); gshiftleft(q, v1); subg(u0, v1); mersennemod(q, x); while (1) { k = -1; if (isZero(x)) { gtog(v1, x); pushg(3); return(0); } while (bitval(x, ++k) == 0); gshiftright(k, x); if (k) { gshiftleft(q-k, u0); mersennemod(q, u0); } if (isone(x)) break; addg(u1, u0); mersennemod(q, u0); negg(u1); addg(u0, u1); mersennemod(q, u1); if (!gcompg(v1,x)) { pushg(3); return(0); } addg(v1, x); negg(v1); addg(x, v1); mersennemod(q, v1); } gtog(u0, x); mersennemod(q,x); pushg(3); return(1); } void cgcdg( giant a, giant v ) /* Classical Euclid GCD. v becomes gcd(a, v). */ { giant u, r; v->sign = abs(v->sign); if (isZero(a)) return; u = popg(); r = popg(); gtog(a, u); u->sign = abs(u->sign); while (!isZero(v)) { gtog(u, r); modg(v, r); gtog(v, u); gtog(r, v); } gtog(u,v); pushg(2); } void gcdg( giant x, giant y ) { if (bitlen(y)<= GCDLIMIT) bgcdg(x,y); else ggcd(x,y); } void bgcdg( giant a, giant b ) /* Binary form of the gcd. b becomes the gcd of a,b. */ { int k = isZero(b), m = isZero(a); giant u, v, t; if (k || m) { if (m) { if (k) itog(1,b); return; } if (k) { if (m) itog(1,b); else gtog(a,b); return; } } u = popg(); v = popg(); t = popg(); /* Now neither a nor b is zero. */ gtog(a, u); u->sign = abs(a->sign); gtog(b, v); v->sign = abs(b->sign); k = numtrailzeros(u); m = numtrailzeros(v); if (k>m) k = m; gshiftright(k,u); gshiftright(k,v); if (u->n[0] & 1) { gtog(v, t); negg(t); } else { gtog(u,t); } while (!isZero(t)) { m = numtrailzeros(t); gshiftright(m, t); if (t->sign > 0) { gtog(t, u); subg(v,t); } else { gtog(t, v); negg(v); addg(u,t); } } gtog(u,b); gshiftleft(k, b); pushg(3); } void powerg( int m, int n, giant g ) /* g becomes m^n, NO mod performed. */ { giant scratch2 = popg(); itog(1, g); itog(m, scratch2); while (n) { if (n & 1) mulg(scratch2, g); n >>= 1; if (n) squareg(scratch2); } pushg(1); } void make_recip( giant d, giant r ) /* r becomes the steady-state reciprocal * 2^(2b)/d, where b = bit-length of d-1. */ { int b; giant tmp, tmp2; if (isZero(d) || (d->sign < 0)) { exit(SIGN); } tmp = popg(); tmp2 = popg(); itog(1, r); subg(r, d); b = bitlen(d); addg(r, d); gshiftleft(b, r); gtog(r, tmp2); while (1) { gtog(r, tmp); squareg(tmp); gshiftright(b, tmp); mulg(d, tmp); gshiftright(b, tmp); addg(r, r); subg(tmp, r); if (gcompg(r, tmp2) <= 0) break; gtog(r, tmp2); } itog(1, tmp); gshiftleft(2*b, tmp); gtog(r, tmp2); mulg(d, tmp2); subg(tmp2, tmp); itog(1, tmp2); while (tmp->sign < 0) { subg(tmp2, r); addg(d, tmp); } pushg(2); } void divg_via_recip( giant d, giant r, giant n ) /* n := n/d, where r is the precalculated * steady-state reciprocal of d. */ { int s = 2*(bitlen(r)-1), sign = gsign(n); giant tmp, tmp2; if (isZero(d) || (d->sign < 0)) { exit(SIGN); } tmp = popg(); tmp2 = popg(); n->sign = abs(n->sign); itog(0, tmp2); while (1) { gtog(n, tmp); mulg(r, tmp); gshiftright(s, tmp); addg(tmp, tmp2); mulg(d, tmp); subg(tmp, n); if (gcompg(n,d) >= 0) { subg(d,n); iaddg(1, tmp2); } if (gcompg(n,d) < 0) break; } gtog(tmp2, n); n->sign *= sign; pushg(2); } #if 1 void modg_via_recip( giant d, giant r, giant n ) /* This is the fastest mod of the present collection. * n := n % d, where r is the precalculated * steady-state reciprocal of d. */ { int s = (bitlen(r)-1), sign = n->sign; giant tmp, tmp2; if (isZero(d) || (d->sign < 0)) { exit(SIGN); } tmp = popg(); tmp2 = popg(); n->sign = abs(n->sign); while (1) { gtog(n, tmp); gshiftright(s-1, tmp); mulg(r, tmp); gshiftright(s+1, tmp); mulg(d, tmp); subg(tmp, n); if (gcompg(n,d) >= 0) subg(d,n); if (gcompg(n,d) < 0) break; } if (sign >= 0) goto done; if (isZero(n)) goto done; negg(n); addg(d,n); done: pushg(2); return; } #else void modg_via_recip( giant d, giant r, giant n ) { int s = 2*(bitlen(r)-1), sign = n->sign; giant tmp, tmp2; if (isZero(d) || (d->sign < 0)) { exit(SIGN); } tmp = popg(); tmp2 = popg() n->sign = abs(n->sign); while (1) { gtog(n, tmp); mulg(r, tmp); gshiftright(s, tmp); mulg(d, tmp); subg(tmp, n); if (gcompg(n,d) >= 0) subg(d,n); if (gcompg(n,d) < 0) break; } if (sign >= 0) goto done; if (isZero(n)) goto done; negg(n); addg(d,n); done: pushg(2); return; } #endif void modg( giant d, giant n ) /* n becomes n%d. n is arbitrary, but the denominator d must be positive! */ { if (cur_recip == NULL) { cur_recip = newgiant(current_max_size); cur_den = newgiant(current_max_size); gtog(d, cur_den); make_recip(d, cur_recip); } else if (gcompg(d, cur_den)) { gtog(d, cur_den); make_recip(d, cur_recip); } modg_via_recip(d, cur_recip, n); } int idivg( int divisor, giant theg ) { /* theg becomes theg/divisor. Returns remainder. */ int n; int base = 1<<(8*sizeof(short)); n = radixdiv(base,divisor,theg); return(n); } void divg( giant d, giant n ) /* n becomes n/d. n is arbitrary, but the denominator d must be positive! */ { if (cur_recip == NULL) { cur_recip = newgiant(current_max_size); cur_den = newgiant(current_max_size); gtog(d, cur_den); make_recip(d, cur_recip); } else if (gcompg(d, cur_den)) { gtog(d, cur_den); make_recip(d, cur_recip); } divg_via_recip(d, cur_recip, n); } void powermod( giant x, int n, giant g ) /* x becomes x^n (mod g). */ { giant scratch2 = popg(); gtog(x, scratch2); itog(1, x); while (n) { if (n & 1) { mulg(scratch2, x); modg(g, x); } n >>= 1; if (n) { squareg(scratch2); modg(g, scratch2); } } pushg(1); } void powermodg( giant x, giant n, giant g ) /* x becomes x^n (mod g). */ { int len, pos; giant scratch2 = popg(); gtog(x, scratch2); itog(1, x); len = bitlen(n); pos = 0; while (1) { if (bitval(n, pos++)) { mulg(scratch2, x); modg(g, x); } if (pos>=len) break; squareg(scratch2); modg(g, scratch2); } pushg(1); } void fermatpowermod( giant x, int n, int q ) /* x becomes x^n (mod 2^q+1). */ { giant scratch2 = popg(); gtog(x, scratch2); itog(1, x); while (n) { if (n & 1) { mulg(scratch2, x); fermatmod(q, x); } n >>= 1; if (n) { squareg(scratch2); fermatmod(q, scratch2); } } pushg(1); } void fermatpowermodg( giant x, giant n, int q ) /* x becomes x^n (mod 2^q+1). */ { giant scratch2 = popg(), scratch3 = popg(); gtog(x, scratch2); gtog(n, scratch3); itog(1, x); while (!isZero(scratch3)) { if (bitval(scratch3, 0)) { mulg(scratch2, x); fermatmod(q, x); } squareg(scratch2); fermatmod(q, scratch2); gshiftright(1, scratch3); } pushg(2); } void mersennepowermod( giant x, int n, int q ) /* x becomes x^n (mod 2^q-1). */ { giant scratch2 = popg(); gtog(x, scratch2); itog(1, x); while (n) { if (n & 1) { mulg(scratch2, x); mersennemod(q, x); } n >>= 1; if (n) { squareg(scratch2); mersennemod(q, scratch2); } } pushg(1); } void mersennepowermodg( giant x, giant n, int q ) /* x becomes x^n (mod 2^q-1). */ { giant scratch2 = popg(), scratch3 = popg(); gtog(x, scratch2); gtog(n, scratch3); itog(1, x); while (!isZero(scratch3)) { if (bitval(scratch3, 0)) { mulg(scratch2, x); mersennemod(q, x); } squareg(scratch2); mersennemod(q, scratch2); gshiftright(1, scratch3); } pushg(1); } void gshiftleft( int bits, giant g ) /* shift g left bits bits. Equivalent to g = g*2^bits. */ { int rem = bits&15, crem = 16-rem, words = bits>>4; int size = abs(g->sign), j, k, sign = gsign(g); unsigned short carry, dat; if (!bits) return; if (!size) return; if (bits < 0) { gshiftright(-bits,g); return; } if (size+words+1 > current_max_size) { error = OVFLOW; exit(error); } if (rem == 0) { memmove(g->n + words, g->n, size * sizeof(short)); for (j = 0; j < words; j++) g->n[j] = 0; g->sign += (g->sign < 0)?(-words):(words); } else { k = size+words; carry = 0; for (j=size-1; j>=0; j--) { dat = g->n[j]; g->n[k--] = (unsigned short)((dat >> crem) | carry); carry = (unsigned short)(dat << rem); } do { g->n[k--] = carry; carry = 0; } while(k>=0); k = size+words; if (g->n[k] == 0) --k; g->sign = sign*(k+1); } } void gshiftright( int bits, giant g ) /* shift g right bits bits. Equivalent to g = g/2^bits. */ { register int j,size=abs(g->sign); register unsigned int carry; int words = bits >> 4; int remain = bits & 15, cremain = (16-remain); if (bits==0) return; if (isZero(g)) return; if (bits < 0) { gshiftleft(-bits,g); return; } if (words >= size) { g->sign = 0; return; } if (remain == 0) { memmove(g->n,g->n + words,(size - words) * sizeof(short)); g->sign += (g->sign < 0)?(words):(-words); } else { size -= words; if (size) { for(j=0;j<size-1;++j) { carry = g->n[j+words+1] << cremain; g->n[j] = (unsigned short)((g->n[j+words] >> remain ) | carry); } g->n[size-1] = (unsigned short)(g->n[size-1+words] >> remain); } if (g->n[size-1] == 0) --size; if (g->sign > 0) g->sign = size; else g->sign = -size; } } void extractbits( int n, giant src, giant dest ) /* dest becomes lowermost n bits of src. Equivalent to dest = src % 2^n. */ { register int words = n >> 4, numbytes = words*sizeof(short); register int bits = n & 15; if (n<=0) return; if (words >= abs(src->sign)) gtog(src,dest); else { memcpy((char *)(dest->n), (char *)(src->n), numbytes); if (bits) { dest->n[words] = (unsigned short)(src->n[words] & ((1<<bits)-1)); ++words; } while ((dest->n[words-1] == 0) && (words > 0)) { --words; } if (src->sign<0) dest->sign = -words; else dest->sign = words; } } int allzeros( int shorts, int bits, giant g ) { int i=shorts; while (i>0) { if (g->n[--i]) return(0); } return((int)(!(g->n[shorts] & ((1<<bits)-1)))); } void fermatnegate( int n, giant g ) /* negate g. g is mod 2^n+1. */ { register int shorts = n>>4, bits = n & 15, i = shorts, mask = 1<<bits; register unsigned carry,temp; for (temp=(unsigned)shorts; (int)temp>g->sign-1; --temp) { g->n[temp] = 0; } if (g->n[shorts] & mask) { /* if high bit is set, -g = 1. */ g->sign = 1; g->n[0] = 1; return; } if (allzeros(shorts,bits,g)) return; /* if g=0, -g = 0. */ while (i>0) { --i; g->n[i] = (unsigned short)(~(g->n[i+1])); } g->n[shorts] ^= mask-1; carry = 2; i = 0; while (carry) { temp = g->n[i]+carry; g->n[i++] = (unsigned short)(temp & 0xffff); carry = temp>>16; } while(!g->n[shorts]) { --shorts; } g->sign = shorts+1; } void mersennemod ( int n, giant g ) /* g := g (mod 2^n - 1) */ { giant scratch3 = popg(), scratch4 = popg(); while (bitlen(g) > n) { gtog(g,scratch3); gshiftright(n,scratch3); addg(scratch3,g); gshiftleft(n,scratch3); subg(scratch3,g); } itog(1,scratch3); gshiftleft(n,scratch3); itog(1,scratch4); subg(scratch4,scratch3); if(gsign(g) < 0) addg(scratch3,g); if(gcompg(g,scratch3) == 0) itog(0,g); pushg(2); } void fermatmod ( int n, giant g ) /* g := g (mod 2^n + 1), */ { giant scratch3 = popg(); while (bitlen(g) > n) { gtog(g,scratch3); gshiftright(n,scratch3); subg(scratch3,g); gshiftleft(n,scratch3); subg(scratch3,g); } if(gsign(g) < 0) { itog(1,scratch3); gshiftleft(n,scratch3); addg(scratch3,g); iaddg(1,g); } pushg(1); } void fer_mod ( int n, giant g, giant modulus ) /* Same as fermatmod(), except modulus = 2^n + 1 should be passed if available (i.e. if already allocated and set). */ { giant scratch3 = popg(); while (bitlen(g) > n) { gtog(g,scratch3); gshiftright(n,scratch3); subg(scratch3,g); gshiftleft(n,scratch3); subg(scratch3,g); } if(gsign(g) < 0) addg(modulus,g); pushg(1); } void smulg( unsigned short i, giant g ) /* g becomes g * i. */ { unsigned short carry = 0; int size = abs(g->sign); register int j,k,mul = abs(i); unsigned short *digit = g->n; for (j=0; j<size; ++j) { k = *digit * mul + carry; carry = (unsigned short)(k>>16); *digit = (unsigned short)(k & 0xffff); ++digit; } if (carry) { if (++j >= current_max_size) { error = OVFLOW; exit(error); } *digit = carry; } if ((g->sign>0) ^ (i>0)) g->sign = -j; else g->sign = j; } void squareg( giant b ) /* b becomes b^2. */ { auxmulg(b,b); } void mulg( giant a, giant b ) /* b becomes a*b. */ { auxmulg(a,b); } void auxmulg( giant a, giant b ) /* Optimized general multiply, b becomes a*b. Modes are: * AUTO_MUL: switch according to empirical speed criteria. * GRAMMAR_MUL: force grammar-school algorithm. * KARAT_MUL: force Karatsuba divide-conquer method. * FFT_MUL: force floating point FFT method. */ { float grammartime; int square = (a==b); int sizea, sizeb; switch (mulmode) { case GRAMMAR_MUL: if (square) grammarsquareg(b); else grammarmulg(a,b); break; case FFT_MUL: if (square) FFTsquareg(b); else FFTmulg(a,b); break; case KARAT_MUL: if (square) karatsquareg(b); else karatmulg(a,b); break; case AUTO_MUL: sizea = abs(a->sign); sizeb = abs(b->sign); if((sizea > KARAT_BREAK) && (sizea <= FFT_BREAK) && (sizeb > KARAT_BREAK) && (sizeb <= FFT_BREAK)){ if(square) karatsquareg(b); else karatmulg(a,b); } else { grammartime = (float)sizea; grammartime *= (float)sizeb; if (grammartime < FFT_BREAK * FFT_BREAK) { if (square) grammarsquareg(b); else grammarmulg(a,b); } else { if (square) FFTsquareg(b); else FFTmulg(a,b); } } break; } } void justg(giant x) { int s = x->sign, sg = 1; if(s<0) { sg = -1; s = -s; } --s; while(x->n[s] == 0) { --s; if(s < 0) break; } x->sign = sg*(s+1); } /* Next, improved Karatsuba routines from A. Powell, improvements by G. Woltman. */ void karatmulg(giant x, giant y) /* y becomes x*y. */ { int s = abs(x->sign), t = abs(y->sign), w, bits, sg = gsign(x)*gsign(y); giant a, b, c, d, e, f; if((s <= KARAT_BREAK) || (t <= KARAT_BREAK)) { grammarmulg(x,y); return; } w = (s + t + 2)/4; bits = 16*w; a = popg(); b = popg(); c = popg(); d = popg(); e = popg(); f = popg(); gtog(x,a); absg(a); if (w <= s) {a->sign = w; justg(a);} gtog(x,b); absg(b); gshiftright(bits, b); gtog(y,c); absg(c); if (w <= t) {c->sign = w; justg(c);} gtog(y,d); absg(d); gshiftright(bits,d); gtog(a,e); normal_addg(b,e); /* e := (a + b) */ gtog(c,f); normal_addg(d,f); /* f := (c + d) */ karatmulg(e,f); /* f := (a + b)(c + d) */ karatmulg(c,a); /* a := a c */ karatmulg(d,b); /* b := b d */ normal_subg(a,f); /* f := (a + b)(c + d) - a c */ normal_subg(b,f); /* f := (a + b)(c + d) - a c - b d */ gshiftleft(bits, b); normal_addg(f, b); gshiftleft(bits, b); normal_addg(a, b); gtog(b, y); y->sign *= sg; pushg(6); return; } void karatsquareg(giant x) /* x becomes x^2. */ { int s = abs(x->sign), w, bits; giant a, b, c; if(s <= KARAT_BREAK) { grammarsquareg(x); return; } w = (s+1)/2; bits = 16*w; a = popg(); b = popg(); c = popg(); gtog(x, a); a->sign = w; justg(a); gtog(x, b); absg(b); gshiftright(bits, b); gtog(a,c); normal_addg(b,c); karatsquareg(c); karatsquareg(a); karatsquareg(b); normal_subg(b, c); normal_subg(a, c); gshiftleft(bits, b); normal_addg(c,b); gshiftleft(bits, b); normal_addg(a, b); gtog(b, x); pushg(3); return; } void grammarmulg( giant a, giant b ) /* b becomes a*b. */ { int i,j; unsigned int prod,carry=0; int asize = abs(a->sign), bsize = abs(b->sign); unsigned short *aptr,*bptr,*destptr; unsigned short mult; giant scratch = popg(); for (i=0; i<asize+bsize; ++i) { scratch->n[i]=0; } bptr = &(b->n[0]); for (i=0; i<bsize; ++i) { mult = *(bptr++); if (mult) { carry = 0; aptr = &(a->n[0]); destptr = &(scratch->n[i]); for (j=0; j<asize; ++j) { prod = *(aptr++) * mult + *destptr + carry; *(destptr++) = (unsigned short)(prod & 0xffff); carry = prod >> 16; } *destptr = (unsigned short)carry; } } bsize+=asize; if (!carry) --bsize; scratch->sign = gsign(a)*gsign(b)*bsize; gtog(scratch,b); pushg(1); } void grammarsquareg ( giant a ) /* a := a^2. */ { unsigned int cur_term; unsigned int prod, carry=0, temp; int asize = abs(a->sign), max = asize * 2 - 1; unsigned short *ptr = a->n, *ptr1, *ptr2; giant scratch; if(asize == 0) { itog(0,a); return; } scratch = popg(); asize--; temp = *ptr; temp *= temp; scratch->n[0] = temp; carry = temp >> 16; for (cur_term = 1; cur_term < max; cur_term++) { ptr1 = ptr2 = ptr; if (cur_term <= asize) { ptr2 += cur_term; } else { ptr1 += cur_term - asize; ptr2 += asize; } prod = carry & 0xFFFF; carry >>= 16; while(ptr1 < ptr2) { temp = *ptr1++ * *ptr2--; prod += (temp << 1) & 0xFFFF; carry += (temp >> 15); } if (ptr1 == ptr2) { temp = *ptr1; temp *= temp; prod += temp & 0xFFFF; carry += (temp >> 16); } carry += prod >> 16; scratch->n[cur_term] = (unsigned short) (prod); } if (carry) { scratch->n[cur_term] = carry; scratch->sign = cur_term+1; } else scratch->sign = cur_term; gtog(scratch,a); pushg(1); } /************************************************************** * * FFT multiply Functions * **************************************************************/ int initL = 0; int lpt( int n, int *lambda ) /* Returns least power of two greater than n. */ { register int i = 1; *lambda = 0; while (i<n) { i<<=1; ++(*lambda); } return(i); } void addsignal( giant x, double *z, int n ) { register int j, k, m, car, last; register double f, g,err; maxFFTerror = 0; last = 0; for (j=0;j<n;j++) { f = gfloor(z[j]+0.5); if(f != 0.0) last = j; if (checkFFTerror) { err = fabs(f - z[j]); if (err > maxFFTerror) maxFFTerror = err; } z[j] =0; k = 0; do { g = gfloor(f*TWOM16); z[j+k] += f-g*TWO16; ++k; f=g; } while(f != 0.0); } car = 0; for(j=0;j < last + 1;j++) { m = (int)(z[j]+car); x->n[j] = (unsigned short)(m & 0xffff); car = (m>>16); } if (car) x->n[j] = (unsigned short)car; else --j; while(!(x->n[j])) --j; x->sign = j+1; } void FFTsquareg( giant x ) { int j,size = abs(x->sign); register int L; if (size<4) { grammarmulg(x,x); return; } L = lpt(size+size, &j); if(!z) z = (double *)my_malloc(MAX_SHORTS * sizeof(double)); giant_to_double(x, size, z, L); fft_real_to_hermitian(z, L); square_hermitian(z, L); fftinv_hermitian_to_real(z, L); addsignal(x,z,L); x->sign = abs(x->sign); } void FFTmulg( giant y, giant x ) { /* x becomes y*x. */ int lambda, sizex = abs(x->sign), sizey = abs(y->sign); int finalsign = gsign(x)*gsign(y); register int L; if ((sizex<=4)||(sizey<=4)) { grammarmulg(y,x); return; } L = lpt(sizex+sizey, &lambda); if(!z) z = (double *)my_malloc(MAX_SHORTS * sizeof(double)); if(!z2) z2 = (double *)my_malloc(MAX_SHORTS * sizeof(double)); giant_to_double(x, sizex, z, L); giant_to_double(y, sizey, z2, L); fft_real_to_hermitian(z, L); fft_real_to_hermitian(z2, L); mul_hermitian(z2, z, L); fftinv_hermitian_to_real(z, L); addsignal(x,z,L); x->sign = finalsign*abs(x->sign); } void scramble_real( double *x, int n ) { register int i,j,k; register double tmp; for (i=0,j=0;i<n-1;i++) { if (i<j) { tmp = x[j]; x[j]=x[i]; x[i]=tmp; } k = n/2; while (k<=j) { j -= k; k>>=1; } j += k; } } void fft_real_to_hermitian( double *z, int n ) /* Output is {Re(z^[0]),...,Re(z^[n/2),Im(z^[n/2-1]),...,Im(z^[1]). * This is a decimation-in-time, split-radix algorithm. */ { register double cc1, ss1, cc3, ss3; register int is, id, i0, i1, i2, i3, i4, i5, i6, i7, i8, a, a3, b, b3, nminus = n-1, dil, expand; register double *x, e; int nn = n>>1; double t1, t2, t3, t4, t5, t6; register int n2, n4, n8, i, j; init_sinCos(n); expand = cur_run/n; scramble_real(z, n); x = z-1; /* FORTRAN compatibility. */ is = 1; id = 4; do { for (i0=is;i0<=n;i0+=id) { i1 = i0+1; e = x[i0]; x[i0] = e + x[i1]; x[i1] = e - x[i1]; } is = (id<<1)-1; id <<= 2; } while(is<n); n2 = 2; while(nn>>=1) { n2 <<= 1; n4 = n2>>2; n8 = n2>>3; is = 0; id = n2<<1; do { for (i=is;i<n;i+=id) { i1 = i+1; i2 = i1 + n4; i3 = i2 + n4; i4 = i3 + n4; t1 = x[i4]+x[i3]; x[i4] -= x[i3]; x[i3] = x[i1] - t1; x[i1] += t1; if (n4==1) continue; i1 += n8; i2 += n8; i3 += n8; i4 += n8; t1 = (x[i3]+x[i4])*SQRTHALF; t2 = (x[i3]-x[i4])*SQRTHALF; x[i4] = x[i2] - t1; x[i3] = -x[i2] - t1; x[i2] = x[i1] - t2; x[i1] += t2; } is = (id<<1) - n2; id <<= 2; } while(is<n); dil = n/n2; a = dil; for (j=2;j<=n8;j++) { a3 = (a+(a<<1))&nminus; b = a*expand; b3 = a3*expand; cc1 = s_cos(b); ss1 = s_sin(b); cc3 = s_cos(b3); ss3 = s_sin(b3); a = (a+dil)&nminus; is = 0; id = n2<<1; do { for(i=is;i<n;i+=id) { i1 = i+j; i2 = i1 + n4; i3 = i2 + n4; i4 = i3 + n4; i5 = i + n4 - j + 2; i6 = i5 + n4; i7 = i6 + n4; i8 = i7 + n4; t1 = x[i3]*cc1 + x[i7]*ss1; t2 = x[i7]*cc1 - x[i3]*ss1; t3 = x[i4]*cc3 + x[i8]*ss3; t4 = x[i8]*cc3 - x[i4]*ss3; t5 = t1 + t3; t6 = t2 + t4; t3 = t1 - t3; t4 = t2 - t4; t2 = x[i6] + t6; x[i3] = t6 - x[i6]; x[i8] = t2; t2 = x[i2] - t3; x[i7] = -x[i2] - t3; x[i4] = t2; t1 = x[i1] + t5; x[i6] = x[i1] - t5; x[i1] = t1; t1 = x[i5] + t4; x[i5] -= t4; x[i2] = t1; } is = (id<<1) - n2; id <<= 2; } while(is<n); } } } void fftinv_hermitian_to_real( double *z, int n ) /* Input is {Re(z^[0]),...,Re(z^[n/2),Im(z^[n/2-1]),...,Im(z^[1]). * This is a decimation-in-frequency, split-radix algorithm. */ { register double cc1, ss1, cc3, ss3; register int is, id, i0, i1, i2, i3, i4, i5, i6, i7, i8, a, a3, b, b3, nminus = n-1, dil, expand; register double *x, e; int nn = n>>1; double t1, t2, t3, t4, t5; int n2, n4, n8, i, j; init_sinCos(n); expand = cur_run/n; x = z-1; n2 = n<<1; while(nn >>= 1) { is = 0; id = n2; n2 >>= 1; n4 = n2>>2; n8 = n4>>1; do { for(i=is;i<n;i+=id) { i1 = i+1; i2 = i1 + n4; i3 = i2 + n4; i4 = i3 + n4; t1 = x[i1] - x[i3]; x[i1] += x[i3]; x[i2] += x[i2]; x[i3] = t1 - 2.0*x[i4]; x[i4] = t1 + 2.0*x[i4]; if (n4==1) continue; i1 += n8; i2 += n8; i3 += n8; i4 += n8; t1 = (x[i2]-x[i1])*SQRTHALF; t2 = (x[i4]+x[i3])*SQRTHALF; x[i1] += x[i2]; x[i2] = x[i4]-x[i3]; x[i3] = -2.0*(t2+t1); x[i4] = 2.0*(t1-t2); } is = (id<<1) - n2; id <<= 2; } while (is<n-1); dil = n/n2; a = dil; for (j=2;j<=n8;j++) { a3 = (a+(a<<1))&nminus; b = a*expand; b3 = a3*expand; cc1 = s_cos(b); ss1 = s_sin(b); cc3 = s_cos(b3); ss3 = s_sin(b3); a = (a+dil)&nminus; is = 0; id = n2<<1; do { for(i=is;i<n;i+=id) { i1 = i+j; i2 = i1+n4; i3 = i2+n4; i4 = i3+n4; i5 = i+n4-j+2; i6 = i5+n4; i7 = i6+n4; i8 = i7+n4; t1 = x[i1] - x[i6]; x[i1] += x[i6]; t2 = x[i5] - x[i2]; x[i5] += x[i2]; t3 = x[i8] + x[i3]; x[i6] = x[i8] - x[i3]; t4 = x[i4] + x[i7]; x[i2] = x[i4] - x[i7]; t5 = t1 - t4; t1 += t4; t4 = t2 - t3; t2 += t3; x[i3] = t5*cc1 + t4*ss1; x[i7] = -t4*cc1 + t5*ss1; x[i4] = t1*cc3 - t2*ss3; x[i8] = t2*cc3 + t1*ss3; } is = (id<<1) - n2; id <<= 2; } while(is<n-1); } } is = 1; id = 4; do { for (i0=is;i0<=n;i0+=id) { i1 = i0+1; e = x[i0]; x[i0] = e + x[i1]; x[i1] = e - x[i1]; } is = (id<<1) - 1; id <<= 2; } while(is<n); scramble_real(z, n); e = 1/(double)n; for (i=0;i<n;i++) { z[i] *= e; } } void mul_hermitian( double *a, double *b, int n ) { register int k, half = n>>1; register double aa, bb, am, bm; b[0] *= a[0]; b[half] *= a[half]; for (k=1;k<half;k++) { aa = a[k]; bb = b[k]; am = a[n-k]; bm = b[n-k]; b[k] = aa*bb - am*bm; b[n-k] = aa*bm + am*bb; } } void square_hermitian( double *b, int n ) { register int k, half = n>>1; register double c, d; b[0] *= b[0]; b[half] *= b[half]; for (k=1;k<half;k++) { c = b[k]; d = b[n-k]; b[n-k] = 2.0*c*d; b[k] = (c+d)*(c-d); } } void giant_to_double ( giant x, int sizex, double *z, int L ) { register int j; for (j=sizex;j<L;j++) { z[j]=0.0; } for (j=0;j<sizex;j++) { z[j] = x->n[j]; } } void gswap( giant *p, giant *q ) { giant t; t = *p; *p = *q; *q = t; } void onestep( giant x, giant y, gmatrix A ) /* Do one step of the euclidean algorithm and modify * the matrix A accordingly. */ { giant s4 = popg(); gtog(x,s4); gtog(y,x); gtog(s4,y); divg(x,s4); punch(s4,A); mulg(x,s4); subg(s4,y); pushg(1); } void mulvM( gmatrix A, giant x, giant y ) /* Multiply vector by Matrix; changes x,y. */ { giant s0 = popg(), s1 = popg(); gtog(A->ur,s0); gtog( A->lr,s1); dotproduct(x,y,A->ul,s0); dotproduct(x,y,A->ll,s1); gtog(s0,x); gtog(s1,y); pushg(2); } void mulmM( gmatrix A, gmatrix B ) /* Multiply matrix by Matrix; changes second matrix. */ { giant s0 = popg(); giant s1 = popg(); giant s2 = popg(); giant s3 = popg(); gtog(B->ul,s0); gtog(B->ur,s1); gtog(B->ll,s2); gtog(B->lr,s3); dotproduct(A->ur,A->ul,B->ll,s0); dotproduct(A->ur,A->ul,B->lr,s1); dotproduct(A->ll,A->lr,B->ul,s2); dotproduct(A->ll,A->lr,B->ur,s3); gtog(s0,B->ul); gtog(s1,B->ur); gtog(s2,B->ll); gtog(s3,B->lr); pushg(4); } void writeM( gmatrix A ) { if (logFile) fprintf(logFile, " ul:"); gout(A->ul); if (logFile) fprintf(logFile, " ur:"); gout(A->ur); if (logFile) fprintf(logFile, " ll:"); gout(A->ll); if (logFile) fprintf(logFile, " lr:"); gout(A->lr); } void punch( giant q, gmatrix A ) /* Multiply the matrix A on the left by [0,1,1,-q]. */ { giant s0 = popg(); gtog(A->ll,s0); mulg(q,A->ll); gswap(&A->ul,&A->ll); subg(A->ul,A->ll); gtog(s0,A->ul); gtog(A->lr,s0); mulg(q,A->lr); gswap(&A->ur,&A->lr); subg(A->ur,A->lr); gtog(s0,A->ur); pushg(1); } static void dotproduct( giant a, giant b, giant c, giant d ) /* Replace last argument with the dot product of two 2-vectors. */ { giant s4 = popg(); gtog(c,s4); mulg(a, s4); mulg(b,d); addg(s4,d); pushg(1); } void ggcd( giant xx, giant yy ) /* A giant gcd. Modifies its arguments. */ { giant x = popg(), y = popg(); gmatrix A = newgmatrix(); gtog(xx,x); gtog(yy,y); for(;;) { fix(&x,&y); if (bitlen(y) <= GCDLIMIT ) break; A->ul = popg(); A->ur = popg(); A->ll = popg(); A->lr = popg(); itog(1,A->ul); itog(0,A->ur); itog(0,A->ll); itog(1,A->lr); hgcd(0,x,y,A); mulvM(A,x,y); pushg(4); fix(&x,&y); if (bitlen(y) <= GCDLIMIT ) break; modg(y,x); gswap(&x,&y); } bgcdg(x,y); gtog(y,yy); pushg(2); free(A); } void fix( giant *p, giant *q ) /* Insure that x > y >= 0. */ { if( gsign(*p) < 0 ) negg(*p); if( gsign(*q) < 0 ) negg(*q); if( gcompg(*p,*q) < 0 ) gswap(p,q); } void hgcd( int n, giant xx, giant yy, gmatrix A ) /* hgcd(n,x,y,A) chops n bits off x and y and computes th * 2 by 2 matrix A such that A[x y] is the pair of terms * in the remainder sequence starting with x,y that is * half the size of x. Note that the argument A is modified * but that the arguments xx and yy are left unchanged. */ { giant x, y; if (isZero(yy)) return; x = popg(); y = popg(); gtog(xx,x); gtog(yy,y); gshiftright(n,x); gshiftright(n,y); if (bitlen(x) <= INTLIMIT ) { shgcd(gtoi(x),gtoi(y),A); } else { gmatrix B = newgmatrix(); int m = bitlen(x)/2; hgcd(m,x,y,A); mulvM(A,x,y); if (gsign(x) < 0) { negg(x); negg(A->ul); negg(A->ur); } if (gsign(y) < 0) { negg(y); negg(A->ll); negg(A->lr); } if (gcompg(x,y) < 0) { gswap(&x,&y); gswap(&A->ul,&A->ll); gswap(&A->ur,&A->lr); } if (!isZero(y)) { onestep(x,y,A); m /= 2; B->ul = popg(); B->ur = popg(); B->ll = popg(); B->lr = popg(); itog(1,B->ul); itog(0,B->ur); itog(0,B->ll); itog(1,B->lr); hgcd(m,x,y,B); mulmM(B,A); pushg(4); } free(B); } pushg(2); } void shgcd( register int x, register int y, gmatrix A ) /* * Do a half gcd on the integers a and b, putting the result in A * It is fairly easy to use the 2 by 2 matrix description of the * extended Euclidean algorithm to prove that the quantity q*t * never overflows. */ { register int q, t, start = x; int Aul = 1, Aur = 0, All = 0, Alr = 1; while (y != 0 && y > start/y) { q = x/y; t = y; y = x%y; x = t; t = All; All = Aul-q*t; Aul = t; t = Alr; Alr = Aur-q*t; Aur = t; } itog(Aul,A->ul); itog(Aur,A->ur); itog(All,A->ll); itog(Alr,A->lr); }
[ [ [ 1, 3271 ] ] ]
5966de8dfecd9499afa06ab0417cad42df7ec8cf
8a47aa7c36fa2b9ea76cf2ef9fea8207d40a71a2
/devilheart/project_pin/library/xed2-ia32/examples/xed-tester.cpp
6421fd4d8ebd391bbfebe3c27048ec37536dcf69
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
iidx/devilheart
4eae52d7201149347d3f93fdf0202e2520313bf3
13a28efa9f9a37a133b52301642c7ebc264697d5
refs/heads/master
2021-01-10T10:17:58.686621
2010-03-16T03:16:18
2010-03-16T03:16:18
46,808,731
0
0
null
null
null
null
UTF-8
C++
false
false
3,066
cpp
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2009 Intel Corporation. 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 Intel Corporation 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 INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ /// @file xed-tester.cpp /// @author Mark Charney <[email protected]> extern "C" { #include "xed-interface.h" } #include <iostream> #include <iomanip> using namespace std; int main(int argc, char** argv); class xed_test_t { public: unsigned int len; unsigned char itext[15]; }; xed_test_t tests[] = { { 2, { 0, 0 } }, { 2, { 2, 0 } }, { 2, { 0xF3, 0x90 } }, { 0 } }; int main(int argc, char** argv) { unsigned int i,j; xed_tables_init(); xed_state_t dstate; xed_state_zero(&dstate); xed_state_init(&dstate, XED_MACHINE_MODE_LEGACY_32, XED_ADDRESS_WIDTH_32b, XED_ADDRESS_WIDTH_32b); for ( i=0; tests[i].len ; i++) { xed_decoded_inst_t xedd; xed_decoded_inst_zero_set_mode(&xedd, &dstate); cout << hex << "Testing: "; for( j=0; j< tests[i].len; j++) { cout << setfill('0') << setw(2); cout << STATIC_CAST(unsigned int,tests[i].itext[j]) << " "; } cout << endl; xed_error_enum_t xed_error = xed_decode(&xedd, REINTERPRET_CAST(xed_uint8_t*,tests[i].itext), tests[i].len); xed_bool_t okay = (xed_error == XED_ERROR_NONE); if (okay) { cout << "OK" << endl; } } (void) argc; (void) argv; //pacify compiler }
[ "hsqfire@86a7f5e6-5eca-11de-8a4b-256bef446c6c" ]
[ [ [ 1, 84 ] ] ]