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
294e2fb98b42e0e63e9be4691a2e275729039075
ef25bd96604141839b178a2db2c008c7da20c535
/src/src/Test/Levels/LevelStart.h
608ac1f780e2922423fc9fff5fa87b65aa1c9700
[]
no_license
OtterOrder/crock-rising
fddd471971477c397e783dc6dd1a81efb5dc852c
543dc542bb313e1f5e34866bd58985775acf375a
refs/heads/master
2020-12-24T14:57:06.743092
2009-07-15T17:15:24
2009-07-15T17:15:24
32,115,272
0
0
null
null
null
null
UTF-8
C++
false
false
766
h
#ifndef _LevelStart_H #define _LevelStart_H //****************************************************************** #include <Game/Level.h> //****************************************************************** #define LEVEL_start 0x9f79558f //****************************************************************** class Camera; class LevelStart : public Level { public: LevelStart ( crc32 levelID ); // Constructeur virtual ~LevelStart ( void ); // Destructeur virtual void Init ( void ); // Initialisation virtual void Update ( void ); // Update du niveau protected: Camera* m_pCamera; //TODO }; //****************************************************************** #endif //_LevelStart_H
[ "mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b" ]
[ [ [ 1, 35 ] ] ]
4d2835d749e4500dfc44e475bf755690952d374c
c6dca462f8e982b2a327285cf084d08fa7f27dd8
/include/liblearning/core/clonable_object.h
5d0cd0023d81d8b36439e490a229f8f79fbdbfda
[]
no_license
nagyistoce/liblearning
2a7e94344f15c5af105974207ece68822102524b
ac0a77dce09ad72f32b2cae067f4616e49d60697
refs/heads/master
2021-01-01T16:59:44.689918
2010-08-20T12:07:22
2010-08-20T12:07:22
32,806,608
0
0
null
null
null
null
UTF-8
C++
false
false
616
h
#ifndef CLONALBE_OBJECT_H #define CLONALBE_OBJECT_H #include <memory> #include <type_traits> #include <loki/Factory.h> template <typename T, bool b> T* do_clone(T * ptr, const std::integral_constant<bool, b> &) { return 0; } template <typename T> T* do_clone(T * ptr, const std::false_type&) { return new T(*ptr); } template <typename T> class clonable_object { protected: virtual T* clone () { typedef std::integral_constant<bool, std::is_abstract<T>::value > truth_type; return do_clone(dynamic_cast<T*>(this), truth_type()); } }; #endif
[ [ [ 1, 44 ] ] ]
c20e07271d6dd171ebc74aa0581009c77a778003
a37df219b4a30e684db85b00dd76d4c36140f3c2
/1.7.1/run/runDlg.h
1dadc8ec956eeb7c7f600527473eca8638640517
[]
no_license
BlackMoon/bm-net
0f79278f8709cd5d0738a6c3a27369726b0bb793
eb6414bc412a8cfc5c24622977e7fa7203618269
refs/heads/master
2020-12-25T20:20:44.843483
2011-11-29T10:33:17
2011-11-29T10:33:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
854
h
// runDlg.h : header file // #include "CApplication.h" #include "CGraph.h" #include "Catl.h" #include "Catl0.h" #pragma once // CrunDlg dialog class CrunDlg : public CDialog { // Construction public: CrunDlg(CWnd* pParent = NULL); // standard constructor ~CrunDlg(); // Dialog Data enum { IDD = IDD_RUN_DIALOG }; CApplication app; Catl atl; CGraph gr; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: HICON m_hIcon; // Generated message map functions virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButton1(); afx_msg void OnBnClickedButton2(); afx_msg void OnBnClickedButton3(); };
[ "[email protected]@b6168ec3-97fc-df6f-cbe5-288b4f99fbbd" ]
[ [ [ 1, 41 ] ] ]
43d1648c2431a14d8d4df2994728d646e01938e5
68d8ddd1f19bcf70c9429f22ff1075c0c6f5479b
/CSALog.h
8ace52aa8c45ceb82afd76f190c9742fedcd787a
[]
no_license
kusano/Shogi55GUI
532df08ca2053dedc0b6ac13e0a3ac6e245fc00a
3b1552ee29578a58929a5c5b9f5a27790fa25d1d
refs/heads/master
2021-05-14T02:08:21.126449
2008-12-18T03:56:58
2008-12-18T03:56:58
116,587,616
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
392
h
#pragma once // CCSALog ダイアログ class CCSALog : public CDialog { DECLARE_DYNAMIC(CCSALog) public: CCSALog(CWnd* pParent = NULL); // 標準コンストラクタ virtual ~CCSALog(); // ダイアログ データ enum { IDD = IDD_CSALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV サポート DECLARE_MESSAGE_MAP() };
[ [ [ 1, 21 ] ] ]
3b3456a0f0af2a54450a5ed58114bfefb911054d
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/EduNetGames/ModNetSoccer/NetSoccerPlugin.cpp
b8aebfd9df6b41e572fa651fda2d01cd36f27d93
[]
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
13,638
cpp
//----------------------------------------------------------------------------- // // // 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. // // //----------------------------------------------------------------------------- // // Simple soccer game by Michael Holm, IO Interactive A/S // // I made this to learn opensteer, and it took me four hours. The players will // hunt the ball with no team spirit, each player acts on his own accord. // // I challenge the reader to change the behavour of one of the teams, to beat my // team. It should not be too hard. If you make a better team, please share the // source code so others get the chance to create a team that'll beat yours :) // // You are free to use this code for whatever you please. // // (contributed on July 9, 2003) // //----------------------------------------------------------------------------- // 10-30-09 cp/jf: modified for educational purpose #include "NetSoccerPlugin.h" #include <iomanip> #include <sstream> #include "OpenSteer/SimpleVehicle.h" #include "OpenSteer/Renderer.h" #include "OpenSteer/Color.h" #include "OpenSteer/UnusedParameter.h" #include "OpenSteer/AABBox.h" #include "OpenSteerUT/AbstractVehicleGroup.h" #include "NetSoccerEntityFactory.h" #include "NetSoccerGameLogic.h" using namespace OpenSteer; //----------------------------------------------------------------------------- // now 1 global vehicle factory NetSoccerEntityFactory gOfflineNetSoccerEntityFactory; //----------------------------------------------------------------------------- NetSoccerPlugin::NetSoccerPlugin ( bool bAddToRegistry ) : BaseClass ( bAddToRegistry ), m_Ball(NULL), m_bbox( NULL ), m_TeamAGoal(NULL), m_TeamBGoal(NULL), m_pCameraPlugin(NULL) { this->setEntityFactory( &gOfflineNetSoccerEntityFactory ); } //----------------------------------------------------------------------------- void NetSoccerPlugin::open ( void ) { // Make a field m_bbox = ET_NEW OpenSteer::AABBox ( Vec3 ( -20,0,-10 ), Vec3 ( 20,0,10 ) ); // Red goal m_TeamAGoal = ET_NEW OpenSteer::AABBox ( Vec3 ( -21,0,-7 ), Vec3 ( -19,0,7 ) ); // Blue Goal m_TeamBGoal = ET_NEW OpenSteer::AABBox ( Vec3 ( 19,0,-7 ), Vec3 ( 21,0,7 ) ); // Make a ball AbstractVehicle* pkVehicle = this->createVehicle( ET_CID_NETSOCCER_BALL ); if (NULL != pkVehicle) { this->addVehicle( pkVehicle ); } // Build team A m_PlayerCountA = 8; this->createTeam(this->m_PlayerCountA, m_kTeamA, true); // Build Team B m_PlayerCountB = 8; this->createTeam(this->m_PlayerCountB, m_kTeamB, false); m_pCameraPlugin = ET_NEW OpenSteer::CameraPlugin(); if(NULL != this->m_Ball) { // initialize camera m_pCameraPlugin->position2dCamera ( *m_Ball ); Camera& kCam(m_pCameraPlugin->accessCamera() ); kCam.mode = Camera::cmFixed; kCam.fixedTarget.set ( 10, CameraPlugin::camera2dElevation, 10 ); kCam.fixedPosition.set ( 40, 40, 40 ); } m_redScore = 0; m_blueScore = 0; this->reset(); } //----------------------------------------------------------------------------- // createTeam //----------------------------------------------------------------------------- void NetSoccerPlugin::createTeam(unsigned int uiTeamMemberCount, NetSoccerPlayer::Group& kPlayerGroup, bool bTeamId) { for ( unsigned int i=0; i < uiTeamMemberCount ; ++i) { AbstractVehicle* pkVehicle = this->createVehicle( ET_CID_NETSOCCER_PLAYER ); if (NULL != pkVehicle) { NetSoccerPlayer* pkPlayerVehicle = dynamic_cast<NetSoccerPlayer*>( pkVehicle ); pkPlayerVehicle->setTeamIdAndPlayerNumber(bTeamId, i); this->addVehicle( pkVehicle ); } } } //----------------------------------------------------------------------------- void NetSoccerPlugin::update ( const float currentTime, const float elapsedTime ) { if( false == this->isEnabled() ) { return; } if( false == this->isRemoteObject() ) { AbstractPlayerGroup& kAllPlayers = this->allPlayers( ); AbstractPlayerGroup::iterator kIter = kAllPlayers.begin(); AbstractPlayerGroup::iterator kEnd = kAllPlayers.end(); while( kIter != kEnd ) { AbstractPlayer* pkPlayer = *kIter; const AbstractController* pkController = pkPlayer->getController(); OpenSteer::CastToAbstractUpdated( pkPlayer )->update( currentTime, elapsedTime ); ++kIter; } } NetSoccerGameLogic kGameLogic; kGameLogic.setPlugin( this ); kGameLogic.update( currentTime, elapsedTime ); AbstractVehicleGroup kVG( this->allVehicles() ); kVG.setCustomUpdated( &kGameLogic ); kVG.update( currentTime, elapsedTime ); if(NULL != m_Ball) { this->checkForGoal(); } m_pCameraPlugin->update( currentTime, elapsedTime); } //----------------------------------------------------------------------------- bool NetSoccerPlugin::checkForGoal( void ) { bool bGoal(false); if ( m_TeamAGoal->insideX ( m_Ball->position() ) && m_TeamAGoal->insideZ ( m_Ball->position() ) ) { m_Ball->reset(); // Ball in blue teams goal, red scores m_redScore++; bGoal = true; } if ( m_TeamBGoal->insideX ( m_Ball->position() ) && m_TeamBGoal->insideZ ( m_Ball->position() ) ) { m_Ball->reset(); // Ball in red teams goal, blue scores m_blueScore++; bGoal = true; } return bGoal; } //----------------------------------------------------------------------------- void NetSoccerPlugin::redraw ( OpenSteer::AbstractRenderer* pRenderer, const float currentTime, const float elapsedTime ) { if( false == this->isVisible() ) { return; } m_pCameraPlugin->redraw( pRenderer, currentTime, elapsedTime); /*this->drawTeam( this->m_kTeamA ); this->drawTeam( this->m_kTeamB ); if (NULL != this->m_Ball) { m_Ball->draw ( currentTime, elapsedTime ); }*/ AbstractVehicleGroup kVG( this->allVehicles() ); kVG.redraw( pRenderer, currentTime, elapsedTime ); m_bbox->draw(pRenderer); m_TeamAGoal->draw(pRenderer); m_TeamBGoal->draw(pRenderer); const float fWidth(pRenderer->drawGetWindowWidth()); const float fHeight(pRenderer->drawGetWindowHeight()); { std::ostringstream annote; annote << "Red: "<< m_redScore; pRenderer->draw2dTextAt3dLocation ( annote, Vec3 ( 23,0,0 ), Color ( 1.0f,0.7f,0.7f ), fWidth, fHeight ); } { std::ostringstream annote; annote << "Blue: "<< m_blueScore; pRenderer->draw2dTextAt3dLocation ( annote, Vec3 ( -23,0,0 ), Color ( 0.7f,0.7f,1.0f ), fWidth, fHeight ); } } //----------------------------------------------------------------------------- void NetSoccerPlugin::close ( void ) { unsigned int uiPlayerCount = m_kTeamA.size(); for ( unsigned int i=0; i < uiPlayerCount ; i++ ) { osAbstractVehicle* pkVehicle = m_kTeamA[i]; this->removeVehicle( pkVehicle ); delete pkVehicle; } m_kTeamA.clear (); uiPlayerCount = m_kTeamB.size(); for ( unsigned int i=0; i < uiPlayerCount ; i++ ) { osAbstractVehicle* pkVehicle = m_kTeamB[i]; this->removeVehicle( pkVehicle ); delete pkVehicle; } m_kTeamB.clear (); m_AllPlayers.clear(); if( NULL != this->m_Ball ) { osAbstractVehicle* pkVehicle = this->m_Ball; this->removeVehicle(pkVehicle); ET_SAFE_DELETE( this->m_Ball ); } ET_SAFE_DELETE(m_pCameraPlugin); } //----------------------------------------------------------------------------- void NetSoccerPlugin::reset ( void ) { static Vec3 playerPosition[9] = {Vec3 ( 4,0,0 ), Vec3 ( 7,0,-5 ), Vec3 ( 7,0,5 ), Vec3 ( 10,0,-3 ), Vec3 ( 10,0,3 ), Vec3 ( 15,0, -8 ), Vec3 ( 15,0,0 ), Vec3 ( 15,0,8 ), Vec3 ( 4,0,0 ) }; // reset vehicle unsigned int uiPlayerCount = m_kTeamA.size(); for ( unsigned int i=0; i < uiPlayerCount ; i++ ) { NetSoccerPlayer* pkPlayer = m_kTeamA[i]; pkPlayer->reset (); pkPlayer->setHomeAndPosition ( playerPosition[i] ); } uiPlayerCount = m_kTeamB.size(); for ( unsigned int i=0; i < uiPlayerCount ; i++ ) { NetSoccerPlayer* pkPlayer = m_kTeamB[i]; pkPlayer->reset (); Vec3 kPos ( playerPosition[i] ); kPos.x *= -1; pkPlayer->setHomeAndPosition ( kPos ); } if (NULL != this->m_Ball) { m_Ball->reset(); } } //----------------------------------------------------------------------------- osAbstractVehicle* NetSoccerPlugin::createVehicle ( osEntityClassId classId) const { AbstractVehicle* pkVehicle = NULL; const AbstractEntityFactory* pkFactory = this->getEntityFactory(); if( NULL != pkFactory ) { pkVehicle = pkFactory->createVehicle( classId ); } return pkVehicle; } //----------------------------------------------------------------------------- void NetSoccerPlugin::addVehicle( AbstractVehicle* pkVehicle ) { if( NULL == pkVehicle ) { return; } AbstractVehicleGroup kVG( this->allVehicles() ); kVG.addVehicleToPlugin( pkVehicle, this ); if(false == pkVehicle->isRemoteObject() ) { NetSoccerPlayer* pkPlayerVehicle = dynamic_cast<NetSoccerPlayer*>( pkVehicle ); if( NULL != pkPlayerVehicle ) { if (pkPlayerVehicle->b_ImTeamA) { this->m_kTeamA.push_back(pkPlayerVehicle ); }else { this->m_kTeamB.push_back(pkPlayerVehicle ); } m_AllPlayers.push_back ( pkPlayerVehicle ); } NetSoccerBall* pkBall = dynamic_cast<NetSoccerBall*>( pkVehicle ); if( NULL != pkBall ) { this->m_Ball = pkBall; this->m_Ball->setBox(m_bbox); } } } //----------------------------------------------------------------------------- void NetSoccerPlugin::removeVehicle ( osAbstractVehicle* pkVehicle) { AbstractVehicleGroup kVG( this->allVehicles() ); if( kVG.end() == kVG.findVehicle( pkVehicle ) ) { return; } NetSoccerBall* pkBall = dynamic_cast<NetSoccerBall*>( pkVehicle ); if( NULL != pkBall ) { this->m_Ball = NULL; } NetSoccerPlayer* pkPlayerVehicle = dynamic_cast<NetSoccerPlayer*>( pkVehicle ); if( NULL != pkPlayerVehicle ) { NetSoccerPlayer::Group::iterator kIter = this->m_AllPlayers.begin(); NetSoccerPlayer::Group::iterator kIterEnd = this->m_AllPlayers.end(); while (kIterEnd != kIter) { NetSoccerPlayer* pkTmpVehicle = (*kIter); if (pkPlayerVehicle == pkTmpVehicle) { kIter = this->m_AllPlayers.erase( kIter ); kIterEnd = this->m_AllPlayers.end(); }else { ++kIter; } } } kVG.removeVehicleFromPlugin( pkVehicle ); } //----------------------------------------------------------------------------- void NetSoccerPlugin::addPlayer (OpenSteer::AbstractPlayer* pkPlayer) { printf( "add player"); NetSoccerPlayer* pkFreeSoccer = this->findUncontrolledSoccer( this->m_kTeamA ); if (NULL != pkFreeSoccer) { pkPlayer->play(pkFreeSoccer); if( SimpleVehicle::getSelectedVehicle() != pkFreeSoccer ) { SimpleVehicle::setSelectedVehicle( pkFreeSoccer ); } } BaseClass::addPlayer( pkPlayer ); } //----------------------------------------------------------------------------- NetSoccerPlayer* NetSoccerPlugin::findUncontrolledSoccer( NetSoccerPlayer::Group& kTeam ) { NetSoccerPlayer::Group::iterator kIter = kTeam.begin(); NetSoccerPlayer::Group::iterator kIterEnd = kTeam.end(); while (kIterEnd != kIter) { NetSoccerPlayer* pkTmpVehicle = (*kIter); if (false == pkTmpVehicle->isPossessed()) { return pkTmpVehicle; } ++kIter; } return NULL; } //----------------------------------------------------------------------------- void NetSoccerPlugin::removePlayer(OpenSteer::AbstractPlayer* pkPlayer) { printf( "remove player"); pkPlayer->play(NULL); BaseClass::removePlayer( pkPlayer ); } //-----------------------------------------------------------------------------
[ "janfietz@localhost", "cy.preuss@localhost" ]
[ [ [ 1, 63 ], [ 70, 435 ] ], [ [ 64, 69 ] ] ]
95482dd8ae43e86b57bf2860da8d036932a5dc8d
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/vehicles.hpp
26bd11a2e45b25c3ee46a91354fba9931ec0e042
[]
no_license
neverm1ndo/gta-paradise-sa
d564c1ed661090336621af1dfd04879a9c7db62d
730a89eaa6e8e4afc3395744227527748048c46d
refs/heads/master
2020-04-27T22:00:22.221323
2010-09-04T19:02:28
2010-09-04T19:02:28
174,719,907
1
0
null
2019-03-09T16:44:43
2019-03-09T16:44:43
null
WINDOWS-1251
C++
false
false
7,984
hpp
#ifndef VEHICLES_HPP #define VEHICLES_HPP #include "core/module_h.hpp" #include "vehicle.hpp" #include "vehicles_t.hpp" #include <vector> #include <string> #include <map> #include <set> #include "basic_types.hpp" #include "core/dynamic_items.hpp" #include "core/utility/locale_ru.hpp" #include "vehicle_fwd.hpp" class vehicles :public application_item ,public createble_i ,public configuradable ,public samp::on_gamemode_init_i ,public samp::on_vehicle_spawn_i ,public samp::on_vehicle_mod_i ,public samp::on_vehicle_paintjob_i ,public samp::on_vehicle_respray_i ,public samp::on_player_connect_i { friend class vehicle_t; public: typedef std::tr1::shared_ptr<vehicles> ptr; static ptr instance(); public: vehicles(); virtual ~vehicles(); public: // createble_i virtual void create(); public: // configuradable virtual void configure_pre(); virtual void configure(buffer::ptr const& buff, def_t const& def); virtual void configure_post(); public: // auto_name SERIALIZE_MAKE_CLASS_NAME(vehicles); public: // samp::* virtual void on_gamemode_init(AMX* amx, samp::server_ver ver); virtual void on_vehicle_spawn(int vehicle_id); virtual bool on_vehicle_mod(int player_id, int vehicle_id, int component_id); virtual bool on_vehicle_paintjob(int player_id, int vehicle_id, int paintjob_id); virtual bool on_vehicle_respray(int player_id, int vehicle_id, int color1, int color2); virtual void on_player_connect(int player_id); private: void on_first_player_connected(); public: vehicle_ptr_t get_vehicle(int vehicle_id); vehicle_ref_t get_vehicle_throw(int vehicle_id); private: typedef std::map<int, vehicle_def_t> vehicle_defs_t; vehicle_defs_t vehicle_defs; typedef std::map<std::string, vehicle_component_def_t> vehicle_component_defs_t; vehicle_component_defs_t vehicle_component_defs; // Список имен компонетов, которые не проверяются на дубликаты std::set<std::string> vehicle_component_ignore_duplicate; typedef dynamic_items<pos_vehicle, int> vehiclesgame_t; typedef std::vector<pos_vehicle> vehicles_static_t; // Транспорт, который будет создаваться только при загрузке игрового режима vehiclesgame_t vehiclesgame; vehicles_static_t vehicles_static; bool is_first_player_connected; std::string plate; typedef std::vector<vehicle_color_t> vehicle_colors_t; vehicle_colors_t vehicle_colors; bool is_dump_vehicles_on_config; void dump_vehicles(vehiclesgame_t::update_t& vehicles); private: // Текущие параметры транспорта typedef std::map<int, vehicle_t> vehicles_state_t; vehicles_state_t vehicles_state; public: int vehicle_create(pos_vehicle const& pos); void vehicle_destroy(int id); public: bool get_component_from_id(int component_id, vehicle_component_defs_t::const_iterator& comp_it) const; bool is_valid_component(int model_id, int component_id); bool is_valid_component(int model_id, std::string const& component_name); bool is_valid_paintjob(int model_id, int paintjob_id); bool is_valid_colors(int model_id, int color1, int color2); private: bool is_player_can_tune(player_ptr_t const& player_ptr); bool cmd_vehicle_paintjob_access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name); bool cmd_vehicle_color_access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name); bool cmd_vehicle_modification_access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name); bool cmd_vehicle_paintjob_access_checker_impl(player_ptr_t const& player_ptr); bool cmd_vehicle_color_access_checker_impl(player_ptr_t const& player_ptr); bool cmd_vehicle_modification_access_checker_impl(player_ptr_t const& player_ptr); bool get_vehicle_def_by_player(player_ptr_t const& player_ptr, int& vehicle_id, vehicle_defs_t::const_iterator& vehicle_def_it) const; bool get_trailer_def_by_player(player_ptr_t const& player_ptr, int& trailer_id, vehicle_defs_t::const_iterator& trailer_def_it) const; command_arguments_rezult cmd_vehicle_paintjob(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_vehicle_color(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_vehicle_modification(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_vehicle_modification_impl(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_vehicle_color_list(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_vehicle_modification_list(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); private: void set_params(vehicle_defs_t::const_iterator const& def_it, messages_params& params, std::string const& prefix = "v_"); void set_params_colors(int index, messages_params& params, std::string const& prefix); public: std::string get_vehicle_info(player_ptr_t const& player_ptr); int get_max_vehicle_id() const; bool is_valid_vehicle_id(int vehicle_id) const; bool is_vehicle_created_by_me(int vehicle_id) const; // Возращает истину, если вихикл создан модом pos4 pos_get(int vehicle_id) const; bool get_model_id_by_name(std::string const& gta_model_name, int& model_id) const; bool get_component_id_by_name(std::string const& gta_component_name, int& first_component_id) const; std::string get_component_name_by_id(int component_id); private: int vehicle_paintjob_price; int vehicle_color_price; bool is_block_on_vehicle_mod; bool is_block_on_vehicle_paintjob; bool is_block_on_vehicle_respray; bool is_trace_enter_leave_mod; private: typedef std::pair<std::string /* gta name */, vehicle_component_def_t const*> mod_item_t; typedef std::multimap<std::string, mod_item_t> mods_group_item_t; typedef std::map<std::string, mods_group_item_t, ilexicographical_less> mods_groups_t; void get_mods_groups(vehicle_defs_t::const_iterator const& vehicle_def_it, mods_groups_t& mods_groups); void add_component(vehicle_component_def_t const& component_def, int vehicle_id); void remove_component(vehicle_component_def_t const& component_def, int vehicle_id); private: // Мод гаражи typedef std::vector<mod_garage_t> mod_garages_t; typedef std::map<int, garage_val_t> garage_vals_t; mod_garages_t mod_garages; garage_vals_t garage_vals; void mod_garages_destroy(); void mod_garages_create(); void mod_garage_item_on_enter(player_ptr_t const& player_ptr, int id); void mod_garage_item_on_leave(player_ptr_t const& player_ptr, int id); private: // Горажи починки typedef std::vector<repair_garage_t> repair_garages_t; repair_garages_t repair_garages; void repair_garages_destroy(); void repair_garages_create(); void repair_garage_item_on_enter(player_ptr_t const& player_ptr, int id); void repair_garage_item_on_leave(player_ptr_t const& player_ptr, int id); }; #endif // VEHICLES_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 171 ] ] ]
b9cc0cfc3233cc23969e5323d23b7237ada4b559
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/utils/MemoryPool.cpp
7cd13ed26e941704cba25279df86fbb1a084f5f2
[ "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
3,362
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "MemoryPool.h" using namespace dingus; CMemoryPool::CMemoryPool( int blockSize, int numElements, bool dontGrow, const char* name ) : mBlockSize( blockSize < sizeof(void*) ? sizeof(void*) : blockSize ), mBlocksPerBubble( numElements ), mDontGrow( dontGrow ), mPeakAllocCount(0), mName(name) { reset(); allocNewBubble(); } CMemoryPool::~CMemoryPool() { if( mAllocCount > 0 ) { ASSERT_FAIL_MSG( "leaked!" ); } deallocateAll(); } void CMemoryPool::reset() { mAllocCount = 0; mHeadOfFreeList = 0; } void CMemoryPool::deallocateAll() { stl_utils::wipe( mBubbles ); reset(); } void CMemoryPool::allocNewBubble() { size_t sizeMultiplier; if( mDontGrow && !mBubbles.empty() ) { ASSERT_FAIL_MSG( "CMemoryPool::allocNewBubble: can't grow" ); return; } sizeMultiplier = mBubbles.size() + 1; size_t elemCount = mBlocksPerBubble * sizeMultiplier; size_t bubbleSize = mBlockSize * elemCount; SBubble *bubble = (SBubble*)malloc( sizeof(SBubble) + bubbleSize - 1 ); assert( bubble ); bubble->mByteCount = bubbleSize; // put to bubble list mBubbles.push_back( bubble ); // setup the free list inside a bubble mHeadOfFreeList = bubble->mData; assert( mHeadOfFreeList ); void **newBubble = (void**)mHeadOfFreeList; for( size_t j = 0; j < elemCount-1; ++j ) { newBubble[0] = (char*)newBubble + mBlockSize; newBubble = (void**)newBubble[0]; } newBubble[0] = NULL; // null terminate the list } void* CMemoryPool::allocate() { return allocate( mBlockSize ); } void *CMemoryPool::allocate( unsigned int amount ) { void *returnBlock; if( amount > (unsigned int)mBlockSize ) { ASSERT_FAIL_MSG( "requested larger amount than block size!" ); return NULL; } if( !mHeadOfFreeList ) { // returning NULL is fine in no-grow mode if( mDontGrow ) return NULL; // allocate new bubble allocNewBubble(); // still failure, error out if( !mHeadOfFreeList ) { ASSERT_FAIL_MSG( "CMemoryPool::allocate: out of memory" ); return NULL; } } ++mAllocCount; if( mAllocCount > mPeakAllocCount ) mPeakAllocCount = mAllocCount; returnBlock = mHeadOfFreeList; // move the pointer the next block mHeadOfFreeList = *((void**)mHeadOfFreeList); return returnBlock; } void CMemoryPool::deallocate( void *memBlock ) { if( !memBlock ) // ignore NULL deletes return; #ifdef _DEBUG // check to see if the memory is from the allocated range bool ok = false; size_t n = mBubbles.size(); for( size_t i = 0; i < n; ++i ) { SBubble* p = mBubbles[i]; if( (char*)memBlock >= p->mData && (char*)memBlock < (p->mData + p->mByteCount) ) { ok = true; break; } } assert( ok ); #endif // _DEBUG #ifdef _DEBUG // invalidate the memory memset( memBlock, 0xDD, mBlockSize ); #endif --mAllocCount; // make the block point to the first free item in the list *((void**)memBlock) = mHeadOfFreeList; // the list head is now the deallocated block mHeadOfFreeList = memBlock; }
[ [ [ 1, 146 ] ] ]
af311874e3b8c4001db052cb90ff1b6c6fdffefb
e587b7fd4e2762dddf7161019bbd6a84b848f8c1
/2007/game/client/multiplayer/basenetworkedragdoll_cl.h
2fbcede17018d0bca97b154e57af6e174c06951c
[ "Apache-2.0" ]
permissive
code-google-com/sourcesdk-skeleton
6bf0791c7fb2c7c17125b11f8172dc1ea03b35d0
016933bfc10331e293dd752750108d7ae76fabb3
refs/heads/master
2021-01-20T08:43:50.735666
2011-08-27T18:14:25
2011-08-27T18:14:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
974
h
#include "cbase.h" class C_BaseNetworkedRagdoll : public C_BaseAnimatingOverlay { public: DECLARE_CLASS( C_BaseNetworkedRagdoll, C_BaseAnimatingOverlay ); DECLARE_CLIENTCLASS(); C_BaseNetworkedRagdoll() {} ~C_BaseNetworkedRagdoll(); virtual void OnDataChanged( DataUpdateType_t type ); int GetPlayerEntIndex() const; C_BaseEntity* GetOwner() { return m_hPlayer.Get(); } IRagdoll* GetIRagdoll() const; void ImpactTrace( trace_t* pTrace, int iDamageType, char* pCustomImpactName ); void UpdateOnRemove( void ); virtual void SetupWeights( const matrix3x4_t* pBoneToWorld, int nFlexWeightCount, float* pFlexWeights, float* pFlexDelayedWeights ); private: C_BaseNetworkedRagdoll( const C_BaseNetworkedRagdoll & ) {} void Interp_Copy( C_BaseAnimatingOverlay* pDestinationEntity ); void CreateRagdoll( void ); private: EHANDLE m_hPlayer; CNetworkVector( m_vecRagdollVelocity ); CNetworkVector( m_vecRagdollOrigin ); };
[ "[email protected]@6febd7a2-65a9-c2d8-fb53-b51429dd0aeb" ]
[ [ [ 1, 34 ] ] ]
e7a8386f3978d047944472ac6bc6da3ba43ab7d9
a699a508742a0fd3c07901ab690cdeba2544a5d1
/RailwayDetection/RWDSClient/Datadef.h
f29a070c838b054de106fe41889d93271fdad4ab
[]
no_license
xiaomailong/railway-detection
2bf92126bceaa9aebd193b570ca6cd5556faef5b
62e998f5de86ee2b6282ea71b592bc55ee25fe14
refs/heads/master
2021-01-17T06:04:48.782266
2011-09-27T15:13:55
2011-09-27T15:13:55
42,157,845
0
1
null
2015-09-09T05:24:10
2015-09-09T05:24:09
null
GB18030
C++
false
false
9,633
h
#pragma once #include <vector> #include <atltypes.h> #include <atlstr.h> #include <sys\timeb.h> using namespace std; typedef struct _RailLine { _RailLine() { iRailID = 0; } int iRailID; CString iRailName; }RailLine; typedef struct _SystemConfigure { int iDuration;//数据有效期 int iAlarmMinute;//告警间隔 }SystemConfigure; extern vector<RailLine*> gRailLineList; extern SystemConfigure gSystemConfigure; //extern int strRailLineNameCount; extern const CString strDirectName[]; extern const int strDirectNameCount; extern const CString StrKm; extern const CString strStartNo[]; extern const int strStartNoCount; extern const CString strClientCaption; extern const CString strPictureErrorType[]; extern const int strPictureErrorTypeCount; extern const CString strPointState[]; extern const int strPointStateCount; #define ENCODERAILWAYFULLNAME(aStr, aRailLineName, aKm, aLineDirect)\ aStr.Format(aRailLineName+_T("%.2f")+StrKm+strDirectName[aLineDirect], aKm); #define DECODERAILWAYFULLNAME(aStr, aRailLine, aKm, aLineDirect)\ aStrLine.Delete(aStrLine.GetLength()-StrKm.GetLength(), StrKm.GetLength());\ for (int i=0; i<RailLineNameCount; i++)\ {\ if(aStrLine.Find(RailLineName[i]) == 0)\ {\ aRailLine = static_cast<RailLine>(i);\ aStrLine.Delete(0, RailLineName[i].GetLength());\ aKm = _ttoi(aStrLine);\ break;\ }\ }; //enum RailLine //{ // Baoji_Chengdu = 0, // Chengdu_Kunming, // Chengdu_Chongqing //}; enum DevState { KRunning = 1, KClosed = 2 }; enum LineDirect { KDownLine = 1, KUpLine = 2 }; enum LineStartNo { KUndefine=0, KFirstDay, KSecondDay, KThirdDay, KFourthDay, KFifthDay, KSixthDay, KSeventhDay }; enum EmergencyStatus { KNormal=0, KFinished }; enum DeviceType { KPicture = 1, KVideo }; enum PictureErrorType { KUnkownType = 0, KDamage = 1, KRailBroken, KAccessoriesFailure, KSleeperFailure, RoadFrothing, SlopCollapse }; enum PointState { KUnkownState = 0, KPointNormal = 1, KPointDelay, KPointUnArrived }; #define PERMISSIONSETPOINT 0x0001 #define PERMISSIONSETLINE 0x0002 #define PERMISSIONSETSTAFF 0x0004 #define PERMISSIONSCHEDULE 0x0008 #define PERMISSIONSETEMERGENCY 0x0010 #define PERMISSIONSETORG 0x0020 #define PERMISSIONSETDEVICE 0x0040 #define PERMISSIONINITIALPASSWORD 0x0080 #define PERMISSIONVIEWPICTURE 0x0100 #define PERMISSIONVIEWVOICE 0x0200 #define PERMISSIONVIEWRECORDE 0x0400 #define PERMISSIONVIEWREPORT 0x0800 typedef struct _Single { _Single() { iBasical = 0; iOperate = 0; iReportForm = 0; } int iBasical; int iOperate; int iReportForm; }PermissionGroup; typedef struct _MapPoint { _MapPoint() { iKM = 0.0; iLon = 0.0; iLat = 0.0; iDirect = KDownLine; } RailLine* iRailLine;//铁路线 double iKM;//公里处 double iLon; double iLat; LineDirect iDirect;//上下行 int iPointId;//点id 从数据库数据 }MapPoint; struct _Staff; typedef struct _Line //线路 { _Line() { iLineID = 0; iLineName = _T(""); iOrgID = 0; iStartKm = 0.0; iStartNo = KFirstDay; iLineRemark = _T(""); } int iLineID; CString iLineName; int iOrgID;//所属机构 double iStartKm; LineStartNo iStartNo;//开始天数 vector<MapPoint*> iLineKmLonLat; //每公里处经纬度 vector<time_t> iLineKmTime; //每公里处时间 CString iLineRemark;//备注 }LineInfo; typedef struct _Device //设备 { _Device() { iDevID = 0; iOrgID = 0; iDeviceType = KPicture; } int iDevID; int iOrgID;//所属机构 CString iPhoneNum; DeviceType iDeviceType; }DeviceInfo; typedef struct _Staff { _Staff() { iOrgID = 0; iLoginPermission = FALSE; iTakeDevice = NULL; iPermissionGroup = 0; } CString iID; int iOrgID; CString iName; CString iPassword; BOOL iLoginPermission; DeviceInfo* iTakeDevice; //所持设备 int iPermissionGroup; }StaffInfo; typedef struct _Calendar //排班表 { _Calendar() { iCaledarID = 0; iOrgID = 0; iStartDay = 0; iPeriods = 0; } int iCaledarID; int iOrgID; time_t iStartDay;//开始日期 int iPeriods;//周期 vector<StaffInfo*> iScheduleStaff; CString iScheduleRemark;//备注 }CalendarSchedule; typedef struct _Emergency { int iTaskID; int iOrgId; CString iTaskName; int iRailLine; int iBeginKm;//开始处 int iEndKm;//终点 time_t iBeginTime;//开始处时间 time_t iEndTime;//终点处时间 EmergencyStatus iStatus;//0正常,1结束 CString iEmergencyRemark; vector<int> iStaffOrgID; vector<CString> iStaffID; vector<CString> iStaffName; }EmergencyTaskInfo; typedef struct _EmergencyLogs//紧急任务的统计信息 { int iTaskID;//任务号 int iStaffOrgID;//人员所属机构 CString iStaffID;//人员ID CString iStaffName;//人员姓名 CString iTotalTime;//总共行走时间 double iTotalKM;//总共行走距离 }EmergencyLogs; typedef struct _RecordStaff//员工所巡查流水 { CString iStaffID; //走过所有点的经纬度以及到达时间 vector<double> iRecordLon; vector<double> iRecordLat; vector<CString> iArrivedTime; }RecordStaff; // //typedef struct _PointArriveInfo //{ // int iRailLineID;//铁路线ID // double iPointKM;//公里处 // CString iStaffID;//员工号 // cstr // CString iPlanArrivedTime;//应该到时间 // CString iActualArrivedTime;//实到时间 // PointState iState;//状态 //}PointArriveInfo; // //typedef struct _ReportAlarm//月告警明细 //{ // CString iDay;//告警日期 // //所有经过点的计划到达时间/实际到达时间/状态 // vector<int> iRailLineID;//铁路线ID // vector<double> iPointKM;//公里处 // vector<CString> iPlanArrivedTime; // vector<CString> iActualArrivedTime; // vector<PointState> iState; //}ReportAlarm; typedef struct _ReportDetail//日明细、告警明细 { vector<CString> iDay;//日期 //所有经过点的计划到达时间/实际到达时间/状态 vector<CString> iStaffID;//员工号 vector<CString> iRailLineID;//铁路线名 vector<double> iPointKM;//公里处 vector<CString> iPlanArrivedTime; vector<CString> iActualArrivedTime; vector<PointState> iState; }ReportDetail; typedef struct _ReportInfo//机构月报表 { _ReportInfo() { iOrgID = 0; iPlanArrived = 0; iActualArrived = 0; iAbnormal = 0; iUnArrived = 0; } int iOrgID; CString iStaffName; CString iReportDay;//报告时间 CString iWeekDay;//星期 int iPlanArrived;//计划到达数 int iActualArrived;//实际到达数 int iAbnormal;//异常数 int iUnArrived;//未到达 }ReportInfo; typedef struct _OrgObj //机构 { inline _OrgObj() { iOrgID = 0; iOrgLevel = 0; iOrgName = _T(""); iOrgAddress = _T(""); iParentOrg = NULL; iDataSet = FALSE; iEmergencyDataSet = FALSE; iBoundaryStartKM = 0; iBoundaryEndKM = 0; iCalendar = new CalendarSchedule; iMapPointSet = FALSE; iStaffSet = FALSE; iDeviceSet = FALSE; iLineSet = FALSE; iCalendarSet = FALSE; iEmergencySet = FALSE; //iSystemConfigure = new OrgSystemConfigure; } //机构基本信息 int iOrgID; int iOrgLevel; CString iOrgName; CString iOrgAddress; int iParentID; struct _OrgObj* iParentOrg;//上级机构 vector<int> iChildID; vector<struct _OrgObj*> iChildOrg;//直接下级机构 int iBoundaryRail;//管辖的铁路线 unsigned int iBoundaryStartKM; unsigned int iBoundaryEndKM; BOOL iDataSet;//机构基本信息是否已经获取 BOOL iEmergencyDataSet;//紧急任务数据是否已经获取 //机构附属信息 //OrgSystemConfigure* iSystemConfigure;//系统配置 vector<MapPoint*> iMapPoint; BOOL iMapPointSet; vector<StaffInfo*> iStaff;//该机构的人员 BOOL iStaffSet; vector<DeviceInfo*> iDevice;//该机构拥有的设备 BOOL iDeviceSet; vector<LineInfo*> iLine;//该机构配置的路线,若不为最后一级,则为NULL BOOL iLineSet; CalendarSchedule* iCalendar;//该机构的排班表 BOOL iCalendarSet; vector<EmergencyTaskInfo*> iEmergency; BOOL iEmergencySet; vector<ReportInfo*> iReportInfo; }OrganizationInfo; typedef struct _PictureInfo//图片信息 { unsigned int iPicID; CString iPicName; CString iShootingTime; int iErrorType; }PictureInfo; ///机构月报表 typedef struct { unsigned int orgid; unsigned int yesrs; unsigned int months; }GetOrgPxEx; typedef struct { CString userid; CString dates; CString xj; unsigned int sTotlePoint;//总点数 unsigned int sGetPoint;//到达点数 正常 unsigned int cPoint;//未正常到达点 unsigned int lPoint;//没有达到点 }getorgpxlistresultEx; //typedef vector <getorgpxlistresult> lOrgMonth; //typedef lOrgMonth::iterator iterOrgMonth;
[ "[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3", "[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3" ]
[ [ [ 1, 234 ], [ 236, 412 ] ], [ [ 235, 235 ] ] ]
a17c4eab299e89ce148e6784a0fae70b930cce3a
29792c63c345f87474136c8df87beb771f0a20a8
/vcmp/net/vehiclepool.cpp
89f7fdc3751ba779a050b435964e32d84eb693c0
[]
no_license
uvbs/jvcmp
244ba6c2ab14ce0a757f3f6044b5982287b01fae
57225e1c52085216a0a4a9c4e33ed324c1c92d39
refs/heads/master
2020-12-29T00:25:39.180996
2009-06-24T14:52:39
2009-06-24T14:52:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,471
cpp
// File Author: kyeman #include "../main.h" #include "../game/util.h" extern CGame *pGame; extern CNetGame *pNetGame; extern CChatWindow *pChatWindow; //---------------------------------------------------- CVehiclePool::CVehiclePool() { BYTE byteVehicleID = 0; while(byteVehicleID != MAX_VEHICLES) { m_bVehicleSlotState[byteVehicleID] = FALSE; m_pVehicles[byteVehicleID] = NULL; m_pGTAVehicles[byteVehicleID] = NULL; byteVehicleID++; } } //---------------------------------------------------- CVehiclePool::~CVehiclePool() { BYTE byteVehicleID = 0; while(byteVehicleID != MAX_VEHICLES) { Delete(byteVehicleID); byteVehicleID++; } } //---------------------------------------------------- BOOL CVehiclePool::New( BYTE byteVehicleID, BYTE byteVehicleType, VECTOR * vecPos, float fRotation, int iColor1, int iColor2, VECTOR * vecSpawnPos, float fSpawnRotation ) { // Setup the spawninfo for the next respawn. m_SpawnInfo[byteVehicleID].byteVehicleType = byteVehicleType; m_SpawnInfo[byteVehicleID].vecPos.X = vecSpawnPos->X; m_SpawnInfo[byteVehicleID].vecPos.Y = vecSpawnPos->Y; m_SpawnInfo[byteVehicleID].vecPos.Z = vecSpawnPos->Z; m_SpawnInfo[byteVehicleID].fRotation = fSpawnRotation; m_SpawnInfo[byteVehicleID].iColor1 = iColor1; m_SpawnInfo[byteVehicleID].iColor2 = iColor2; // Now go ahead and spawn it at the location we got passed. return Spawn(byteVehicleID,byteVehicleType,vecPos,fRotation,iColor1,iColor2); } //---------------------------------------------------- BOOL CVehiclePool::Delete(BYTE byteVehicleID) { if(!GetSlotState(byteVehicleID) || !m_pVehicles[byteVehicleID]) { return FALSE; } m_bVehicleSlotState[byteVehicleID] = FALSE; delete m_pVehicles[byteVehicleID]; m_pVehicles[byteVehicleID] = NULL; return TRUE; } //---------------------------------------------------- BOOL CVehiclePool::Spawn( BYTE byteVehicleID, BYTE byteVehicleType, VECTOR * vecPos, float fRotation, int iColor1, int iColor2 ) { if(m_pVehicles[byteVehicleID] != NULL) { Delete(byteVehicleID); } m_pVehicles[byteVehicleID] = pGame->NewVehicle(byteVehicleType, vecPos->X,vecPos->Y,vecPos->Z,fRotation); if(m_pVehicles[byteVehicleID]) { if(iColor1 != (-1)) { m_pVehicles[byteVehicleID]->SetColor(iColor1,iColor2); } m_pGTAVehicles[byteVehicleID] = m_pVehicles[byteVehicleID]->m_pVehicle; m_bVehicleSlotState[byteVehicleID] = TRUE; m_bIsActive[byteVehicleID] = TRUE; m_bIsWasted[byteVehicleID] = FALSE; return TRUE; } else { return FALSE; } } //---------------------------------------------------- int CVehiclePool::FindIDFromGtaPtr(VEHICLE_TYPE * pGtaVehicle) { int x=1; while(x!=MAX_VEHICLES) { if(pGtaVehicle == m_pGTAVehicles[x]) return x; x++; } return (-1); } //---------------------------------------------------- int CVehiclePool::FindGtaIDFromID(int iID) { return GamePool_Vehicle_GetIndex(m_pGTAVehicles[iID]); } //---------------------------------------------------- void CVehiclePool::Process() { BYTE x=0; CVehicle *pVehicle; DWORD dwThisTime = GetTickCount(); while(x != MAX_VEHICLES) { if(GetSlotState(x) == TRUE) { // It's inuse. pVehicle = m_pVehicles[x]; if(m_bIsActive[x]) { if(pVehicle->GetHealth() == 0.0f) { // It's dead SetForRespawn(x); } else if(pVehicle->HasExceededWorldBoundries( pNetGame->m_WorldBounds[0],pNetGame->m_WorldBounds[1], pNetGame->m_WorldBounds[2],pNetGame->m_WorldBounds[3])) { if(pVehicle->IsOkToRespawn()) { SetForRespawn(x); } } else if(pVehicle->GetVehicleSubtype() != VEHICLE_SUBTYPE_BOAT && pVehicle->GetVehicleSubtype() != VEHICLE_SUBTYPE_PLANE && pVehicle->HasSunk()) // Not boat and has sunk. { SetForRespawn(x); } else { if(pVehicle->IsDriverLocalPlayer()) { pVehicle->SetInvulnerable(FALSE); } else { pVehicle->SetInvulnerable(TRUE); } // Lock vehicles beyond given radius. if(pVehicle->GetDistanceFromLocalPlayerPed() > 300.0f) { pVehicle->SetLockedState(1); } else { pVehicle->SetLockedState(0); } if(pVehicle->GetVehicleSubtype() == VEHICLE_SUBTYPE_BIKE) { pVehicle->VerifyControlState(); } // code to respawn vehicle after it has been idle for 4 minutes pVehicle->UpdateLastDrivenTime(); if(pVehicle->m_bHasBeenDriven) { if((dwThisTime - pVehicle->m_dwTimeSinceLastDriven) > 250000) { SetForRespawn(x); } } } } else // !m_bIsActive { if(m_iRespawnDelay[x] != 0) { m_iRespawnDelay[x]--; } else { if(pVehicle->IsOkToRespawn()) { Spawn(x,m_SpawnInfo[x].byteVehicleType,&m_SpawnInfo[x].vecPos, m_SpawnInfo[x].fRotation,m_SpawnInfo[x].iColor1,m_SpawnInfo[x].iColor2); } } } } x++; } } //---------------------------------------------------- void CVehiclePool::SetForRespawn(BYTE byteVehicleID) { CVehicle *pVehicle = m_pVehicles[byteVehicleID]; if(pVehicle->IsOkToRespawn()) { m_bIsActive[byteVehicleID] = FALSE; m_bIsWasted[byteVehicleID] = TRUE; m_iRespawnDelay[byteVehicleID] = 150; } } //----------------------------------------------------
[ "jacks.mini.net@43d76e2e-6035-11de-a55d-e76e375ae706" ]
[ [ [ 1, 219 ] ] ]
d585298c3262b356369e6c82866a32d904480698
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCTestLib/SolidSBCCPUConfig.cpp
9fd793d99cc32513896b16831395fe04da4f0777
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
cpp
#include "StdAfx.h" #include "SolidSBCCPUConfig.h" CSolidSBCCPUConfig::CSolidSBCCPUConfig(const CString& strXml) : CSolidSBCTestConfig(_T(SSBC_CPU_TEST_NAME),strXml) { RegisterAttributes(); Init(); } CSolidSBCCPUConfig::~CSolidSBCCPUConfig(void) { } void CSolidSBCCPUConfig::RegisterAttributes(void) { RegisterAttribute(_T("Randomize"), _T("1")); RegisterAttribute(_T("MaxRand") , _T("20")); RegisterAttribute(_T("SleepMS") , _T("5.000000")); RegisterAttribute(_T("ThreadCnt"), _T("2")); } BOOL CSolidSBCCPUConfig::GetRandomize(void) { BOOL bRandomize = false; GetAttributeByName<BOOL>(_T("Randomize"), bRandomize); return bRandomize; } UINT CSolidSBCCPUConfig::GetMaxRand(void) { UINT nMaxRand = 0; GetAttributeByName<UINT>(_T("MaxRand"), nMaxRand); return nMaxRand; } double CSolidSBCCPUConfig::GetSleepMS(void) { double dSleepMS = 0.0; GetAttributeByName<double>(_T("SleepMS"), dSleepMS); return dSleepMS; } UINT CSolidSBCCPUConfig::GetThreadCnt(void) { UINT nThreadCnt = 0; GetAttributeByName<UINT>(_T("ThreadCnt"), nThreadCnt); return nThreadCnt; }
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 49 ] ] ]
5834ee039c824a37e72d5c1637bfe8fd9f82ef7b
6a1a184ceb7be1f73c490fcbaf8fba7a64cab1ff
/Source/TestFluidic/TestScene2D.cpp
2817a107ec22b1f23d5bbe0efd96e8615dc2c481
[ "MIT" ]
permissive
alexsaen/fluidic
c8aa913ce03e8d3d9bc8091a31aa96a7d1e5b4ad
bf7eb0f3e9ca4e15f53623020c7f0313315f4e49
refs/heads/master
2020-12-24T15:14:17.261742
2010-04-06T13:10:54
2010-04-06T13:10:54
32,979,664
1
0
null
null
null
null
UTF-8
C++
false
false
4,296
cpp
/* Copyright (c) 2010 Steven Leigh Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "TestScene2D.h" #include <GL/glut.h> using namespace Fluidic; using namespace TestFluidic; TestScene2D::TestScene2D() { fluid = new Fluid2D(CG_PROGRAM_DIR); options = Fluid2D::DefaultOptions(); fluid->Init(options); fluid->SetColorDensities(1, 0, -1); obj = new TestObject(options.Size/2, Vector::Zero2D(), 1); fluid->AttachPoller(obj); glMatrixMode (GL_PROJECTION); glLoadIdentity(); glOrtho(0, options.Size.x, 0, options.Size.y, 0, 4); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } TestScene2D::~TestScene2D() { glDisable(GL_BLEND); cgDestroyContext(cgContext); } void TestScene2D::Interact() { TestScene::Interact(); } void TestScene2D::Update(float time) { float xPos = options.Size.x * (float)mouseState.x / options.RenderResolution.x; float yPos = options.Size.y * (1 - (float)mouseState.y/options.RenderResolution.y); Vector position(xPos, yPos); float dx = options.Size.x * (float)mouseState.dx / options.RenderResolution.x; float dy = -options.Size.y * (float)mouseState.dy / options.RenderResolution.y; Vector d(dx, dy); bool lmb = ((mouseState.buttons & MB_LEFT) == MB_LEFT); bool mmb = ((mouseState.buttons & MB_MIDDLE) == MB_MIDDLE); bool rmb = ((mouseState.buttons & MB_RIGHT) == MB_RIGHT); bool ctrl = (mouseState.modifiers & GLUT_ACTIVE_CTRL) == GLUT_ACTIVE_CTRL; bool shift = (mouseState.modifiers & GLUT_ACTIVE_SHIFT) == GLUT_ACTIVE_SHIFT; bool noMods = !ctrl && !shift; float size = options.Size.Length(); if (lmb || rmb || mmb) { //dye injection if (lmb && noMods) fluid->Inject(position, 40*time, 0, 0, 0.05f * size, false); //red if (rmb && noMods) fluid->Inject(position, 0, 40*time, 0, 0.05f * size, false); //green if (mmb && noMods) fluid->Inject(position, 0, 0, 40*time, 0.05f * size, false); //blue //fluid perturbation if (lmb && ctrl) fluid->Perturb(position, d*5, 0.025f*size); //normal if (rmb && ctrl) fluid->Perturb(position, d, 0.025*size); //slow if (mmb && ctrl) fluid->Perturb(position, d*20, 0.025*size); //fast // arbitrary boundaries if (lmb && shift) fluid->AddArbitraryBoundary(position, 0.05*size); if (mmb && shift) fluid->AddArbitraryBoundary(position, 0.1*size); if (rmb && shift) fluid->AddArbitraryBoundary(position, 0.2*size); } TestScene::Update(time); fluid->Update(time); obj->Update(time); } void TestScene2D::Display() { glPushMatrix(); glTranslatef(options.Size.x*0.1, options.Size.y*0.4, 0); glScalef(options.Size.x*0.8, options.Size.y*0.2, 0); DrawFluidText(); glPopMatrix(); fluid->Render(); glColor3f(1, 1, 1); glPushMatrix(); const Vector &objPosition = obj->GetPosition(); glTranslatef(objPosition.x, objPosition.y, 0); glutSolidSphere(options.Size.Length()/80, 16, 16); glPopMatrix(); } void TestScene2D::Resize(int w, int h) { options.Size = options.Size * Vector(w, h) / options.RenderResolution; glMatrixMode (GL_PROJECTION); glLoadIdentity(); glOrtho(0, options.Size.x, 0, options.Size.y, 0, 4); glMatrixMode (GL_MODELVIEW); TestScene::Resize(w, h); }
[ "xwipeoutx@6c3c8482-2914-11df-ad47-1d73243ccc9f" ]
[ [ [ 1, 131 ] ] ]
8a7de51db0e64fe93485084bb7f5cec4c2ec5e6c
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/MediaPlayers/DShowEngine.h
2311a228d88f8ffae5f8a7372675020cbc4a1452
[]
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
4,503
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #ifndef _DShowEngine_h_ #define _DShowEngine_h_ #include "MediaPlayerEngine.h" struct IGraphBuilder; struct IMediaSeeking; struct IMediaControl; struct IMediaEventEx; struct IMediaPosition; struct IVideoWindow; struct IBasicAudio; struct IBaseFilter; struct IVMRWindowlessControl; struct IFilterGraph; #ifdef _UNITTESTING BOOL TestDShowEngine(); #endif class DShowEngine:public MediaPlayerEngine { friend class CDShowWnd; public: DShowEngine(); virtual ~DShowEngine(); virtual void SetConfig(MediaEngineConfigOption meco, INT value) {} virtual INT GetConfig(MediaEngineConfigOption meco) {return -1;} virtual BOOL Supports(MediaEngineConfigOption meco) {return FALSE;} virtual void SetEventTarget(EventTarget* evTarg) {m_pEvTarget = evTarg;} virtual EventTarget* GetEventTarget() {return m_pEvTarget;} //This will be The MediaPlayer Engine virtual BOOL Open(LPCTSTR str); virtual void Close(); //Playback Commands virtual BOOL Start(); virtual BOOL Pause(); virtual BOOL Stop(); virtual PlayState GetPlayState(); virtual INT GetMediaInfo(MediaEngineOptionalIntInfoEnum meoii); virtual LPCTSTR GetLocation(); virtual DOUBLE GetMediaLength(); //Media Position is seconds virtual DOUBLE GetMediaPos(); virtual void SetMediaPos(DOUBLE secs); //Settings //Should be between 0-100 virtual void SetVolume(INT volume); virtual INT GetVolume(); virtual void SetMute(BOOL bMute); virtual BOOL GetMute(); virtual BOOL CanPlay(LPCTSTR str); virtual MediaEngineState GetEngineState(); virtual MediaEngineErrorEnum GetLastError(); virtual BOOL IsVideo() {return m_bIsVideo;} virtual BOOL GetSoundData(MediaEngineSoundData mesd, void* buffer, UINT bufferLen) {return FALSE;} virtual const TCHAR* GetEngineDescription() {return _T("Direct Show");} virtual void SetVideoContainerHWND(HWND hwnd); virtual HWND GetVideoContainerHWND(); virtual void SetVideoPosition(int x, int y, int cx, int cy); private: HWND GetVideoHWND(); HRESULT InitializeWindowlessVMR( HWND hwndApp, // Application window. IFilterGraph* pFG, // Pointer to the Filter Graph Manager. IVMRWindowlessControl** ppWc, // Receives the interface. DWORD dwNumStreams, // Number of streams to use. BOOL fBlendAppImage // Are we alpha-blending a bitmap? ); HWND m_hwndVideoContainer; HWND m_hwndVideo; HWND m_hwndVideoHiddenContainer; void InitWindow(); void SetRealVolume(INT volume); //HWND m_hwndVideo; MediaEngineState m_EngineState; MediaEngineErrorEnum m_LastError; void SetError(LPCTSTR msg); void PlayStateChanged(); //void OnSize(UINT nType, int cx, int cy); EventTarget* m_pEvTarget; //MediaInfo m_mf; std::tstring m_location; void OnGraphEvent(); void OnDisplayModeChanged(); BOOL OnPaint(); IGraphBuilder* m_pGraphBuilder; IMediaSeeking* m_pMediaSeeking; IMediaControl* m_pMediaControl; IMediaEventEx* m_pMediaEvent; IMediaPosition* m_pMediaPosition; IVideoWindow* m_pVideoWindow; IBasicAudio* m_pBasicAudio; IBaseFilter* m_pVMR; IVMRWindowlessControl* m_pWindowlessControl; BOOL m_bIsVideo; BOOL m_bFullScreen; //INT m_mutedVolume; BOOL m_bMuted; INT m_volume; DWORD m_dwCaps; //DWORD m_oldStyle; static LRESULT CALLBACK WindowProcST(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); LRESULT WinProc(UINT message, WPARAM wParam, LPARAM lParam, BOOL& bHandled); //CPlayerWindow m_PlayerWindow; //CRect m_oldRect; }; #endif
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 153 ] ] ]
e80fe7ce0e27f423afc2f7fbc52ac0d77c9e8b4c
1c028f7f14916bec8ee5a686d2c7bf9abff77a8e
/cse486/termProj/TERM/linklist2.h
8552a982bed7eed72d2e5e594645af9e1c97d193
[]
no_license
jasonfsmitty/psu_projects
f70a88664352f79be137d1bc429eeb23a13e0fe0
0a29e57dd942bf36212b6c054331b5c728e0b6a8
refs/heads/master
2021-01-19T13:32:59.539871
2009-07-09T02:20:30
2009-07-09T02:20:30
232,685
0
0
null
null
null
null
UTF-8
C++
false
false
9,513
h
/*---------------------------------------------------------------------------+ linklist2.h Jason F Smith A double linked list template. I didn't like my old one, so I wrote this one rather quickly. Maybe if I use it again I'll add more to it. +---------------------------------------------------------------------------*/ #ifndef LINKED_LIST_H #define LINKED_LIST_H #include <iostream.h> #include <stddef.h> //////////////////////////////////////////////////////////// #if defined( DEBUG ) # define LINKLIST_DEBUG # pragma message ("INFO - LinkList template debug: ON") #else # pragma message ("INFO - LinkList template debug: OFF") #endif //////////////////////////////////////////////////////////// template <class T> struct Node { T data; Node* next; Node* prev; }; // struct Node ///////////////////////////////////////////////////////////// template <class T> class LinkList { protected: Node<T> *head; Node<T> *tail; Node<T> *current; int size; public: LinkList( void ); ~LinkList( void ); int DeleteAll( void ); bool DeleteCurrent( void ); bool MoveForward( void ); bool MoveBackward( void ); T& operator[]( int index ); T& GetCurrent( void ); int GetSize( void ); bool SetCurrent( int index ); bool MoveToTail( void ); bool MoveToHead( void ); bool InsertBefore( T add ); bool InsertAfter( T add ); bool InsertAtTail( T add ); bool InsertAtHead( T add ); bool IsEmpty( void ); }; // class LinkList<T> ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // now on to the actual code... ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> LinkList<T>::LinkList( void ) { head = tail = current = NULL; size = 0; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> LinkList<T>::~LinkList( void ) { DeleteAll(); } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> int LinkList<T>::DeleteAll( void ) { int i; while( head ){ current = head; head = head->next; delete current; i++; } // now set up the variables correctly head = tail = current = NULL; size = 0; return i; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::DeleteCurrent( void ) { if( !current ){ #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - error deleting current (LinkList::DeleteCurrent), no current\n"; #endif // LINKLIST_DEBUG return false; } if( current->prev ) current->prev->next = current->next; else // no previous must be head head = current->next; if( current->next ) current->next->prev = current->prev; else // no next, must be at tail tail = current->prev; delete current; current = head; size--; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::MoveForward( void ) { if( !current || !current->next ){ #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not move forward - LinkedList::MoveForward()\n"; #endif // LINKLIST_DEBUG return false; } current = current->next; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::MoveBackward( void ) { if( !current || !current->prev ){ #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not move backward - LinkList::MoveBackward()\n"; #endif // LINKLIST_DEBUG return false; } current = current->prev; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> T& LinkList<T>::operator[]( int index ) { static T dummy; if( SetCurrent(index) ) return (current->data); #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not use [] operator, invalid call to SetCurrent() - LinkeList::operator[]()\n"; #endif // LINKLIST_DEBUG return dummy; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> T& LinkList<T>::GetCurrent( void ) { static T dummy; if( !current ){ #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not return current, (none to return) - LinkList::GetCurrent()\n"; #endif // LINKLIST_DEBUG return dummy; } return (current->data); } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> int LinkList<T>::GetSize( void ) { return size; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::SetCurrent( int index ) { if( index<0 || index>=size ) { #if defined( LINKLIST_DEBUG ) if( index<0 ) cout <<"DEBUG - could not set current, index<0 - LinkList::SetCurrent()\n"; else cout <<"DEBUG - could not set current, index>=size - LinkList::SetCurrent()\n"; #endif // LINKLIST_DEBUG return false; } current=head; for( int i=0; i<index; i++ ) current = current->next; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::MoveToTail( void ) { return ((current=tail)!=NULL); } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::MoveToHead( void ) { return ((current=head)!=NULL); } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::InsertBefore( T add ) { Node<T>* temp; if( !current || (current==head) ) return InsertAtHead(); temp = new Node<T>; if( !temp ) { #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not insert node (new failed) - LinkList::InsertBefore()\n"; #endif // LINKLIST_DEBUG return false; } memcpy( (void*)&(temp->data), (void*)&add, sizeof( T ) ); temp->next = current; temp->prev = current->prev; current->prev->next = temp; current->prev = temp; current = temp; size++; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::InsertAfter( T add ) { Node<T>* temp; if( !current || (current==tail) ) return InsertAtTail(); temp = new Node<T>; if( !temp ) { #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not insert node (new failed) - LinkList::InsertAfter()\n"; #endif // LINKLIST_DEBUG return false; } memcpy( (void*)&(temp->data), (void*)&add, sizeof( T ) ); temp->prev = current; temp->next = current->next; current->next->prev = temp; current->next = temp; current = temp; size++; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::InsertAtTail( T add ) { Node<T>* temp; temp = new Node<T>; if( !temp ) { #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not insert node (new failed) - LinkList::InsertAtTail()\n"; #endif // LINKLIST_DEBUG return false; } memcpy( (void*)&(temp->data), (void*)&add, sizeof( T ) ); if( !tail ){ head = tail = temp; } else { tail->next = temp; temp->prev = tail; temp->next = NULL; tail = temp; } size++; current = temp; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::InsertAtHead( T add ) { Node<T>* temp; temp = new Node<T>; if( !temp ) { #if defined( LINKLIST_DEBUG ) cout <<"DEBUG - could not insert node (new failed) - LinkList::InsertAtHead()\n"; #endif // LINKLIST_DEBUG return false; } memcpy( (void*)&(temp->data), (void*)&add, sizeof( T ) ); if( head ){ head->prev = temp; temp->next = head; temp->prev = NULL; head = temp; } else { head = tail = temp; } size++; current = temp; return true; } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// template <class T> bool LinkList<T>::IsEmpty( void ) { return (size==0); } ///////////////////////////////////////////// ///////////////////////////////////////////// #ifdef LINKLIST_DEBUG #undef LINKLIST_DEBUG #endif ///////////////////////////////////////////// #endif // ! LINKED_LIST_H
[ "jasmith@bumblebee.(none)" ]
[ [ [ 1, 397 ] ] ]
0820a227375666a35d61c5ab00f717251ed3be2c
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/MemoryIOWrapper.h
e3b2b2d0adcbcc50f83b9fdf1760b06a9e82744b
[ "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
5,806
h
/* 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 MemoryIOWrapper.h * Handy IOStream/IOSystem implemetation to read directly from a memory buffer */ #ifndef AI_MEMORYIOSTREAM_H_INC #define AI_MEMORYIOSTREAM_H_INC namespace Assimp { #define AI_MEMORYIO_MAGIC_FILENAME "$$$___magic___$$$" #define AI_MEMORYIO_MAGIC_FILENAME_LENGTH 17 // ---------------------------------------------------------------------------------- /** Implementation of IOStream to read directly from a memory buffer */ // ---------------------------------------------------------------------------------- class MemoryIOStream : public IOStream { //friend class MemoryIOSystem; public: MemoryIOStream (const uint8_t* buff, size_t len) : buffer (buff), length(len), pos((size_t)0) { } public: ~MemoryIOStream () { } // ------------------------------------------------------------------- // Read from stream size_t Read(void* pvBuffer, size_t pSize, size_t pCount) { const size_t cnt = std::min(pCount,(length-pos)/pSize),ofs = pSize*cnt; memcpy(pvBuffer,buffer+pos,ofs); pos += ofs; return cnt; } // ------------------------------------------------------------------- // Write to stream size_t Write(const void* /*pvBuffer*/, size_t /*pSize*/,size_t /*pCount*/) { ai_assert(false); // won't be needed return 0; } // ------------------------------------------------------------------- // Seek specific position aiReturn Seek(size_t pOffset, aiOrigin pOrigin) { if (aiOrigin_SET == pOrigin) { if (pOffset >= length) { return AI_FAILURE; } pos = pOffset; } else if (aiOrigin_END == pOrigin) { if (pOffset >= length) { return AI_FAILURE; } pos = length-pOffset; } else { if (pOffset+pos >= length) { return AI_FAILURE; } pos += pOffset; } return AI_SUCCESS; } // ------------------------------------------------------------------- // Get current seek position size_t Tell() const { return pos; } // ------------------------------------------------------------------- // Get size of file size_t FileSize() const { return length; } // ------------------------------------------------------------------- // Flush file contents void Flush() { ai_assert(false); // won't be needed } private: const uint8_t* buffer; size_t length,pos; }; // --------------------------------------------------------------------------- /** Dummy IO system to read from a memory buffer */ class MemoryIOSystem : public IOSystem { public: /** Constructor. */ MemoryIOSystem (const uint8_t* buff, size_t len) : buffer (buff), length(len) { } /** Destructor. */ ~MemoryIOSystem() { } // ------------------------------------------------------------------- /** Tests for the existence of a file at the given path. */ bool Exists( const char* pFile) const { return !strncmp(pFile,AI_MEMORYIO_MAGIC_FILENAME,AI_MEMORYIO_MAGIC_FILENAME_LENGTH); } // ------------------------------------------------------------------- /** Returns the directory separator. */ char getOsSeparator() const { return '/'; // why not? it doesn't care } // ------------------------------------------------------------------- /** Open a new file with a given path. */ IOStream* Open( const char* pFile, const char* /*pMode*/ = "rb") { if (strncmp(pFile,AI_MEMORYIO_MAGIC_FILENAME,AI_MEMORYIO_MAGIC_FILENAME_LENGTH)) { return NULL; } return new MemoryIOStream(buffer,length); } // ------------------------------------------------------------------- /** Closes the given file and releases all resources associated with it. */ void Close( IOStream* /*pFile*/) { } // ------------------------------------------------------------------- /** Compare two paths */ bool ComparePaths (const char* /*one*/, const char* /*second*/) const { return false; } private: const uint8_t* buffer; size_t length; }; } // end namespace Assimp #endif
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 181 ] ] ]
a6e2a49339557d836574ba8ef4b751bddc24584f
42b578d005c2e8870a03fe02807e5607fec68f40
/src/keymap.cc
d8c660f47a19d1d2bdc0b744af15447580421a0a
[ "MIT" ]
permissive
hylom/xom
e2b02470cd984d0539ded408d13f9945af6e5f6f
a38841cfe50c3e076b07b86700dfd01644bf4d4a
refs/heads/master
2021-01-23T02:29:51.908501
2009-10-30T08:41:30
2009-10-30T08:41:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,792
cc
#include "ed.h" #define KEYMAP_LENGTH (128 + 4 * NFUNCTION_KEYS) static inline u_int keymap_length (lisp map) { return u_int (xvector_length (map)); } lisp Fkeymapp (lisp map) { if (map == Qnil) return Qnil; if (symbolp (map)) map = xsymbol_function (map); if (general_vector_p (map)) return xvector_length (map) == KEYMAP_LENGTH ? map : Qnil; return consp (map) && xcar (map) == Qkeymap ? map : Qnil; } lisp Fmake_keymap () { lisp map = make_vector (KEYMAP_LENGTH, Qnil); return map; } lisp Fmake_sparse_keymap () { return xcons (Qkeymap, Qnil); } static u_int full_keymap_index (Char c) { if (function_char_p (c)) { int x = 128 + (c & CCF_CHAR_MASK); if (c & CCF_SHIFT_BIT) x += NFUNCTION_KEYS; if (c & CCF_CTRL_BIT) x += 2 * NFUNCTION_KEYS; return x; } return c < 128 ? c : -1; } static lisp parse_keymap (Char c, lisp map) { if (general_vector_p (map)) { u_int i = full_keymap_index (c); if (i < keymap_length (map)) return xvector_contents (map) [i]; return Qnil; } if (consp (map) && xcar (map) == Qkeymap) { lisp cc = make_char (c); for (map = xcdr (map); consp (map); map = xcdr (map)) { lisp p = xcar (map); if (consp (p) && xcar (p) == cc) return xcdr (p); } } return Qnil; } lisp Fcurrent_selection_keymap () { Window *wp = selected_window (); if (wp->w_selection_type != Buffer::SELECTION_VOID) switch (wp->w_selection_type & Buffer::SELECTION_TYPE_MASK) { case Buffer::SELECTION_LINEAR: case Buffer::SELECTION_REGION: case Buffer::SELECTION_RECTANGLE: return Fkeymapp (symbol_value (Vselection_keymap, wp->w_bufp)); } return Qnil; } lisp lookup_keymap (Char c, lisp *map, int n) { int i; if (meta_function_char_p (c)) { for (i = 0; i < n; i++) map[i] = parse_keymap (CC_ESC, Fkeymapp (map[i])); c = meta_function_to_function (c); } else if (meta_char_p (c)) { for (i = 0; i < n; i++) map[i] = parse_keymap (CC_ESC, Fkeymapp (map[i])); c = meta_char_to_char (c); } lisp *save = 0; if (alpha_char_p (c)) { save = (lisp *)alloca (sizeof *save * n); memcpy (save, map, sizeof *save * n); } for (i = 0; i < n; i++) { map[i] = parse_keymap (c, Fkeymapp (map[i])); if (map[i] != Qnil) save = 0; } if (save) { c = _char_transpose_case (c); for (i = 0; i < n; i++) map[i] = parse_keymap (c, Fkeymapp (save[i])); } int f_contunue = 0; for (i = 0; i < n; i++) if (map[i] != Qnil) { if (!f_contunue && Fkeymapp (map[i]) == Qnil) return map[i]; f_contunue = 1; } return f_contunue ? 0 : Qnil; } lisp Fuse_keymap (lisp keymap, lisp buffer) { if (Fkeymapp (keymap) == Qnil) FEtype_error (keymap, Qkeymap); Buffer::coerce_to_buffer (buffer)->lmap = keymap; return Qt; } lisp Fset_minor_mode_map (lisp keymap, lisp buffer) { if (Fkeymapp (keymap) == Qnil) FEtype_error (keymap, Qkeymap); Buffer *bp = Buffer::coerce_to_buffer (buffer); if (!memq (keymap, bp->lminor_map)) bp->lminor_map = xcons (keymap, bp->lminor_map); return Qt; } lisp Funset_minor_mode_map (lisp keymap, lisp buffer) { Buffer *bp = Buffer::coerce_to_buffer (buffer); return boole (delq (keymap, &bp->lminor_map)); } lisp Fminor_mode_map (lisp buffer) { return Buffer::coerce_to_buffer (buffer)->lminor_map; } static lisp * scan_key_slot (lisp keymap, Char c, int igcase) { if (general_vector_p (keymap)) { u_int i = full_keymap_index (c); if (i >= keymap_length (keymap)) return 0; lisp *v = &xvector_contents (keymap) [i]; if (!igcase || *v != Qnil || !alpha_char_p (c)) return v; i = full_keymap_index (_char_transpose_case (c)); if (i >= keymap_length (keymap)) return 0; return &xvector_contents (keymap) [i]; } lisp cc = make_char (c); for (lisp p = keymap; consp (p); p = xcdr (p)) { lisp x = xcar (p); if (consp (x) && xcar (x) == cc) return &xcdr (x); } if (igcase && alpha_char_p (c)) { cc = make_char (_char_transpose_case (c)); for (p = keymap; consp (p); p = xcdr (p)) { lisp x = xcar (p); if (consp (x) && xcar (x) == cc) return &xcdr (x); } } return 0; } static lisp * make_key_slot (lisp keymap, Char c) { if (general_vector_p (keymap)) { u_int i = full_keymap_index (c); if (i >= keymap_length (keymap)) return 0; return &xvector_contents (keymap) [i]; } if (consp (keymap)) { lisp x = xcons (make_char (c), Qnil); xcdr (keymap) = xcons (x, xcdr (keymap)); return &xcdr (x); } return 0; } static lisp * search_key_slot (lisp keymap, lisp key, int bindp, int igcase) { lisp *v; lisp map = Fkeymapp (keymap); if (map == Qnil) FEtype_error (keymap, Qkeymap); if (charp (key)) { Char c = xchar_code (key); if (meta_char_p (c)) c = meta_char_to_char (c); else if (meta_function_char_p (c)) c = meta_function_to_function (c); else { v = scan_key_slot (map, c, igcase); if (v || !bindp) return v; return make_key_slot (map, c); } v = scan_key_slot (map, CC_ESC, igcase); if (!v) { if (!bindp) return 0; v = make_key_slot (map, CC_ESC); if (!v) return 0; map = *v = Fmake_sparse_keymap (); } else { map = Fkeymapp (*v); if (map == Qnil) { if (!bindp) return 0; map = *v = Fmake_sparse_keymap (); } } v = scan_key_slot (map, c, igcase || !bindp); if (v || !bindp) return v; return make_key_slot (map, c); } if (!consp (key)) FEtype_error (key, xsymbol_value (Qor_character_cons)); while (1) { v = search_key_slot (map, xcar (key), bindp, igcase); if (!v) return 0; key = xcdr (key); if (!consp (key)) return v; map = Fkeymapp (*v); if (map == Qnil) { if (!bindp) return 0; map = *v = Fmake_sparse_keymap (); } if (!bindp) igcase = 1; } } lisp Fdefine_key (lisp keymap, lisp key, lisp fn) { lisp *x = search_key_slot (keymap, key, 1, 0); if (!x) return Qnil; *x = fn; return Qt; } lisp PASCAL Flookup_keymap (lisp keymap, lisp key, lisp ignore_case, lisp symbol_only) { lisp *x = search_key_slot (keymap, key, 0, ignore_case && ignore_case != Qnil); if (!x) return Qnil; if (symbol_only && symbol_only != Qnil) return symbolp (*x) ? *x : Qnil; return *x; } lisp Flocal_keymap (lisp buffer) { return Buffer::coerce_to_buffer (buffer)->lmap; } lisp Fkeymap_index_char (lisp code) { int n = fixnum_value (code); if (n < 0 || n >= KEYMAP_LENGTH) return Qnil; if (n < 128) return make_char (n); n -= 128; Char c = CCF_CHAR_MIN + n % NFUNCTION_KEYS; n /= NFUNCTION_KEYS; if (n & 1) c |= CCF_SHIFT_BIT; if (n & 2) c |= CCF_CTRL_BIT; return make_char (c); } lisp Fkeymap_char_index (lisp c) { check_char (c); u_int i = full_keymap_index (xchar_code (c)); return i < KEYMAP_LENGTH ? make_fixnum (i) : Qnil; } static lisp * expand_keymap (lisp keymap, lisp *buf) { if (general_vector_p (keymap)) return xvector_contents (keymap); for (int i = 0; i < KEYMAP_LENGTH; i++) buf[i] = Qnil; if (consp (keymap) && xcar (keymap) == Qkeymap) for (lisp p = xcdr (keymap); consp (p); p = xcdr (p)) { lisp x = xcar (p); if (consp (x) && charp (xcar (x))) { u_int idx = full_keymap_index (xchar_code (xcar (x))); if (idx < KEYMAP_LENGTH) buf[idx] = xcdr (x); } } return buf; } struct keyseq_list { keyseq_list *prev; keyseq_list *next; Char c; }; static int command_shadow_p (const keyseq_list *p, lisp keymap) { for (; p; p = p->next) { keymap = parse_keymap (p->c, Fkeymapp (keymap)); if (keymap == Qnil) return 0; } return 1; } static int command_shadow_p (keyseq_list *tail, const lisp *shadow, int nshadow) { for (keyseq_list *head = tail, *last = 0; (head->next = last), head->prev; last = head, head = head->prev) ; for (int i = 0; i < nshadow; i++) if (command_shadow_p (head, shadow[i])) return 1; return 0; } static lisp command_keys (lisp command, lisp keymap, keyseq_list *prev, const lisp *shadow, int nshadow) { keyseq_list keyseq; keyseq.prev = prev; int i; lisp result = Qnil; lisp b[KEYMAP_LENGTH]; lisp *map = expand_keymap (Fkeymapp (keymap), b); lisp *p; for (i = 0, p = map; i < KEYMAP_LENGTH; i++, p++) if (*p == command) { lisp lc = Fkeymap_index_char (make_fixnum (i)); keyseq.c = xchar_code (lc); if (!command_shadow_p (&keyseq, shadow, nshadow)) result = Fcons (lc, result); } for (i = 0, p = map; i < KEYMAP_LENGTH; i++, p++) if (Fkeymapp (*p) != Qnil) { lisp lc = Fkeymap_index_char (make_fixnum (i)); keyseq.c = xchar_code (lc); lisp sub = command_keys (command, *p, &keyseq, shadow, nshadow); if (sub != Qnil) result = Fcons (Fcons (lc, sub), result); } return Fnreverse (result); } lisp Fcommand_keys (lisp command, lisp gmap, lisp lmap, lisp minor_map) { if (!minor_map) minor_map = Qnil; int nmaps = xlist_length (minor_map) + 2; lisp *map = (lisp *)alloca (nmaps * sizeof *map); for (lisp *p = map; consp (minor_map); minor_map = xcdr (minor_map)) *p++ = xcar (minor_map); *p++ = lmap; *p++ = gmap; lisp result = Qnil; for (int i = 0; i < nmaps; i++) { lisp r = command_keys (command, map[i], 0, map, i); if (consp (r)) { for (lisp x = r; consp (xcdr (x)); x = xcdr (x)) ; xcdr (x) = result; result = r; } } return result; } static int command_shadow_p (const Char *b, const Char *be, lisp keymap) { for (; b < be; b++) { keymap = parse_keymap (*b, Fkeymapp (keymap)); if (keymap == Qnil) return 0; } return 1; } static int command_shadow_p (const Char *b, const Char *be, const lisp *shadow, int nshadow) { for (int i = 0; i < nshadow; i++) if (command_shadow_p (b, be, shadow[i])) return 1; return 0; } Char * lookup_command_keyseq (lisp command, lisp keymap, const lisp *shadow, int nshadow, Char *keyb, Char *keyp, Char *keye) { if (keyp == keye) return 0; int i; lisp *p; lisp b[KEYMAP_LENGTH]; lisp *map = expand_keymap (Fkeymapp (keymap), b); for (i = 0, p = map; i < KEYMAP_LENGTH; i++, p++) if (*p == command) { *keyp++ = xchar_code (Fkeymap_index_char (make_fixnum (i))); if (!command_shadow_p (keyb, keyp, shadow, nshadow)) return keyp; } for (i = 0, p = map; i < KEYMAP_LENGTH; i++, p++) if (Fkeymapp (*p) != Qnil) { *keyp = xchar_code (Fkeymap_index_char (make_fixnum (i))); Char *e = lookup_command_keyseq (command, *p, shadow, nshadow, keyb, keyp + 1, keye); if (e) return e; } return 0; } static int find_in_current_keymaps (Char c, lisp map) { lisp command = parse_keymap (c, map); return command != Qnil && Fkeymapp (command) == Qnil; } int find_in_current_keymaps (Char c) { if (find_in_current_keymaps (c, xsymbol_value (Vglobal_keymap))) return 1; Buffer *bp = selected_buffer (); if (find_in_current_keymaps (c, bp->lmap)) return 1; if (Flist_length (bp->lminor_map) != Qnil) for (lisp p = bp->lminor_map; consp (p); p = xcdr (p)) if (find_in_current_keymaps (c, xcar (p))) return 1; if (find_in_current_keymaps (c, Fcurrent_selection_keymap ())) return 1; return 0; }
[ [ [ 1, 552 ] ] ]
6b01156c13cc4c4037bbe7b8806877dd7ba9b612
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/Math/QsTransform/hkQsTransform.h
9026e9ccf48720891d46f14da97247bc98807dd5
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,455
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_MATH_QSTRANSFORM_H #define HK_MATH_QSTRANSFORM_H #ifndef HK_MATH_MATH_H # error Please include Common/Base/hkBase.h instead of this file. #endif /// An hkQsTransform represents a T*R*S transformation where translation is /// represented with a vector4, rotation is represented with a quaternion and scale /// is represented with a vector4. /// When applied to a point (hkVector4::setTransformedPos()), the point is first scaled, then rotated and /// finally translated. /// Direct read/write access to the three components of the hkQsTransform is available through he public /// members m_translation, m_rotation, m_scale. Const access can be done through get() methods. /// It is important to notice that, due to the nature of the TRS representation, and since not all affine /// transformations can be represented with an hkQsTransform, operations like multiplications have specific definitions /// in order to keep the result inside the space of hkQsTransforms. /// For more information about this, please check the Havok User Manual. class hkQsTransform { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_MATH, hkQsTransform); // This enum is used to specify a constructor that initializes to identity enum IdentityInitializer { IDENTITY, }; // This enum is used to specify a constructor that initializes to zero enum ZeroInitializer { ZERO, }; /// Default constructor - all elements are uninitialized. HK_FORCE_INLINE hkQsTransform() { } /// Constructor - hkQsTransform(hkQsTransform::IDENTITY) initializes to identity HK_FORCE_INLINE hkQsTransform(IdentityInitializer init); /// Constructor - hkQsTransform(hkQsTransform::ZERO) initializes to zero HK_FORCE_INLINE hkQsTransform(ZeroInitializer init); /// Creates a new hkQsTransform using the rotation r, translation t and scale s HK_FORCE_INLINE hkQsTransform(const hkVector4& translation, const hkQuaternion& rotation, const hkVector4& scale); /// Creates a new hkQsTransform using the rotation r, translation t. Sets scale to identity (1,1,1) HK_FORCE_INLINE hkQsTransform(const hkVector4& translation, const hkQuaternion& rotation); /// Copy constructor HK_FORCE_INLINE hkQsTransform(const hkQsTransform& other); /// Sets the hkQsTransform's values using the rotation quaternion q, translation t and scale s HK_FORCE_INLINE void set(const hkVector4& translation, const hkQuaternion& rotation, const hkVector4& scale); /// Sets this hkQsTransform to be the identity transform. HK_FORCE_INLINE void setIdentity(); /// Returns a global identity transform. HK_FORCE_INLINE static const hkQsTransform& HK_CALL getIdentity(); /// Gets the translation component. HK_FORCE_INLINE const hkVector4& getTranslation() const; /// Sets the translation component. HK_FORCE_INLINE void setTranslation(const hkVector4& t); /// Gets the scale component. HK_FORCE_INLINE const hkVector4& getScale() const; /// Sets the scale component. HK_FORCE_INLINE void setScale(const hkVector4& s); /// Gets the rotation component. HK_FORCE_INLINE const hkQuaternion& getRotation() const; /// Sets the rotation component (using a hkQuaternion). HK_FORCE_INLINE void setRotation(const hkQuaternion& rotation); /// Sets the rotation component (using a hkRotation). HK_FORCE_INLINE void setRotation(const hkRotation& rotation); /// Sets this transform to a linear interpolation of the transforms a and b. /// Quaternions are checked for polarity and the resulting rotation is normalized HK_FORCE_INLINE void setInterpolate4( const hkQsTransform& a, const hkQsTransform& b, hkSimdRealParameter t); /// Conversion from hkTransform. Assume no scale void setFromTransformNoScale (const hkTransform& transform); /// Conversion to hkTransform. Assume no scale void copyToTransformNoScale (hkTransform& transformOut) const; /// Conversion from hkTransform - scale. void setFromTransform (const hkTransform& transform); /// Conversion to hkTransform - scale. void copyToTransform (hkTransform& transformOut) const; /// Sets this transform to be the inverse of the given transform t. HK_FORCE_INLINE void setInverse( const hkQsTransform &t ); /// Sets this transform to be the product of t1 and t2. (this = t1 * t2) HK_FORCE_INLINE void setMul( const hkQsTransform &t1, const hkQsTransform &t2 ); /// Sets this transform to be the product of the inverse of t1 by t2. (this = t1^-1 * t2) HK_FORCE_INLINE void setMulInverseMul( const hkQsTransform& t1, const hkQsTransform &t2 ); /// Sets this transform to be the product of t1 and the inverse of t2. (this = t1 * t2^-1) HK_FORCE_INLINE void setMulMulInverse( const hkQsTransform &t1, const hkQsTransform &t2 ); /// Sets this transform to be the product of itself and the transform b. (this *= b) HK_FORCE_INLINE void setMulEq( const hkQsTransform& b ); /// Writes a 4x4 matrix suitable for rendering into p. void get4x4ColumnMajor(hkReal* p) const; /// Sets the components from a 4x4 matrix. Returns false if the matrix cannot be /// decomposed to form a proper hkQsTransform. hkBool set4x4ColumnMajor(const hkReal* p); /// Checks for bad values (denormals or infinities). hkBool isOk() const; /// Checks if this transform is equal to the other within an optional epsilon. hkBool isApproximatelyEqual( const hkQsTransform& other, hkReal epsilon=1e-3f ) const; /* ** Blending operations */ /// Prepares the qs transform for blending (sets all to zero) HK_FORCE_INLINE void setZero(); /// Blends a weighted qs transform into this one. /// Quaternions are checked for polarity but the resulting rotation is NOT normalized. /// Start with a hkQsTransform with all zeros (including the quaternion). /// Call blendAddMul for each transform. /// Call blendNormalize or fastRenormalize when finished blending. HK_FORCE_INLINE void blendAddMul(const hkQsTransform& other, hkSimdRealParameter weight = 1.0f ); /// Renormalizes after blending. If a total weight is given, /// the whole transformation is weighted by 1.0f / total weight. /// Takes the "zero" cases into account. HK_FORCE_INLINE void blendNormalize( hkSimdRealParameter totalWeight = 1.0f); /// Renormalizes without error checking HK_FORCE_INLINE void fastRenormalize( hkSimdRealParameter totalWeight = 1.0f); /// Renormalizes a group of quaternions at once. This allows for some /// vector optimizations on different platforms. static void HK_CALL fastRenormalizeBatch( hkQsTransform* poseOut, hkReal* weight, hkUint32 numTransforms); public: /// Direct access to the translation component (vector4) of this hkQsTransform. /// Fourth component is not used. hkVector4 m_translation; /// Direct access to the rotation component (quaternion) of this hkQsTransform hkQuaternion m_rotation; /// Direct access to the scale component (vector4) of this hkQsTransform. /// The fourth component is not used. hkVector4 m_scale; }; #endif //HK_MATH_QSTRANSFORM_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 193 ] ] ]
c1a781a0cc62e3087cacd5a858643e0f71b7987d
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/framework/movie/mediatimer.h
e045a0d2ec564d54d41b3756a6cf32ef3e07e6fd
[]
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
588
h
#ifndef maid2_framework_movie_mediatimer_h #define maid2_framework_movie_mediatimer_h #include"../../config/define.h" #include"../../auxiliary/timer.h" namespace Maid { class IMediaTimer { public: virtual ~IMediaTimer(){} virtual double Get() const=0; }; class MediaTimer :public IMediaTimer { public: MediaTimer(); void Start(); void Stop(); void SetOffset( double time ); virtual double Get() const; private: unt m_StartTime; double m_Offset; Timer m_Timer; }; } #endif
[ [ [ 1, 37 ] ] ]
76c4e58fb874e28ec1a921370e0ec489c682a8a1
e6abea92f59a1031d94bbcb3cee828da264c04cf
/NppPluginIface/src/NppPluginIface_CmdMap.h
cf8a4fedbcb8ac2127a83bb69b246df816c3a06e
[]
no_license
bruderstein/nppifacelib_mob
5b0ad8d47a19a14a9815f6b480fd3a56fe2c5a39
a34ff8b5a64e237372b939106463989b227aa3b7
refs/heads/master
2021-01-15T18:59:12.300763
2009-08-13T19:57:24
2009-08-13T19:57:24
285,922
0
1
null
null
null
null
UTF-8
C++
false
false
1,478
h
/* NppPluginIface_CmdMap.h * * This file is part of the Notepad++ Plugin Interface Lib. * Copyright 2008 - 2009 Thell Fowler ([email protected]) * * This program is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Notepad++ Plugin Interface Lib extension providing funcItem cmdID mapping from the plugin's * internal cmdID to the funcItems N++ assigned/modified cmdID. * */ #ifndef NPP_PLUGININTERFACE_CMDMAP_EXTENSION_H #define NPP_PLUGININTERFACE_CMDMAP_EXTENSION_H #include "NppPluginIface.h" namespace npp_plugin { void createCmdIdMap (); // Creates a cmdID to funcItem mapping. int getCmdId ( int cmdId ); // Returns the N++ assigned cmdId matching the plugin's assigned cmdId. } // End namespace: npp_plugin #endif // End include guard: NPP_PLUGININTERFACE_CMDMAP_EXTENSION_H
[ "T B Fowler@2fa2a738-4fc5-9a49-b7e4-8bd4648edc6b" ]
[ [ [ 1, 37 ] ] ]
e698cb7e2d77b4b0935a0211f7b8a57e35df3b03
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ui/src/MainMenuWindow.cpp
be95f7d1dacdda107eb618f0253e96ed776c1708
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,329
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" //precompiled header #include "MainMenuWindow.h" #include <boost/bind.hpp> #include <CEGUIWindowManager.h> #include "CoreSubsystem.h" #include "ConfigurationManager.h" #include "ContentModule.h" #include "MainMenuEngineWindow.h" #include "SoundConfig.h" #include "WindowFactory.h" using namespace CEGUI; using namespace Ogre; namespace rl { MainMenuWindow::MainMenuWindow(MainMenuEngineWindow* enginewindow) : AbstractWindow("mainmenuwindow.xml", WIT_MOUSE_INPUT, false, false), mActiveModule(NULL), mEngineWindow(enginewindow) { getWindow("MainMenu/Game/Start")->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleStart, this)); getWindow("MainMenu/Game/Load")->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleLoad, this)); getWindow("MainMenu/Game/Quit")->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleQuit, this)); getWindow("MainMenu/Options")->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleSettings, this)); fillModules(); mWindow->moveToBack(); } MainMenuWindow::~MainMenuWindow() { delete mEngineWindow; } void MainMenuWindow::fillModules() { MenuBase* modulesMenu = getMenu("MainMenu/Modules/Menu"); ModuleMap modules = CoreSubsystem::getSingleton().getAllModules(); mActiveModule = CoreSubsystem::getSingleton().getActiveAdventureModule(); for(ModuleMap::iterator modIt = modules.begin(); modIt != modules.end(); modIt++) { ContentModule* mod = (*modIt).second; if (!mod->isCommon()) { if (mActiveModule == NULL) mActiveModule = mod; MenuItem* it = static_cast<MenuItem*>( CEGUI::WindowManager::getSingleton().createWindow("RastullahLook/MenuItem", getNamePrefix()+"MainMenu/Modules/" + mod->getId())); if (mod == mActiveModule) it->setText(mod->getName() + " *"); else it->setText(mod->getName()); modulesMenu->addItem(it); it->subscribeEvent( MenuItem::EventClicked, boost::bind(&MainMenuWindow::handleChooseModule, this, it, mod)); } } } bool MainMenuWindow::handleChooseModule(MenuItem* it, ContentModule* module) { MenuBase* modulesMenu = getMenu("MainMenu/Modules/Menu"); ItemEntry* itOld = NULL; for (size_t i=0; i<modulesMenu->getItemCount(); i++) { ItemEntry* curr = modulesMenu->getItemFromIndex(i); if (curr->getText().compare(mActiveModule->getName()+" *") == 0) { itOld = curr; break; } } itOld->setText(mActiveModule->getName()); mActiveModule = module; it->setText(module->getName()+" *"); return true; } bool MainMenuWindow::handleStart() { WindowFactory::getSingleton().hideMainMenuLoadWindow(); setVisible(false); destroyWindow(); CoreSubsystem::getSingleton().startAdventureModule(mActiveModule); return true; } bool MainMenuWindow::handleLoad() { WindowFactory::getSingleton().showMainMenuLoadWindow(this); return true; } bool MainMenuWindow::handleQuit() { WindowFactory::getSingleton().showExitConfirmation(); return true; } bool MainMenuWindow::handleSettings() { WindowFactory::getSingleton().showGameSettings(); return true; } void MainMenuWindow::setVisible(bool visible, bool destroyAfterHide) { AbstractWindow::setVisible(visible, destroyAfterHide); mEngineWindow->setVisible(visible, destroyAfterHide); } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 154 ] ] ]
1f4fcae55c16698e4abb858f7ddfaf638dbc6fbb
d7320c9c1f155e2499afa066d159bfa6aa94b432
/ghostgproxy/gameprotocol.cpp
47bf7d192262a9aace79cb7b8ef7894bd54982ed
[]
no_license
HOST-PYLOS/ghostnordicleague
c44c804cb1b912584db3dc4bb811f29f3761a458
9cb262d8005dda0150b75d34b95961d664b1b100
refs/heads/master
2016-09-05T10:06:54.279724
2011-02-23T08:02:50
2011-02-23T08:02:50
32,241,503
0
1
null
null
null
null
UTF-8
C++
false
false
35,536
cpp
/* Copyright [2008] [Trevor Hogan] 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 "ghost.h" #include "util.h" #include "crc32.h" #include "gameplayer.h" #include "gameprotocol.h" #include "game_base.h" // // CGameProtocol // CGameProtocol :: CGameProtocol( CGHost *nGHost ) { m_GHost = nGHost; } CGameProtocol :: ~CGameProtocol( ) { } /////////////////////// // RECEIVE FUNCTIONS // /////////////////////// CIncomingJoinPlayer *CGameProtocol :: RECEIVE_W3GS_REQJOIN( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_REQJOIN" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Host Counter (Game ID) // 4 bytes -> Entry Key (used in LAN) // 1 byte -> ??? // 2 bytes -> Listen Port // 4 bytes -> Peer Key // null terminated string -> Name // 4 bytes -> ??? // 2 bytes -> InternalPort (???) // 4 bytes -> InternalIP if( ValidateLength( data ) && data.size( ) >= 20 ) { uint32_t HostCounter = UTIL_ByteArrayToUInt32( data, false, 4 ); uint32_t EntryKey = UTIL_ByteArrayToUInt32( data, false, 8 ); BYTEARRAY Name = UTIL_ExtractCString( data, 19 ); if( !Name.empty( ) && data.size( ) >= Name.size( ) + 30 ) { BYTEARRAY InternalIP = BYTEARRAY( data.begin( ) + Name.size( ) + 26, data.begin( ) + Name.size( ) + 30 ); return new CIncomingJoinPlayer( HostCounter, EntryKey, string( Name.begin( ), Name.end( ) ), InternalIP ); } } return NULL; } uint32_t CGameProtocol :: RECEIVE_W3GS_LEAVEGAME( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_LEAVEGAME" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Reason if( ValidateLength( data ) && data.size( ) >= 8 ) return UTIL_ByteArrayToUInt32( data, false, 4 ); return 0; } bool CGameProtocol :: RECEIVE_W3GS_GAMELOADED_SELF( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_GAMELOADED_SELF" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length if( ValidateLength( data ) ) return true; return false; } CIncomingAction *CGameProtocol :: RECEIVE_W3GS_OUTGOING_ACTION( BYTEARRAY data, unsigned char PID ) { //DEBUG_Print( "RECEIVED W3GS_OUTGOING_ACTION" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> CRC // remainder of packet -> Action if( PID != 255 && ValidateLength( data ) && data.size( ) >= 8 ) { BYTEARRAY CRC = BYTEARRAY( data.begin( ) + 4, data.begin( ) + 8 ); BYTEARRAY Action = BYTEARRAY( data.begin( ) + 8, data.end( ) ); DEBUG_Print( Action ); return new CIncomingAction( PID, CRC, Action ); } return NULL; } uint32_t CGameProtocol :: RECEIVE_W3GS_OUTGOING_KEEPALIVE( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_OUTGOING_KEEPALIVE" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 1 byte -> ??? // 4 bytes -> CheckSum??? (used in replays) if( ValidateLength( data ) && data.size( ) == 9 ) return UTIL_ByteArrayToUInt32( data, false, 5 ); return 0; } CIncomingChatPlayer *CGameProtocol :: RECEIVE_W3GS_CHAT_TO_HOST( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_CHAT_TO_HOST" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 1 byte -> Total // for( 1 .. Total ) // 1 byte -> ToPID // 1 byte -> FromPID // 1 byte -> Flag // if( Flag == 16 ) // null term string -> Message // elseif( Flag == 17 ) // 1 byte -> Team // elseif( Flag == 18 ) // 1 byte -> Colour // elseif( Flag == 19 ) // 1 byte -> Race // elseif( Flag == 20 ) // 1 byte -> Handicap // elseif( Flag == 32 ) // 4 bytes -> ExtraFlags // null term string -> Message if( ValidateLength( data ) ) { unsigned int i = 5; unsigned char Total = data[4]; if( Total > 0 && data.size( ) >= i + Total ) { BYTEARRAY ToPIDs = BYTEARRAY( data.begin( ) + i, data.begin( ) + i + Total ); i += Total; unsigned char FromPID = data[i]; unsigned char Flag = data[i + 1]; i += 2; if( Flag == 16 && data.size( ) >= i + 1 ) { // chat message BYTEARRAY Message = UTIL_ExtractCString( data, i ); return new CIncomingChatPlayer( FromPID, ToPIDs, Flag, string( Message.begin( ), Message.end( ) ) ); } else if( ( Flag >= 17 && Flag <= 20 ) && data.size( ) >= i + 1 ) { // team/colour/race/handicap change request unsigned char Byte = data[i]; return new CIncomingChatPlayer( FromPID, ToPIDs, Flag, Byte ); } else if( Flag == 32 && data.size( ) >= i + 5 ) { // chat message with extra flags BYTEARRAY ExtraFlags = BYTEARRAY( data.begin( ) + i, data.begin( ) + i + 4 ); BYTEARRAY Message = UTIL_ExtractCString( data, i + 4 ); return new CIncomingChatPlayer( FromPID, ToPIDs, Flag, string( Message.begin( ), Message.end( ) ), ExtraFlags ); } } } return NULL; } bool CGameProtocol :: RECEIVE_W3GS_SEARCHGAME( BYTEARRAY data, unsigned char war3Version ) { uint32_t ProductID = 1462982736; // "W3XP" uint32_t Version = war3Version; // DEBUG_Print( "RECEIVED W3GS_SEARCHGAME" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> ProductID // 4 bytes -> Version // 4 bytes -> ??? (Zero) if( ValidateLength( data ) && data.size( ) >= 16 ) { if( UTIL_ByteArrayToUInt32( data, false, 4 ) == ProductID ) { if( UTIL_ByteArrayToUInt32( data, false, 8 ) == Version ) { if( UTIL_ByteArrayToUInt32( data, false, 12 ) == 0 ) return true; } } } return false; } CIncomingMapSize *CGameProtocol :: RECEIVE_W3GS_MAPSIZE( BYTEARRAY data, BYTEARRAY mapSize ) { // DEBUG_Print( "RECEIVED W3GS_MAPSIZE" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> ??? // 1 byte -> SizeFlag (1 = have map, 3 = continue download) // 4 bytes -> MapSize if( ValidateLength( data ) && data.size( ) >= 13 ) return new CIncomingMapSize( data[8], UTIL_ByteArrayToUInt32( data, false, 9 ) ); return NULL; } uint32_t CGameProtocol :: RECEIVE_W3GS_MAPPARTOK( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_MAPPARTOK" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 1 byte -> SenderPID // 1 byte -> ReceiverPID // 4 bytes -> ??? // 4 bytes -> MapSize if( ValidateLength( data ) && data.size( ) >= 14 ) return UTIL_ByteArrayToUInt32( data, false, 10 ); return 0; } uint32_t CGameProtocol :: RECEIVE_W3GS_PONG_TO_HOST( BYTEARRAY data ) { // DEBUG_Print( "RECEIVED W3GS_PONG_TO_HOST" ); // DEBUG_Print( data ); // 2 bytes -> Header // 2 bytes -> Length // 4 bytes -> Pong // the pong value is just a copy of whatever was sent in SEND_W3GS_PING_FROM_HOST which was GetTicks( ) at the time of sending // so as long as we trust that the client isn't trying to fake us out and mess with the pong value we can find the round trip time by simple subtraction // (the subtraction is done elsewhere because the very first pong value seems to be 1 and we want to discard that one) if( ValidateLength( data ) && data.size( ) >= 8 ) return UTIL_ByteArrayToUInt32( data, false, 4 ); return 1; } //////////////////// // SEND FUNCTIONS // //////////////////// BYTEARRAY CGameProtocol :: SEND_W3GS_PING_FROM_HOST( ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_PING_FROM_HOST ); // W3GS_PING_FROM_HOST packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, GetTicks( ), false ); // ping value AssignLength( packet ); // DEBUG_Print( "SENT W3GS_PING_FROM_HOST" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_SLOTINFOJOIN( unsigned char PID, BYTEARRAY port, BYTEARRAY externalIP, vector<CGameSlot> &slots, uint32_t randomSeed, unsigned char layoutStyle, unsigned char playerSlots ) { unsigned char Zeros[] = { 0, 0, 0, 0 }; BYTEARRAY SlotInfo = EncodeSlotInfo( slots, randomSeed, layoutStyle, playerSlots ); BYTEARRAY packet; if( port.size( ) == 2 && externalIP.size( ) == 4 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_SLOTINFOJOIN ); // W3GS_SLOTINFOJOIN packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, (uint16_t)SlotInfo.size( ), false ); // SlotInfo length UTIL_AppendByteArrayFast( packet, SlotInfo ); // SlotInfo packet.push_back( PID ); // PID packet.push_back( 2 ); // AF_INET packet.push_back( 0 ); // AF_INET continued... UTIL_AppendByteArray( packet, port ); // port UTIL_AppendByteArrayFast( packet, externalIP ); // external IP UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_SLOTINFOJOIN" ); // DEBUG_Print( "SENT W3GS_SLOTINFOJOIN" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_REJECTJOIN( uint32_t reason ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_REJECTJOIN ); // W3GS_REJECTJOIN packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, reason, false ); // reason AssignLength( packet ); // DEBUG_Print( "SENT W3GS_REJECTJOIN" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_PLAYERINFO( unsigned char PID, string name, BYTEARRAY externalIP, BYTEARRAY internalIP ) { unsigned char PlayerJoinCounter[] = { 2, 0, 0, 0 }; unsigned char Zeros[] = { 0, 0, 0, 0 }; BYTEARRAY packet; if( !name.empty( ) && name.size( ) <= 15 && externalIP.size( ) == 4 && internalIP.size( ) == 4 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_PLAYERINFO ); // W3GS_PLAYERINFO packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, PlayerJoinCounter, 4 ); // player join counter packet.push_back( PID ); // PID UTIL_AppendByteArrayFast( packet, name ); // player name packet.push_back( 1 ); // ??? packet.push_back( 0 ); // ??? packet.push_back( 2 ); // AF_INET packet.push_back( 0 ); // AF_INET continued... packet.push_back( 0 ); // port packet.push_back( 0 ); // port continued... UTIL_AppendByteArrayFast( packet, externalIP ); // external IP UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? packet.push_back( 2 ); // AF_INET packet.push_back( 0 ); // AF_INET continued... packet.push_back( 0 ); // port packet.push_back( 0 ); // port continued... UTIL_AppendByteArrayFast( packet, internalIP ); // internal IP UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? UTIL_AppendByteArray( packet, Zeros, 4 ); // ??? AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_PLAYERINFO" ); // DEBUG_Print( "SENT W3GS_PLAYERINFO" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_PLAYERLEAVE_OTHERS( unsigned char PID, uint32_t leftCode ) { BYTEARRAY packet; if( PID != 255 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_PLAYERLEAVE_OTHERS ); // W3GS_PLAYERLEAVE_OTHERS packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( PID ); // PID UTIL_AppendByteArray( packet, leftCode, false ); // left code (see PLAYERLEAVE_ constants in gameprotocol.h) AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_PLAYERLEAVE_OTHERS" ); // DEBUG_Print( "SENT W3GS_PLAYERLEAVE_OTHERS" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_GAMELOADED_OTHERS( unsigned char PID ) { BYTEARRAY packet; if( PID != 255 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_GAMELOADED_OTHERS ); // W3GS_GAMELOADED_OTHERS packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( PID ); // PID AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_GAMELOADED_OTHERS" ); // DEBUG_Print( "SENT W3GS_GAMELOADED_OTHERS" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_SLOTINFO( vector<CGameSlot> &slots, uint32_t randomSeed, unsigned char layoutStyle, unsigned char playerSlots ) { BYTEARRAY SlotInfo = EncodeSlotInfo( slots, randomSeed, layoutStyle, playerSlots ); BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_SLOTINFO ); // W3GS_SLOTINFO packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, (uint16_t)SlotInfo.size( ), false ); // SlotInfo length UTIL_AppendByteArrayFast( packet, SlotInfo ); // SlotInfo AssignLength( packet ); // DEBUG_Print( "SENT W3GS_SLOTINFO" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_COUNTDOWN_START( ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_COUNTDOWN_START ); // W3GS_COUNTDOWN_START packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later AssignLength( packet ); // DEBUG_Print( "SENT W3GS_COUNTDOWN_START" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_COUNTDOWN_END( ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_COUNTDOWN_END ); // W3GS_COUNTDOWN_END packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later AssignLength( packet ); // DEBUG_Print( "SENT W3GS_COUNTDOWN_END" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_INCOMING_ACTION( queue<CIncomingAction *> actions, uint16_t sendInterval ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_INCOMING_ACTION ); // W3GS_INCOMING_ACTION packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, sendInterval, false ); // send interval // create subpacket if( !actions.empty( ) ) { BYTEARRAY subpacket; while( !actions.empty( ) ) { CIncomingAction *Action = actions.front( ); actions.pop( ); subpacket.push_back( Action->GetPID( ) ); UTIL_AppendByteArray( subpacket, (uint16_t)Action->GetAction( )->size( ), false ); UTIL_AppendByteArrayFast( subpacket, *Action->GetAction( ) ); } // calculate crc (we only care about the first 2 bytes though) BYTEARRAY crc32 = UTIL_CreateByteArray( m_GHost->m_CRC->FullCRC( (unsigned char *)string( subpacket.begin( ), subpacket.end( ) ).c_str( ), subpacket.size( ) ), false ); crc32.resize( 2 ); // finish subpacket UTIL_AppendByteArrayFast( packet, crc32 ); // crc UTIL_AppendByteArrayFast( packet, subpacket ); // subpacket } AssignLength( packet ); // DEBUG_Print( "SENT W3GS_INCOMING_ACTION" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_CHAT_FROM_HOST( unsigned char fromPID, BYTEARRAY toPIDs, unsigned char flag, BYTEARRAY flagExtra, string message ) { BYTEARRAY packet; if( !toPIDs.empty( ) && !message.empty( ) && message.size( ) < 255 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_CHAT_FROM_HOST ); // W3GS_CHAT_FROM_HOST packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( toPIDs.size( ) ); // number of receivers UTIL_AppendByteArrayFast( packet, toPIDs ); // receivers packet.push_back( fromPID ); // sender packet.push_back( flag ); // flag UTIL_AppendByteArrayFast( packet, flagExtra ); // extra flag UTIL_AppendByteArrayFast( packet, message ); // message AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_CHAT_FROM_HOST" ); // DEBUG_Print( "SENT W3GS_CHAT_FROM_HOST" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_START_LAG( vector<CGamePlayer *> players, bool loadInGame ) { BYTEARRAY packet; unsigned char NumLaggers = 0; for( vector<CGamePlayer *> :: iterator i = players.begin( ); i != players.end( ); i++ ) { if( loadInGame ) { if( !(*i)->GetFinishedLoading( ) ) NumLaggers++; } else { if( (*i)->GetLagging( ) ) NumLaggers++; } } if( NumLaggers > 0 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_START_LAG ); // W3GS_START_LAG packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( NumLaggers ); for( vector<CGamePlayer *> :: iterator i = players.begin( ); i != players.end( ); i++ ) { if( loadInGame ) { if( !(*i)->GetFinishedLoading( ) ) { packet.push_back( (*i)->GetPID( ) ); UTIL_AppendByteArray( packet, (uint32_t)0, false ); } } else { if( (*i)->GetLagging( ) ) { packet.push_back( (*i)->GetPID( ) ); UTIL_AppendByteArray( packet, GetTicks( ) - (*i)->GetStartedLaggingTicks( ), false ); } } } AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] no laggers passed to SEND_W3GS_START_LAG" ); // DEBUG_Print( "SENT W3GS_START_LAG" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_STOP_LAG( CGamePlayer *player, bool loadInGame ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_STOP_LAG ); // W3GS_STOP_LAG packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( player->GetPID( ) ); if( loadInGame ) UTIL_AppendByteArray( packet, (uint32_t)0, false ); else UTIL_AppendByteArray( packet, GetTicks( ) - player->GetStartedLaggingTicks( ), false ); AssignLength( packet ); // DEBUG_Print( "SENT W3GS_STOP_LAG" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_SEARCHGAME( bool TFT, unsigned char war3Version ) { unsigned char ProductID_ROC[] = { 51, 82, 65, 87 }; // "WAR3" unsigned char ProductID_TFT[] = { 80, 88, 51, 87 }; // "W3XP" unsigned char Version[] = { war3Version, 0, 0, 0 }; unsigned char Unknown[] = { 0, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_SEARCHGAME ); // W3GS_SEARCHGAME packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later if( TFT ) UTIL_AppendByteArray( packet, ProductID_TFT, 4 ); // Product ID (TFT) else UTIL_AppendByteArray( packet, ProductID_ROC, 4 ); // Product ID (ROC) UTIL_AppendByteArray( packet, Version, 4 ); // Version UTIL_AppendByteArray( packet, Unknown, 4 ); // ??? AssignLength( packet ); // DEBUG_Print( "SENT W3GS_SEARCHGAME" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_GAMEINFO( bool TFT, unsigned char war3Version, BYTEARRAY mapGameType, BYTEARRAY mapFlags, BYTEARRAY mapWidth, BYTEARRAY mapHeight, string gameName, string hostName, uint32_t upTime, string mapPath, BYTEARRAY mapCRC, uint32_t slotsTotal, uint32_t slotsOpen, uint16_t port, uint32_t hostCounter, uint32_t entryKey ) { unsigned char ProductID_ROC[] = { 51, 82, 65, 87 }; // "WAR3" unsigned char ProductID_TFT[] = { 80, 88, 51, 87 }; // "W3XP" unsigned char Version[] = { war3Version, 0, 0, 0 }; unsigned char Unknown2[] = { 1, 0, 0, 0 }; BYTEARRAY packet; if( mapGameType.size( ) == 4 && mapFlags.size( ) == 4 && mapWidth.size( ) == 2 && mapHeight.size( ) == 2 && !gameName.empty( ) && !hostName.empty( ) && !mapPath.empty( ) && mapCRC.size( ) == 4 ) { // make the stat string BYTEARRAY StatString; UTIL_AppendByteArrayFast( StatString, mapFlags ); StatString.push_back( 0 ); UTIL_AppendByteArrayFast( StatString, mapWidth ); UTIL_AppendByteArrayFast( StatString, mapHeight ); UTIL_AppendByteArrayFast( StatString, mapCRC ); UTIL_AppendByteArrayFast( StatString, mapPath ); UTIL_AppendByteArrayFast( StatString, hostName ); StatString.push_back( 0 ); StatString = UTIL_EncodeStatString( StatString ); // make the rest of the packet packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_GAMEINFO ); // W3GS_GAMEINFO packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later if( TFT ) UTIL_AppendByteArray( packet, ProductID_TFT, 4 ); // Product ID (TFT) else UTIL_AppendByteArray( packet, ProductID_ROC, 4 ); // Product ID (ROC) UTIL_AppendByteArray( packet, Version, 4 ); // Version UTIL_AppendByteArray( packet, hostCounter, false ); // Host Counter UTIL_AppendByteArray( packet, entryKey, false ); // Entry Key UTIL_AppendByteArrayFast( packet, gameName ); // Game Name packet.push_back( 0 ); // ??? (maybe game password) UTIL_AppendByteArrayFast( packet, StatString ); // Stat String packet.push_back( 0 ); // Stat String null terminator (the stat string is encoded to remove all even numbers i.e. zeros) UTIL_AppendByteArray( packet, slotsTotal, false ); // Slots Total UTIL_AppendByteArrayFast( packet, mapGameType ); // Game Type UTIL_AppendByteArray( packet, Unknown2, 4 ); // ??? UTIL_AppendByteArray( packet, slotsOpen, false ); // Slots Open UTIL_AppendByteArray( packet, upTime, false ); // time since creation UTIL_AppendByteArray( packet, port, false ); // port AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_GAMEINFO" ); // DEBUG_Print( "SENT W3GS_GAMEINFO" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_CREATEGAME( bool TFT, unsigned char war3Version ) { unsigned char ProductID_ROC[] = { 51, 82, 65, 87 }; // "WAR3" unsigned char ProductID_TFT[] = { 80, 88, 51, 87 }; // "W3XP" unsigned char Version[] = { war3Version, 0, 0, 0 }; unsigned char HostCounter[] = { 1, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_CREATEGAME ); // W3GS_CREATEGAME packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later if( TFT ) UTIL_AppendByteArray( packet, ProductID_TFT, 4 ); // Product ID (TFT) else UTIL_AppendByteArray( packet, ProductID_ROC, 4 ); // Product ID (ROC) UTIL_AppendByteArray( packet, Version, 4 ); // Version UTIL_AppendByteArray( packet, HostCounter, 4 ); // Host Counter AssignLength( packet ); // DEBUG_Print( "SENT W3GS_CREATEGAME" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_REFRESHGAME( uint32_t players, uint32_t playerSlots ) { unsigned char HostCounter[] = { 1, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_REFRESHGAME ); // W3GS_REFRESHGAME packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, HostCounter, 4 ); // Host Counter UTIL_AppendByteArray( packet, players, false ); // Players UTIL_AppendByteArray( packet, playerSlots, false ); // Player Slots AssignLength( packet ); // DEBUG_Print( "SENT W3GS_REFRESHGAME" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_DECREATEGAME( ) { unsigned char HostCounter[] = { 1, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_DECREATEGAME ); // W3GS_DECREATEGAME packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, HostCounter, 4 ); // Host Counter AssignLength( packet ); // DEBUG_Print( "SENT W3GS_DECREATEGAME" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_MAPCHECK( string mapPath, BYTEARRAY mapSize, BYTEARRAY mapInfo, BYTEARRAY mapCRC, BYTEARRAY mapSHA1 ) { unsigned char Unknown[] = { 1, 0, 0, 0 }; BYTEARRAY packet; if( !mapPath.empty( ) && mapSize.size( ) == 4 && mapInfo.size( ) == 4 && mapCRC.size( ) == 4 && mapSHA1.size( ) == 20 ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_MAPCHECK ); // W3GS_MAPCHECK packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, Unknown, 4 ); // ??? UTIL_AppendByteArrayFast( packet, mapPath ); // map path UTIL_AppendByteArrayFast( packet, mapSize ); // map size UTIL_AppendByteArrayFast( packet, mapInfo ); // map info UTIL_AppendByteArrayFast( packet, mapCRC ); // map crc UTIL_AppendByteArrayFast( packet, mapSHA1 ); // map sha1 AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_MAPCHECK" ); // DEBUG_Print( "SENT W3GS_MAPCHECK" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_STARTDOWNLOAD( unsigned char fromPID ) { unsigned char Unknown[] = { 1, 0, 0, 0 }; BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_STARTDOWNLOAD ); // W3GS_STARTDOWNLOAD packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later UTIL_AppendByteArray( packet, Unknown, 4 ); // ??? packet.push_back( fromPID ); // from PID AssignLength( packet ); // DEBUG_Print( "SENT W3GS_STARTDOWNLOAD" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_MAPPART( unsigned char fromPID, unsigned char toPID, uint32_t start, string *mapData ) { unsigned char Unknown[] = { 1, 0, 0, 0 }; BYTEARRAY packet; if( start < mapData->size( ) ) { packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_MAPPART ); // W3GS_MAPPART packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( toPID ); // to PID packet.push_back( fromPID ); // from PID UTIL_AppendByteArray( packet, Unknown, 4 ); // ??? UTIL_AppendByteArray( packet, start, false ); // start position // calculate end position (don't send more than 1442 map bytes in one packet) uint32_t End = start + 1442; if( End > mapData->size( ) ) End = mapData->size( ); // calculate crc BYTEARRAY crc32 = UTIL_CreateByteArray( m_GHost->m_CRC->FullCRC( (unsigned char *)mapData->c_str( ) + start, End - start ), false ); UTIL_AppendByteArrayFast( packet, crc32 ); // map data BYTEARRAY Data = UTIL_CreateByteArray( (unsigned char *)mapData->c_str( ) + start, End - start ); UTIL_AppendByteArrayFast( packet, Data ); AssignLength( packet ); } else CONSOLE_Print( "[GAMEPROTO] invalid parameters passed to SEND_W3GS_MAPPART" ); // DEBUG_Print( "SENT W3GS_MAPPART" ); // DEBUG_Print( packet ); return packet; } BYTEARRAY CGameProtocol :: SEND_W3GS_INCOMING_ACTION2( queue<CIncomingAction *> actions ) { BYTEARRAY packet; packet.push_back( W3GS_HEADER_CONSTANT ); // W3GS header constant packet.push_back( W3GS_INCOMING_ACTION2 ); // W3GS_INCOMING_ACTION2 packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // packet length will be assigned later packet.push_back( 0 ); // ??? (send interval?) packet.push_back( 0 ); // ??? (send interval?) // create subpacket if( !actions.empty( ) ) { BYTEARRAY subpacket; while( !actions.empty( ) ) { CIncomingAction *Action = actions.front( ); actions.pop( ); subpacket.push_back( Action->GetPID( ) ); UTIL_AppendByteArray( subpacket, (uint16_t)Action->GetAction( )->size( ), false ); UTIL_AppendByteArrayFast( subpacket, *Action->GetAction( ) ); } // calculate crc (we only care about the first 2 bytes though) BYTEARRAY crc32 = UTIL_CreateByteArray( m_GHost->m_CRC->FullCRC( (unsigned char *)string( subpacket.begin( ), subpacket.end( ) ).c_str( ), subpacket.size( ) ), false ); crc32.resize( 2 ); // finish subpacket UTIL_AppendByteArrayFast( packet, crc32 ); // crc UTIL_AppendByteArrayFast( packet, subpacket ); // subpacket } AssignLength( packet ); // DEBUG_Print( "SENT W3GS_INCOMING_ACTION2" ); // DEBUG_Print( packet ); return packet; } ///////////////////// // OTHER FUNCTIONS // ///////////////////// bool CGameProtocol :: AssignLength( BYTEARRAY &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes = UTIL_CreateByteArray( (uint16_t)content.size( ), false ); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } bool CGameProtocol :: ValidateLength( BYTEARRAY &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length uint16_t Length; BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = UTIL_ByteArrayToUInt16( LengthBytes, false ); if( Length == content.size( ) ) return true; } return false; } BYTEARRAY CGameProtocol :: EncodeSlotInfo( vector<CGameSlot> &slots, uint32_t randomSeed, unsigned char layoutStyle, unsigned char playerSlots ) { BYTEARRAY SlotInfo; SlotInfo.push_back( (unsigned char)slots.size( ) ); // number of slots for( unsigned int i = 0; i < slots.size( ); i++ ) UTIL_AppendByteArray( SlotInfo, slots[i].GetByteArray( ) ); UTIL_AppendByteArray( SlotInfo, randomSeed, false ); // random seed SlotInfo.push_back( layoutStyle ); // LayoutStyle (0 = melee, 1 = custom forces, 3 = custom forces + fixed player settings) SlotInfo.push_back( playerSlots ); // number of player slots (non observer) return SlotInfo; } // // CIncomingJoinPlayer // CIncomingJoinPlayer :: CIncomingJoinPlayer( uint32_t nHostCounter, uint32_t nEntryKey, string nName, BYTEARRAY &nInternalIP ) { m_HostCounter = nHostCounter; m_EntryKey = nEntryKey; m_Name = nName; m_InternalIP = nInternalIP; } CIncomingJoinPlayer :: ~CIncomingJoinPlayer( ) { } // // CIncomingAction // CIncomingAction :: CIncomingAction( unsigned char nPID, BYTEARRAY &nCRC, BYTEARRAY &nAction ) { m_PID = nPID; m_CRC = nCRC; m_Action = nAction; } CIncomingAction :: ~CIncomingAction( ) { } // // CIncomingChatPlayer // CIncomingChatPlayer :: CIncomingChatPlayer( unsigned char nFromPID, BYTEARRAY &nToPIDs, unsigned char nFlag, string nMessage ) { m_Type = CTH_MESSAGE; m_FromPID = nFromPID; m_ToPIDs = nToPIDs; m_Flag = nFlag; m_Message = nMessage; } CIncomingChatPlayer :: CIncomingChatPlayer( unsigned char nFromPID, BYTEARRAY &nToPIDs, unsigned char nFlag, string nMessage, BYTEARRAY &nExtraFlags ) { m_Type = CTH_MESSAGEEXTRA; m_FromPID = nFromPID; m_ToPIDs = nToPIDs; m_Flag = nFlag; m_Message = nMessage; m_ExtraFlags = nExtraFlags; } CIncomingChatPlayer :: CIncomingChatPlayer( unsigned char nFromPID, BYTEARRAY &nToPIDs, unsigned char nFlag, unsigned char nByte ) { if( nFlag == 17 ) m_Type = CTH_TEAMCHANGE; else if( nFlag == 18 ) m_Type = CTH_COLOURCHANGE; else if( nFlag == 19 ) m_Type = CTH_RACECHANGE; else if( nFlag == 20 ) m_Type = CTH_HANDICAPCHANGE; m_FromPID = nFromPID; m_ToPIDs = nToPIDs; m_Flag = nFlag; m_Byte = nByte; } CIncomingChatPlayer :: ~CIncomingChatPlayer( ) { } // // CIncomingMapSize // CIncomingMapSize :: CIncomingMapSize( unsigned char nSizeFlag, uint32_t nMapSize ) { m_SizeFlag = nSizeFlag; m_MapSize = nMapSize; } CIncomingMapSize :: ~CIncomingMapSize( ) { }
[ "fredrik.sigillet@4a4c9648-eef2-11de-9456-cf00f3bddd4e", "[email protected]@4a4c9648-eef2-11de-9456-cf00f3bddd4e" ]
[ [ [ 1, 109 ], [ 111, 1054 ] ], [ [ 110, 110 ] ] ]
aa328b9ee3eb2a0ff749eb5423d9622802694c07
07305381b1c15c68398c50c4e10220fd3bf2f08b
/src/TurnBehaviour.cpp
8d33caad01d3767dfb2f832e534d31d8d2ee5c25
[]
no_license
jaspervdj/AstroBot
7f69e1da916d7a47d14ecc0aadb712c08137aeea
c0f9f1cb43161ae3b083e8929a9d908f297576f2
refs/heads/master
2020-06-03T23:00:11.741537
2009-12-13T18:59:59
2009-12-13T18:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
766
cpp
/** * Pieter De Baets * Jasper Van der Jeugt * Groep 31 * TurnBehaviour.cpp */ #include "TurnBehaviour.h" #include "Robot.h" #include "ObstacleEvent.h" #include "Obstacle.h" #include "Orientation.h" #include "GUI.h" TurnBehaviour::TurnBehaviour(Robot *robot) : Behaviour() { this->robot = robot; active = false; } TurnBehaviour::~TurnBehaviour() { } bool TurnBehaviour::isActive() { return active; } void TurnBehaviour::obstacleDetected(const ObstacleEvent &event) { active = true; } void TurnBehaviour::noObstacle() { active = false; } void TurnBehaviour::action() { Orientation next = (Orientation) ((robot->getOrientation() + 1) % ORIENTATION_SIZE); robot->setOrientation(next); GUI::show(GUI::ROTATE); }
[ [ [ 1, 6 ], [ 41, 43 ], [ 45, 45 ] ], [ [ 7, 10 ], [ 13, 13 ], [ 15, 15 ], [ 18, 23 ], [ 29, 30 ], [ 32, 35 ], [ 37, 40 ] ], [ [ 11, 12 ], [ 14, 14 ], [ 16, 17 ], [ 24, 28 ], [ 31, 31 ], [ 36, 36 ], [ 44, 44 ] ] ]
088c55f163799ad2e5f067eb9b19717b81b666c2
ffa46b6c97ef6e0c03e034d542fa94ba02d519e5
/qtabeditor.h
e5a1acbde3969d80283e2f67c3074ab689ba297e
[]
no_license
jason-cpc/chmcreator
50467a2bc31833aef931e24be1ac68f5c06efd97
5da66666a9df47c5cf67b71bfb115b403f41b72b
refs/heads/master
2021-12-04T11:22:23.616758
2010-07-20T23:50:15
2010-07-20T23:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
732
h
#ifndef QTABEDITOR_H #define QTABEDITOR_H #include <QtGui> #include <QMdiArea> #include <QWebView> #include <QTabWidget> #include "qhtmleditor.h" class QTabEditor : public QTabWidget { Q_OBJECT public: QTabEditor(); ~QTabEditor(); int addTab (const QString& fileName); void save(); void saveAll(); public slots: void changeStatus(bool); private: QString getFileName(const QString& fileName){ name = fileName; return name.right(name.length()-name.lastIndexOf('/')-1); } QString name; QStringList list; QVector<QHTMLEditor*> tabList; QToolButton* closeButton; private slots: void closeCurrentTab(); }; #endif // QTABEDITOR_H
[ "zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb" ]
[ [ [ 1, 34 ] ] ]
5b2fb5288816f8de0217e930f0d01f35daf53dba
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestnote/inc/bctesteikinfodialogcase.h
a9ec86a68d3e198be7de802926b300b449522712
[]
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,789
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares test bc for eik info dialog testcase. * */ #ifndef C_CBCTESTEIKINFODIALOGCASE_H #define C_CBCTESTEIKINFODIALOGCASE_H #include "bctestcase.h" class CBCTestNoteContainer; class CCoeControl; /** * test case for various note classes */ class CBCTestEikInfoDialogCase: public CBCTestCase { public: // constructor and destructor /** * Symbian 2nd static constructor */ static CBCTestEikInfoDialogCase* NewL( CBCTestNoteContainer* aContainer ); /** * Destructor */ virtual ~CBCTestEikInfoDialogCase(); // from CBCTestCase /** * Execute corresponding test functions for UI command * @param aCmd, UI command */ void RunL( TInt aCmd ); protected: // new functions /** * Build autotest script */ void BuildScriptL(); /** * TestEikInfoDialogL function */ void TestEikInfoDialogL(); private: // constructor /** * C++ default constructor */ CBCTestEikInfoDialogCase( CBCTestNoteContainer* aContainer ); /** * Symbian 2nd constructor */ void ConstructL(); private: // data /** * Pointer to container. * not own */ CBCTestNoteContainer* iContainer; }; #endif // C_CBCTESTEIKINFODIALOGCASE_H
[ "none@none" ]
[ [ [ 1, 86 ] ] ]
ae9d92a59fdedbc7eefb0af42e7911f943609fb4
b03f367d0c655c7776c8474c5e21a44d0890ea3d
/ship_sim_old/source/nxaux/allocator.h
e2e9ed8962887b5e83bae2556177ef7e8b19bd27
[]
no_license
Jacobi20/nano-vis
0f94c77c5a03a5d1185f654528c69e5841571cb9
9c713a5f20c5b8c676e0a0847c8131e2a996d784
refs/heads/master
2021-01-20T11:31:23.350419
2011-08-09T13:22:57
2011-08-09T13:22:57
37,013,226
0
0
null
null
null
null
UTF-8
C++
false
false
1,806
h
/* The MIT License Copyright (c) 2010 IFMO/GameDev Studio 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. */ #pragma once /*----------------------------------------------------------------------------- Allocator : -----------------------------------------------------------------------------*/ #undef malloc #undef realloc #undef free class EAllocator : public NxUserAllocator { public: EAllocator ( void ); ~EAllocator ( void ); virtual void *malloc ( NxU32 size ); virtual void *mallocDEBUG ( NxU32 size, const char *fileName, int line ); virtual void *realloc ( void * memory, NxU32 size ); virtual void free ( void * memory ); private: volatile LONG num_allocs; };
[ "demiurghg@6d03c5d0-0fef-11df-8179-3f26cfb4ba5f" ]
[ [ [ 1, 47 ] ] ]
12cca9a77cc8a755cb2f0a32ca598945956ab3c3
f241b6224086eaba2de42d674e2f189a66419a63
/old/cs4280/GroupWork/Game/Game/rocket.cpp
643063b3a43263ab0de0b3ab5c13a9d385b8210d
[]
no_license
davidwiggy/Joshs-School
17c78dc953ffdc5db5fc0524248f1638b64a082c
87937141406847adcff18741882f53f1a5c44007
refs/heads/master
2020-04-08T01:25:17.915887
2011-09-24T03:51:44
2011-09-24T03:51:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,927
cpp
#include "rocket.h" CRocket::CRocket() { velocity = CVector(0.0, 0.0, 120.0); acceleration = CVector(0.0, 0.0, 0.0); distanceTravel = 0.0; size = 1.0f; isExplosion = false; explosion = NULL; explosionTex = new CTexture; Load(); } CRocket::~CRocket() { if (explosion != NULL) { explosion->KillSystem(); delete [] explosion; explosion = NULL; } if (explosionTex != NULL) { delete explosionTex; explosionTex = NULL; } } void CRocket::SetupExplosionTexture() { glGenTextures(1, &explosionTex->texID); glBindTexture(GL_TEXTURE_2D, explosionTex->texID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, explosionTex->width, explosionTex->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, explosionTex->data); gluBuild2DMipmaps(GL_TEXTURE_2D, 4, explosionTex->width, explosionTex->height, GL_RGBA, GL_UNSIGNED_BYTE, explosionTex->data); } void CRocket::OnAnimate(scalar_t deltaTime) { float cosYaw = (float)cos(DEG2RAD(direction)); float sinYaw = (float)sin(DEG2RAD(direction)); float sinPitch = (float)sin(DEG2RAD(pitch)); float speed = velocity.z * deltaTime; position.x += float(cosYaw)*speed; position.y += float(sinPitch)*speed; position.z += float(sinYaw)*speed; distanceTravel += position.Length(); if (isExplosion) explosion->Update(deltaTime); if (!isExplosion) { if (distanceTravel >= 500000.0f) { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(10, position, 0.1f, explosionTex->texID); } } } void CRocket::OnCollision(CObject *collisionObject) { if (!isExplosion) { if (typeid(*collisionObject) == typeid(CTerrain)) { if (((CTerrain*)collisionObject)->GetHeight(position.x, position.z) + size >= position.y) { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } // do explosion } if (typeid(*collisionObject) == typeid(COgroEnemy)) { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } if (typeid(*collisionObject) == typeid(CSodEnemy)) { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } if (typeid(*collisionObject) == typeid(CCowEnemy)) { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } if (typeid(*collisionObject) == typeid(CMechEnemy)) { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } if (typeid(*collisionObject) == typeid(CDroidEnemy)) // Added by Lorin { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } if (typeid(*collisionObject) == typeid(CDragonEnemy)) // Added by Lorin { isExplosion = true; velocity = CVector(0.0, 0.0, 0.0); explosion = new CExplosion(500, position, 8.0, explosionTex->texID); PlaySound(); } } } void CRocket::OnDraw(CCamera *camera) { // if the rocket has not yet exploded, draw the rocket model if (!isExplosion) { glEnable(GL_TEXTURE_2D); glColor3f(1.0, 1.0, 1.0); glTranslatef(position.x, position.y, position.z); glRotatef(-direction, 0.0, 1.0, 0.0); glScalef(0.025f, 0.025f, 0.025f); RenderFrame(0); glDisable(GL_TEXTURE_2D); } // draw explosion else { // Phase 16 - take out fog commands until fog is defined // Phase 20 - Uncomment fog statements glDisable(GL_FOG); explosion->Render(); glEnable(GL_FOG); // Phase 16 - End } } void CRocket::Load() { CMD2Model::Load("models\\rocketair.md2", "models\\rocket.pcx"); explosionTex->LoadTexture("bluering2.tga"); SetupExplosionTexture(); } void CRocket::Unload() { } void CRocket::OnPrepare() { // perform collision detection from this entity with all other objects in world if (!isExplosion) ProcessCollisions(FindRoot()); if (isExplosion) { // Phase 16 - Take out for now // Phase 19 - Uncomment the following if (explosion->IsDead() && !audioSys->GetPerformance()->IsPlaying(entitySound->GetSegment(), NULL)) { explosion->KillSystem(); delete explosion; explosion = NULL; isExplosion = false; isDead = true; } } }
[ "arnie@67c49fff-0526-0410-8e7c-b4c1397322bd" ]
[ [ [ 1, 194 ] ] ]
655e2100ccdc05fd14de770040f46bff9a4f8c70
e0e50fa9f430c28677e9294ce9f02d99e4ffbd79
/ARSLAM/include/arslam.hpp
ec24971f3a096f7098f50d8d5fbfebda867bf3d5
[]
no_license
geetavin464/arslam
01b2bb2bef07ac7b4e5263fa4ffecb94895cc814
8e63a641662479fa943abb17055cac6c46cddd20
refs/heads/master
2020-05-30T23:10:03.805373
2010-03-14T21:11:44
2010-03-14T21:11:44
32,117,031
0
0
null
null
null
null
UTF-8
C++
false
false
135
hpp
#ifndef ARSLAM_HPP #define ARSLAM_HPP // defining #define _DEBUG_MODE_ #ifndef _DEBUG #undef _DEBUG_MODE_ #endif #endif
[ "[email protected]@3a8c47d8-2d88-11df-8971-ebb891de2ff2" ]
[ [ [ 1, 12 ] ] ]
37defe84637e294ff6024b3840b32b9a135f4f11
16d8b25d0d1c0f957c92f8b0d967f71abff1896d
/obse/obse/Utilities.cpp
ba75d2a087c02563c8e11cf12e5e592e0d6d1b52
[]
no_license
wlasser/oonline
51973b5ffec0b60407b63b010d0e4e1622cf69b6
fd37ee6985f1de082cbc9f8625d1d9307e8801a6
refs/heads/master
2021-05-28T23:39:16.792763
2010-05-12T22:35:20
2010-05-12T22:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,605
cpp
#include "Utilities.h" #include "GameAPI.h" #ifdef OBLIVION void PrintItemType(TESForm * form) { Console_Print("%s (%s)", GetFullName(form), GetObjectClassName(form)); } const char GetSeparatorChar() { if (IsConsoleMode()) return '@'; else return '|'; } const char* GetSeparatorChars() { if (IsConsoleMode()) return "@"; else return "|"; } #endif void DumpClass(void * theClassPtr, UInt32 nIntsToDump) { _MESSAGE("DumpClass:"); UInt32* basePtr = (UInt32*)theClassPtr; gLog.Indent(); if (!theClassPtr) return; for (UInt32 ix = 0; ix < nIntsToDump; ix++ ) { UInt32* curPtr = basePtr+ix; const char* curPtrName = NULL; UInt32 otherPtr = 0; float otherFloat = 0.0; const char* otherPtrName = NULL; if (curPtr) { curPtrName = GetObjectClassName((void*)curPtr); __try { otherPtr = *curPtr; otherFloat = *(float*)(curPtr); } __except(EXCEPTION_EXECUTE_HANDLER) { // } if (otherPtr) { otherPtrName = GetObjectClassName((void*)otherPtr); } } _MESSAGE("%3d +%03X ptr: 0x%08X: %32s *ptr: 0x%08x | %f: %32s", ix, ix*4, curPtr, curPtrName, otherPtr, otherFloat, otherPtrName); } gLog.Outdent(); } std::string GetOblivionDirectory(void) { static std::string s_oblivionDirectory; if(s_oblivionDirectory.empty()) { // can't determine how many bytes we'll need, hope it's not more than MAX_PATH char oblivionPathBuf[MAX_PATH]; UInt32 oblivionPathLength = GetModuleFileName(GetModuleHandle(NULL), oblivionPathBuf, sizeof(oblivionPathBuf)); if(oblivionPathLength && (oblivionPathLength < sizeof(oblivionPathBuf))) { std::string oblivionPath(oblivionPathBuf, oblivionPathLength); // truncate at last slash std::string::size_type lastSlash = oblivionPath.rfind('\\'); if(lastSlash != std::string::npos) // if we don't find a slash something is VERY WRONG { s_oblivionDirectory = oblivionPath.substr(0, lastSlash + 1); _DMESSAGE("oblivion root = %s", s_oblivionDirectory.c_str()); } else { _WARNING("no slash in oblivion path? (%s)", oblivionPath.c_str()); } } else { _WARNING("couldn't find oblivion path (len = %d, err = %08X)", oblivionPathLength, GetLastError()); } } return s_oblivionDirectory; } #if OBLIVION #if OBLIVION_VERSION == OBLIVION_VERSION_1_1 const char*** g_KeyNames = (const char***)0xAF8B10; const char*** g_ButtonNames = (const char***)0xAF8AE8; #elif OBLIVION_VERSION == OBLIVION_VERSION_1_2 const char*** g_KeyNames = (const char***)0xB39578; const char*** g_ButtonNames = (const char***)0xB39554; #elif OBLIVION_VERSION == OBLIVION_VERSION_1_2_416 const char*** g_KeyNames = (const char***)0xB39578; const char*** g_ButtonNames = (const char***)0xB39554; #else #error unsupported version of oblivion #endif const char* GetDXDescription(UInt32 keycode) { const char* keyName = "<no key>"; if (keycode <= 220) { if (g_KeyNames[keycode]) keyName = *(g_KeyNames[keycode]); } else if (255 <= keycode && keycode <= 263) { if (keycode == 255) keycode = 256; if (g_ButtonNames[keycode - 256]) keyName = *(g_ButtonNames[keycode - 256]); } else if (keycode == 264) //OB doesn't provide names for wheel up/down keyName = "WheelUp"; else if (keycode == 265) keyName = "WheelDown"; return keyName; } #endif namespace MersenneTwister { /* A C-program for MT19937, with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto. Before using, initialize the state by using init_genrand(seed) or init_by_array(init_key, key_length). Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of its contributors 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 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. Any feedback is very welcome. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) */ /* Period parameters */ #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ static unsigned long mt[N]; /* the array for the state vector */ static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ /* initializes mt[N] with a seed */ void init_genrand(unsigned long s) { mt[0]= s & 0xffffffffUL; for (mti=1; mti<N; mti++) { mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ void init_by_array(unsigned long init_key[], int key_length) { int i, j, k; init_genrand(19650218UL); i=1; j=0; k = (N>key_length ? N : key_length); for (; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + init_key[j] + j; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=key_length) j=0; } for (k=N-1; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ } /* generates a random number on [0,0xffffffff]-interval */ unsigned long genrand_int32(void) { unsigned long y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489UL); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } /* generates a random number on [0,0x7fffffff]-interval */ long genrand_int31(void) { return (long)(genrand_int32()>>1); } /* generates a random number on [0,1]-real-interval */ double genrand_real1(void) { return genrand_int32()*(1.0/4294967295.0); /* divided by 2^32-1 */ } /* generates a random number on [0,1)-real-interval */ double genrand_real2(void) { return genrand_int32()*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on (0,1)-real-interval */ double genrand_real3(void) { return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on [0,1) with 53-bit resolution*/ double genrand_res53(void) { unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } /* These real versions are due to Isaku Wada, 2002/01/09 added */ #undef N #undef M #undef MATRIX_A #undef UPPER_MASK #undef LOWER_MASK };
[ "masterfreek64@2644d07b-d655-0410-af38-4bee65694944", "obliviononline@2644d07b-d655-0410-af38-4bee65694944" ]
[ [ [ 1, 10 ], [ 27, 141 ], [ 146, 332 ] ], [ [ 11, 26 ], [ 142, 145 ] ] ]
e807e3b68c2d45eb63c9857429e2571448e5a4d3
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/video/d3d9/sphere.h
bb4c754c0fe6bd3079ecb026cc7b5b710252a381
[]
no_license
dtbinh/loci-extended
772239e63b4e3e94746db82d0e23a56d860b6f0d
f4b5ad6c4412e75324d19b71559a66dd20f4f23f
refs/heads/master
2021-01-10T12:23:52.467480
2011-03-15T22:03:06
2011-03-15T22:03:06
36,032,427
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
h
#ifndef LOCI_VIDEO_D3D9_SPHERE_H_ #define LOCI_VIDEO_D3D9_SPHERE_H_ /** * Encapsulates a d3dxmesh modelling a sphere. * Maintains a d3dxmesh with proper RAII support. * * @file sphere.h * @author David Gill * @date 08/02/2010 */ #include <memory> #include <boost/shared_ptr.hpp> #include <boost/utility.hpp> #include <d3dx9.h> namespace loci { namespace video { namespace d3d9 { // forward declaration class device_services; class sphere : boost::noncopyable { public: sphere(const boost::shared_ptr<device_services> & device, float radius, unsigned int slices, unsigned int stacks); ~sphere(); void draw(); void release(); void reload(); private: boost::shared_ptr<device_services> device; LPD3DXMESH mesh; // for recovery float radius; unsigned int slices; unsigned int stacks; }; } // namespace d3d9 } // namespace video } // namespace loci #endif // LOCI_VIDEO_D3D9_SPHERE_H_
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 52 ] ] ]
484907c06e9db658b58b160c1000c27ed0b83480
5a9924aff39460fa52f1f55ff387d9ab82c3470f
/tibia81/trainer/trainer.cpp
695985d5c44208c792987d3bffa44d4a25b9a92c
[]
no_license
PimentelM/evremonde
170e4f1916b0a1007c6dbe52b578db53bc6e70de
6b56e8461a602ea56f0eae47a96d340487ba987d
refs/heads/master
2021-01-10T16:03:38.410644
2010-12-04T17:31:01
2010-12-04T17:31:01
48,460,569
0
1
null
null
null
null
UTF-8
C++
false
false
2,627
cpp
/* Trainer by Evremonde */ #include "trainer.h" /* constructor and deconstructor */ CTrainer::CTrainer() { // } CTrainer::~CTrainer() { // } /* game window and process */ HWND CTrainer::getHwnd() { return _hwnd; } DWORD CTrainer::getProcessId() { return _processId; } HANDLE CTrainer::getProcessHandle() { return _processHandle; } void CTrainer::setProcess(HWND gameWindow) { // get game window _hwnd = gameWindow; // get process id ::GetWindowThreadProcessId(_hwnd, &_processId); // get process handle _processHandle = ::OpenProcess(PROCESS_ALL_ACCESS, false, _processId); } void CTrainer::closeProcess() { // close process handle ::CloseHandle(_processHandle); } /* protection */ DWORD CTrainer::setProtection(DWORD address, DWORD type, int bytes) { DWORD oldProtection; ::VirtualProtectEx(_processHandle, reinterpret_cast<void*>(address), bytes, type, &oldProtection); return oldProtection; } /* read and write memory */ void CTrainer::writeBytes(DWORD address, int value, int bytes) { ::WriteProcessMemory(_processHandle, reinterpret_cast<void*>(address), &value, bytes, 0); } int CTrainer::readBytes(DWORD address, int bytes) { int buffer = 0; ::ReadProcessMemory(_processHandle, reinterpret_cast<void*>(address), &buffer, bytes, 0); return buffer; } void CTrainer::writeDouble(DWORD address, double value) { ::WriteProcessMemory(_processHandle, reinterpret_cast<void*>(address), &value, sizeof(value), 0); } void CTrainer::writeChar(DWORD address, unsigned char* value, int bytes) { // value passed without address of operator ::WriteProcessMemory(_processHandle, reinterpret_cast<void*>(address), value, bytes, 0); } void CTrainer::writeString(DWORD address, std::string value) { int j = 0; for(unsigned int i = 0; i < value.size(); i++) { ::WriteProcessMemory(_processHandle, reinterpret_cast<void*>(address + j), &value[i], 1, 0); j++; // increment address } unsigned char nullTerminator = 0x00; // end of string ::WriteProcessMemory(_processHandle, reinterpret_cast<void*>(address + j), &nullTerminator, 1, 0); } std::string CTrainer::readString(DWORD address) { static char buffer[256]; ::ReadProcessMemory(_processHandle, reinterpret_cast<void*>(address), &buffer, sizeof(buffer), 0); return buffer; } void CTrainer::writeNops(DWORD address, int nops) { int j = 0; for (int i = 0; i < nops; i++) { unsigned char nop = 0x90; ::WriteProcessMemory(_processHandle, reinterpret_cast<void*>(address + j), &nop, 1, 0); j++; // increment address } }
[ "evretibia@cc901e99-3b3f-0410-afbc-77a0fa429cc7" ]
[ [ [ 1, 108 ] ] ]
2409a218418eed56b73ee8e7dd46daa05afddaa2
e2ec2e508517c592eebceb505ece24ef8ddfb32e
/IPTVWeb/cgi/SetAccount.cpp
9e37aff34ea8728ebf8e6e7bbcf49c5c03c3eaa1
[]
no_license
lanxianhui/iptvgui
c8bbf3b09552be074e90738243825a9922db0f7a
07a9db17e3442a4941fca643b179e6654bb536c0
refs/heads/master
2021-01-22T02:57:50.117200
2010-04-13T02:57:16
2010-04-13T02:57:16
33,531,815
1
1
null
null
null
null
UTF-8
C++
false
false
747
cpp
#include <stdio.h> #include <stdlib.h> #include <string> using namespace std; int main( void ) { fprintf( stdout, "Content-type:text/html\n\n"); fprintf( stdout, "<html><title>get</title>\n"); string username = ""; string password = ""; if( getenv("QUERY_STRING" ) ) { char* queryStr = getenv("QUERY_STRING"); if(scanf(queryStr,"username=%s&password=%s",&username,&password) == 2) { fprintf( stdout, username + "|" + password); } } else { fprintf( stdout, "(NULL)\n" ); } fprintf( stdout, "</html>\n" ); return 0; }
[ "silentbalanceyh@e528dd6c-a225-11de-a69d-91aafc7ba57a" ]
[ [ [ 1, 30 ] ] ]
07fe06b4bb83bb5840c5bc453f663a11338cc3db
b4d726a0321649f907923cc57323942a1e45915b
/CODE/Fonttool/FontCreate.cpp
5f1f6d67b59bceb91de14f3ee22a703399189ecf
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
15,598
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/fonttool/FontCreate.cpp $ * $Revision: 4 $ * $Date: 1/06/99 2:25p $ * $Author: Dave $ * * Tool for creating new fonts * * $Log: /Freespace2/code/fonttool/FontCreate.cpp $ * * 4 1/06/99 2:25p Dave * Stubs and release build fixes. * * 3 12/02/98 9:58a Dave * Got fonttool working under glide/direct3d. * * 2 10/24/98 5:15p Dave * * 1 10/24/98 4:58p Dave * * 4 10/31/97 10:30a Adam * fixed a bug passing wrong pointer to pcx_read trashing memory. * * 3 10/30/97 4:56p John * Fixed up font stuff to build. Fixed bug where it didn't show the last * 3 characters in kerning table. * * 2 6/05/97 4:53p John * First rev of new antialiased font stuff. * * 1 6/02/97 4:04p John * * $NoKeywords: $ */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <io.h> #include <conio.h> #include "globalincs/pstypes.h" #include "osapi/osapi.h" #include "cfile/cfile.h" #include "graphics/2d.h" #include "io/key.h" #include "io/mouse.h" #include "palman/palman.h" #include "io/timer.h" #include "pcxutils/pcxutils.h" #include "graphics/Font.h" #include "bmpman/BmpMan.h" #include "fonttool/FontTool.h" static bitmap bmp; static ubyte *data; static int offset; static ubyte pal[768]; static ubyte bkg; static ubyte border; int num_bad_pixels=0; static void myexit(int value) { // getch(); exit(value); } ubyte PIX(int x,int y) { if ( x<0 || x >= bmp.w ) return bkg; if ( y<0 || y >= bmp.h ) return bkg; return data[x+y*offset]; } // Attempts to find a box at pixel (x,y) if it can't, then it // returns 0, else returns 1 and w&h are filled in. int find_box( int x, int y, int *w, int *h ) { int w1, w2, h1, h2; int y1,x1,tmp; char buf[100]; if ( PIX(x,y) != border ) return 0; x1 = x; y1 = y; // printf( "--------- Finding box at %d, %d ----------\n", x1, y1 ); //======================= FIND LEFT EDGE ====================== y++; while ( PIX(x,y)==border ) { if ( PIX(x+1,y)==border) { goto LeftSideFound; } y++; if ( y > bmp.h ) { sprintf(buf, "Box at (%d,%d) goes off bottom of screen.", x1, y1); print_out(buf); return 1; } } // printf( "Box at (%d,%d) doesn't have bottom border.\n", x1, y1 ); // myexit(1); return 0; LeftSideFound: h1 = y - y1 - 1; // printf( "Has a left height of %d\n", h1 ); //======================= FIND BOTTOM EDGE ====================== x++; while ( PIX(x,y)==border ) { if ( PIX(x,y-1)==border) { goto BottomSideFound; } x++; if ( x > bmp.w ) { sprintf(buf, "Box at (%d,%d) goes off left of screen.", x1, y1); print_out(buf); return 1; } } sprintf(buf, "Box at (%d,%d) doesn't have right border connected to bottom.", x1, y1); print_out(buf); return 1; BottomSideFound: w1 = x - x1 - 1; // printf( "Has a bottom width of %d\n", w1 ); //======================= FIND RIGHT EDGE ====================== tmp = y; y--; while ( PIX(x,y)==border ) { if ( PIX(x-1,y)==border) { goto RightSideFound; } y--; if ( y < 0 ) { sprintf(buf, "Box at (%d,%d) goes off top of screen.", x1, y1 ); print_out(buf); return 1; } } sprintf(buf, "Box at (%d,%d) doesn't have top border connected to right border.", x1, y1 ); print_out(buf); return 1; RightSideFound: h2 = tmp - y - 1; // printf( "Has a right height of %d\n", h2 ); //======================= FIND TOP EDGE ====================== tmp = x; x--; while ( PIX(x,y)==border ) { if ( PIX(x,y+1)==border) { goto TopSideFound; } x--; if ( x < 0 ) { sprintf(buf, "Box at (%d,%d) goes off left of screen.", x1, y1 ); print_out(buf); return 1; } } sprintf(buf, "Box at (%d,%d) doesn't have left border connected to top border.", x1, y1 ); print_out(buf); return 1; TopSideFound: w2 = tmp - x - 1; // printf( "Has a top width of %d\n", w2 ); //==================== if ( h1 != h2 ) { sprintf(buf, "Box at (%d,%d) has unequal top/bottom .", x1, y1 ); print_out(buf); return 1; } if ( w1 != w2 ) { sprintf(buf, "Box at (%d,%d) has unequal left/right.", x1, y1 ); print_out(buf); return 1; } if ( w1 < 1 ) { printf(buf, "Box at (%d,%d) is less than 1 pixel wide.", x1, y1 ); return 1; } if ( h1 < 1 ) { sprintf(buf, "Box at (%d,%d) is less than 1 pixel tall.", x1, y1 ); print_out(buf); return 1; } *w = w1; *h = h1; return 1; } void found_box( font *fnt, int x, int y, int w, int h ); void find_all_boxes(font *fnt) { int x = 0; int y = 0; char buf[100]; data = (ubyte *)bmp.data; offset = bmp.w; bkg = data[0]; sprintf(buf, "Background color = %d", bkg ); print_out(buf); for ( y=0; y<bmp.h; y++ ) { for ( x=0; x<bmp.w; x++ ) { if ( PIX(x,y) != bkg ) { border = PIX(x,y); goto FoundBorder; } } } sprintf(buf, "Couldn't find anything but background pixels" ); print_out(buf); return; FoundBorder: sprintf(buf, "Border color = %d, starts at %d,%d", border, x, y ); print_out(buf); int w,h; int row_height = 0; while(1) { if ( find_box( x, y, &w, &h ) ) { found_box( fnt, x+1, y+1, w, h ); x = x + w + 1; if ( row_height < 1 ) { row_height = h; } else { // if ( row_height != h ) { // printf( "Uneven row height!\n" ); // myexit(1); // } } } else { x++; if ( x >= bmp.w ) { x = 0; if ( row_height ) { //printf( "Moving down %d pixels\n", row_height+2); y += row_height+2; row_height = 0; } else { y++; } if ( y >= bmp.h ) { break; } } } } } void fonttool_create_new( font *fnt ) { strncpy( (char *)&fnt->id, "IAFT", 4 ); fnt->version = FONT_VERSION; fnt->num_chars = 0; fnt->first_ascii = ' '; fnt->w = 0; fnt->h = 0; fnt->num_kern_pairs = 0; fnt->pixel_data = NULL; fnt->pixel_data_size = 0; fnt->kern_data = NULL; fnt->kern_data_size = 0; fnt->char_data = NULL; fnt->char_data_size = 0; } void fonttool_add_char( font *fnt, int x1, int y1, int real_w, int h, ubyte *data, int rowsize ) { int x, y, n, offset; int w; char buf[100]; n = fnt->num_chars; w = real_w; while ( w & 1) w++; sprintf(buf, "Adding character %d (%c) from the %dx%d pixels at (%d,%d)", n, n + fnt->first_ascii, real_w, h, x1, y1 ); print_out(buf); // add new character data font_char * new_char; new_char = (font_char *)malloc( fnt->char_data_size + sizeof(font_char) ); if ( !new_char ) { sprintf(buf, "Not enough memory to create a new character" ); print_out(buf); return; } if ( fnt->char_data ) { memcpy( new_char, fnt->char_data, fnt->char_data_size ); free(fnt->char_data); fnt->char_data = NULL; } fnt->char_data = new_char; fnt->char_data_size += sizeof(font_char); new_char = fnt->char_data + fnt->num_chars; fnt->num_chars++; // add new character pixel data ubyte *new_pixel_data = (ubyte *)malloc( fnt->pixel_data_size+w*h ); if ( !new_pixel_data ) { sprintf(buf, "Not enough memory to create new %dx%d character", w, h); print_out(buf); return; } if ( fnt->pixel_data ) { memcpy( new_pixel_data, fnt->pixel_data, fnt->pixel_data_size ); free(fnt->pixel_data); fnt->pixel_data = NULL; } offset = fnt->pixel_data_size; fnt->pixel_data_size += w*h; fnt->pixel_data = new_pixel_data; new_pixel_data = fnt->pixel_data + offset; new_char->byte_width = w; new_char->spacing = real_w; new_char->offset = offset; new_char->kerning_entry = -1; new_char->user_data = 0; for ( y=0; y<h; y++ ) { for (x=0; x<w; x++ ) { ubyte c; if ( x >= real_w) c = 0; else c = data[x+y*rowsize]; if ( c > 15 ) { num_bad_pixels++; c = 15; } *new_pixel_data++ = c; } } if ( fnt->h < 1 ) fnt->h = h; int i, wtotal = 0; for (i=0; i<fnt->num_chars; i++ ) { wtotal += fnt->char_data[i].spacing; } fnt->w = wtotal / fnt->num_chars; if ( fnt->w < 1 ) fnt->w = 1; } void fonttool_dump( char *filename, font *fnt ) { FILE *fp; char tmp_name[128], *p; int garbage = 42; char buf[100]; strcpy( tmp_name, filename ); p = strchr( tmp_name, '.' ); if ( p ) *p = 0; strcat( tmp_name, ".if" ); fp = fopen( tmp_name, "wb" ); if ( fp == NULL ) { sprintf(buf, "Couldn't open font file '%s' for writing!", tmp_name); print_out(buf); return; } fwrite( &fnt->id, 4, 1, fp ); fwrite( &fnt->version, sizeof(int), 1, fp ); fwrite( &garbage, sizeof(int), 1, fp ); fwrite( &fnt->num_chars, sizeof(int), 1, fp ); fwrite( &fnt->first_ascii, sizeof(int), 1, fp ); fwrite( &fnt->w, sizeof(int), 1, fp ); fwrite( &fnt->h, sizeof(int), 1, fp ); fwrite( &fnt->num_kern_pairs, sizeof(int), 1, fp ); fwrite( &fnt->kern_data_size, sizeof(int), 1, fp ); fwrite( &fnt->char_data_size, sizeof(int), 1, fp ); fwrite( &fnt->pixel_data_size, sizeof(int), 1, fp ); if ( fnt->kern_data_size ) { fwrite( fnt->kern_data, fnt->kern_data_size, 1, fp ); } if ( fnt->char_data_size ) { fwrite( fnt->char_data, fnt->char_data_size, 1, fp ); } if ( fnt->pixel_data_size ) { fwrite( fnt->pixel_data, fnt->pixel_data_size, 1, fp ); } fclose(fp); } void fonttool_read( char *filename, font *fnt ) { FILE *fp; char tmp_name[MAX_PATH], *p; int garbage; char buf[100]; strcpy( tmp_name, filename ); p = strchr( tmp_name, '.' ); if ( p ) *p = 0; strcat( tmp_name, ".if" ); fp = fopen( tmp_name, "rb" ); if ( fp == NULL ) { sprintf(buf, "Couldn't open font file '%s' for reading!", tmp_name ); print_out(buf); return; } fread( &fnt->id, 4, 1, fp ); fread( &fnt->version, sizeof(int), 1, fp ); fread( &garbage, sizeof(int), 1, fp); fread( &fnt->num_chars, sizeof(int), 1, fp ); fread( &fnt->first_ascii, sizeof(int), 1, fp ); fread( &fnt->w, sizeof(int), 1, fp ); fread( &fnt->h, sizeof(int), 1, fp ); fread( &fnt->num_kern_pairs, sizeof(int), 1, fp ); fread( &fnt->kern_data_size, sizeof(int), 1, fp ); fread( &fnt->char_data_size, sizeof(int), 1, fp ); fread( &fnt->pixel_data_size, sizeof(int), 1, fp ); if ( fnt->kern_data_size ) { fnt->kern_data = (font_kernpair *)malloc( fnt->kern_data_size ); if (!fnt->kern_data) { sprintf(buf, "Out of memory reading %d bytes of font data from %s", tmp_name ); print_out(buf); return; } fread( fnt->kern_data, fnt->kern_data_size, 1, fp ); } else { fnt->kern_data = NULL; } if ( fnt->char_data_size ) { fnt->char_data = (font_char *)malloc( fnt->char_data_size ); if (!fnt->char_data) { sprintf(buf, "Out of memory reading %d bytes of font data from %s", tmp_name ); print_out(buf); return; } fread( fnt->char_data, fnt->char_data_size, 1, fp ); } else { fnt->char_data = NULL; } if ( fnt->pixel_data_size ) { fnt->pixel_data = (ubyte *)malloc( fnt->pixel_data_size ); if (!fnt->pixel_data) { sprintf(buf, "Out of memory reading %d bytes of font data from %s", tmp_name ); print_out(buf); return; } fread( fnt->pixel_data, fnt->pixel_data_size, 1, fp ); } else { fnt->pixel_data = NULL; } fclose(fp); // Create a bitmap for hardware cards. // JAS: Try to squeeze this into the smallest square power of two texture. // This should probably be done at font generation time, not here. int w, h; if ( fnt->pixel_data_size < 64*64 ) { w = h = 64; } else if ( fnt->pixel_data_size < 128*128 ) { w = h = 128; } else { w = h = 256; } fnt->bm_w = w; fnt->bm_h = h; fnt->bm_data = (ubyte *)malloc(fnt->bm_w*fnt->bm_h); fnt->bm_u = (int *)malloc(sizeof(int)*fnt->num_chars); fnt->bm_v = (int *)malloc(sizeof(int)*fnt->num_chars); int i,x,y; x = y = 0; for (i=0; i<fnt->num_chars; i++ ) { ubyte * fp; int x1, y1; fp = &fnt->pixel_data[fnt->char_data[i].offset]; if ( x + fnt->char_data[i].byte_width >= fnt->bm_w ) { x = 0; y += fnt->h; if ( y+fnt->h > fnt->bm_h ) { Error( LOCATION, "Font too big!\n" ); } } fnt->bm_u[i] = x; fnt->bm_v[i] = y; for( y1=0; y1<fnt->h; y1++ ) { for (x1=0; x1<fnt->char_data[i].byte_width; x1++ ) { uint c = *fp++; if ( c > 14 ) c = 14; fnt->bm_data[(x+x1)+(y+y1)*fnt->bm_w] = unsigned char(c); } } x += fnt->char_data[i].byte_width; } fnt->bitmap_id = bm_create( 8, fnt->bm_w, fnt->bm_h, fnt->bm_data, BMP_AABITMAP ); } void fonttool_copy_kern( font *src, font *dst ) { char buf[100]; if ( dst->kern_data ) { free( dst->kern_data ); dst->kern_data = NULL; } else { sprintf(buf, "Error with destination font data."); print_out(buf); } if ( (src->kern_data_size < 1) || (!src->kern_data) ) { dst->num_kern_pairs = 0; dst->kern_data_size = 0; dst->kern_data = NULL; fonttool_resync_kerning(dst); return; } dst->kern_data = (font_kernpair *)malloc( src->kern_data_size ); if (!dst->kern_data) { sprintf(buf, "Out of memory copying %d bytes of font data." ); print_out(buf); return; } memcpy( dst->kern_data, src->kern_data, src->kern_data_size ); dst->kern_data_size = src->kern_data_size; dst->num_kern_pairs = src->num_kern_pairs; fonttool_resync_kerning(dst); } void found_box( font *fnt, int x, int y, int w, int h ) { fonttool_add_char( fnt, x, y, w, h, &data[x+y*offset], offset ); } void fonttool_create_font(char *pcx_filename, char *font_filename) { font fnt1, fnt2; char buf[100]; sprintf(buf, "Creating font file from '%s'", pcx_filename ); print_out(buf); if ( font_filename ) { } int w, h; int pcx_error = pcx_read_header( pcx_filename, &w, &h, NULL ); if ( pcx_error != PCX_ERROR_NONE ) { sprintf(buf, "Error reading PCX file, '%s'", pcx_filename ); print_out(buf); return; } bmp.w = (short)w; bmp.h = (short)h; bmp.data = (uint)malloc( w*h + 768 ); bmp.palette = (ubyte *)(bmp.data +w*h ); if ( !bmp.data ) { sprintf(buf, "Error mallocing PCX data, '%s'", pcx_filename ); print_out(buf); return; } pcx_error = pcx_read_bitmap_8bpp( pcx_filename, (ubyte *)bmp.data, pal ); if ( pcx_error != PCX_ERROR_NONE ) { sprintf(buf, "Error reading PCX file, '%s'", pcx_filename ); print_out(buf); return; } fonttool_create_new( &fnt1 ); find_all_boxes(&fnt1); if (font_filename) { sprintf(buf, "Using kern data from font '%s'", font_filename ); print_out(buf); vm_init(5*1024*1024); app_init(); fonttool_read( font_filename, &fnt2 ); fonttool_copy_kern( &fnt2, &fnt1 ); close_graphics(); } sprintf(buf, ""); print_out(buf); sprintf(buf, "Font is, on average, %dx%d and has %d characters, %d kerning pairs.", fnt1.w, fnt1.h, fnt1.num_chars, fnt1.num_kern_pairs ); print_out(buf); if ( num_bad_pixels > 0 ) { sprintf(buf, "It had %d bad pixel(s) in it.", num_bad_pixels); print_out(buf); sprintf(buf, "(Bad means the pixel index was greater than 15)."); print_out(buf); } fonttool_dump( pcx_filename, &fnt1 ); return; }
[ [ [ 1, 660 ] ] ]
21f974eebf7e21a42158b877642cbbf6a163630e
e4bad8b090b8f2fd1ea44b681e3ac41981f50220
/trunk/gui/abeetlesgui/NewEnvDialog.cpp
5b946663a490bc5e6b300fe42787f19d21cfb657
[]
no_license
BackupTheBerlios/abeetles-svn
92d1ce228b8627116ae3104b4698fc5873466aff
803f916bab7148290f55542c20af29367ef2d125
refs/heads/master
2021-01-22T12:02:24.457339
2007-08-15T11:18:14
2007-08-15T11:18:14
40,670,857
0
0
null
null
null
null
UTF-8
C++
false
false
6,544
cpp
#include "NewEnvDialog.h" #include "Beetle.h" #include "defines.h" #include "COneRun.h" #include <QtGui> #include <QTime> NewEnvDialog::NewEnvDialog( QWidget * parent, Qt::WindowFlags f):QDialog(parent,f) { MapFN=MAP_BMP_FILE; EffFN= EFF_BMP_FILE; BeetleFN = DEFAULT_BEETLES_FILE; RandomRadio = new QRadioButton(tr("Random beetles")); RandomRadio->setChecked(true); QLabel * seedLabel = new QLabel("Seed: "); SeedSpin = new QSpinBox(); SeedSpin->setMaximum(MAX_INT); SeedSpin->setValue(( QTime::currentTime().msec() * QTime::currentTime().minute() ) % MAX_INT); QLabel * numBeetlesLabel = new QLabel("Number of beetles: "); NumBeetlesSpin = new QSpinBox(); NumBeetlesSpin->setMaximum(G_WIDTH_MAX * G_HEIGHT_MAX); NumBeetlesSpin->setMinimum(-1); NumBeetlesSpin->setValue(100); QLabel * stepOnFlowerLabel = new QLabel("Use rule \"Step On Flower\""); StepOnFlowerCheck = new QCheckBox(); StepOnFlowerCheck->setCheckState(Qt::Checked); QLabel * noExpectationsLabel = new QLabel("Initially widest expectations"); NoExpectationsCheck= new QCheckBox(); NoExpectationsCheck->setCheckState(Qt::Checked); QGridLayout * randomGrid = new QGridLayout(); randomGrid->addWidget(seedLabel,0,0); randomGrid->addWidget(SeedSpin,0,1); randomGrid->addWidget(numBeetlesLabel,1,0); randomGrid->addWidget(NumBeetlesSpin,1,1); randomGrid->addWidget(StepOnFlowerCheck,2,0,Qt::AlignRight); randomGrid->addWidget(stepOnFlowerLabel,2,1,Qt::AlignLeft); randomGrid->addWidget(NoExpectationsCheck,3,0,Qt::AlignRight); randomGrid->addWidget(noExpectationsLabel,3,1,Qt::AlignLeft); QGroupBox * randomGroup = new QGroupBox(); randomGroup->setLayout(randomGrid); BeetleFileRadio = new QRadioButton(tr("Beetles from file")); BeetleFileRadio->setChecked(false); BeetleFileBut= new QPushButton("File of beetles"); BeetleFileLabel = new QLabel("Default"); connect(BeetleFileBut,SIGNAL(pressed()),this,SLOT(setBeetleFN())); QHBoxLayout * beetleFileLayout = new QHBoxLayout(); beetleFileLayout->addWidget(BeetleFileBut); beetleFileLayout->addWidget(BeetleFileLabel); QGroupBox * beetleFileGroup = new QGroupBox(); beetleFileGroup->setEnabled (false); beetleFileGroup->setLayout(beetleFileLayout); connect(RandomRadio,SIGNAL(toggled(bool)),randomGroup,SLOT(setEnabled(bool))); connect(BeetleFileRadio,SIGNAL(toggled(bool)),beetleFileGroup,SLOT(setEnabled(bool))); MapLabel = new QLabel("Default"); MapBut= new QPushButton("Map"); connect(MapBut,SIGNAL(pressed()),this,SLOT(setMapFN())); EffLabel = new QLabel("Default"); EffBut= new QPushButton("Energy From Flower"); connect(EffBut,SIGNAL(pressed()),this,SLOT(setEffFN())); QLabel * mutationLabel = new QLabel("Probability of mutation: "); MutationSpin = new QSpinBox();MutationSpin->setMaximum(10);MutationSpin->setMinimum(0);MutationSpin->setValue(MUTATION_PROB_DEFAULT); QLabel * costsLabel = new QLabel("Costs of Actions: "); QLabel * costStepLabel = new QLabel("Step: "); QLabel * costRotLabel = new QLabel("Rotation: "); QLabel * costCopulLabel = new QLabel("Copulation: "); QLabel * costWaitLabel = new QLabel("Waiting: "); CostStepSpin = new QSpinBox();CostStepSpin->setMaximum(10);CostStepSpin->setMinimum(1);CostStepSpin->setValue(1); CostRotSpin = new QSpinBox();CostRotSpin->setMaximum(10);CostRotSpin->setMinimum(1);CostRotSpin->setValue(1); CostCopulSpin = new QSpinBox();CostCopulSpin->setMaximum(10);CostCopulSpin->setMinimum(1);CostCopulSpin->setValue(1); CostWaitSpin = new QSpinBox();CostWaitSpin->setMaximum(10);CostWaitSpin->setMinimum(1);CostWaitSpin->setValue(1); QPushButton * okBut = new QPushButton(tr("OK")); connect(okBut,SIGNAL(clicked()),this,SLOT(accept())); okBut->setDefault(true); QPushButton * cancelBut = new QPushButton(tr("Cancel")); connect(cancelBut,SIGNAL(clicked()),this,SLOT(reject())); QGridLayout * bottomGrid = new QGridLayout (); bottomGrid->addWidget(MapBut,0,0); bottomGrid->addWidget(MapLabel,0,1); bottomGrid->addWidget(EffBut,1,0); bottomGrid->addWidget(EffLabel,1,1); bottomGrid->addWidget(mutationLabel,2,0); bottomGrid->addWidget(MutationSpin,2,1); bottomGrid->addWidget(costsLabel,3,0,1,2); bottomGrid->addWidget(costStepLabel,4,0); bottomGrid->addWidget(CostStepSpin,4,1); bottomGrid->addWidget(costRotLabel,5,0); bottomGrid->addWidget(CostRotSpin,5,1); bottomGrid->addWidget(costCopulLabel,6,0); bottomGrid->addWidget(CostCopulSpin,6,1); bottomGrid->addWidget(costWaitLabel,7,0); bottomGrid->addWidget(CostWaitSpin,7,1); bottomGrid->addWidget(okBut,8,0,Qt::AlignCenter); bottomGrid->addWidget(cancelBut,8,1,Qt::AlignCenter); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(RandomRadio); layout->addWidget(randomGroup); layout->addWidget(BeetleFileRadio); layout->addWidget(beetleFileGroup); layout->addLayout(bottomGrid); setLayout(layout); setWindowTitle(tr("Settings of New Environment")); } NewEnvDialog::~NewEnvDialog(void) { } void NewEnvDialog::setBeetleFN() { QFileDialog openDlg; if (!(BeetleFN = openDlg.getOpenFileName(this,"File of beetles","","Txt files (*.txt)")).isNull()); BeetleFileLabel->setText(BeetleFN); } void NewEnvDialog::setMapFN() { QFileDialog openDlg; if (!(MapFN = openDlg.getOpenFileName(this,"File of map","","Bmp files (*.bmp)")).isNull()); MapLabel->setText(MapFN); } void NewEnvDialog::setEffFN() { QFileDialog openDlg; if (!(EffFN = openDlg.getOpenFileName(this,"File of energy from flower function","","Bmp files (*.bmp)")).isNull()); EffLabel->setText(EffFN); } void NewEnvDialog::getData(COneRun * oneRun) { if (RandomRadio->isChecked()==true) { oneRun->IsBtlRandom=true; oneRun->Seed = SeedSpin->value(); oneRun->NumRandBeetles = NumBeetlesSpin->value(); if (StepOnFlowerCheck->checkState()==Qt::Checked) oneRun->IsStepOnFlower=true; else oneRun->IsStepOnFlower=false; oneRun->BeetlesFN=""; if (NoExpectationsCheck->checkState()==Qt::Checked) oneRun->IsNoExpectations=true; else oneRun->IsNoExpectations=false; } else { oneRun->IsBtlRandom=false; oneRun->BeetlesFN = BeetleFN; } oneRun->EffFN = EffFN; oneRun->MapFN = MapFN; oneRun->MutationProb = MutationSpin->value(); oneRun->StepCost =CostStepSpin->value(); oneRun->RotCost = CostRotSpin->value(); oneRun->CopulCost = CostCopulSpin->value(); oneRun->WaitCost = CostWaitSpin->value(); }
[ "ibart@60a5a0de-1a2f-0410-942a-f28f22aea592" ]
[ [ [ 1, 184 ] ] ]
7aa2db242edb015c131a46a98243e6ea75adcaeb
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/DOM_XMLDecl.hpp
4bd412551f31701033eed27181e1bd5ff92f8905
[]
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,683
hpp
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOM_XMLDecl.hpp 176026 2004-09-08 13:57:07Z peiyongz $ * */ #ifndef DOM_XMLDecl_HEADER_GUARD_ #define DOM_XMLDecl_HEADER_GUARD_ #include <xercesc/util/XercesDefs.hpp> #include "DOM_Node.hpp" XERCES_CPP_NAMESPACE_BEGIN class XMLDeclImpl; /** * Class to refer to XML Declaration nodes in the DOM. * */ class DEPRECATED_DOM_EXPORT DOM_XMLDecl: public DOM_Node { public: /** @name Constructors and assignment operators */ //@{ /** * The default constructor for DOM_XMLDecl creates a null * DOM_XMLDecl object that refers to a declaration node with * version= 1.0, encoding=utf-8 and standalone=no * */ DOM_XMLDecl(); /** * Copy constructor. Creates a new <code>DOM_XMLDecl</code> that refers to the * same underlying actual xmlDecl node as the original. * * @param other The object to be copied */ DOM_XMLDecl(const DOM_XMLDecl &other); /** * Assignment operator * * @param other The object to be copied */ DOM_XMLDecl & operator = (const DOM_XMLDecl &other); /** * Assignment operator. This overloaded variant is provided for * the sole purpose of setting a DOM_Node reference variable to * zero. Nulling out a reference variable in this way will decrement * the reference count on the underlying Node object that the variable * formerly referenced. This effect is normally obtained when reference * variable goes out of scope, but zeroing them can be useful for * global instances, or for local instances that will remain in scope * for an extended time, when the storage belonging to the underlying * node needs to be reclaimed. * * @param val Only a value of 0, or null, is allowed. */ DOM_XMLDecl & operator = (const DOM_NullPtr *val); //@} /** @name Destructor */ //@{ /** * Destructor. The object being destroyed is the reference * object, not the underlying Document itself. * * <p>The reference counting memory management will * delete the underlying document itself if this * DOM_XMLDecl is the last remaining to refer to the Document, * and if there are no remaining references to any of the nodes * within the document tree. If other live references do remain, * the underlying document itself remains also. * */ ~DOM_XMLDecl(); //@} //@{ /** * To get the version string of the xmlDeclaration statement */ DOMString getVersion() const; /** * To get the encoding string of the xmlDeclaration statement */ DOMString getEncoding() const; /** * To get the standalone string of the xmlDeclaration statement */ DOMString getStandalone() const; //@} protected: DOM_XMLDecl( XMLDeclImpl *impl); friend class DOM_Document; }; XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 129 ] ] ]
1afb0e2170ae476733afb00fb1dedb8ea17f9254
be2e23022d2eadb59a3ac3932180a1d9c9dee9c2
/GameServer/MapGroupKernel/MercenaryTask.h
6ad249b7955ed4e8feb80559102d23ff152e5c0b
[]
no_license
cronoszeu/revresyksgpr
78fa60d375718ef789042c452cca1c77c8fa098e
5a8f637e78f7d9e3e52acdd7abee63404de27e78
refs/heads/master
2020-04-16T17:33:10.793895
2010-06-16T12:52:45
2010-06-16T12:52:45
35,539,807
0
2
null
null
null
null
GB18030
C++
false
false
1,711
h
#pragma once #pragma warning(disable:4786) #include "define.h" //#include "ConstGameData.h" //#include "GameData.h" //#include "GameObj.h" //#include "Myheap.h" #include "TimeOut.h" #include "MercenaryTaskData.h" #include <vector> //typedef ISingleMap2<CMercenaryTaskData> IMTaskDataSet; //typedef CSingleMap2<CMercenaryTaskData> CMTaskDataSet; // 目前不考虑开多个MapGroup,为了加快工作进度,佣兵任务暂时不做成世界同步 // 如果开了多个MapGroup,就必须修改这部分,象帮派系统一样做世界同步处理 // —— zlong 2004.11.12 class IDatabase; class IRole; class CMercenaryTask //: public CMercenaryTaskData { public: CMercenaryTask(); virtual ~CMercenaryTask(); public: static CMercenaryTask* CreateNew() { return new CMercenaryTask; } ULONG Release () { delete this; return 0; } bool Create (PROCESS_ID idProcess); bool CreateNewTask(const ST_MTASK_DATA* pInfo); bool DeleteTask (OBJID idTask); int GetTaskAmount() { return m_setData.size(); } CMercenaryTaskData* QueryTaskDataByIndex (int nIdx); CMercenaryTaskData* QueryTaskDataByID (OBJID idTask); CMercenaryTaskData* QueryTaskDataByOwner (OBJID idUser); CMercenaryTaskData* QueryTaskDataAccepted (OBJID idAccepter); void OnTimer(time_t tCurr); public: bool SendTaskList(IRole* pRole, UCHAR usType, OBJID idLast); bool SendTaskInfo(IRole* pRole, OBJID idTask); protected: // IMTaskDataSet* m_setData; typedef std::vector<CMercenaryTaskData*> TASKDATA_SET; TASKDATA_SET m_setData; CTimeOut m_tCheckInterval; PROCESS_ID m_idProcess; // MYHEAP_DECLARATION(s_heap) };
[ "rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1" ]
[ [ [ 1, 71 ] ] ]
6a38b60a3c546a4da391009cd1cc33cbb1ac06fe
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/Lokapala/Operator/MSCommunicationSD.cpp
e64416bcf1b125e1f33439ac7cd386ce904f85a7
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
/**@file MSCommunicationSD.cpp * @brief MSM의 CommunicationSD의 멤버함수 구현 * @author siva */ #include "stdafx.h" #include "MSCommunicationSD.h" /**@brief CCM을 이용해서 텍스트 메세지를 랩터에게 보낸다. */ void CMSCommunicationSD::SendTextMessageToRaptor(void *a_messageData) { CCBFMediator::Instance()->SendTextMessageToRaptor(a_messageData); }
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 15 ] ] ]
d37a08cb4f9a60ff79d0e420688f0b7ca2f28476
3bfe835203f793ee00bdf261c26992b1efea69ed
/misc/Inject!/patient.cpp
f60a76876faa691356ec6fa699d8e8d224f7c305
[]
no_license
yxrkt/DigiPen
0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3
e1bb773d15f63c88ab60798f74b2e424bcc80981
refs/heads/master
2020-06-04T20:16:05.727685
2009-11-18T00:26:56
2009-11-18T00:26:56
814,145
1
3
null
null
null
null
UTF-8
C++
false
false
2,111
cpp
#include <windows.h> #include <sstream> #include "common.h" StageData *g_pStageData; LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); int APIENTRY WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, int ) { WNDCLASSEX wcex; memset( &wcex, 0, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.lpfnWndProc = &WndProc; wcex.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH ); wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hInstance = hInst; wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpszClassName = "patient"; ASSERT( RegisterClassEx( &wcex ), "creating patient window class failed =(" ); HWND hWnd = CreateWindowEx( 0, "patient", "patient", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 256, 256, NULL, NULL, hInst, NULL ); ShowWindow( hWnd, SW_SHOW ); MSG msg; memset( &msg, 0, sizeof( msg ) ); while ( msg.message != WM_QUIT ) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } Sleep( 1 ); if ( g_pStageData ) { if ( g_pStageData->width == 666 ) MessageBox( NULL, "waesome", "waesome", MB_OK ); } } return (int)msg.wParam; } LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch ( msg ) { case WM_APP: { std::stringstream stageInfo; g_pStageData = (StageData *)lParam; stageInfo << "width = " << g_pStageData->width << ", height = " << g_pStageData->height; //MessageBox( NULL, stageInfo.str().c_str(), "Success!", MB_ICONINFORMATION ); } break; case WM_APP + 1: { ( (StageData *)lParam )->width = 100; ( (StageData *)lParam )->height = 100; ( (StageData *)lParam )->changed = true; } break; case WM_CLOSE: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0L; }
[ [ [ 1, 81 ] ] ]
d7defc72e16bd4167cdf9c65c9a07508aae8fb23
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-realmserver/Master.cpp
d34f0555c186e85c19dadf69a1c2709335a6eafa
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
3,263
cpp
/* * ArcEmu MMORPG Server * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "RStdAfx.h" #include "../ascent-shared/svn_revision.h" Database * Database_Character; Database * Database_World; int main(int argc, char *argv[]) { sLog.Init(-1, -1); sLog.outString("TexT"); /* Initialize global timestamp */ UNIXTIME = time(NULL); /* Print Banner */ Log.Notice("Server", "=============================================================="); Log.Notice("Server", "| Codename Ascent Cluster - Realm Server |"); Log.Notice("Server", "| Version 0.1, Revision %04u |", BUILD_REVISION); Log.Notice("Server", "=============================================================="); Log.Line(); Database_Character = Database::CreateDatabaseInterface( 1 ); Database_World = Database::CreateDatabaseInterface( 1 ); Log.Success("Database", "Interface Created."); new ClusterMgr; new ClientMgr; ThreadPool.Startup(); Log.Line(); Log.Notice("Database", "Connecting to database..."); if(Database_Character->Initialize("localhost", 3306, "moocow", "moo", "antrix-character", 1, 1000) && Database_World->Initialize("localhost", 3306, "moocow", "moo", "antrix-world", 1, 1000)) { Log.Success("Database", "Connections established."); } else { Log.Error("Database", "One or more errors occured while connecting to databases."); exit(-1); } Log.Line(); Log.Success("Storage", "DBC Files Loaded..."); Storage_Load(); Log.Line(); //CreateSocketEngine(); //sSocketEngine.SpawnThreads(); new SocketMgr; new SocketGarbageCollector; sSocketMgr.SpawnWorkerThreads(); Log.Success("Network", "Network Subsystem Started."); Log.Notice("Network", "Opening Client Port..."); ListenSocket<WorldSocket> * wsl = new ListenSocket<WorldSocket>("0.0.0.0", 8129); bool lsc = wsl->IsOpen(); Log.Notice("Network", "Opening Server Port..."); ListenSocket<WSSocket> * isl = new ListenSocket<WSSocket>("0.0.0.0", 11010); bool ssc = isl->IsOpen(); Config.MainConfig.SetSource("ascent.conf"); Config.RealmConfig.SetSource("realms.conf"); if(!lsc || !ssc) { Log.Error("Network", "Could not open one of the sockets."); return 1; } /* connect to LS */ new LogonCommHandler; sLogonCommHandler.Startup(); /* main loop */ for(;;) { sLogonCommHandler.UpdateSockets(); //wsl->Update(); //isl->Update(); sClientMgr.Update(); sClusterMgr.Update(); Sleep(50); } } void OnCrash(bool Terminate) { }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 4, 69 ], [ 71, 113 ] ], [ [ 2, 3 ], [ 70, 70 ] ] ]
66f0ffc55ceaa67f742448b1cd2323dd3ce21052
fd518ed0226c6a044d5e168ab50a0e4a37f8efa9
/iAuthor/AmpSdk/XInkTest/ChildView.h
653e3501e8509ce214a3702463753957836a6032
[]
no_license
shilinxu/iprojects
e2e2394df9882afaacfb9852332f83cbef6a8c93
79bc8e45596577948c45cf2afcff331bc71ab026
refs/heads/master
2020-05-17T19:15:43.197685
2010-04-02T15:58:11
2010-04-02T15:58:11
41,959,151
0
0
null
null
null
null
UTF-8
C++
false
false
2,795
h
// ChildView.h : interface of the CChildView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_CHILDVIEW_H__5F0D869A_ADC4_413A_A3B5_3D7C7117080B__INCLUDED_) #define AFX_CHILDVIEW_H__5F0D869A_ADC4_413A_A3B5_3D7C7117080B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "XInkTest.h" ///////////////////////////////////////////////////////////////////////////// // CChildView window class CChildView : public CWnd { // Construction public: CChildView(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CChildView) protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: int GetVideoHWAccelerationLevel(); bool SetVideoHWAccelerationLevel(const int level, const bool bForever=false); virtual ~CChildView(); protected: XInk::xCanvas* m_pCanvas; XInk::xPen m_pen; bool m_bDisableHardwareAcceleration; // Generated message map functions protected: //{{AFX_MSG(CChildView) afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnEditUndo(); afx_msg void OnColorBlack(); afx_msg void OnColorGreen(); afx_msg void OnColorBlue(); afx_msg void OnColorRed(); afx_msg void OnColorWhite(); afx_msg void OnWidth01(); afx_msg void OnWidth02(); afx_msg void OnWidth03(); afx_msg void OnWidth05(); afx_msg void OnWidth07(); afx_msg void OnWidth09(); afx_msg void OnWidth20(); afx_msg void OnWidth30(); afx_msg void OnDtoolChpen(); afx_msg void OnDtoolEraser(); afx_msg void OnDtoolHlighter(); afx_msg void OnDtoolPen(); afx_msg void OnDtoolEraserAll(); afx_msg void OnViewRefresh(); afx_msg void OnDtoolEraserRect(); afx_msg void OnDtoolShapeLine(); afx_msg void OnDtoolShapeLineArrow(); afx_msg void OnDtoolShapeRect(); afx_msg void OnDtoolShapeEllipse(); afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnDtoolHlighterEl(); afx_msg void OnRecordStart(); afx_msg void OnRecordStop(); afx_msg void OnWidth15(); afx_msg void OnUpdateAppHaccel(CCmdUI* pCmdUI); afx_msg void OnAppHaccel(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_CHILDVIEW_H__5F0D869A_ADC4_413A_A3B5_3D7C7117080B__INCLUDED_)
[ [ [ 1, 96 ] ] ]
5a18d91c5185deee60538ed459323b873ea915a5
c505530b90c827e446fb3355a299bf58c65da353
/component_tree.cpp
e41538d3c3cb000aa5d19f438ca646eafd03c0dc
[]
no_license
marvis/finetuning
04fe92c8c28db68a47abd963644f0ce968424a02
7c89616e30bc7eed775fd26cf3751a99037df2ae
refs/heads/master
2021-01-13T01:15:40.316790
2011-05-20T18:11:40
2011-05-20T18:11:40
1,772,802
0
0
null
null
null
null
UTF-8
C++
false
false
39,413
cpp
// //======================================================================= // Copyright 2011 Institute PICB. // Authors: Hang Xiao // Data : March 20, 2011 //======================================================================= // #include <iostream> #include <fstream> #include <string> #include <assert.h> #include <map> #include <deque> #include <stack> #include <cmath> #include "component_tree.h" #include "myalgorithms.h" #include <cstdio> #include <cstdlib> #include <cstring> #ifndef INT_MAX #define INT_MAX 2147483647 #endif using namespace std; bool component_tree_verbose = false; /****************************************************************** * ComponentTree::Pixel *****************************************************************/ ComponentTree::Pixel::Pixel() { } bool ComponentTree::Pixel::save(ofstream& ofs, bool saveType) const { if(saveType == 0) // binary format { writeValue(ofs, pos); writeValue(ofs, next->pos); writeValue(ofs, level); writeValue(ofs, node->label); } else // txt format { ofs<<pos<<" "; ofs<<next->pos<<" "; ofs<<level<<" "; ofs<<node->label<<" "; ofs<<endl; } if(ofs.good()) return true; else return false; } bool ComponentTree::Pixel::load(ifstream& ifs, vector<Pixel>& pixels,vector<Node*>& nodes, bool saveType) { if(saveType == 0) // binary format { readValue(ifs, pos); int next_pos; readValue(ifs, next_pos); next=&pixels[next_pos]; readValue(ifs, level); int node_label; readValue(ifs, node_label); node = nodes[node_label]; } else // txt format { ifs>>pos; int next_pos; ifs>>next_pos; next=&pixels[next_pos]; ifs>>level; int node_label; ifs>>node_label; node = nodes[node_label]; } if(ifs.good()) return true; else return false; } void ComponentTree::Pixel::merge_entry(ComponentTree::Pixel *entry) { Pixel* temp = this->next; this->next = entry->next; entry->next = temp; } ComponentTree::Node* ComponentTree::Pixel::getNode() const { return node; } /****************************************************************** * ComponentTree::Node ****************************************************************/ bool ComponentTree::Node::save(ofstream& ofs, bool saveType) const { if(saveType == 0) // binary format { writeValue(ofs, label); writeValue(ofs, lowest_level); writeValue(ofs, highest_alpha_level); writeValue(ofs, alpha_size); writeValue(ofs, beta_size); writeValue(ofs, parent->label); writeValue(ofs, entry_pixel->pos); if(childs.empty()) { int child_size = 0; writeValue(ofs,child_size); } else { int child_size = childs.size(); writeValue(ofs, child_size); vector<Node*>::const_iterator it = childs.begin(); while(it != childs.end()) { writeValue(ofs, (*it)->label); it++; } } } else // txt format { ofs<<label<<" "; ofs<<lowest_level<<" "; ofs<<highest_alpha_level<<" "; ofs<<alpha_size<<" "; ofs<<beta_size<<" "; ofs<<parent->label<<" "; // not necessary when load ofs<<entry_pixel->pos<<" "; if(childs.empty()) { ofs<<(int)0<<" "; } else { ofs<<childs.size()<<" "; vector<Node*>::const_iterator it = childs.begin(); while(it != childs.end()) { ofs<<(*it)->label<<" "; it++; } } ofs<<endl; } if(ofs.good()) return true; else return false; } bool ComponentTree::Node::load(ifstream& ifs, vector<ComponentTree::Pixel>& pixels, vector<ComponentTree::Node*>& nodes, bool saveType) { if(saveType == 0) // binary format { readValue(ifs, label); readValue(ifs, lowest_level); readValue(ifs, highest_alpha_level); readValue(ifs, alpha_size); readValue(ifs, beta_size); int par_label; readValue(ifs, par_label); assert(par_label >= label); parent = nodes[par_label]; int pixel_pos; readValue(ifs, pixel_pos); entry_pixel = &pixels[pixel_pos]; int child_size; readValue(ifs, child_size); for(int i = 0; i < child_size; i++) { int child_label; readValue(ifs, child_label); assert(child_label < label); childs.push_back(nodes[child_label]); } } else // read from txt files { ifs>>label; ifs>>lowest_level; ifs>>highest_alpha_level; ifs>>alpha_size; ifs>>beta_size; int par_label; ifs>>par_label; assert(par_label >= label); parent = nodes[par_label]; int pixel_pos; ifs>>pixel_pos; entry_pixel = &pixels[pixel_pos]; int child_size; ifs>>child_size; for(int i=0; i < child_size; i++) { int child_label; ifs>>child_label; assert(child_label < label); childs.push_back(nodes[child_label]); } } if(ifs.good()) return true; else return false; } vector<ComponentTree::Pixel*> ComponentTree::Node::getAlphaPixels() { vector<Pixel*> pixels; Pixel* start = this->entry_pixel; pixels.push_back(start); Pixel* p = this->entry_pixel->next; while(p!=start) { pixels.push_back(p); p = p->next; } return pixels; } vector<ComponentTree::Pixel*> ComponentTree::Node::getBetaPixels() { vector<Pixel*> pixels; // = getAlphaPixels(); vector<Node*> post_order = this->getPostOrderNodes(); vector<Node*>::iterator itr = post_order.begin(); while(itr != post_order.end()) { vector<Pixel*> temp_pixels = (*itr)->getAlphaPixels(); pixels.insert(pixels.end(),temp_pixels.begin(), temp_pixels.end()); itr++; } return pixels; } vector<int> ComponentTree::Node::getAlphaPoints() { vector<int> points; Pixel* start = this->entry_pixel; points.push_back(start->pos); Pixel* p = this->entry_pixel->next; while(p!=start) { points.push_back(p->pos); p = p->next; } return points; } vector<int> ComponentTree::Node::getBetaPoints() { vector<Pixel*> pixels = getBetaPixels(); vector<int> points; vector<Pixel*>::iterator itr = pixels.begin(); while(itr != pixels.end()) { points.push_back((*itr)->pos); itr++; } return points; } void ComponentTree::Node::getCenter(float & cx, float & cy, float & cz, int width, int height, int depth) { vector<int> vertices = getBetaPoints(); cx = 0.0; cy = 0.0; cz = 0.0; vector<int>::iterator it = vertices.begin(); while(it != vertices.end()) { int index = *it; int w = index % width; int h = index / width % height; int d = index / width / height % depth; cx += w; cy += h; cz += d; it++; } cx = cx / vertices.size(); cy = cy / vertices.size(); cz = cz / vertices.size(); } vector<int> ComponentTree::Node::getCenterPoints(int width, int height, int depth) { vector<int> vertices = getBetaPoints(); int minX = INT_MAX; int minY = INT_MAX; int minZ = INT_MAX; int maxX = 0; int maxY = 0; int maxZ = 0; float a = 0.0; float b = 0.0; float c = 0.0; float cx = 0.0; float cy = 0.0; float cz = 0.0; vector<int>::iterator it = vertices.begin(); while(it != vertices.end()) { int index = *it; int w = index % width; int h = index / width % height; int d = index / width / height % depth; minX = w < minX ? w : minX; minY = h < minY ? h : minY; minZ = d < minZ ? d : minZ; maxX = w > maxX ? w : maxX; maxY = h > maxY ? h : maxY; maxZ = d > maxZ ? d : maxZ; cx += w; cy += h; cz += d; it++; } a = (maxX - minX)/3.0; b = (maxY - minY)/3.0; c = (maxZ - minZ)/3.0; cx = cx / vertices.size(); cy = cy / vertices.size(); cz = cz / vertices.size(); vector<int> centers; it = vertices.begin(); float aa = a * a; float bb = b * b; float cc = c * c; while(it != vertices.end()) { int index = *it; int w = index % width; int h = index / width % height; int d = index /width / height % depth; if((w - cx)*(w - cx)/aa + (h - cy)*(h - cy)/bb + (d - cz)*(d - cz)/cc <= 1.0 ) { centers.push_back(index); } it++; } return centers; } void ComponentTree::Node::merge_node(ComponentTree::Node *node) { this->entry_pixel->merge_entry(node->entry_pixel); this->alpha_size += node->alpha_size; this->highest_alpha_level = node->highest_alpha_level > this->highest_alpha_level ? node->highest_alpha_level: this->highest_alpha_level; if(node->parent != this) // 'node' is not child, it maybe adjacent node || small node || large node { this->beta_size += node->beta_size; } else if(node->childs.size() == 1) { vector<Node*>::iterator it=this->childs.begin(); while(it != this->childs.end()) { if(*it == node) { this->childs.erase(it); break; } it++; } } else cerr<<"merge_node error!"<<endl; vector<Node*>::iterator itr = node->childs.begin(); while(itr != node->childs.end()) { this->childs.push_back(*itr); (*itr)->parent = this; itr++; } delete node; } ComponentTree::Nodes ComponentTree::Node::getPostOrderNodes() const { vector<Node*> postOrder; stack<const Node*> post_stack; stack<bool> status_stack; post_stack.push(this); status_stack.push(false); while(! post_stack.empty()) { Node* top =(Node*) post_stack.top(); bool& top_status = status_stack.top(); if(top_status || top->childs.empty()) { post_stack.pop(); status_stack.pop(); postOrder.push_back(top); } else { top_status = true; vector<Node*>::reverse_iterator it = top->childs.rbegin(); while(it != top->childs.rend()) { post_stack.push(*it); status_stack.push(false); it++; } } } return postOrder; } ComponentTree::Nodes ComponentTree::Node::getPreOrderNodes() const { vector<Node*> preOrder; stack<const Node*> pre_stack; pre_stack.push(this); while(! pre_stack.empty()) { Node* top =(Node*) pre_stack.top(); pre_stack.pop(); preOrder.push_back(top); vector<Node*>::reverse_iterator it = top->childs.rbegin(); while(it != top->childs.rend()) { pre_stack.push(*it); it++; } } return preOrder; } ComponentTree::Nodes ComponentTree::Node::getBreadthFirstNodes() const { vector<Node*> breadthFirst; deque<const Node*> breadth_queue; Node* front; breadth_queue.push_back(this); while(!breadth_queue.empty()) { front = (Node*)breadth_queue.front(); breadth_queue.pop_front(); breadthFirst.push_back(front); vector<Node*>::iterator it = front->childs.begin(); while(it != front->childs.end()) { breadth_queue.push_back(*it); it++; } } return breadthFirst; } vector<ComponentTree::Node*>& ComponentTree::Node::getChilds() { return childs; } int ComponentTree::Node::getTreeHeight() const { if(this == this->parent) return 0; else { int height = 1; Node* node = this->parent; while(node != node->parent) { height++; node = node->parent; } return height; } } int ComponentTree::Node::getLabel() const { return this->label; } int ComponentTree::Node::getLowestLevel() const { return this->lowest_level; } int ComponentTree::Node::getHighestAlphaLevel() const { return this->highest_alpha_level; } int ComponentTree::Node::getHighestLevel() const { return -1; } int ComponentTree::Node::getAlphaSize() const { return this->alpha_size; } int ComponentTree::Node::getBetaSize() const { return this->beta_size; } ComponentTree::Node* ComponentTree::Node::getParent() const { return this->parent; } /****************************************************************** * ComponentTree : construct component tree * 1. create : create the tree * 2. postProcess : * a. set a label to each node by post search order * b. store the node address according to the label * c. get the leaf nodes * 3. setPaths : set pathlist from leaf nodes *****************************************************************/ ComponentTree::ComponentTree() { m_root = NULL; m_numPixels = 0; m_numNodes = 0; m_numLeafs = 0; } ComponentTree::ComponentTree(char * imgfile, int _minSize, int _maxSize, int _singleSize) { create(imgfile,_minSize,_maxSize,_singleSize); } /******************************************************************** * ComponentTree : construct component tree by saved component tree file * load : m_numPixels, m_numNods, m_numLeafs, m_pixels, m_nodes, m_leafs * m_root * m_width, m_height, m_depth ********************************************************************/ ComponentTree::ComponentTree(char* treefile) { m_root = NULL; m_numPixels = 0; m_numNodes = 0; m_numLeafs = 0; load(treefile); } /******************************************************************* *~ComponentTree : destruct component tree. * 1. delete all the node * 2. clear 4 containers * 3. re initial variable *******************************************************************/ ComponentTree::~ComponentTree() { clear(); } /************************************************************************************ * create : create component tree * * create will set these * member variables : m_root, m_numPixels, m_pixels * global variables : m_width, m_height, m_depth ************************************************************************************/ bool ComponentTree::create(char * imgfile , int _minSize , int _maxSize, int _singleSize) { /* * 1. get _width, _height, _depth, _channel, img */ int _width = 0; int _height = 0; int _depth = 0; int _channels = 1; unsigned char * img = NULL; img = readtiff(imgfile, &_width,&_height, &_depth, &_channels); if((long)_width * (long)_height * (long)_depth >= 2147483648) { cerr<<"image size too large "<<_width<<"*"<<_height<<"*"<<_depth<<" >= 2147483648"<<endl; return false; } //check parameters assert(_width * _height * _depth <= 2147483647); //don't use m_numPixels < 2147483648 (2^31) assert(_minSize >= 0); assert(_maxSize >= 0); if(_maxSize < _minSize) { cerr<<"_max("<<_maxSize<<" < _min("<<_minSize<<")"<<endl; return false; } if(_channels > 1) { cerr<<"_channels > 1 , convert to grayscale ... "<<endl; int _size = _width * _height *_depth; unsigned char* _img = new unsigned char[_size]; for(int i = 0; i < _size; i++) { float average = 0.0; int index = i * _channels; for(int j = 0; j < _channels; j++) { average += img[index+j]; } _img[i] = (int)(average/_channels); } delete img; img = _img; } m_width = _width; m_height = _height; m_depth = _depth; m_minSize = _minSize; m_maxSize = _maxSize; m_singleSize = _singleSize; /* * 2. initial member variable */ m_numPixels = _width * _height * _depth; m_pixels.resize(m_numPixels); for(int i = 0; i < m_numPixels; i++) { m_pixels[i].pos = i; m_pixels[i].level = img[i]; m_pixels[i].next = &m_pixels[i]; m_pixels[i].node = NULL; } DisjointSets djs(m_numPixels); vector<Node*> lowestNode; lowestNode.resize(m_numPixels); for(int v = 0; v < m_numPixels ; v++) lowestNode[v] = NULL; /* * 3. sort img to get the visiting order */ vector<int> order = bucketSort(img,m_numPixels); vector<int>::iterator it; int curId; Node* curNode; int adjId; Node* adjNode; for(it = order.begin(); it!=order.end(); it++) { Vertex v = *it; curId = djs.FindSet(v); curNode = lowestNode[curId]; /// Debug cout<<"v = "<<v<<" curId = "<<curId<<" -> "; // The following if/else will make sure curNode is not NULL if(curNode == NULL) // curPoint is unvisited, create a new node { curNode = new Node; //curNode->pixelNum = 1; curNode->alpha_size = 1; curNode->beta_size = 1; curNode->parent = curNode; curNode->entry_pixel = &m_pixels[v]; //m_pixels[v].parent = curNode; // we should keep the entry's node curNode->lowest_level = img[v]; curNode->highest_alpha_level = img[v]; lowestNode[curId] = curNode; /// Debug cout<<"create node : "<<curNode<<endl; } else // curPoint is visited, we can get the node which contains it { /// Debug cout<<"find set : "<<curNode<<endl; } vector<Vertex> neighbors = neighbor(v, _width, _height, _depth); vector<Vertex>::iterator itr; for(itr = neighbors.begin(); itr != neighbors.end(); itr++) { Vertex u = *itr; if(img[u] >= img[v]) { adjId = djs.FindSet(u); //todo: link curId and adjId and refresh lowestNode adjNode = lowestNode[adjId]; /// Debug cout<<"\tu = "<<u<<" adjId = "<<adjId<<" -> "; //if NULL, add pixel // just put it in the entry's link, other member doesn't change if(adjNode == NULL) // "adjId unsivisited" => "img[u] <= img[v]" => "img[u] == img[v]" { //Pixel& entry = m_pixels[curNode->entry_pixel]; //m_pixels[u].next = entry.next; //entry.next = u; curNode->entry_pixel->merge_entry(&m_pixels[u]); curNode->alpha_size++; curNode->beta_size++; //curNode->pixelNum++; } else if(curNode == adjNode) { // nothing happened here, maybe the adj point is visited earlier } //if different component, v is a connector between currentNode and adjNode else if(curNode != adjNode) { /// Debug cout<<" adjNode = "<<adjNode<<" -> "; //If the same level //add adjacent point to current component //merge their childNode and delete adjNode if(curNode->lowest_level == adjNode->lowest_level) { curNode->merge_node(adjNode); } else //in different level, adj intensity "img[u]" > "img[v]" cur intensity { //Three filter : MIN FILTER, MAX FILTER, SINGLE FILTER //1. Because the beta_size of adjNode is already fixed, we can filter it // if the size of adjNode is too small or too large, merge it to current Node if((_minSize > 0 && adjNode->beta_size < _minSize) || (_maxSize>=_minSize && adjNode->beta_size > _maxSize)) { /// Debug cout<<"filter by min/max, merge different level->"; curNode->merge_node(adjNode); } else// if(adjNode->beta_size >= _minSize && adjNode->beta_size <= _maxSize) { //2. filter the single node /// Debug cout<<" add child ->"; curNode->childs.push_back(adjNode); adjNode->parent = curNode; curNode->beta_size = curNode->beta_size + adjNode->beta_size; if(adjNode->childs.size() == 1) { /// Debug cout<<" merge single child ->"; //Node* childNode = adjNode->childs.front(); /* * if _singleSize = 1 means is_cut_single = false * if _singleSize > maxSize of every single node than is_cut_single = true */ // The alpha_size if fixed, so we can check it here if(adjNode->alpha_size < _singleSize) { // add the (alpha) points of childNode to (alpha) points of curNode, instead of childNod of adjNode curNode->merge_node(adjNode); } } } } } /// Debug cout<<"union("<<curId<<","<<adjId<<") = "; curId = djs.Union(curId,adjId); /// Debug cout<<curId<<endl; lowestNode[curId] = curNode; } } } /* * 4. get m_root */ m_root = lowestNode[djs.FindSet(0)]; /* * 5. build the tree completely by post process */ //m_nodes, m_leafs,m_numLeafs,m_numNodes m_nodes = m_root->getPostOrderNodes(); m_numNodes = m_nodes.size(); for(int i = 0; i < m_numNodes; i++) { Node* node = m_nodes[i]; node->label = i; if(node->childs.empty()) m_leafs.push_back(node); vector<Pixel*> pixels = node->getAlphaPixels(); vector<Pixel*>::iterator it = pixels.begin(); while(it != pixels.end()) { (*it)->node = node; it++; } } m_numLeafs = m_leafs.size(); /* * 6. set mean and paths */ //setStatistic(img); //setCenter(); //setPaths(); /* * 7. free space */ delete img; return true; } /************************************************************************** * save : save these variables to file * member variable: m_numPixels, m_numNodes, m_pixels, m_nodes * global variable: m_width, m_height, m_depth **************************************************************************/ bool ComponentTree::save(const char* treefile) const { assert(m_numPixels > 0); assert(m_numNodes > 0); ofstream ofs; bool saveType = false; string str_file(treefile); if(str_file.find(".bin") != string::npos) { cout<<"save to binary file : "<<treefile<<endl; saveType = false; ofs.open(treefile, ios_base::out|ios_base::binary); } else if(str_file.find(".txt") != string::npos) { cout<<"save to txt file : "<<treefile<<endl; saveType = true; ofs.open(treefile); } else { } if(ofs.fail()) { ofs.close(); return false; } bool rt = save(ofs, saveType); ofs.close(); return rt; } bool ComponentTree::save(ofstream& ofs, bool saveType) const { //cout<<"save type = "<<saveType<<endl; assert(m_numPixels > 0); assert(m_numNodes > 0); if(saveType == 0) // binary format save { writeValue(ofs, m_width); writeValue(ofs, m_height); writeValue(ofs, m_depth); writeValue(ofs, m_minSize); writeValue(ofs, m_maxSize); writeValue(ofs, m_singleSize); writeValue(ofs, m_numPixels); writeValue(ofs, m_numNodes); writeValue(ofs, m_numLeafs); vector<Pixel>::const_iterator it = m_pixels.begin(); while(it != m_pixels.end()) { (*it).save(ofs, saveType); it++; } vector<Node*>::const_iterator itr = m_nodes.begin(); while(itr != m_nodes.end()) { (*itr)->save(ofs,saveType); itr++; } itr = m_leafs.begin(); while(itr != m_leafs.end()) { writeValue(ofs, (*itr)->label); itr++; } writeValue(ofs, m_root->label); } else //txt format { ofs<<m_width<<" "; ofs<<m_height<<" "; ofs<<m_depth<<" "; ofs<<endl; ofs<<m_minSize<<" "; ofs<<m_maxSize<<" "; ofs<<m_singleSize<<" "; ofs<<endl; ofs<<m_numPixels<<" "; ofs<<m_numNodes<<" "; ofs<<m_numLeafs<<" "; ofs<<endl; vector<Pixel>::const_iterator it = m_pixels.begin(); while(it != m_pixels.end()) { (*it).save(ofs, saveType); it++; } vector<Node*>::const_iterator itr = m_nodes.begin(); while(itr != m_nodes.end()) { (*itr)->save(ofs,saveType); itr++; } itr = m_leafs.begin(); while(itr != m_leafs.end()) { ofs<<(*itr)->label<<" "; itr++; } ofs<<endl; ofs<<m_root->label<<endl; } if(ofs.good()) return true; else return false; } /********************************************************************************* * load : load the file to set many * member variable : m_numPixel, m_numNodes, m_root, m_pixels, m_nodes * global variables : m_width, m_height, m_depth * * the same role as create(), but load will do one more thing, set * m_leafs and m_numLeafs **********************************************************************************/ bool ComponentTree::reload(const char* treefile) { this->clear(); return this->load(treefile); } bool ComponentTree::load(const char* treefile) { assert(this->m_numNodes == 0 && this->m_numPixels == 0); if(this->m_numNodes != 0 || this->m_numPixels != 0) { cerr<<"Load error: Please clear the data first"<<endl; return false; } ifstream ifs; bool saveType = false; string str_file(treefile); if(str_file.find(".bin") != string::npos) { cout<<"load binary tree file: "<<treefile<<endl; saveType = false; ifs.open(treefile, ios_base::in|ios_base::binary); } else if(str_file.find(".txt") != string::npos) { cout<<"load txt tree file: "<<treefile<<endl; saveType = true; ifs.open(treefile); } else { } if(ifs.fail()) { ifs.close(); return false; } bool rt = load(ifs, saveType); ifs.close(); return rt; } bool ComponentTree::load(ifstream& ifs, bool saveType) { if(saveType == 0) { readValue(ifs, m_width); readValue(ifs, m_height); readValue(ifs, m_depth); readValue(ifs, m_minSize); readValue(ifs, m_maxSize); readValue(ifs, m_singleSize); readValue(ifs, m_numPixels); readValue(ifs, m_numNodes); readValue(ifs, m_numLeafs); m_pixels.resize(m_numPixels); m_nodes.resize(m_numNodes); for(int i = 0; i < m_numNodes; i++) m_nodes[i] = new Node; m_leafs.resize(m_numLeafs); for(int i = 0; i < m_numPixels; i++) { m_pixels[i].load(ifs, m_pixels,m_nodes,saveType); } for(int i = 0; i < m_numNodes; i++) { m_nodes[i]->load(ifs, m_pixels,m_nodes,saveType); } for(int i = 0; i < m_numLeafs; i++) { int leaf_label; readValue(ifs, leaf_label); m_leafs[i] = m_nodes[leaf_label]; } int root_label; readValue(ifs, root_label); m_root = m_nodes[root_label]; } else { ifs>>m_width; ifs>>m_height; ifs>>m_depth; ifs>>m_minSize; ifs>>m_maxSize; ifs>>m_singleSize; ifs>>m_numPixels; ifs>>m_numNodes; ifs>>m_numLeafs; m_pixels.resize(m_numPixels); m_nodes.resize(m_numNodes); for(int i = 0; i < m_numNodes; i++) m_nodes[i] = new Node; m_leafs.resize(m_numLeafs); for(int i = 0; i < m_numPixels; i++) { m_pixels[i].load(ifs, m_pixels,m_nodes,saveType); } for(int i = 0; i < m_numNodes; i++) { m_nodes[i]->load(ifs, m_pixels,m_nodes,saveType); } for(int i = 0; i < m_numLeafs; i++) { int leaf_label; ifs>>leaf_label; m_leafs[i] = m_nodes[leaf_label]; } int root_label; ifs>>root_label; m_root = m_nodes[root_label]; } if(ifs.good()) return true; else return false; } bool ComponentTree::saveGraph(char* graph_file) { ofstream ofs(graph_file); if(ofs.fail()) { cerr<<"unable to open"<<graph_file<<endl; return false; } ofs<<"graph G{"<<endl; vector<Node*> nodes = m_root->getBreadthFirstNodes(); vector<Node*>::iterator it = nodes.begin(); while(it != nodes.end()) { Node* node = *it; vector<Node*> child_nodes = node->getChilds(); vector<Node*>::iterator itr = child_nodes.begin(); while(itr != child_nodes.end()) { Node* child_node = *itr; ofs<<node->getLabel()<<" -- "<<child_node->getLabel()<<";"<<endl; itr++; } it++; } ofs<<"}"<<endl; ofs.close(); return true; } void ComponentTree::clear() { for(int i= 0; i< m_numNodes; i++) { Node* node = m_nodes[i]; delete node; } m_pixels.clear(); m_nodes.clear(); m_leafs.clear(); m_numLeafs = 0; m_numPixels = 0; m_numNodes = 0; m_root = NULL; } int ComponentTree::width() const { return m_width; } int ComponentTree::height() const { return m_height; } int ComponentTree::depth() const { return m_depth; } int ComponentTree::getMinThresh() const { return this->m_minSize; } int ComponentTree::getMaxThresh() const { return this->m_maxSize; } int ComponentTree::getSingleThresh() const { return this->m_singleSize; } ComponentTree::Node* ComponentTree::root() const { return m_root; } ComponentTree::Node* ComponentTree::getNode(int label) const { assert(label >= 0); assert(label < (int)m_nodes.size()); return m_nodes[label]; } ComponentTree::Node* ComponentTree::getNode(vector<int> points) const { assert(!points.empty()); vector<int>::iterator it = points.begin(); Node* root_node = NULL; // find root_node while(it != points.end()) { Node* node = m_pixels[*it].getNode(); if(root_node == NULL) { root_node = node; } else { if(root_node->getBetaSize() < node->getBetaSize()) { root_node = node; } if(root_node->getBetaSize() == points.size()) { break; } } it++; } // check root_node it = points.begin(); while(it != points.end()) { Node* p = m_pixels[*it].getNode(); while(p != root_node && p != p->getParent()) p = p->getParent(); if(p != root_node) return NULL; it++; } return root_node; } ComponentTree::Pixel* ComponentTree::getPixel(int pos) { return &m_pixels[pos]; } ComponentTree::Paths ComponentTree::getPaths() const { vector<vector<int> > paths; Nodes::const_iterator it = m_leafs.begin(); while(it!= m_leafs.end()) { vector<int> path; Node* p = *it; while(p != p->parent) { path.push_back(p->label); p = p->parent; } // p == p->parent path.push_back(p->label); paths.push_back(path); it++; } return paths; } /***************************************** * setStatistic : set the Mean and std of each component * * This work should be down after the post store of each node *****************************************/ //void ComponentTree::setStatistic(unsigned char* img) //{ //} /******************************************** * setCenter : set the center of each node ********************************************/ //void ComponentTree::setCenter() //{ //} int ComponentTree::nodeNum() const { return m_numNodes; } int ComponentTree::pixelNum() const { return m_numPixels; } int ComponentTree::leafNum() const { return m_numLeafs; } /***************************************************************** * printTree : print component Node recursively *****************************************************************/ void ComponentTree::printTree(ComponentTree::Node* node) const { if(node == NULL) { node = m_root; assert(node != NULL); } cout<<"---------------Component Tree-------------------------"<<endl; cout<<"width = "<<m_width<<"\theight = "<<m_height<<"\tdepth = "<<m_depth<<endl; cout<<"minSize = "<<m_minSize<<"\tmaxSize = "<<m_maxSize<<"\tsingleSize = "<<m_singleSize<<endl; cout<<"total node : "<<m_numNodes<<"\tleaf node : "<<m_numLeafs<<endl; cout<<endl; cout<<"pre order : "; vector<Node*> pre_nodes = node->getPreOrderNodes(); vector<Node*>::iterator it = pre_nodes.begin(); while(it != pre_nodes.end()) { cout<<(*it)->label<<" "; it++; } cout<<endl<<endl; cout<<"post order : "; vector<Node*> post_nodes = this->root()->getPostOrderNodes(); it = post_nodes.begin(); while(it != post_nodes.end()) { cout<<(*it)->label<<" "; it++; } cout<<endl<<endl; cout<<"breadth first : "; vector<Node*> breadth_nodes = this->root()->getBreadthFirstNodes(); it = breadth_nodes.begin(); while(it != breadth_nodes.end()) { cout<<(*it)->label<<" "; it++; } cout<<endl<<endl; cout<<"label : lowest_level alphasize betaSize"<<endl; it = pre_nodes.begin(); cout.precision(3); while(it != pre_nodes.end()) { if((*it) != node) { int space_count = 3 * ((*it)->getTreeHeight()-1); for(int i=0; i < space_count; i++) { cout<<" "; } cout<<"|"<<endl; for(int i=0; i < space_count; i++) { cout<<" "; } cout<<"|__"; } cout<<(*it)->label<<" : "<<(*it)->lowest_level<<" "<<(*it)->alpha_size<<" "<<(*it)->beta_size; if((*it)->childs.empty()) { cout<<" leaf"; } cout<<endl; it++; } cout<<endl; cout<<"------------------------------------------------------------"<<endl; } /**************************************************************************** * printReverseAlphaMapping : print each point's label * * used function : label(vertex) ****************************************************************************/ vector<int> ComponentTree::getReverseAlphaMapping() const { vector<int> matrix(m_numPixels); for(int i = 0; i < m_numPixels; i++) { matrix[i] = m_pixels[i].node->label; } return matrix; } /******************************************************************** * getMatrix : get the vertices with label in labels * intput : labels , values, initial value * output : a int* matrix, the vertice will be assign with * the pixel of values ********************************************************************/ /*int* ComponentTree::getMatrix(vector<int> labels, vector<int> values ,int ini) const { int* matrix = new int[m_numPixels]; //memset(matrix,0,m_numPixels); for(int i = 0; i< m_numPixels ;i++) { matrix[i] = ini; } int label= -1 ; int value = -1; for(int i = 0; i < (int)labels.size(); i++) { label = labels[i]; //the label will start from 0 value = values[i]; Node* node = m_nodes[label]; vector<int> points = node->getBetaPoints(); vector<int>::iterator it = points.begin(); while(it != points.end()) { matrix[*it] = value; it++; } } return matrix; } */ void ComponentTree::setWeightMatrix(ComponentTree* tree2, vector<float> &weights) { int rows = this->m_numNodes; int cols = tree2->m_numNodes; weights.resize(rows*cols); for(int i=0; i < rows*cols; i++) weights[i]=0.0; vector<int> matrix1 = this->getReverseAlphaMapping(); vector<int> matrix2 = tree2->getReverseAlphaMapping(); int pixel_num = this->m_numPixels; for(int i = 0; i < pixel_num; i++) { int label1 = matrix1[i]; int label2 = matrix2[i]; weights[label1 * cols + label2] = weights[label1 * cols + label2] + 1.0; } /* for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cout<<weights[i*cols + j]<<" "; } cout<<endl; } */ for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { ComponentTree::Node* node2 = tree2->getNode(j); if(! node2->childs.empty()) { vector<Node*>::iterator it = node2->childs.begin(); while( it != node2->childs.end()) { int jj = (*it)->label; weights[i*cols + j] += weights[i*cols + jj]; it++; } } } } for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { ComponentTree::Node* node1 = this->getNode(i); if(! node1->childs.empty()) { vector<Node*>::iterator it = node1->childs.begin(); while( it != node1->childs.end()) { int ii = (*it)->label; weights[i*cols + j] += weights[ii*cols + j]; it++; } } } } for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { float intersection = weights[i* cols + j]; float joint = this->getNode(i)->beta_size + tree2->getNode(j)->beta_size - intersection; //if(intersection >= joint) cout<<"intersection "<<intersection<<" joint "<<joint<<endl; assert(intersection <= joint); weights[i*cols + j] = intersection/joint; } } } void ComponentTree::printReverseAlphaMapping() const { vector<int> matrix = getReverseAlphaMapping(); cout<<"------------------------ All Labels -----------------------------------"<<endl; int i = 0; int w = (int)(log10((float)m_numNodes)) + 1; char format[10]; if(w == 1) { sprintf(format,"%sd ","%"); } else { sprintf(format,"%s%d%dd ","%",0,w); } while(i < m_numPixels) { char out[10]; sprintf(out,format,matrix[i]); cout<<out; if(i%(m_width * m_height) == 0 && i/(m_width * m_height) > 0) cout<<"layer "<<i/(m_width * m_height)+1<<": "<<endl; if((i+1)%m_width == 0)cout<<endl; i++; } cout<<endl; cout<<"width = "<<m_width<<"\t height = "<<m_height<<"\t depth = "<<m_depth<<endl<<endl; cout<<"label count : "<<m_numNodes<<endl; cout<<"----------------------------------------------------------------------"<<endl; } /************************************************************* * printPaths : print paths *************************************************************/ void ComponentTree::printPaths() const { cout<<"---------------------- All Paths -----------------------"<<endl; Paths paths = this->getPaths(); Paths::const_iterator it; int i = 1; for(it = paths.begin(); it != paths.end(); it++) { cout<<"Path "<<i++<<" -> "; Path::const_iterator itr; for(itr = (*it).begin(); itr != (*it).end(); itr++) { cout<<(*itr)<<" "; } cout<<endl; } //cout<<"path count :"<<m_numLeafs<<endl; cout<<"--------------------------------------------------------"<<endl; } DisjointSets::DisjointSets() { m_numPixels = 0; m_numSets = 0; } DisjointSets::DisjointSets(int count) { m_numPixels = 0; m_numSets = 0; AddPixels(count); } DisjointSets::DisjointSets(const DisjointSets & s) { this->m_numPixels = s.m_numPixels; this->m_numSets = s.m_numSets; // Copy nodes m_nodes.resize(m_numPixels); for(int i = 0; i < m_numPixels; ++i) m_nodes[i] = new Node(*s.m_nodes[i]); // Update parent pointers to point to newly created nodes rather than the old ones for(int i = 0; i < m_numPixels; ++i) if(m_nodes[i]->parent != NULL) m_nodes[i]->parent = m_nodes[s.m_nodes[i]->parent->index]; } DisjointSets::~DisjointSets() { for(int i = 0; i < m_numPixels; ++i) delete m_nodes[i]; m_nodes.clear(); m_numPixels = 0; m_numSets = 0; } // Note: some internal data is modified for optimization even though this method is consant. int DisjointSets::FindSet(int pixelId) const { assert(pixelId < m_numPixels); Node* curNode; // Find the root pixel that represents the set which `pixelId` belongs to curNode = m_nodes[pixelId]; while(curNode->parent != NULL) curNode = curNode->parent; Node* root = curNode; // Walk to the root, updating the parents of `pixelId`. Make those pixels the direct // children of `root`. This optimizes the tree for future FindSet invokations. curNode = m_nodes[pixelId]; while(curNode != root) { Node* next = curNode->parent; curNode->parent = root; curNode = next; } return root->index; } int DisjointSets::Union(int setId1, int setId2) { assert(setId1 < m_numPixels); assert(setId2 < m_numPixels); if(setId1 == setId2) return FindSet(setId1); // already unioned Node* set1 = m_nodes[setId1]; Node* set2 = m_nodes[setId2]; // Determine which node representing a set has a higher rank. The node with the higher rank is // likely to have a bigger subtree so in order to better balance the tree representing the // union, the node with the higher rank is made the parent of the one with the lower rank and // not the other way around. if(set1->rank > set2->rank) { set2->parent = set1; } else if(set1->rank < set2->rank) { set1->parent = set2; } else // set1->rank == set2->rank { set2->parent = set1; ++set1->rank; // update rank } // Since two sets have fused into one, there is now one less set so update the set count. --m_numSets; return FindSet(setId1); } void DisjointSets::AddPixels(int numToAdd) { assert(numToAdd >= 0); // insert and initialize the specified number of pixel nodes to the end of the `m_nodes` array m_nodes.insert(m_nodes.end(), numToAdd, (Node*)NULL); for(int i = m_numPixels; i < m_numPixels + numToAdd; ++i) { m_nodes[i] = new Node(); m_nodes[i]->parent = NULL; m_nodes[i]->index = i; m_nodes[i]->rank = 0; } // update pixel and set counts m_numPixels += numToAdd; m_numSets += numToAdd; } int DisjointSets::NumPixels() const { return m_numPixels; } int DisjointSets::NumSets() const { return m_numSets; }
[ [ [ 1, 1614 ] ] ]
fb2c22cd0415bedcaf2e20f1228e99c22b4c96a0
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SESystem/SESystem.h
a48769d53cb2834e659bcf286c6864da1f1d13d1
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
8,473
h
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #ifndef Swing_System_H #define Swing_System_H // C++标准库 #include <cassert> #include <cctype> #include <cfloat> #include <cmath> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iostream> #include <fstream> // STL 常用数据结构 #include <algorithm> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> #include "SEFoundationLIB.h" #include "SEPlatforms.h" #include "SEAssert.h" #include "SEMemory.h" namespace Swing { //---------------------------------------------------------------------------- // 说明: // Author:Sun Che // Date:20080202 //---------------------------------------------------------------------------- class SE_FOUNDATION_API SESystem { public: // 交换一个C内置类型数据的字节内存排放位置(iSize = 2,4,8) static void SE_SwapBytes(int iSize, void* pValue); // 交换一组C内置类型数据的字节内存排放位置(iSize = 2,4,8) static void SE_SwapBytes(int iSize, int iCount, void* pValue); // 统一输出数据为little endian形式 static bool SE_IsBigEndian(void); static void SE_EndianCopy(int iSize, const void* pSrc, void* pDst); static void SE_EndianCopy(int iSize, int iCount, const void* pSrc, void* pDst); // 返回单位为秒 static double SE_GetTime(void); // 支持文件的load,save static bool SE_Load(const char* pFileName, char*& rDstBuffer, int& riSize); static bool SE_Save(const char* pFileName, const char* pSrcBuffer, int iSize); static bool SE_Append(const char* pFileName, const char* pSrcBuffer, int iSize); // buffer读写,文件读写,单字节数据流,endianness无关 static int SE_Read1(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Write1(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Read1(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Write1(FILE* pDstFile, int iCount, const void* pSrcData); // buffer读写,文件读写,2,4,8字节数据流,源数据为little endian static int SE_Read2le(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Read4le(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Read8le(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Write2le(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Write4le(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Write8le(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Read2le(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Read4le(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Read8le(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Write2le(FILE* pDstFile, int iCount, const void* pSrcData); static int SE_Write4le(FILE* pDstFile, int iCount, const void* pSrcData); static int SE_Write8le(FILE* pDstFile, int iCount, const void* pSrcData); // buffer读写,文件读写,2,4,8字节数据流,源数据为big endian static int SE_Read2be(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Read4be(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Read8be(const char* pSrcBuffer, int iCount, void* pDstData); static int SE_Write2be(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Write4be(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Write8be(char* pDstBuffer, int iCount, const void* pSrcData); static int SE_Read2be(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Read4be(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Read8be(FILE* pSrcFile, int iCount, void* pDstData); static int SE_Write2be(FILE* pDstFile, int iCount, const void* pSrcData); static int SE_Write4be(FILE* pDstFile, int iCount, const void* pSrcData); static int SE_Write8be(FILE* pDstFile, int iCount, const void* pSrcData); // Macintosh平台需要此函数是由于其复杂的应用程序结构, // 特别的,此函数用于Xcode项目并且忽略目录项,但假设应用程序所需 // 的数据文件在项目的资源文件夹下, // 其他的平台连接目录名与文件名,结果值储存在类静态全局内存中(多线程时需 // 注意). static const char* SE_GetPath(const char* pDirectory, const char* pFileName); // 维护一个目录列表,供应用程序查询,列表初始为空, // 由应用程序插入若干期望目录,目录名不能用目录分隔符结尾(比如"/"), // SE_InsertDirectory和SE_RemoveDirectory将会自动管理该字符 static void SE_Initialize(void); static void SE_Terminate(void); static int SE_GetDirectoryCount(void); static const char* SE_GetDirectory(int i); static bool SE_InsertDirectory(const char* pDirectory); static bool SE_RemoveDirectory(const char* pDirectory); static void SE_RemoveAllDirectories(void); // SE_GetPath搜索目录列表,如果指定文件名存在,则返回其完整路径名称,否则返回 // null,eMode以下是枚举值. enum { SM_READ, SM_WRITE, SM_READ_WRITE }; static const char* SE_GetPath(const char* pFileName, int eMode); // 创建一个颜色值,隐藏endian细节 static unsigned int SE_MakeRGB(unsigned char ucR, unsigned char ucG, unsigned char ucB); static unsigned int SE_MakeRGBA(unsigned char ucR, unsigned char ucG, unsigned char ucB, unsigned char ucA); // 封装标准I/O函数从而解决buffer读写溢出等问题,提高安全性能, // 目前MSVC8.0实现的方式好于早先的标准I/O库 static FILE* SE_Fopen(const char* pFileName, const char* pMode); static int SE_Fprintf(FILE* pFile, const char* pFormat, ...); static int SE_Fclose(FILE* pFile); static const char* SE_GetEnv(const char* pEnvVarName); static void* SE_Memcpy(void* pDst, size_t uiDstSize, const void* pSrc, size_t uiSrcSize); static int SE_Sprintf(char* pDst, size_t uiDstSize, const char* pFormat, ...); static char* SE_Strcpy(char* pDst, size_t uiDstSize, const char* pSrc); static char* SE_Strcat(char* pDst, size_t uiDstSize, const char* pSrc); static char* SE_Strncpy(char* pDst, size_t uiDstSize, const char* pSrc, size_t uiSrcSize); static char* SE_Strtok(char* pToken, const char* pDelimiters, char*& rpNextToken); private: enum { SYSTEM_MAX_PATH = 1024, SYSTEM_MAX_ENVVAR = 1024 }; static char Path[SYSTEM_MAX_PATH]; static char EnvVar[SYSTEM_MAX_ENVVAR]; static std::vector<std::string>* Directories; // 系统维护的目录列表 public: static char SE_PATH[SYSTEM_MAX_ENVVAR]; }; // 2D数组的分配与释放,释放时数组指针被设为null template <class T> void Allocate(int iCols, int iRows, T**& raatArray); template <class T> static void Deallocate(T**& raatArray); // 3D数组的分配与释放,释放时数组指针被设为null template <class T> void Allocate(int iCols, int iRows, int iSlices, T***& raaatArray); template <class T> void Deallocate(T***& raaatArray); #include "SESystem.inl" } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 195 ] ] ]
10fe788a6a64f89e54418548cf684974d0339398
37426b6752e2a3f0a254f76168f55fed549594da
/unit_test++/src/tests/TestTest.cpp
d6c2aac72f36ce718c904d515726102288038ff2
[ "MIT" ]
permissive
Over-Zero/amf3lib
09c3db95b3b60bcdd78791e282a9803fc6e2cfee
527c3e1c66b5fb858a859c4bc631733e23c91132
refs/heads/master
2021-01-22T03:01:28.063344
2011-11-08T15:42:04
2011-11-08T15:42:04
2,732,494
0
1
null
null
null
null
UTF-8
C++
false
false
2,640
cpp
#include "../UnitTest++.h" #include "../TestReporter.h" #include "../TimeHelpers.h" #include "ScopedCurrentTest.h" using namespace UnitTest; namespace { TEST(PassingTestHasNoFailures) { class PassingTest : public Test { public: PassingTest() : Test(UNITTEST_TEXT("passing")) {} virtual void RunImpl() const { CHECK(true); } }; TestResults results; { ScopedCurrentTest scopedResults(results); PassingTest().Run(); } CHECK_EQUAL(0, results.GetFailureCount()); } TEST(FailingTestHasFailures) { class FailingTest : public Test { public: FailingTest() : Test(UNITTEST_TEXT("failing")) {} virtual void RunImpl() const { CHECK(false); } }; TestResults results; { ScopedCurrentTest scopedResults(results); FailingTest().Run(); } CHECK_EQUAL(1, results.GetFailureCount()); } TEST(ThrowingTestsAreReportedAsFailures) { class CrashingTest : public Test { public: CrashingTest() : Test(UNITTEST_TEXT("throwing")) {} virtual void RunImpl() const { throw "Blah"; } }; TestResults results; { ScopedCurrentTest scopedResult(results); CrashingTest().Run(); } CHECK_EQUAL(1, results.GetFailureCount()); } #ifndef UNITTEST_MINGW TEST(CrashingTestsAreReportedAsFailures) { class CrashingTest : public Test { public: CrashingTest() : Test(UNITTEST_TEXT("crashing")) {} virtual void RunImpl() const { reinterpret_cast< void (*)() >(0)(); } }; TestResults results; { ScopedCurrentTest scopedResult(results); CrashingTest().Run(); } CHECK_EQUAL(1, results.GetFailureCount()); } #endif TEST(TestWithUnspecifiedSuiteGetsDefaultSuite) { Test test(UNITTEST_TEXT("test")); CHECK(test.m_details.suiteName != NULL); CHECK_EQUAL(UNITTEST_TEXT("DefaultSuite"), test.m_details.suiteName); } TEST(TestReflectsSpecifiedSuiteName) { Test test(UNITTEST_TEXT("test"), UNITTEST_TEXT("testSuite")); CHECK(test.m_details.suiteName != NULL); CHECK_EQUAL(UNITTEST_TEXT("testSuite"), test.m_details.suiteName); } void Fail() { CHECK(false); } TEST(OutOfCoreCHECKMacrosCanFailTests) { TestResults results; { ScopedCurrentTest scopedResult(results); Fail(); } CHECK_EQUAL(1, results.GetFailureCount()); } }
[ [ [ 1, 129 ] ] ]
b439f54718c4db8e01d2988d72bc945c938bb298
b7fe6d0c96eea2d5eaf84920d228e4e20b6b0d38
/timer.h
847b3ecc9a86f41a49c6aa5d6fa6db9d760d044d
[]
no_license
nickik/stratego
76b922c7d68f5c0c64572caf55d56ffd02d17d5e
a04c45846a3453d74eee513269eb32c32eb51b60
refs/heads/master
2021-01-01T15:15:44.993878
2010-04-27T14:16:55
2010-04-27T14:16:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
441
h
#ifndef TIMER_H_INCLUDED #define TIMER_H_INCLUDED #include "SDL/SDL.h" #include <sstream> class timer{ public: timer(); void start(); void stop(); void pause(); void unpause(); int ticks_getter(); bool is_started(); bool is_paused(); private: int start_ticks; int paused_ticks; bool paused; bool started; }; #endif // TIMER_H_INCLUDED
[ [ [ 1, 25 ] ] ]
866ee2fa92c64c584034452928b917d60b4baa43
be7eef50e21e11340134d150f78db8d6f5423e66
/D4/D4.cpp
acace28350cf6f6be1e7c01d914ebd4b03025b06
[]
no_license
Maciej-Poleski/Algorytmika
8023aef976c1087e25a4f9079de65769cf690ae3
3a3818f82738d9ea42aba24dea89e9280d504f00
refs/heads/master
2023-07-06T03:57:54.430947
2011-05-26T15:57:11
2011-05-26T15:57:11
395,015,968
0
0
null
null
null
null
UTF-8
C++
false
false
2,998
cpp
#ifdef full_debug #define debug #endif #define _GNU_SOURCE #undef _FORTFIY_SOURCE #include <cstdio> #include <cstring> #include <algorithm> using namespace std; char a[30005]; char b[30005]; int *LCSP; int *LCSS; int n; int m; int LCS(const int PA,const int KA,const int PB,const int KB) { #ifdef debug printf("\t%d %d %d %d:\n",PA,KA,PB,KB); #endif if(KB-PB==1) { for(int i=PA;i<KA;++i) if(a[i]==b[PB]) { printf("%c",b[PB]); return 1; } return 0; } int l=KA-PA; // Długość części prefixu słowa a if(l==0) // Nie zajmuje się słowem którego nie ma. return 0; LCSP=new int[l]; // Tablica O(n) dla prefixów LCSS=new int[l]; // Dla sufiksów int x,q; // Dodatkowy element /* PREFIXY */ LCSP[0]=(a[PA]==b[PB])?1:0; for(int i=1;i<l;++i) // Wypełniam LCS prefixów pierwszy rząd LCSP[i]=max(LCSP[i-1],(a[PA+i]==b[PB])?1:0); #ifdef full_debug printf("int:"); for(int i=0;i<l;++i) printf(" %d",LCSP[i]); puts(""); #endif for(int i=PB+1;i<(PB+KB)/2;++i) // Wyznaczam LCS prefixów (rozwiązanie w LCSP[l-1]) { x=LCSP[0]; LCSP[0]=max(LCSP[0],(b[i]==a[PA])?1:0); for(int j=1;j<l;++j) { q=LCSP[j]; LCSP[j]=(b[i]==a[j+PA])?1+x:max(LCSP[j],LCSP[j-1]); x=q; } } /* SUFIXY */ LCSS[l-1]=(a[KA-1]==b[KB-1])?1:0; for(int i=l-2;i>=0;--i) // Wypełniam LCS sufiksów pierwszy rząd LCSS[i]=max(LCSS[i+1],a[PA+i]==b[KB-1]?1:0); for(int i=KB-2;i>=(PB+KB)/2;--i) // Wyznaczam LCS sufixów (rozwiązanie w LCSS[l-1]) { x=LCSS[l-1]; LCSS[l-1]=max(LCSS[l-1],(b[i]==a[KA-1])?1:0); for(int j=l-2;j>=0;--j) { q=LCSS[j]; LCSS[j]=(b[i]==a[PA+j])?1+x:max(LCSS[j],LCSS[j+1]); x=q; } } #ifdef debug for(int i=0;i<l;++i) printf("%d ",LCSP[i]); puts(""); for(int i=0;i<l;++i) printf("%d ",LCSS[i]); puts(""); #endif x=-1; q=LCSS[0]; for(int i=0;i<l-1;++i) { if(LCSP[i]+LCSS[i+1]>q) { x=i; q=LCSP[i]+LCSS[i+1]; } } if(LCSP[l-1]>q) { q=LCSP[l-1]; x=l-1; } #ifdef debug int t1=(x>=0)?LCSP[x]:0; int t2=(x+1<l)?LCSS[x+1]:0; #endif delete [] LCSP; delete [] LCSS; #ifdef debug if(int e=LCS(PA,PA+x+1,PB,(PB+KB)/2)!=t1) printf("|To rozwiązanie jest błędne!, oczekiwano %d a otrzymano %d|",t1,e); if(int e=LCS(PA+x+1,KA,(PB+KB)/2,KB)!=t2) printf("|To rozwiązanie jest błędne!, oczekiwano %d a otrzymano %d|",t2,e); #endif return q; } int main() { int z; scanf("%d\n",&z); while(z--) { scanf("%s %s\n",a,b); // Słowa a i b n=strlen(a); // Długości m=strlen(b); if(LCS(0,n,0,m)==0) printf("-"); printf("\n"); } return 0; }
[ [ [ 1, 149 ] ] ]
0cbec522927b1e749a582541f569b9cbeea97644
44db48cc516623a52391749be8d2211427391969
/gingacc-mmi/include/Utility.h
fba40bba6998d6916e148bb3812542c85142bb35
[]
no_license
wincax88/ginga-multimodal
d787052bc4b96006dfe63436b55ec0b2c882249c
4448fdb3043f7b8c0b8c6a6d6cf3f8179b8ecdf1
refs/heads/master
2021-01-17T21:03:58.222493
2011-10-17T13:55:03
2011-10-17T13:55:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,151
h
/************************************************************************* * Copyright (c) 2008 Hewlett-Packard Development Company, L.P. * 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. **************************************************************************/ /************************************************************************ * SVN MACROS * * $Revision: 261 $ * $Author: mnab $ * $LastChangedDate: 2008-07-07 17:30:50 +0530 (Mon, 07 Jul 2008) $ ************************************************************************************/ /************************************************************************ * FILE DESCR: utility.h - This class contains miscellaneous utility methods * and enumeration, constant data members * AUTHOR: Birendra * DATE: 24th July 2007 * Author Date Description of change * Muthu 17-June-08 Added comment statements * Balaji M N A18-June-08 1. Moved Drawline and DrawBezier methods into * Renderer class. * 2. Global functions move to GlobalFunction class ************************************************************************/ /****************************************************************************** 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] [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br http://www.icmc.usp.br/php/laboratorio.php?origem=icmc&id_lab=3&nat=icmc ****************************************************************************** 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] [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /******************************************************************************* As seguintes modificações foram feitas em cima do código original: - Acréscimo dos namespaces. - Acréscimo de comentários *******************************************************************************/ #ifndef UTILITY_H #define UTILITY_H #include <string.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include <vector> namespace br{ namespace ufscar{ namespace lince{ namespace ginga{ namespace core{ namespace mmi{ namespace inkmllib{ using namespace std; #define SUCCESS true /** * Desc - structure to define the BoundingBox of the trace data * and hence helps in normalizing trace co-ordinate data * to fit in the rendering area co-ordinate. **/ typedef struct structBoundingBox{ /// Limite inferior horizontal long minX; /// Limite superior vertical long minY; /// Limite superior horizontal long maxX; /// Limite inferior vertical long maxY; }BoundingBox; /** * Desc - Error constants **/ enum InkMLError{NoError, NoInkRoot, MalFormedXml/*, TinyXmlError*/}; #define E_NOINKROOT 1 #define E_XMLPARSE 2 /** * Classe que possui métodos úteis para a realização do parser de um InkML. * Mais informações em http://sourceforge.net/apps/trac/inkmltk/wiki/InkMLLib */ class GlobalFunction { public: // static char* tinyXmlError; static char* checkAndRemoveHash(char *str); static char* removeVelocity(char *str); static char* decodeError(InkMLError errorNo); static char* toLower(char *s); }; } } } } } } } #endif // UTILITY_H
[ [ [ 1, 166 ] ] ]
b00d0e63f680b0d67ce92f0ae42f5d6b1e44f6b7
71db16f07e91c3d49691f99c3edbfcba6a604189
/FahProxy/Uploader.cpp
fc6612703a8c1dac32e64d1be6277d6f516ec430
[]
no_license
jaboles/fahproxy
503832879d9c1081e69b642d8cfe32fd0334a3b2
131b97ddf86220e4ba52878ba22d06f97003a023
refs/heads/master
2022-12-07T13:26:03.522052
2008-08-26T11:29:01
2008-08-26T11:29:01
290,090,861
0
0
null
null
null
null
UTF-8
C++
false
false
4,959
cpp
#include "Uploader.h" #include "WorkUnit.h" #include "Utils.h" #include "UploadManager.h" using namespace FahProxy; using namespace System; using namespace System::IO; using namespace System::Net; using namespace System::Net::Sockets; using namespace System::Threading; Uploader::Uploader(int index) { m_index = index; m_buffer = gcnew array<unsigned char, 1>(BUFFER_SIZE); } Uploader::~Uploader() { } void Uploader::DoUpload(UploadQueueEntry^ qe) { m_currentUpload = qe; m_bytesUploaded = 0; m_isactive = true; ThreadStart^ ts = gcnew ThreadStart(this, &Uploader::UploadThreadEntry); (gcnew Thread(ts))->Start(); } void Uploader::UploadThreadEntry() { m_currentUpload->SetStatus(UploadQueueEntry::UPLOADING); ProgressChanged(this, System::EventArgs::Empty); Stream^ wuDataStream; try { m_socket = gcnew Socket(AddressFamily::InterNetwork, SocketType::Stream, ProtocolType::Tcp); wuDataStream = m_currentUpload->GetWorkUnit()->GetDataStream(); m_socket->Connect(m_currentUpload->GetWorkUnit()->GetUploadHost(), m_currentUpload->GetWorkUnit()->GetUploadPort()); m_networkStream = gcnew System::Net::Sockets::NetworkStream(m_socket, true); Utils::WriteLineToStream(m_networkStream, "POST / HTTP/1.1"); Utils::WriteLineToStream(m_networkStream, String::Format("Host: {0}:{1}", m_currentUpload->GetWorkUnit()->GetUploadHost(), m_currentUpload->GetWorkUnit()->GetUploadPort())); Utils::WriteLineToStream(m_networkStream, "Connection: Keep-Alive"); Utils::WriteLineToStream(m_networkStream, String::Format("Content-Length: {0}", m_currentUpload->GetWorkUnit()->GetDataSize())); Utils::WriteLineToStream(m_networkStream, ""); m_networkStream->Flush(); for (m_bytesUploaded = 0; m_bytesUploaded < m_currentUpload->GetWorkUnit()->GetDataSize();) { int b = wuDataStream->Read(m_buffer, 0, BUFFER_SIZE); m_bytesUploaded += b; //m_networkStream->WriteByte(15); m_networkStream->Write(m_buffer, 0, b); ProgressChanged(this, System::EventArgs::Empty); } m_networkStream->Flush(); wuDataStream->Close(); array<unsigned char, 1>^ receiptBuffer = gcnew array<unsigned char, 1>(512); int responseContentLength = 0; int httpResponseCode = 0; String^ httpResponseLine; String^ line1; String^ line2; String^ line3; for ( String^ line = Utils::ReadLineFromStream(m_networkStream); line != ""; line = Utils::ReadLineFromStream(m_networkStream) ) { if (line->StartsWith("HTTP/")) { httpResponseCode = Convert::ToInt32(line->Substring(9, 3)); httpResponseLine = line->Substring(9); } // Stanford server doesn't specify content-length in the response. /*if (line->StartsWith("Content-Length:")) { responseContentLength = Convert::ToInt32(line->Substring(16)); }*/ } if (httpResponseCode == 200) { //if (responseContentLength > 0) { line1 = Utils::ReadLineFromStream(m_networkStream); responseContentLength -= (line1->Length + 2); } //if (responseContentLength > 0) { // Read the 512-byte receipt m_networkStream->Read(receiptBuffer, 0, 512); responseContentLength -= 512; } //if (responseContentLength > 0) { line2 = Utils::ReadLineFromStream(m_networkStream); responseContentLength -= (line2->Length + 2); } //if (responseContentLength > 0) { line3 = Utils::ReadLineFromStream(m_networkStream); responseContentLength -= (line3->Length + 2); } m_currentUpload->SetStatus(UploadQueueEntry::UPLOAD_COMPLETED); m_currentUpload->GetWorkUnit()->WriteReceipt(receiptBuffer); m_currentUpload->GetWorkUnit()->WriteSimulatedResponse(); UploadComplete(this, System::EventArgs::Empty); } else { m_currentUpload->SetStatus(UploadQueueEntry::UPLOAD_FAILED); m_currentUpload->SetErrorString(httpResponseLine); UploadFailed(this, System::EventArgs::Empty); } } catch (System::Exception^ ex) { m_currentUpload->SetStatus(UploadQueueEntry::UPLOAD_FAILED); m_currentUpload->SetErrorString(ex->Message); UploadFailed(this, System::EventArgs::Empty); } finally { //ProgressChanged(this, System::EventArgs::Empty); if (wuDataStream) { wuDataStream->Close(); } if (m_networkStream) { m_networkStream->Close(); } if (m_socket) { m_socket->Close(); } m_isactive = false; } } UploadQueueEntry^ Uploader::GetCurrentQueueEntry() { return m_currentUpload; } int Uploader::GetIndex() { return m_index; } double Uploader::GetProgress() { if (m_currentUpload->GetStatus() == UploadQueueEntry::UPLOADING && m_currentUpload->GetWorkUnit()->GetDataSize() > 0) { return ((double)m_bytesUploaded / (double)m_currentUpload->GetWorkUnit()->GetDataSize());; } else { return -1; } } bool Uploader::IsActive() { return m_isactive; }
[ "jb@dc620d95-ca3a-fc45-9de6-42b3e20515ab" ]
[ [ [ 1, 183 ] ] ]
c0a4e262c0fbbe34f2657f1e22e7b0807899362a
ff44f2ae11d39c5a3dcc0c76ea8e0c7d2543787e
/seqlib/Seq/SequenceTools.h
1565400d786bd0cd1b1232af38adf689c3f85f4f
[]
no_license
pjotrp/biopp
0de35b3a8f1c973c61fb394ae57202ba75a7ac63
5214440cff8ff858704377e7dfed57fc026dfcb2
refs/heads/master
2016-09-11T03:42:33.892136
2009-05-22T10:12:04
2009-05-22T10:12:04
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
9,552
h
// // File: SequenceTools.h // Created by: Guillaume Deuchst // Julien Dutheil // Created on: Tue Aug 21 2003 // /* Copyright or © or Copr. CNRS, (November 17, 2004) This software is a computer program whose purpose is to provide classes for sequences analysis. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ #ifndef _SEQUENCETOOLS_H_ #define _SEQUENCETOOLS_H_ #include "Alphabet.h" #include "DNA.h" #include "RNA.h" #include "Sequence.h" #include "SymbolListTools.h" #include "NucleicAcidsReplication.h" // From NumCalc: #include <NumCalc/RandomTools.h> #include <NumCalc/StatTest.h> // From utils: #include <Utils/Exceptions.h> // From the STL: #include <string> #include <map> #include <vector> #include <algorithm> using namespace std; namespace bpp { /** * @brief Bowker's homogeneity test results class. */ class BowkerTest: public StatTest { protected: double _pvalue; double _stat; public: BowkerTest() {} virtual ~BowkerTest() {} #ifndef NO_VIRTUAL_COV BowkerTest* #else Clonable* #endif clone() const { return new BowkerTest(*this); } public: string getName() const { return "Bowker's test for homogeneity."; } double getStatistic() const { return _stat; } double getPValue() const { return _pvalue; } void setStatistic(double stat) { _stat = stat; } void setPValue(double pvalue) { _pvalue = pvalue; } }; /** * @brief SequenceTools static class * * Implement methods to manipulate sequences */ class SequenceTools: public SymbolListTools { private: static DNA _DNA; static RNA _RNA; static NucleicAcidsReplication _DNARep; static NucleicAcidsReplication _RNARep; static NucleicAcidsReplication _transc; public: SequenceTools() {} virtual ~SequenceTools() {} public: /** * @brief Get a sub-sequence. * * @param sequence The sequence to trunc. * @param begin The first position of the subsequence. * @param end The last position of the subsequence. * @return A new sequence object with the given subsequence. * @throw IndexOutOfBoundsException, Exception In case of bad indices. */ static Sequence * subseq(const Sequence & sequence, unsigned int begin, unsigned int end) throw (IndexOutOfBoundsException, Exception) ; /** * @brief Concatenate two sequences. * * Sequences must have the same name and alphabets. * Only first sequence's commentaries are kept. * * @param seq1 The first sequence. * @param seq2 The second sequence. * @return A new sequence object with the concatenation of the two sequences. * @throw AlphabetMismatchException If the two alphabets do not match. * @throw Exception If the sequence names do not match. */ static Sequence * concatenate(const Sequence & seq1, const Sequence & seq2) throw (AlphabetMismatchException, Exception) ; /** * @brief Get the complementary sequence of a nucleotide sequence. * * @see DNAReplication * @return sequence A new sequence object with the complementary sequence. * @param sequence The sequence to complement. * @throw AlphabetException If the sequence is not a nucleotide sequence. */ static Sequence * complement(const Sequence & sequence) throw (AlphabetException); /** * @brief Get the transcription sequence of a DNA sequence. * * @see DNAReplication * @return sequence A new sequence object with the transcription sequence. * @param sequence The sequence to transcript. * @throw AlphabetException If the sequence is not a DNA sequence. */ static Sequence * transcript(const Sequence & sequence) throw (AlphabetException); /** * @brief Get the reverse-transcription sequence of a RNA sequence. * * @see DNAReplication * @return sequence A new sequence object with the reverse-transcription sequence. * @param sequence The sequence to reverse-transcript. * @throw AlphabetException If the sequence is not a RNA sequence. */ static Sequence * reverseTranscript(const Sequence & sequence) throw (AlphabetException); /** * @brief Inverse a sequence from 5'->3' to 3'->5' and vice-versa. * * ABCDEF becomes FEDCBA, and the sense attribute is changed (may be inhibited). * * @return A new sequence object containing the inverted sequence. * @param sequence The sequence to inverse. * @param chgSense Tell if the sense tag should be shifted. */ static Sequence * invert(const Sequence & sequence, bool chgSense = true); /** * @brief Alias for invert (DEPRECATED). * * ABCDEF becomes FEDCBA, and the sense attribute is changed (may be inhibited). * * @return A new sequence object containing the inverted sequence. * @param sequence The sequence to inverse. */ static Sequence * reverse(const Sequence & sequence) { return invert(sequence, true); } /** * @return The identity percent of 2 sequence. * One match is counted if the two sequences have identical states. * @param seq1 The first sequence. * @param seq2 The second sequence. * @throw AlphabetMismatchException If the two sequences do not have the same alphabet. * @throw SequenceNotAlignedException If the two sequences do not have the same length. */ static double getPercentIdentity(const Sequence & seq1, const Sequence & seq2) throw (AlphabetMismatchException, SequenceNotAlignedException); /** * @return The number of sites in the sequences, <i>i.e.</i> all positions without gaps. * * @param seq The sequence to analyse. */ static unsigned int getNumberOfSites(const Sequence & seq); /** * @return The number of complete sites in the sequences, <i>i.e.</i> all positions without gaps and unresolved states (generic characters). * * @param seq The sequence to analyse. */ static unsigned int getNumberOfCompleteSites(const Sequence & seq); /** * @brief Remove gaps from a sequence. * * @param seq The sequence to analyse. * @return A new sequence object without gaps. */ static Sequence * removeGaps(const Sequence & seq); /** * @brief Bowker's test for homogeneity. * * Computes the contingency table of occurrence of all pairs of states and test its symmetry using Bowker's (1948) test. * * Reference:<br> * @code * Ababneh F. Bioinformatics 2006 22(10) 1225-1231 * @endcode * * @param seq1 The first sequence. * @param seq2 The second sequence. * @return A BowkerTest object with the computed statistic and p-value (computed from a chi square distribution). * @throw SequenceNotAlignedException If the two sequences do not have the same length. */ static BowkerTest* bowkerTest(const Sequence & seq1, const Sequence & seq2) throw (SequenceNotAlignedException); /** * @brief Subtract haplotype from an heterozygous sequence. * * Subtract an haplotype (i.e. a fully resolved sequence) from an heterozygous * sequence to get the other haplotype. The new haplotype could be an unresolved * sequence if unresolved characters in the sequence code for more than 2 states. * * For example:<br> * @code * >heterozygous sequence * ATTCGGGKWTATRYRM * >haplotype * ATTCGGGTATATGCAA * >subtracted haplotype * ATTCGGGGTTATATGC * @endcode * * @param s The heterozygous sequence. * @param h The haplotype to subtract. * @param name The name of the new computed haplotype. * @param level The number of states from which the site is set to fully unresolved. * @throw SequenceNotAlignedException if s and h don't have the same size. */ static Sequence * subtractHaplotype(const Sequence & s, const Sequence & h, string name = "", unsigned int level = 1) throw (SequenceNotAlignedException); }; } //end of namespace bpp. #endif // _SEQUENCETOOLS_H_
[ [ [ 1, 277 ] ] ]
4209167707e417bdc813ec6802ae4f0d00777607
538a869b8352e231eaceefdc02ce8ebc7b05718a
/stdafx.cpp
596dcf47332374be628aef4aceb57a9119988677
[]
no_license
EmilHernvall/cropper
14630a7ff34c9da97b1422476f89cc3bf30e3dc3
5461fe69f9226a97a08ef710e9730e9191a62911
refs/heads/master
2020-04-01T13:18:03.629608
2011-05-03T21:09:51
2011-05-03T21:09:51
1,697,512
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
// stdafx.cpp : source file that includes just the standard includes // MDISandbox.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
[ "emil@8ed1686d-faac-4ee6-b542-108cb1ec3b87" ]
[ [ [ 1, 8 ] ] ]
d7d6c5787e1c30b944322aec0585e78927ac3c17
11c7904170760e079f064347e62570ec3e1549fd
/borb/Module.cpp.h
bec88d5f736f07f6535b079bd4d175ce3d3769c0
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
rstarkov/BoostOrbiter
17f68b289f513cf056dc4324ac9c927f271dd849
f9e481f23831edcf9ea799b56fe6768465316703
refs/heads/master
2020-11-29T20:44:32.725856
2011-03-27T21:27:36
2011-03-27T21:27:36
96,652,896
0
0
null
null
null
null
UTF-8
C++
false
false
8,397
h
//---------------------------------------------------------------------------- // This file is part of the BoostOrbiter project, and is subject to the terms // and conditions defined in file 'license.txt'. Full list of contributors is // available in file 'contributors.txt'. //---------------------------------------------------------------------------- // WHAT THIS FILE GIVES YOU: // // - your module methods are invoked regardless of which Orbiter API version you're compiling against // // - smarter callbacks: the loading/saving callbacks have significant amounts of logic to make your life simpler, // in particular making global settings (not specific to a scenario) easy. // // - any C++/SEH exceptions that escape your callbacks will be captured, displayed along with your module's name // (so that the user knows who to blame for the almost-crash), and then stops invoking any further callbacks, effectively // shutting down your module. Of course this still doesn't completely prevent your module from CTDing Orbiter... // // - your module is properly deallocated before shutting down, allowing the use of msvc runtime leak tracking. // // // HOW TO USE THIS FILE: // // - add a "Module.cpp" and a "Module.h" to your module project // // - define your borb::ModuleBase descendant in Module.h, e.g.: // class ReFuelModule : public borb::ModuleBase { ... } // // - insert the following lines at the beginning of your Module.cpp: // #define BORB_MODULE_VARIABLE Module // #define BORB_MODULE_CLASS ReFuelModule // #define BORB_MODULE_NAME "ReFuelMFD" // #include "borb/Module.cpp.h" // std::shared_ptr<ReFuelModule> Module; // // (where "Module" is the name of the shared_ptr variable storing your module instance, "ReFuelModule" is // the name of the subclass you defined, "ReFuelMFD" is the string displayed in Orbiter UI and also used as // the filename for the module's global settings) // // - implement callbacks by adding overrides for the methods you're interested in. See documentation in // borb/Module.h which explains each available override. #include "borb.h" #if !defined(BORB_MODULE_VARIABLE) # error Module variable (BORB_MODULE_VARIABLE) is undefined. Define it before including this file, and ensure it's of type "std::shared_ptr<BORB_MODULE_CLASS>". #endif #if !defined(BORB_MODULE_CLASS) # error Module class (BORB_MODULE_CLASS) is undefined. Define it before including this file. #endif #if !defined(BORB_MODULE_NAME) # error User-friendly module name (BORB_MODULE_NAME) is undefined. Define it before including this file. #endif // The following is never compiled into the final module, but helps make changes to this file with Intellisense operational. #if !defined(BORB_MODULE_CLASS) || !defined(BORB_MODULE_CLASS) || !defined(BORB_MODULE_VARIABLE) class dummyModuleClass : public borb::ModuleBase { }; std::shared_ptr<dummyModuleClass> dummyModule; # define BORB_MODULE_VARIABLE dummyModule # define BORB_MODULE_CLASS dummyModuleClass # define BORB_MODULE_NAME "dummy" #endif using namespace std; void StartLeakMonitor(); void LogLeaks(); std::string getGlobalSettingsFilename() { return std::string("Config/Modules/") + BORB_MODULE_NAME + ".cfg"; } void loadGlobalSettings(); void saveGlobalSettings(); void loadGlobalSettings() { borb::ScenarioNode root; FILEHANDLE file = oapiOpenFile(getGlobalSettingsFilename().c_str(), FILE_IN); if (file != NULL) { root.LoadFrom(file); oapiCloseFile(file, FILE_IN); } BORB_MODULE_VARIABLE->LoadFromGlobal(&root); } void saveGlobalSettings() { std::string filename = getGlobalSettingsFilename(); borb::ScenarioNode root; BORB_MODULE_VARIABLE->SaveToGlobal(&root); if (root.IsEmpty()) { // Ensure the file is deleted if the module doesn't use settings DeleteFile(filename.c_str()); } else { namespace fs = boost::filesystem; try { fs::create_directories(fs::path(filename).parent_path()); } catch (...) { borb::WriteLog(std::string("Not saving global settings for module ") + BORB_MODULE_NAME + " - couldn't create path for file " + filename); } FILEHANDLE file = oapiOpenFile(filename.c_str(), FILE_OUT); if (file != NULL) { root.SaveTo(file); oapiCloseFile(file, FILE_OUT); } } } DLLCLBK void InitModule(HINSTANCE hDLL) { try { StartLeakMonitor(); BORB_MODULE_VARIABLE = make_shared<BORB_MODULE_CLASS>(); // Load & save global settings once whenever Launchpad starts or the module is enabled, to ensure the // file exists and is up-to-date. This allows the user to create/edit this file without starting full simulation. // (of course the file still won't be created if the module doesn't use any global settings) loadGlobalSettings(); saveGlobalSettings(); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void ExitModule(HINSTANCE hDLL) { if (borb::HadUnhandledException()) return; try { BORB_MODULE_VARIABLE.reset(); LogLeaks(); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcOpenRenderViewport(HWND renderWnd, DWORD width, DWORD height, bool fullscreen) { if (borb::HadUnhandledException()) return; try { loadGlobalSettings(); // load on simulation start, so that any changes the user made to the file between sessions are effected BORB_MODULE_VARIABLE->SimulationStart(); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcCloseRenderViewport() { if (borb::HadUnhandledException()) return; try { BORB_MODULE_VARIABLE->SimulationEnd(); saveGlobalSettings(); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcLoadState(FILEHANDLE scn) { if (borb::HadUnhandledException()) return; try { borb::ScenarioNode root; root.LoadFrom(scn); BORB_MODULE_VARIABLE->LoadFromScenario(&root); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcSaveState(FILEHANDLE scn) { if (borb::HadUnhandledException()) return; try { borb::ScenarioNode root; BORB_MODULE_VARIABLE->SaveToScenario(&root); if (!root.IsEmpty()) root.SaveTo(scn); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcPreStep(double simt, double simdt, double mjd) { if (borb::HadUnhandledException()) return; try { BORB_MODULE_VARIABLE->PreStep(simt, simdt, mjd); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcPostStep(double simt, double simdt, double mjd) { if (borb::HadUnhandledException()) return; try { BORB_MODULE_VARIABLE->PostStep(simt, simdt, mjd); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } DLLCLBK void opcDeleteVessel(OBJHANDLE hVessel) { if (borb::HadUnhandledException()) return; try { BORB_MODULE_VARIABLE->DeleteVessel(oapiGetVesselInterface(hVessel)); } catch (exception& ex) { borb::UnhandledException(ex, BORB_MODULE_NAME); } } #ifdef _DEBUG static _CrtMemState state; void StartLeakMonitor() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF); _CrtMemCheckpoint(&state); } void LogLeaks() { OutputDebugString("--- Start Leak Dump ---\n"); // The CRT dumps all leaks too early, so make the true dump visually clearer in the trace _CrtMemDumpAllObjectsSince(&state); } #else void StartLeakMonitor() { } void LogLeaks() { } #endif
[ [ [ 1, 281 ] ] ]
d54dcae84c1529adf5e8c260b66954c926c2ad06
90834e9db9d61688c796d0a30e77dd3acc2a9492
/SauerbratenRemote/src/engine/cubeloader.cpp
c9a3ef525340fa1b867e32c69f921aeb4d6823e5
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib" ]
permissive
zot/Plexus-original
1a79894797ca209af566bb67f72d6164869d7742
f9c3c66c697066e63ea0509c5ff9a8d6b27e369a
refs/heads/master
2020-09-20T21:51:57.194398
2009-04-21T12:45:19
2009-04-21T12:45:19
224,598,317
0
0
null
null
null
null
UTF-8
C++
false
false
12,975
cpp
#include "pch.h" #include "engine.h" VAR(importcuberemip, 0, 1024, 2048); struct cubeloader { enum // block types, order matters! { C_SOLID = 0, // entirely solid cube [only specifies wtex] C_CORNER, // half full corner of a wall C_FHF, // floor heightfield using neighbour vdelta values C_CHF, // idem ceiling C_SPACE, // entirely empty cube C_SEMISOLID, // generated by mipmapping C_MAXTYPE }; struct c_sqr { uchar type; // one of the above char floor, ceil; // height, in cubes uchar wtex, ftex, ctex; // wall/floor/ceil texture ids uchar vdelta; // vertex delta, used for heightfield cubes uchar utex; // upper wall tex id }; struct c_persistent_entity // map entity { short x, y, z; // cube aligned position short attr1; uchar type; // type is one of the above uchar attr2, attr3, attr4; }; struct c_header // map file format header { char head[4]; // "CUBE" int version; // any >8bit quantity is little endian int headersize; // sizeof(header) int sfactor; // in bits int numents; char maptitle[128]; uchar texlists[3][256]; int waterlevel; int reserved[15]; }; c_sqr *world; int ssize; int x0, x1, y0, y1, z0, z1; c_sqr *o[4]; int lastremip; int progress; void create_ent(c_persistent_entity &ce) { if(ce.type>=7) ce.type++; // grenade ammo if(ce.type>=8) ce.type++; // pistol ammo if(ce.type==16) ce.type = ET_MAPMODEL; else if(ce.type>=ET_MAPMODEL && ce.type<16) ce.type++; if(ce.type>=ET_ENVMAP) ce.type++; if(ce.type>=ET_PARTICLES) ce.type++; if(ce.type>=ET_SOUND) ce.type++; if(ce.type>=ET_SPOTLIGHT) ce.type++; extentity &e = *et->newentity(); et->getents().add(&e); e.type = ce.type; e.spawned = false; e.inoctanode = false; e.o = vec(ce.x*4+hdr.worldsize/4, ce.y*4+hdr.worldsize/4, (ce.z+ce.attr3)*4+hdr.worldsize/2); e.light.color = vec(1, 1, 1); e.light.dir = vec(0, 0, 1); e.attr1 = ce.attr1; e.attr2 = ce.attr2; if(e.type == ET_MAPMODEL) e.attr3 = e.attr4 = 0; else { e.attr3 = ce.attr3; e.attr4 = ce.attr4; } e.attr5 = 0; } cube &getcube(int x, int y, int z) { return lookupcube(x*4+hdr.worldsize/4, y*4+hdr.worldsize/4, z*4+hdr.worldsize/2, 4); } int neighbours(c_sqr &t) { o[0] = &t; o[1] = &t+1; o[2] = &t+ssize; o[3] = &t+ssize+1; int best = 0xFFFF; loopi(4) if(o[i]->vdelta<best) best = o[i]->vdelta; return best; } void preprocess_cubes() // pull up heighfields to where they don't cross cube boundaries { for(;;) { bool changed = false; loop(x, ssize) { loop(y, ssize) { c_sqr &t = world[x+y*ssize]; if(t.type==C_FHF || t.type==C_CHF) { int bottom = (neighbours(t)&(~3))+4; loopj(4) if(o[j]->vdelta>bottom) { o[j]->vdelta = bottom; changed = true; } } } } if(!changed) break; } } int getfloorceil(c_sqr &s, int &floor, int &ceil) { floor = s.floor; ceil = s.ceil; int cap = 0; switch(s.type) { case C_SOLID: floor = ceil; break; case C_FHF: floor -= (cap = neighbours(s)&(~3))/4; break; case C_CHF: ceil += (cap = neighbours(s)&(~3))/4; break; } return cap; } void boundingbox() { x0 = y0 = ssize; x1 = y1 = 0; z0 = 128; z1 = -128; loop(x, ssize) loop(y, ssize) { c_sqr &t = world[x+y*ssize]; if(t.type!=C_SOLID) { if(x<x0) x0 = x; if(y<y0) y0 = y; if(x>x1) x1 = x; if(y>y1) y1 = y; int floor, ceil; getfloorceil(t, floor, ceil); if(floor<z0) z0 = floor; if(ceil>z1) z1 = ceil; } } } void hf(int x, int y, int z, int side, int dir, int cap) { cube &c = getcube(x, y, z); loopi(2) loopj(2) edgeset(cubeedge(c, 2, i, j), side, dir*(o[(j<<1)+i]->vdelta-cap)*2+side*8); } bool cornersolid(int z, c_sqr *s) { return s->type==C_SOLID || z<s->floor || z>=s->ceil; } void createcorner(cube &c, int lstart, int lend, int rstart, int rend) { int ledge = edgemake(lstart, lend); int redge = edgemake(rstart, rend); cubeedge(c, 1, 0, 0) = ledge; cubeedge(c, 1, 1, 0) = ledge; cubeedge(c, 1, 0, 1) = redge; cubeedge(c, 1, 1, 1) = redge; } void create_cubes() { preprocess_cubes(); boundingbox(); lastremip = allocnodes; progress = 0; for(int x = x0-1; x<=x1+1; x++) for(int y = y0-1; y<=y1+1; y++) { c_sqr &s = world[x+y*ssize]; int floor, ceil, cap = getfloorceil(s, floor, ceil); for(int z = z0-1; z<=z1+1; z++) { cube &c = getcube(x, y, z); c.texture[O_LEFT] = c.texture[O_RIGHT] = c.texture[O_BACK] = c.texture[O_FRONT] = s.type!=C_SOLID && z<ceil ? s.wtex : s.utex; c.texture[O_BOTTOM] = s.ctex; c.texture[O_TOP] = s.ftex; if(z>=floor && z<ceil) { setfaces(c, F_EMPTY); } else if(s.type==C_CORNER) { c_sqr *ts, *bs, *ls, *rs; bool tc = cornersolid(z, ts = &s-ssize); bool bc = cornersolid(z, bs = &s+ssize); bool lc = cornersolid(z, ls = &s-1); bool rc = cornersolid(z, rs = &s+1); if (tc && lc && !bc && !rc) createcorner(c, 0, 8, 0, 0); // TOP LEFT else if(tc && !lc && !bc && rc) createcorner(c, 0, 0, 0, 8); // TOP RIGHT else if(!tc && lc && bc && !rc) createcorner(c, 0, 8, 8, 8); // BOT LEFT else if(!tc && !lc && bc && rc) createcorner(c, 8, 8, 0, 8); // BOT RIGHT else // fix texture on ground of a corner { if (ts->floor-1==z && bs->floor-1!=z) { c.texture[O_TOP] = ts->ftex; } else if (ts->floor-1!=z && bs->floor-1==z) { c.texture[O_TOP] = bs->ftex; } if (ts->ceil==z && bs->ceil!=z) { c.texture[O_BOTTOM] = ts->ctex; } else if (ts->ceil!=z && bs->ceil==z) { c.texture[O_BOTTOM] = bs->ctex; } } } } switch(s.type) { case C_FHF: hf(x, y, floor-1, 1, -1, cap); break; case C_CHF: hf(x, y, ceil, 0, 1, cap); break; } if(importcuberemip && (allocnodes - lastremip) * 8 > importcuberemip * 1024) { mpremip(true); lastremip = allocnodes; } if((progress++&0x7F)==0) { float bar2 = float((y1-y0+2)*(x-x0+1) + y-y0+1) / float((y1-y0+2)*(x1-x0+2)); s_sprintfd(text2)("%d%%", int(bar2*100)); show_out_of_renderloop_progress(0, "creating cubes...", bar2, text2); } } } void load_cube_world(char *mname) { int loadingstart = SDL_GetTicks(); string pakname, cgzname; s_sprintf(pakname)("cube/%s", mname); s_sprintf(cgzname)("packages/%s.cgz", pakname); gzFile f = opengzfile(path(cgzname), "rb9"); if(!f) { conoutf(CON_ERROR, "could not read cube map %s", cgzname); return; } c_header hdr; gzread(f, &hdr, sizeof(c_header)-sizeof(int)*16); endianswap(&hdr.version, sizeof(int), 4); bool mod = false; if(strncmp(hdr.head, "CUBE", 4)) { if(!strncmp(hdr.head, "ACMP", 4)) mod = true; else { conoutf(CON_ERROR, "map %s has malformatted header", cgzname); gzclose(f); return; } } else if(hdr.version>5) mod = true; if(hdr.version>5 && !mod) { conoutf(CON_ERROR, "map %s requires a newer version of the cube 1 importer", cgzname); gzclose(f); return; } emptymap(12, true); freeocta(worldroot); worldroot = newcubes(F_SOLID); s_sprintfd(cs)("importing %s", cgzname); computescreen(cs); if(hdr.version>=4) { gzread(f, &hdr.waterlevel, sizeof(int)*16); endianswap(&hdr.waterlevel, sizeof(int), 16); } else { hdr.waterlevel = -100000; } if(mod) gzseek(f, hdr.numents*sizeof(c_persistent_entity), SEEK_CUR); else loopi(hdr.numents) { c_persistent_entity e; gzread(f, &e, sizeof(c_persistent_entity)); endianswap(&e, sizeof(short), 4); create_ent(e); } ssize = 1<<hdr.sfactor; world = new c_sqr[ssize*ssize]; c_sqr *t = NULL; loopk(ssize*ssize) { c_sqr *s = &world[k]; int type = gzgetc(f); switch(type) { case 255: { int n = gzgetc(f); for(int i = 0; i<n; i++, k++) memcpy(&world[k], t, sizeof(c_sqr)); k--; break; } case 254: // only in MAPVERSION<=2 { memcpy(s, t, sizeof(c_sqr)); gzgetc(f); gzgetc(f); break; } case C_SOLID: { s->type = C_SOLID; s->wtex = gzgetc(f); s->vdelta = gzgetc(f); if(hdr.version<=2) { gzgetc(f); gzgetc(f); } s->ftex = DEFAULT_FLOOR; s->ctex = DEFAULT_CEIL; s->utex = s->wtex; s->floor = 0; s->ceil = 16; break; } default: { if(type<0 || type>=C_MAXTYPE) { s_sprintfd(t)("%d @ %d", type, k); fatal("while reading map: type out of range: ", t); } s->type = type; s->floor = gzgetc(f); s->ceil = gzgetc(f); if(s->floor>=s->ceil) s->floor = s->ceil-1; // for pre 12_13 s->wtex = gzgetc(f); s->ftex = gzgetc(f); s->ctex = gzgetc(f); if(hdr.version<=2) { gzgetc(f); gzgetc(f); } s->vdelta = gzgetc(f); s->utex = (hdr.version>=2) ? gzgetc(f) : s->wtex; if(hdr.version>=5) gzgetc(f); s->type = type; } } t = s; } gzclose(f); string cfgname; s_sprintf(cfgname)("packages/cube/%s.cfg", mname); exec("packages/cube/package.cfg"); exec(path(cfgname)); create_cubes(); mpremip(true); clearlights(); allchanged(); loopv(et->getents()) if(et->getents()[i]->type!=ET_LIGHT) dropenttofloor(et->getents()[i]); entitiesinoctanodes(); conoutf("read cube map %s (%.1f seconds)", cgzname, (SDL_GetTicks()-loadingstart)/1000.0f); startmap(pakname); } }; void importcube(char *name) { if(multiplayer()) return; cubeloader().load_cube_world(name); } COMMAND(importcube, "s");
[ "bill@sheba.(none)" ]
[ [ [ 1, 364 ] ] ]
9c4638a69d68f6c1f394f2bf6692f9ebf79cc80f
886d53dfd22fff2dda2e021d0dc8035723ed60ef
/private/tasks/1051/1.cpp
eb27fea2f01a20b3dbb01afdc593916f069e30d5
[]
no_license
stden/dm-judge
0d3a373349bc7c7b7e1a43cb8c451fbba10fea9b
2dbf7429694441c8447aad09a3d528283d034dfc
refs/heads/master
2021-01-10T03:28:24.820940
2011-01-29T23:02:25
2011-01-29T23:02:25
45,978,812
0
0
null
null
null
null
UTF-8
C++
false
false
1,526
cpp
#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> int min(int x,int y) { if(x<=y) return x; return y; }; typedef char M[10]; class matrix { public: M *matr; int N; matrix(char*); ~matrix(); void floid(); void in_file(char*); }; matrix::matrix(char *name) { FILE *f=fopen(name,"r"); char c[2]; c[1]=0; fscanf(f,"%d",&N); matr=new M[N*N]; for(int i=0;i<N*N;i++) { strcpy(matr[i],""); c[0]=getc(f); while(c[0]==' '||c[0]=='\n') c[0]=getc(f); while(c[0]!='\n'&&c[0]!=' '&&!feof(f)) { strcat(matr[i],c); c[0]=getc(f); }; }; fclose(f); }; matrix::~matrix() { delete [] matr; matr=0; }; void matrix::floid() { int x,y,z; int k1,k2,k3; int t,tt; for(x=0;x<N;x++) { for(y=0;y<N;y++) for(z=0;z<N;z++) { k1=y*N+x; k2=x*N+z; k3=y*N+z; if ( !strcmp(matr[k1],"no") || !strcmp(matr[k2],"no") ); else { t=atoi(matr[k1])+atoi(matr[k2]); if(!strcmp(matr[k3],"no")) { strcpy(matr[k3],""); itoa(t,matr[k3],10); } else { tt=atoi(matr[k3]); strcpy(matr[k3],""); itoa(min(tt,t),matr[k3],10); }; }; }; }; }; void matrix::in_file(char *name) { FILE *f=fopen(name,"w+"); int i,j; for(i=0;i<N;i++) { for(j=0;j<N;j++) { fputs(matr[i*N+j],f); fputs(" ",f); }; fputs("\n",f); }; fclose(f); }; void main() { matrix x("in1.txt"); x.floid(); x.in_file("out1.txt"); };
[ [ [ 1, 102 ] ] ]
9390bada07ed6845ad44aaa7d2b1e9752d3a23e3
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/GodDK/util/AbstractMap.h
a3b3b28cf8d8da26571aa6469c3831e3da84340c
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
8,714
h
#ifndef _ABSTRACT_CLASS_GOD_UTIL_ABSTRACTMAP_H #define _ABSTRACT_CLASS_GOD_UTIL_ABSTRACTMAP_H #ifdef __cplusplus #include "lang/NullPointerException.h" #include "util/Map.h" #include "util/AbstractSet.h" using namespace goddk::util; namespace goddk { namespace util { /*!\ingroup CXX_UTIL_m */ template <class K, class V> class AbstractMap : public virtual Map<K,V> { private: class KeySet : public virtual AbstractSet<K> { private: class Iter : virtual public Iterator<K> { private: Iterator<class Map<K,V>::Entry>* _it; public: Iter(AbstractMap* m) : _it(m->entrySet().iterator()) { } Iter(const AbstractMap* m) : _it(m->entrySet().iterator()) { } virtual ~Iter() { delete _it; } virtual bool hasNext() throw () { return _it->hasNext(); } virtual K* next() throw (NoSuchElementExceptionPtr) { return _it->next()->getKey(); } virtual void remove() { _it->remove(); } }; private: AbstractMap* _m; public: KeySet(AbstractMap* m) : _m(m) { } virtual ~KeySet() {} virtual Iterator<K>* iterator() { return new Iter(_m); } virtual Iterator<K>* iterator() const { return new Iter(_m); } virtual jint size() const throw () { return _m->size(); } }; class Values : public virtual AbstractCollection<V> { private: class Iter : virtual public Iterator<V> { private: Iterator<class Map<K,V>::Entry>* _it; public: Iter(AbstractMap* m) : _it(m->entrySet().iterator()) { } Iter(const AbstractMap* m) : _it(m->entrySet().iterator()) { } virtual ~Iter() { delete _it; } virtual bool hasNext() throw () { return _it->hasNext(); } virtual V* next() throw (NoSuchElementExceptionPtr) { return _it->next()->getValue(); } virtual void remove() { _it->remove(); } }; private: AbstractMap* _m; public: Values(AbstractMap* m) : _m(m) { } virtual ~Values() {} virtual Iterator<V>* iterator() { return new Iter(_m); } virtual Iterator<V>* iterator() const { return new Iter(_m); } virtual jint size() const throw () { return _m->size(); } }; private: mutable Set<K>* _keys; mutable Collection<V>* _values; protected: AbstractMap() { _keys = 0; _values = 0; } public: virtual ~AbstractMap() { clear(); delete _keys; delete _values; } bool instanceof(const char* class_name)const throw() { if(strcmp("AbstractMap", class_name)== 0) return true; else if(strcmp("Map", class_name)== 0) return true; else return __super::instanceof(class_name); } virtual void clear() { entrySet().clear(); } virtual bool containsKey(const K* key) const { bool result = false; jint pos = size(); Iterator<class Map<K,V>::Entry>* it = entrySet().iterator(); assert(it != 0); if (key) { while (--pos >= 0) { class Map<K,V>::Entry* e = it->next(); if (e->getKey->equals(key)) { result = true; break; } } } else { while (--pos >= 0) if (!it->next()) { result = true; break; } } delete it; return result; } virtual bool containsValue(const V* value) const { bool result = false; jint pos = size(); Iterator<class Map<K,V>::Entry>* it = entrySet().iterator(); assert(it != 0); if (value) { while (--pos >= 0) { V* tmp = it->next()->getValue(); if (tmp && tmp->equals(value)) { result = true; break; } } } else { while (--pos >= 0) if (!it->next()) { result = true; break; } } delete it; return false; } virtual Set<class Map<K,V>::Entry>& entrySet() = 0; virtual const Set<class Map<K,V>::Entry>& entrySet() const = 0; virtual bool equals(const ObjectImpl* obj) const throw () { if (this == obj) return true; if (obj) { const Map<K,V>* map = dynamic_cast<const Map<K,V> >(obj); if (map) { if (map->size() != size()) return false; bool result = true; jint pos = size(); Iterator<class Map<K,V>::Entry>* it = entrySet().iterator(); assert(it != 0); while (--pos >= 0) { class Map<K,V>::Entry* e = it.next(); K* k = e->getKey(); V* v = e->getValue(); if (v) { if (!v->equals(map->get(k))) { result = false; break; } } else { if (map->get(k) || !map->containsKey(k)) { result = false; break; } } } delete it; return result; } } return false; } virtual V* get(const Object* key) const { V* result = 0; jint pos = size(); Iterator<class Map<K,V>::Entry>* it = entrySet().iterator(); assert(it != 0); if (key) { while (--pos >= 0) { class Map<K,V>::Entry* e = it->next(); if (key->equals(e->getKey())) { result = e->getValue(); break; } } } else { while (--pos >= 0) { class Map<K,V>::Entry* e = it->next(); if (!e->getKey()) { result = e->getValue(); break; } } } delete it; return result; } virtual jint hashCode() const throw () { jint pos = size(), result = 0; Iterator<class Map<K,V>::Entry>* it = entrySet().iterator(); assert(it != 0); while (--pos >= 0) result += it->next()->hashCode(); delete it; return result; } virtual bool isEmpty() { return entrySet().size() == 0; } virtual Set<K>& keySet() { if (!_keys) _keys = new KeySet(this); return *_keys; } virtual const Set<K>& keySet() const { if (!_keys) _keys = new KeySet(const_cast<AbstractMap*>(this)); return *_keys; } virtual V* put(K* key, V* value) { THROWEXCEPTIONPTR(UnsupportedOperationException) } virtual void putAll(const Map<K,V>& m) { jint pos = m.size(); Iterator<class Map<K,V>::Entry>* mit = m.entrySet().iterator(); assert(mit != 0); while (--pos >= 0) { class Map<K,V>::Entry* e = mit->next(); V* tmp = put(e->getKey(), e->getValue()); collection_rcheck(tmp); } delete mit; } virtual V* remove(const K* key) { V* result = 0; jint pos = size(); Iterator<class Map<K,V>::Entry>* it = entrySet().iterator(); assert(it != 0); if (key) { while (--pos >= 0) { class Map<K,V>::Entry* e = it->next(); if (key->equals(e->getKey())) { result = e->getValue(); break; } } } else { while (--pos >= 0) { class Map<K,V>::Entry* e = it->next(); if (!e->getKey()) { result = e->getValue(); break; } } } if (result) it->remove(); delete it; return result; } virtual jint size() { return entrySet().size(); } virtual string toString() const throw () { Iterator<class Map<K,V>::Entry>& it = entrySet.iterator(); StringBuilder buf("{"); for (jint pos = size(); pos > 0; pos--) { class Map<K,V>::Entry* e = it.next(); K* k = e->getKey(); V* v = e->getValue(); if (k == this) buf.append("(this map)"); else buf.append(k); buf.append("="); if (v == this) buf.append("(this map)"); else buf.append(v); if (pos > 1) buf.append(", "); } buf.append("}"); return buf.toString(); } virtual Collection<V>& values() { if (!_values) _values = new Values(this); return *_values; } virtual const Collection<V>& values() const { if (!_values) _values = new Values(const_cast<AbstractMap*>(this)); return *_values; } }; } } #endif #endif
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 444 ] ] ]
bdc5af37d0cf1c5a787091d6d105da82e03e0553
b90f7dce513fd3d13bab0b8769960dea901d4f3b
/game_client/game_client/ProtocolFactory.h
4bd5df174f2badb238bfbe0cdf2ab414cb27a784
[]
no_license
lasti15/easygametools
f447052cd4c42609955abd76b4c8571422816b11
0b819c957077a4eeaf9a2492772040dafdfca4c3
refs/heads/master
2021-01-10T09:14:52.182154
2011-03-09T01:51:51
2011-03-09T01:51:51
55,684,684
0
0
null
null
null
null
UTF-8
C++
false
false
2,564
h
#ifndef __PROTOCOLFACTORY_H #define __PROTOCOLFACTORY_H #include "User.h" #include "Protocol.pb.h" #include "ProtoChallenge.pb.h" #include "User.pb.h" namespace ROG { class ProtocolFactory { public: inline const static protocol::ProtocolMessage* getProtoChallengeMessage(const long challengerId) { protocol::ProtocolMessage* message = new protocol::ProtocolMessage(); message->set_messageid(protocol::CHALLENGE); protocol::ProtoChallenge* instance = message->MutableExtension(protocol::ProtoChallenge::challenge); instance->set_challengerid(challengerId); return message; } inline const static protocol::ProtocolMessage* getUserMessage(const long userId, const char* username) { protocol::ProtocolMessage* message = new protocol::ProtocolMessage(); message->set_messageid(protocol::USER); protocol::User* response = message->MutableExtension(protocol::User::user); response->set_userid(userId); response->set_username(username); return message; } inline const static protocol::ProtocolMessage* getProtoChallengeResponseMessage(Object<User> user) { protocol::ProtocolMessage* message = new protocol::ProtocolMessage(); message->set_messageid(protocol::CHALLENGERESPONSE); protocol::ProtoChallengeResponse* response = message->MutableExtension(protocol::ProtoChallengeResponse::challengeResponse); protocol::User* userP = response->mutable_userdetails(); userP->set_userid(user->getUserId()); userP->set_username(user->getUsername()); return message; } inline const static protocol::ProtocolMessage* getProtoChallengeAcceptedMessage(Object<User> host) { protocol::ProtocolMessage* message = new protocol::ProtocolMessage(); message->set_messageid(protocol::CHALLENGEACCEPTED); protocol::ProtoChallengeAccepted* response = message->MutableExtension(protocol::ProtoChallengeAccepted::challengeAccepted); protocol::User* userP = response->mutable_hostdetails(); userP->set_userid(host->getUserId()); userP->set_username(host->getUsername()); return message; } inline const static protocol::ProtocolMessage* getProtoNewHostMessage(long gameid) { protocol::ProtocolMessage* message = new protocol::ProtocolMessage(); message->set_messageid(protocol::NEWHOST); protocol::ProtoNewHost* response = message->MutableExtension(protocol::ProtoNewHost::newHost); response->set_gamesync(gameid); return message; } }; } #endif
[ [ [ 1, 92 ] ] ]
0776f146e9672611621a4176991c133b93904370
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/source/graphics/texture2dbase.cpp
cc048f2281d0d109b187c5332adf6e8cc0a3748d
[]
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
1,627
cpp
#include"texture2dbase.h" namespace Maid { Texture2DBase::Texture2DBase() :m_VirtualSize(0,0) ,m_RealSize(0,0) ,m_TextureSize(0,0) ,m_VirtualFormat(PIXELFORMAT_NONE) ,m_RealFormat(PIXELFORMAT_NONE) { } RECT2DF Texture2DBase::CalcUV( const RECT2DI& rc ) const { const SIZE2DI& image = GetSize(); const SIZE2DI& real = GetRealSize(); const SIZE2DI& texsize=GetTextureSize(); const int x = rc.x * real.w / image.w; const int y = rc.y * real.h / image.h; const int w = rc.w * real.w / image.w; const int h = rc.h * real.h / image.h; const float ux = float(x) / float(texsize.w); const float vy = float(y) / float(texsize.h); const float uw = float(w) / float(texsize.w); const float vh = float(h) / float(texsize.h); return RECT2DF( POINT2DF(ux,vy), SIZE2DF(uw,vh) ); } void Texture2DBase::Clear() { IMaterial::Clear(); ITexture2D::Clear(); m_VirtualSize = SIZE2DI(0,0); m_RealSize = SIZE2DI(0,0); m_TextureSize = SIZE2DI(0,0); m_VirtualFormat = PIXELFORMAT_NONE; m_RealFormat = PIXELFORMAT_NONE; } bool Texture2DBase::IsSetupped() const { return ITexture2D::Get().get()!=NULL && IMaterial::Get().get()!=NULL; } void Texture2DBase::Setup( const Graphics::SPTEXTURE2D& pTex, const Graphics::SPMATERIAL& pMat, const SIZE2DI& Virtual, const SIZE2DI& real, PIXELFORMAT fmt ) { ITexture2D::Set(pTex); IMaterial::Set(pMat); m_VirtualSize = Virtual; m_RealSize = real; m_TextureSize = pTex->GetParam().Size; m_VirtualFormat = fmt; m_RealFormat = pTex->GetParam().Format; } }
[ [ [ 1, 70 ] ] ]
92daffa2b52fb41ff77648c6cc75ce9575a1b2a2
d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189
/tags/pygccxml_dev_1.0.0/unittests/data/attributes.hpp
1a603b9ee460091953a201d12ef67fce9f86406f
[ "BSL-1.0" ]
permissive
gatoatigrado/pyplusplusclone
30af9065fb6ac3dcce527c79ed5151aade6a742f
a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede
refs/heads/master
2016-09-05T23:32:08.595261
2010-05-16T10:53:45
2010-05-16T10:53:45
700,369
4
2
null
null
null
null
UTF-8
C++
false
false
625
hpp
// Copyright 2004-2008 Roman Yakovenko. // 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) #ifndef __atributes_hpp__ #define __atributes_hpp__ #ifdef __GCCXML__ #define _out_ __attribute( (gccxml( "out" ) ) ) #define _sealed_ __attribute( (gccxml( "sealed" ) ) ) #define _no_throw_ __attribute( (gccxml( "no throw" ) ) ) namespace attributes{ _sealed_ struct numeric_t{ _no_throw_ void do_nothing( _out_ int& x ){} }; } #endif//__GCCXML__ #endif//__atributes_hpp__
[ "roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76" ]
[ [ [ 1, 28 ] ] ]
6312bc8555d696253d943378beb72979aea99c55
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/093.cpp
636d4e46cc77df6c317c15a6a5216166f1aea44c
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
717
cpp
///////////////////////////////////////////////////////////////////// // Mapper 93 void NES_mapper93_Init() { g_NESmapper.Reset = NES_mapper93_Reset; g_NESmapper.MemoryWriteSaveRAM = NES_mapper93_MemoryWriteSaveRAM; } void NES_mapper93_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_banks4(0,1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1); // set PPU bank pointers g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } void NES_mapper93_MemoryWriteSaveRAM(uint32 addr, uint8 data) { if(addr == 0x6000) { g_NESmapper.set_CPU_bank4(data*2+0); g_NESmapper.set_CPU_bank5(data*2+1); } } /////////////////////////////////////////////////////////////////////
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 28 ] ] ]
e0eea51b1ba28ab9fef4d39e9aa16e0a6ba1c951
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/coords/v3d.h
499722b49e9c3570073de911af5dff7fc0340f0a
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,050
h
#ifndef VECTOR_3_D_MAR_23_2005 #define VECTOR_3_D_MAR_23_2005 #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #include <math.h> #define NULL_VECTOR_D v3d(0.0,0.0,0.0) inline void normalize_3(double* v){ double mag = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); v[0] /= mag; v[1] /= mag; v[2] /= mag; } class v3d{ public: double x,y,z; v3d():x(0),y(0),z(0){}; v3d(double v):x(v),y(v),z(v){}; v3d(double X, double Y, double Z):x(X),y(Y),z(Z){}; v3d(double* d):x(d[0]),y(d[1]),z(d[2]){}; inline v3d operator+(const v3d b) const{ return v3d(x+b.x,y+b.y,z+b.z); }; inline v3d operator*(const v3d b) const{ return v3d(x*b.x,y*b.y,z*b.z); }; inline v3d operator/(const v3d b) const{ return v3d(x/b.x,y/b.y,z/b.z); }; inline v3d operator-(const v3d b) const{ return v3d(x-b.x,y-b.y,z-b.z); }; inline v3d operator+(const double b) const{ return v3d(x+b,y+b,z+b); }; inline v3d operator*(const double b) const{ return v3d(x*b,y*b,z*b); }; inline v3d operator/(const double b) const{ return v3d(x/b,y/b,z/b); }; inline v3d operator-(const double b) const{ return v3d(x-b,y-b,z-b); }; inline bool operator==(const v3d& b) const{ return (b.x==x && b.y==y && b.z==z);} inline bool operator!=(const v3d& b) const{ return (b.x!=x || b.y!=y || b.z!=z);} inline v3d operator/=(const v3d b){ *this = *this / b; return *this;} inline v3d operator*=(const v3d b){ *this = *this * b; return *this;} inline v3d operator+=(const v3d b){ *this = *this + b; return *this;} inline v3d operator-=(const v3d b){ *this = *this - b; return *this;} inline v3d sq() const{ return operator*(*this);} inline v3d operator - () const { return v3d(-x, -y, -z); } inline double mag() const{return sqrt(x*x+y*y+z*z); } inline bool isZero() const{return (x==0.0 && y==0.0 && z==0.0);}; inline void zero(){x=y=z=0.0;}; inline double operator[](const int i) const { switch (i) { case 0: return x; case 1: return y; default: return z; } } inline double& operator[](const int i){ switch(i){ case 0: return x; case 1: return y; default: return z; } } inline void get(double* v) const {v[0] = x; v[1] = y; v[2] = z;}; inline void set(double* v) {x = v[0]; y = v[1]; z = v[2];}; inline v3d cross(const v3d v) const{ v3d resVector; resVector.x = y*v.z - z*v.y; resVector.y = z*v.x - x*v.z; resVector.z = x*v.y - y*v.x; return resVector; } inline double dot(const v3d a) const{ return x*a.x + y*a.y + z*a.z; } inline v3d norm() const{ v3d res; double l = mag(); if (l == 0.0) return NULL_VECTOR_D; return operator/(l); } inline double sum() const{ return x+y+z;}; inline double dist(const v3d b) const{ return operator-(b).mag(); } inline double dist_sq(const v3d b) const{ return operator-(b).sq().sum(); } }; #endif //VECTOR_3_MAR_08_2005
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 100 ] ] ]
6e452642f43896cf8890750f750f70e47cef713c
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/VideoContainer.cpp
c1a72adfb56074442dfa6b9e245a70a97c09221e
[]
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
4,326
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 "VideoContainer.h" #define PLAYERSTATUS_TIMER 100 CVideoContainer::~CVideoContainer() { } BOOL CVideoContainer::Init(MediaPlayer* pPlayer) { ASSERT(m_hWnd != NULL); ASSERT(pPlayer != NULL); if (pPlayer == NULL || m_hWnd == 0) { ASSERT(0); return FALSE; } HWND hwnd = pPlayer->GetVideoContainerHWND(); if (hwnd == 0) { //=== The player does not have anything attached //=== DECISION: Attach it pPlayer->SetVideoContainerHWND(m_hWnd); pPlayer = pPlayer; SetTimer(PLAYERSTATUS_TIMER, 1000, NULL); } else if (hwnd == m_hWnd) { //=== The player is already attached in this viewer //=== DECISION: Do nothing } else { //=== The player is already attached to a different viewer return FALSE; } m_pMediaPlayer = pPlayer; return TRUE; } BEGIN_MESSAGE_MAP(CVideoContainer, CWnd) ON_WM_SIZE() ON_WM_ERASEBKGND() ON_WM_DESTROY() END_MESSAGE_MAP() void CVideoContainer::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); if (m_pMediaPlayer != NULL && cx != 0 && cy != 0) { TRACEST(_T("CVideoContainer::OnSize")); if (m_pMediaPlayer->GetVideoContainerHWND() != m_hWnd) m_pMediaPlayer->SetVideoContainerHWND(m_hWnd); m_pMediaPlayer->SetVideoPosition(0,0,cx,cy); } } BOOL CVideoContainer::OnEraseBkgnd(CDC* pDC) { if(m_pMediaPlayer != NULL) { if (m_pMediaPlayer->IsVideo()) return TRUE; } CRect rc; GetClientRect(&rc); pDC->FillSolidRect(&rc, RGB(0,0,0)); return TRUE; } LRESULT CVideoContainer::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_LBUTTONDBLCLK) { TRACE(_T("@4 CVideoContainer::WindowProc. WM_LBUTTONDBLCLK\r\n")); SetFullScreen(!m_bFullScreen); } return CWnd::WindowProc(message, wParam, lParam); } void CVideoContainer::SetFullScreen(BOOL bFullScreen) { if (bFullScreen == m_bFullScreen) return; m_bFullScreen = bFullScreen; if (m_bFullScreen) { CRect rc; GetWindowRect(&rc); HMONITOR mon = ::MonitorFromRect(&rc, MONITOR_DEFAULTTONEAREST); MONITORINFO mi; mi.cbSize = sizeof( mi ); ::GetMonitorInfo( mon, &mi ); rc = mi.rcMonitor; GetWindowRect(&m_rcWindow); CPoint p(m_rcWindow.left, m_rcWindow.top); CSize sz(m_rcWindow.Width(), m_rcWindow.Height()); ::ScreenToClient(::GetParent(m_hWnd), &p); m_rcWindow.SetRect(p.x, p.y, p.x + sz.cx, p.y + sz.cy); m_windowStyle = GetWindowLong(m_hWnd, GWL_STYLE); m_windowExStyle = GetWindowLong(m_hWnd, GWL_EXSTYLE); m_windowParent = GetParent(); DWORD newExStyle = m_windowExStyle & (~WS_EX_CLIENTEDGE); ::ShowWindow(m_hWnd, SW_HIDE); SetWindowLong(m_hWnd, GWL_EXSTYLE, newExStyle); SetParent(NULL); ::SetWindowPos(m_hWnd, HWND_TOPMOST, rc.left, rc.top, rc.Width(), rc.Height(), 0); ::UpdateWindow(m_hWnd); ::ShowWindow(m_hWnd, SW_SHOW); } else { SetParent(m_windowParent); SetWindowLong(m_hWnd, GWL_EXSTYLE, m_windowExStyle); SetWindowLong(m_hWnd, GWL_STYLE, m_windowStyle); ::MoveWindow(m_hWnd, m_rcWindow.left, m_rcWindow.top, m_rcWindow.Width(), m_rcWindow.Height(), FALSE); } } void CVideoContainer::OnDestroy() { if (m_pMediaPlayer != NULL) { if (m_pMediaPlayer->GetVideoContainerHWND() == m_hWnd) m_pMediaPlayer->SetVideoContainerHWND(NULL); } CWnd::OnDestroy(); }
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 159 ] ] ]
79180ebc0319539a7105f93858f7160a9d48a911
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/Collide/hkpSimpleConstraintContactMgr.h
1d499abecbc09a63ea0b7551ae83086cdf0972a7
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,206
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_SIMPLE_CONSTRAINT_CONTACT_MGR_H #define HK_DYNAMICS2_SIMPLE_CONSTRAINT_CONTACT_MGR_H #include <Physics/Collide/Dispatch/ContactMgr/hkpContactMgrFactory.h> #include <Physics/Dynamics/Collide/hkpDynamicsContactMgr.h> #include <Physics/Dynamics/Constraint/Contact/hkpSimpleContactConstraintData.h> class hkpWorld; /// This class acts as a bridge between hkCollide and hkDynamics constraint system. /// It collects all contact point information from the collision detector through the hkpContactMgr interface /// and copies this data to an internal hkContactConstraint class hkpSimpleConstraintContactMgr: public hkpDynamicsContactMgr { public: hkpSimpleConstraintContactMgr( hkpWorld* world, hkpRigidBody *bodyA, hkpRigidBody *bodyB ); ~hkpSimpleConstraintContactMgr(); #if !defined(HK_PLATFORM_SPU) inline hkpSimpleConstraintContactMgr( hkFinishLoadedObjectFlag f ) : hkpDynamicsContactMgr( hkpContactMgr::TYPE_SIMPLE_CONSTRAINT_CONTACT_MGR), m_contactConstraintData(f), m_constraint(f) {} #endif /// hkpDynamicsContactMgr interface implementation. hkContactPoint* getContactPoint( hkContactPointId id ); /// hkpDynamicsContactMgr interface implementation. hkpContactPointProperties* getContactPointProperties( hkContactPointId id ); /// hkpContactMgr interface implementation. hkContactPointId addContactPointImpl( const hkpCdBody& a, const hkpCdBody& b, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& output, const hkpGskCache* contactCache, hkContactPoint& cp ); /// hkpContactMgr interface implementation. hkResult reserveContactPointsImpl( int numPoints ); /// hkpContactMgr interface implementation. void removeContactPointImpl( hkContactPointId cpId, hkCollisionConstraintOwner& constraintOwner ); /// hkpContactMgr interface implementation. void processContactImpl( const hkpCollidable& a, const hkpCollidable& b, const hkpProcessCollisionInput& input, hkpProcessCollisionData& collisionData ); /// hkpContactMgr interface implementation. ToiAccept addToiImpl( const hkpCdBody& a, const hkpCdBody& b, const hkpProcessCollisionInput& input, hkpProcessCollisionOutput& output, hkTime toi, hkContactPoint& cp, const hkpGskCache* gskCache, hkReal& projectedVelocity, hkpContactPointProperties& properties ); /// hkpContactMgr interface implementation. void removeToiImpl( class hkCollisionConstraintOwner& constraintOwner, hkpContactPointProperties& properties ); /// hkpContactMgr interface implementation; apply custom toi-collision handling before localized solving HK_NOSPU_VIRTUAL void confirmToi( struct hkpToiEvent& event, hkReal rotateNormal, class hkArray<class hkpEntity*>& outToBeActivated ); HK_NOSPU_VIRTUAL void cleanup(){ delete this; } HK_NOSPU_VIRTUAL Type getType() const { return TYPE_SIMPLE_CONSTRAINT_CONTACT_MGR; } /// Get the ids of all contact points in this collision. HK_NOSPU_VIRTUAL void getAllContactPointIds( hkArray<hkContactPointId>& contactPointIds ) const; HK_FORCE_INLINE hkpSimpleContactConstraintAtom* getAtom() { HK_ASSERT2(0xad76aba3, m_contactConstraintData.m_atom, "Atom not created yet."); return m_contactConstraintData.m_atom; } HK_FORCE_INLINE const hkpSimpleContactConstraintAtom* getAtom() const { HK_ASSERT2(0xad76aba3, m_contactConstraintData.m_atom, "Atom not created yet."); return m_contactConstraintData.m_atom; } /// Get the constraint instance virtual hkpConstraintInstance* getConstraintInstance(); virtual void toiCollisionResponseBeginCallback( const hkContactPoint& cp, struct hkpSimpleConstraintInfoInitInput& inA, struct hkpBodyVelocity& velA, hkpSimpleConstraintInfoInitInput& inB, hkpBodyVelocity& velB); virtual void toiCollisionResponseEndCallback( const hkContactPoint& cp, hkReal impulseApplied, struct hkpSimpleConstraintInfoInitInput& inA, struct hkpBodyVelocity& velA, hkpSimpleConstraintInfoInitInput& inB, hkpBodyVelocity& velB); protected: #if !defined(HK_PLATFORM_SPU) inline #endif hkpRigidBody* setContactPointProperties( const hkpCdBody& a, const hkpCdBody& b, int maxNumExtraDataInEvent, hkpContactPointProperties* cpi ); /// produce some memory statistics void calcStatistics( hkStatisticsCollector* collector ) const; public: /// Class that creates instances of hkpSimpleConstraintContactMgr. class Factory: public hkpContactMgrFactory { //+vtable(true) public: Factory(hkpWorld* mgr); hkpContactMgr* createContactMgr( const hkpCollidable& a, const hkpCollidable& b, const hkpCollisionInput& input ); protected: hkpWorld* m_world; }; // // For internal use only // public: hkUint16 m_reservedContactPoints; hkUint16 m_skipNextNprocessCallbacks; hkpSimpleContactConstraintData m_contactConstraintData; hkpConstraintInstance m_constraint; hkUint32 m_pad[4]; }; #endif // HK_DYNAMICS2_SIMPLE_CONSTRAINT_CONTACT_MGR_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 135 ] ] ]
5ed615b47a22b4c995c21a59b11796b0958998ca
41c264ec05b297caa2a6e05e4476ce0576a8d7a9
/OpenHoldem/DialogSelectTable.cpp
ad1ec1d75d7b85507ec7cd278d551b081f864d69
[]
no_license
seawei/openholdem
cf19a90911903d7f4d07f956756bd7e521609af3
ba408c835b71dc1a9d674eee32958b69090fb86c
refs/heads/master
2020-12-25T05:40:09.628277
2009-01-25T01:17:10
2009-01-25T01:17:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,698
cpp
// SelectTableDialog.cpp : implementation file // #include "stdafx.h" #include "OpenHoldem.h" #include "DialogSelectTable.h" // CDlgSelectTable dialog IMPLEMENT_DYNAMIC(CDlgSelectTable, CDialog) CDlgSelectTable::CDlgSelectTable(CWnd* pParent /*=NULL*/) : CDialog(CDlgSelectTable::IDD, pParent) { __SEH_SET_EXCEPTION_HANDLER } CDlgSelectTable::~CDlgSelectTable() { } void CDlgSelectTable::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //DDX_Control(pDX, IDC_LIST_SELECT_TABLE, m_List_Select_Table); DDX_Control(pDX, IDC_LIST_SELECT_TABLE, m_HSLB); DDX_Control(pDX, IDOK, m_OK); } BEGIN_MESSAGE_MAP(CDlgSelectTable, CDialog) ON_BN_CLICKED(IDOK, &CDlgSelectTable::OnBnClickedOk) ON_LBN_DBLCLK(IDC_LIST_SELECT_TABLE, &CDlgSelectTable::OnLbnDblclkListSelectTable) ON_LBN_SELCHANGE(IDC_LIST_SELECT_TABLE, &CDlgSelectTable::OnLbnSelchangeListSelectTable) END_MESSAGE_MAP() // CDlgSelectTable message handlers void CDlgSelectTable::OnBnClickedOk() { selected_item = m_HSLB.GetCurSel(); OnOK(); } BOOL CDlgSelectTable::OnInitDialog() { int i = 0, N = 0; CString t = ""; CDialog::OnInitDialog(); selected_item = -1; // Populate listbox N = (int) tlist.GetSize(); for (i=0; i<N; i++) { t = tlist[i].title + " {" + tlist[i].path + "}"; m_HSLB.AddString(t); } m_OK.EnableWindow(false); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgSelectTable::OnLbnDblclkListSelectTable() { OnBnClickedOk(); } void CDlgSelectTable::OnLbnSelchangeListSelectTable() { m_OK.EnableWindow(true); }
[ [ [ 1, 73 ] ] ]
777b831b004b50d2874b68d0a34dd0b2e71cc72e
cf579692f2e289563160b6a218fa5f1b6335d813
/XBpatch/Patchers/CUnknownPatcher.cpp
28a90363c0f2ee0f8ce8e098ddb41502d1e6eb0d
[]
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
2,501
cpp
////////////////////////////////////////////////////////////////////////////// // CUnknownPatcher.cpp // XBpatch - Xbox BIOS recognition and patch library // Copyright (C) 2003 Mitch Crane // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <atlstr.h> #include "CUnknownPatcher.h" int CUnknownPatcher::Read(unsigned char *kernelBuffer, BIOS_Options *BIOSOptions) { mpKernelBuffer = kernelBuffer; BIOSOptions = BIOSOptions; BIOSOptions->Supported = false; strncpy(BIOSOptions->Name, "Unsupported Kernel", 63); if(kernelBuffer) { ReadBootFlags(BIOSOptions->BootFlags); ReadKernelVersion(&BIOSOptions->Version); } return 1; } int CUnknownPatcher::Write(unsigned char *kernelBuffer, BIOS_Options *BIOSOptions) { mpKernelBuffer = kernelBuffer; BIOSOptions = BIOSOptions; if (!WriteBootFlags(BIOSOptions->BootFlags)) return errWriteBootFlags; return 0; } void CUnknownPatcher::GetSupportedOptions(BIOS_Supported_Options &SupOpts) { mSupOpts.Animation = 0; mSupOpts.BootPart = 0; mSupOpts.DashName = 0; mSupOpts.ExtendedDashNames = 0; mSupOpts.DefaultXbeName = 0; mSupOpts.DVDCheck = 0; mSupOpts.LEDColor = 1; mSupOpts.SplashLogo = 0; mSupOpts.TrademarkSymbol = 0; mSupOpts.XboxColor = 1; mSupOpts.XGlowColor = 1; mSupOpts.XLipColor = 1; mSupOpts.XLipHighlightsColor = 1; mSupOpts.XLogo = 0; mSupOpts.XWallColor = 1; mSupOpts.BootFlags = 1; mSupOpts.LBA48 = 0; mSupOpts.IgnoreHDTable = 0; mSupOpts.PartitionOpt = 0; mSupOpts.FanSpeed = 0; mSupOpts.ResetOnEject = 0; mSupOpts.EmbedEeprom = 0; mSupOpts.EmbedHDKey = 0; SupOpts = mSupOpts; }
[ [ [ 1, 80 ] ] ]
d9e7936137634acddad32c3362e6c8ac668587c8
672d939ad74ccb32afe7ec11b6b99a89c64a6020
/Graph/GraphStudio/GraphStudio/CJFlatButton.h
a12dbb111d8231f22235bfeb3d56ff5f3ab80c74
[]
no_license
cloudlander/legacy
a073013c69e399744de09d649aaac012e17da325
89acf51531165a29b35e36f360220eeca3b0c1f6
refs/heads/master
2022-04-22T14:55:37.354762
2009-04-11T13:51:56
2009-04-11T13:51:56
256,939,313
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
8,483
h
// CJFlatButton.h : header file // // Copyright © 1998-99 Kirk W. Stowell // mailto:[email protected] // http://www.codejockeys.com/kstowell/ // // This source code may be used in compiled form in any way you desire. // Source file(s) may be redistributed unmodified by any means PROVIDING // they ARE NOT sold for profit without the authors expressed written // consent, and providing that this notice and the authors name and all // copyright notices remain intact. This software is by no means to be // included as part of any third party components library, or as part any // development solution that offers MFC extensions that are sold for profit. // // If the source code is used in any commercial applications then a statement // along the lines of: // // "Portions Copyright © 1998-99 Kirk Stowell" must be included in the startup // banner, "About" box or printed documentation. This software is provided // "as is" without express or implied warranty. Use it at your own risk! The // author(s) accepts no liability for any damage/loss of business that this // product may cause. // ///////////////////////////////////////////////////////////////////////////// /**************************************************************************** * * $Date: 7/25/99 10:00p $ * $Revision: 10 $ * $Archive: /CodeJockey/Include/CJFlatButton.h $ * * $History: CJFlatButton.h $ * * ***************** Version 10 ***************** * User: Kirk Stowell Date: 7/25/99 Time: 10:00p * Updated in $/CodeJockey/Include * * ***************** Version 9 ***************** * User: Kirk Stowell Date: 7/25/99 Time: 12:42a * Updated in $/CodeJockey/Include * * ***************** Version 8 ***************** * User: Kirk Stowell Date: 6/23/99 Time: 12:33a * Updated in $/CodeJockey/Include * * ***************** Version 7 ***************** * User: Kirk Stowell Date: 7/18/99 Time: 10:17p * Updated in $/CodeJockey/Include * Cleaned up inline functions, and import/export macro so that class will * be imported when linked to, and exported at compile time. * * ***************** Version 6 ***************** * User: Kirk Stowell Date: 7/14/99 Time: 9:58p * Updated in $/CodeJockey/Include * Re-wrote class to handle icons, text and bitmaps and added additional * functionality which was needed by the CCJCaption class. * * ***************** Version 5 ***************** * User: Kirk Stowell Date: 6/09/99 Time: 8:45p * Updated in $/CodeJockey/Include * cleaned up _CJXLIB_INLINE functions, added validation assert. * * ***************** Version 4 ***************** * User: Kirk Stowell Date: 4/03/99 Time: 4:23p * Updated in $/CodeJockey/Include * Added comments and cleaned up code. * * ***************** Version 3 ***************** * User: Kirk Stowell Date: 3/13/99 Time: 4:24p * Updated in $/CodeJockey/Include * Patrick Bergeron [[email protected]] fixed the following bugs: * * Moving the cursor over the flat button doesn't raise the button right * away. We have to wait for the first timer message to arrive, which is a * bit annoying. It gives the impression that the system isn't very * responsive. So in the OnMouseMove method, we call OnTimer(1) to force * the initial update of the button. * * Sometimes, a CJFlatButton would stay in a raised state when moving the * mouse quickly over the client area of a few CJFlatButtons. The reason * turned out to be the use of a static (ahem, global) variable * "bPainted". The simple fix for this was to put bPainted as a member * variable ("m_bPainted") and use this member variable instead. * * Flat buttons are now much more responsive and behave correctly in all * cases. * * ***************** Version 2 ***************** * User: Kirk Stowell Date: 10/17/98 Time: 4:24p * Updated in $/CodeJockey/Include * Code clean up and re-organization, renamed CCJButton to CCJFlatButton. * * ***************** Version 1 ***************** * User: Kirk Stowell Date: 10/17/98 Time: 4:23p * Created in $/CodeJockey/Include * Initial re-write and release. * ***************************************************************************/ ///////////////////////////////////////////////////////////////////////////// #ifndef __CJFLATBUTTON_H__ #define __CJFLATBUTTON_H__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // CCJFlatButton is a CButton derived class used to create flat buttons. // this class can only be used with the BS_OWNERDRAW style bit set. class CCJFlatButton : public CButton { public: // Default constructor // CCJFlatButton(); // Virtual destructor // virtual ~CCJFlatButton(); protected: BOOL m_bMouseOver; BOOL m_bLBtnDown; // true if left mouse button is pressed BOOL m_bFlatLook; // true for flat buttons see DisableFlatLook() CSize m_sizeIcon; // size of the icon if any associated with the button COLORREF m_clrHilite; // set to ::GetSysColor(COLOR_BTNHIGHLIGHT) COLORREF m_clrShadow; // set to ::GetSysColor(COLOR_BTNSHADOW) COLORREF m_clrDkShad; // set to ::GetSysColor(COLOR_3DDKSHADOW) COLORREF m_clrNormal; // set to ::GetSysColor(COLOR_BTNFACE) COLORREF m_clrTextGy; // set to ::GetSysColor(COLOR_GRAYTEXT) COLORREF m_clrTextNm; // set to ::GetSysColor(COLOR_BTNTEXT) BOOL m_bPainted; // used during paint operations HICON m_hPushed; CFont* m_pFont; CFont m_Font; // default font created by control if m_pFont is NULL HCURSOR m_hCursor; public: void UpdateFont(); void SetButtonFont(CFont* pFont); // this member function is used to disable or enable the flat // look for the button // void DisableFlatLook( // set to true to disable the flat look. BOOL bDisable = FALSE); // this memeber function is used to associate an icon with the // flat button. // void SetIcon( // handle to icon to be associated with button. HICON hIcon, // desired size of the icon, must be smaller than // button size for best results. CSize size); // this memeber function is used to associate an icon with the // flat button. // void SetIcon( // handle to icon to be associated with button. HICON hIcon, // handle of the pushed icon to be associated with button. HICON hPushed, // desired size of the icon, must be smaller than // button size for best results. CSize size); protected: // this memeber funcion is called by the button during paint // operations. // virtual void DrawButtonIcon(CDC* pDC, UINT nState, CRect& rcItem); virtual void DrawButtonText(CDC* pDC, UINT nState, CRect& rcItem); virtual void DrawButtonBitmap(CDC* pDC, UINT nState, CRect& rcItem); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCJFlatButton) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CCJFlatButton) afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnSysColorChange(); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // Inline Functions ///////////////////////////////////////////////////////////////////////////// _CJXLIB_INLINE void CCJFlatButton::DisableFlatLook(BOOL bDisable) { ASSERT(::IsWindow(m_hWnd)); m_bFlatLook = bDisable; Invalidate(); } _CJXLIB_INLINE void CCJFlatButton::SetIcon(HICON hIcon, CSize size) { ASSERT(::IsWindow(m_hWnd)); m_sizeIcon = size; ::DestroyIcon( CButton::SetIcon(hIcon) ); } _CJXLIB_INLINE void CCJFlatButton::SetIcon(HICON hIcon, HICON hPushed, CSize size) { ASSERT(::IsWindow(m_hWnd)); m_hPushed = hPushed; SetIcon(hIcon, size); } _CJXLIB_INLINE void CCJFlatButton::SetButtonFont(CFont *pFont) { ASSERT(::IsWindow(m_hWnd)); m_pFont = pFont; } ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // __CJFLATBUTTON_H__
[ "xmzhang@5428276e-be0b-f542-9301-ee418ed919ad" ]
[ [ [ 1, 225 ] ] ]
72a9a211e95152ef7469d011ce20e2d416468788
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/DOM_NamedNodeMap.cpp
cead8661e60e637748ab6ba1a2a83f79fc19acd6
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
5,491
cpp
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOM_NamedNodeMap.cpp 176278 2005-01-07 14:38:22Z amassari $ */ #include "DOM_Node.hpp" #include "DOM_NamedNodeMap.hpp" #include "NamedNodeMapImpl.hpp" #include "ElementImpl.hpp" XERCES_CPP_NAMESPACE_BEGIN const unsigned short DOM_NamedNodeMap::NNM_ELEMENT = 0; const unsigned short DOM_NamedNodeMap::NNM_OTHER = 1; DOM_NamedNodeMap::DOM_NamedNodeMap() { fImpl = 0; flagElem = NNM_OTHER; } DOM_NamedNodeMap::DOM_NamedNodeMap(const DOM_NamedNodeMap & other) { this->fImpl = other.fImpl; this->flagElem = other.flagElem; (other.flagElem == NNM_ELEMENT) ? NodeImpl::addRef((NodeImpl *)fImpl) : NamedNodeMapImpl::addRef((NamedNodeMapImpl *)fImpl); } DOM_NamedNodeMap::DOM_NamedNodeMap(NamedNodeMapImpl *impl) { fImpl = impl; flagElem = NNM_OTHER; if (impl != null) NamedNodeMapImpl::addRef((NamedNodeMapImpl *)fImpl); } DOM_NamedNodeMap::DOM_NamedNodeMap(NodeImpl *impl) { fImpl = impl; flagElem = NNM_ELEMENT; NodeImpl::addRef((NodeImpl *)fImpl); } DOM_NamedNodeMap::~DOM_NamedNodeMap() { (flagElem == NNM_OTHER) ? NamedNodeMapImpl::removeRef((NamedNodeMapImpl *)fImpl) : NodeImpl::removeRef((NodeImpl *)fImpl); } bool DOM_NamedNodeMap::operator == (const DOM_NamedNodeMap &other) const { return this->fImpl == other.fImpl; } bool DOM_NamedNodeMap::operator != (const DOM_NamedNodeMap &other) const { return this->fImpl != other.fImpl; } bool DOM_NamedNodeMap::operator == (const DOM_NullPtr * /*p*/) const { return this->fImpl == 0; } bool DOM_NamedNodeMap::operator != (const DOM_NullPtr * /*p*/) const { return this->fImpl != 0; } DOM_NamedNodeMap & DOM_NamedNodeMap::operator = (const DOM_NamedNodeMap & other) { if (this->fImpl != other.fImpl) { // update reference counts and change pointers (flagElem == NNM_OTHER) ? NamedNodeMapImpl::removeRef((NamedNodeMapImpl *)fImpl) : NodeImpl::removeRef((NodeImpl *)fImpl); this->fImpl = other.fImpl; this->flagElem = other.flagElem; (flagElem == NNM_OTHER) ? NamedNodeMapImpl::addRef((NamedNodeMapImpl *)fImpl) : NodeImpl::addRef((NodeImpl *)fImpl); } return *this; } DOM_NamedNodeMap & DOM_NamedNodeMap::operator = (const DOM_NullPtr * /*other*/) { (flagElem == NNM_OTHER) ? NamedNodeMapImpl::removeRef((NamedNodeMapImpl *)fImpl) : NodeImpl::removeRef((NodeImpl *)fImpl); this->fImpl = 0; this->flagElem = NNM_OTHER; return *this; } DOM_Node DOM_NamedNodeMap::getNamedItem(const DOMString &name) const { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->getNamedItem(name)) : DOM_Node(((ElementImpl *)fImpl)->NNM_getNamedItem(name)); } DOM_Node DOM_NamedNodeMap::setNamedItem(DOM_Node arg) { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->setNamedItem(arg.fImpl)) : DOM_Node(((ElementImpl *)fImpl)->NNM_setNamedItem(arg.fImpl)); } DOM_Node DOM_NamedNodeMap::removeNamedItem(const DOMString &name) { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->removeNamedItem(name)) : DOM_Node(((ElementImpl *)fImpl)->NNM_removeNamedItem(name)); } DOM_Node DOM_NamedNodeMap::item(unsigned int index) const { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->item(index)) : DOM_Node(((ElementImpl *)fImpl)->NNM_item(index)); } unsigned int DOM_NamedNodeMap::getLength() const { return (flagElem == NNM_OTHER) ? ((NamedNodeMapImpl *)fImpl)->getLength() : ((ElementImpl *)fImpl)->NNM_getLength(); } //Introduced in DOM Level 2 DOM_Node DOM_NamedNodeMap::getNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->getNamedItemNS(namespaceURI, localName)) : DOM_Node(((ElementImpl *)fImpl)->NNM_getNamedItemNS(namespaceURI, localName)); } DOM_Node DOM_NamedNodeMap::setNamedItemNS(DOM_Node arg) { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->setNamedItemNS(arg.fImpl)) : DOM_Node(((ElementImpl *)fImpl)->NNM_setNamedItemNS(arg.fImpl)); } DOM_Node DOM_NamedNodeMap::removeNamedItemNS(const DOMString &namespaceURI, const DOMString &localName) { return (flagElem == NNM_OTHER) ? DOM_Node(((NamedNodeMapImpl *)fImpl)->removeNamedItemNS(namespaceURI, localName)) : DOM_Node(((ElementImpl *)fImpl)->NNM_removeNamedItemNS(namespaceURI, localName)); } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 180 ] ] ]
470f9ee652640be8d6ddc9ff996b724cb56b9103
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-world/WeatherMgr.cpp
d0ecb5a3573461b7d7e311b71127540ae9a2ffc0
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
8,831
cpp
/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" /// Weather defines enum WeatherTypes { WEATHER_TYPE_NORMAL = 0, // NORMAL WEATHER_TYPE_FOG = 1, // FOG --> current value irrelant WEATHER_TYPE_RAIN = 2, // RAIN WEATHER_TYPE_HEAVY_RAIN = 4, // HEAVY_RAIN WEATHER_TYPE_SNOW = 8, // SNOW WEATHER_TYPE_SANDSTORM = 16 // SANDSTORM }; enum WeatherSounds { WEATHER_NOSOUND = 0, WEATHER_RAINLIGHT = 8533, WEATHER_RAINMEDIUM = 8534, WEATHER_RAINHEAVY = 8535, WEATHER_SNOWLIGHT = 8536, WEATHER_SNOWMEDIUM = 8537, WEATHER_SNOWHEAVY = 8538, WEATHER_SANDSTORMLIGHT = 8556, WEATHER_SANDSTORMMEDIUM = 8557, WEATHER_SANDSTORMHEAVY = 8558 }; initialiseSingleton( WeatherMgr ); void BuildWeatherPacket(WorldPacket * data, uint32 Effect, float Density ) { data->Initialize(SMSG_WEATHER); if(Effect == 0 ) // set all parameter to 0 for sunny. *data << uint32(0) << float(0) << uint32(0) << uint8(0); else if (Effect == 1) // No sound/density for fog *data << Effect << float(0) << uint32(0) << uint8(0); else *data << Effect << Density << GetSound(Effect,Density) << uint8(0) ; // sLog.outDebug("Send Weather Update %d, Density %f, Sound %d, unint8(0)", Effect,Density,GetSound(Effect,Density)); } uint32 GetSound(uint32 Effect, float Density) { uint32 sound; if(Density<=0.30f) return WEATHER_NOSOUND; switch(Effect) { case 2: //rain case 4: if(Density <0.40f) sound = WEATHER_RAINLIGHT; else if(Density <0.70f) sound = WEATHER_RAINMEDIUM; else sound = WEATHER_RAINHEAVY; break; case 8: //snow if(Density <0.40f) sound = WEATHER_SNOWLIGHT; else if(Density <0.70f) sound = WEATHER_SNOWMEDIUM; else sound = WEATHER_SNOWHEAVY; break; case 16: //storm if(Density <0.40f) sound = WEATHER_SANDSTORMLIGHT; else if(Density <0.70f) sound = WEATHER_SANDSTORMMEDIUM; else sound = WEATHER_SANDSTORMHEAVY; break; default: //no sound sound = WEATHER_NOSOUND; break; } return sound; } WeatherMgr::WeatherMgr() { } WeatherMgr::~WeatherMgr() { std::map<uint32, WeatherInfo*>::iterator itr; for(itr = m_zoneWeathers.begin(); itr != m_zoneWeathers.end(); itr++) { delete itr->second; } m_zoneWeathers.clear(); } void WeatherMgr::LoadFromDB() { //sLog.outString(" Loading Weather..."); // weather type 0= sunny / 1= fog / 2 = light_rain / 4 = rain / 8 = snow / ?? = sandstorm QueryResult *result = WorldDatabase.Query( "SELECT zoneId,high_chance,high_type,med_chance,med_type,low_chance,low_type FROM weather" ); if( !result ) return; do { Field *fields = result->Fetch(); WeatherInfo *wi = new WeatherInfo; wi->m_zoneId = fields[0].GetUInt32(); wi->m_effectValues[0] = fields[1].GetUInt32(); // high_chance wi->m_effectValues[1] = fields[2].GetUInt32(); // high_type wi->m_effectValues[2] = fields[3].GetUInt32(); // med_chance wi->m_effectValues[3] = fields[4].GetUInt32(); // med_type wi->m_effectValues[4] = fields[5].GetUInt32(); // low_chance wi->m_effectValues[5] = fields[6].GetUInt32(); // low_type m_zoneWeathers[wi->m_zoneId] = wi; wi->_GenerateWeather(); } while( result->NextRow() ); Log.Notice("WeatherMgr", "Loaded weather information for %u zones.", result->GetRowCount()); delete result; } void WeatherMgr::SendWeather(Player *plr) //Update weather when player has changed zone (WorldSession::HandleZoneUpdateOpcode) { std::map<uint32, WeatherInfo*>::iterator itr; itr = m_zoneWeathers.find(plr->GetZoneId()); if (itr == m_zoneWeathers.end()) { WorldPacket data(SMSG_WEATHER, 9); BuildWeatherPacket(&data, 0, 0); plr->GetSession()->SendPacket( &data ); plr->m_lastSeenWeather = 0; return; } else { itr->second->SendUpdate(plr); } } WeatherInfo::WeatherInfo() { m_currentDensity = 0; m_currentEffect = 0; m_currentTime = 0; m_maxDensity = 0; m_totalTime = 0; m_zoneId = 0; } WeatherInfo::~WeatherInfo() { } void WeatherInfo::_GenerateWeather() { m_currentTime = 0; m_currentEffect = 0; m_currentDensity = 0.30f;//Starting Offset (don't go below, it's annoying fog) float fd = RandomFloat(); m_maxDensity = fd+1; //1 - 2 m_totalTime = (RandomUInt(11) + 5)*1000*120;//update approx. every 1-2 minutes uint32 rv = RandomUInt(100); std::map<uint32, uint32>::iterator itr; if (rv <= m_effectValues[4]) // %chance on changing weather from sunny to m_effectValues[5] { m_currentEffect = m_effectValues[5]; } else if (rv <= m_effectValues[2]) // %chance on changing weather from sunny to m_effectValues[3] { m_currentEffect = m_effectValues[3]; } else if (rv <= m_effectValues[0]) // %chance on changing weather from sunny to m_effectValues[1] { m_currentEffect = m_effectValues[1]; } SendUpdate(); sEventMgr.AddEvent(this, &WeatherInfo::BuildUp, EVENT_WEATHER_UPDATE, (uint32)(m_totalTime/ceil(m_maxDensity/WEATHER_DENSITY_UPDATE)*2), 0,0); Log.Debug("WeatherMgr", "Forecast for zone:%d new type:%d new interval:%d ms",m_zoneId,m_currentEffect,(uint32)(m_totalTime/ceil(m_maxDensity/WEATHER_DENSITY_UPDATE)*2)); } void WeatherInfo::BuildUp() { // Increase until 0.5, start random counter when reached if (m_currentDensity >= 0.50f) { sEventMgr.RemoveEvents(this, EVENT_WEATHER_UPDATE); sEventMgr.AddEvent(this, &WeatherInfo::Update, EVENT_WEATHER_UPDATE, (uint32)(m_totalTime/ceil(m_maxDensity/WEATHER_DENSITY_UPDATE)*4), 0,0); // sLog.outDebug("Weather starting random for zone:%d type:%d new interval:%d ms",m_zoneId,m_currentEffect,(uint32)(m_totalTime/ceil(m_maxDensity/WEATHER_DENSITY_UPDATE)*4)); } else { m_currentDensity += WEATHER_DENSITY_UPDATE; // sLog.outDebug("Weather increased for zone:%d type:%d density:%f",m_zoneId,m_currentEffect,m_currentDensity); SendUpdate(); } } void WeatherInfo::Update() { // There will be a 66% the weather density decreases. If Sunny, use as currentDensity as countdown if (m_currentEffect == 0 || RandomUInt(100) < 66) { m_currentDensity -= WEATHER_DENSITY_UPDATE; if (m_currentDensity < 0.30f) //0.20 is considered fog, lower values are anoying { m_currentDensity = 0.0f; m_currentEffect = 0; sEventMgr.RemoveEvents(this, EVENT_WEATHER_UPDATE); _GenerateWeather(); return; } } else { m_currentDensity += WEATHER_DENSITY_UPDATE; if (m_currentDensity >= m_maxDensity) { m_currentDensity = m_maxDensity; return; } } SendUpdate(); // sLog.outDebug("Weather Updated,zoneId:%d type:%d density:%f", m_zoneId, m_currentEffect, m_currentDensity); } void WeatherInfo::SendUpdate() { WorldPacket data(SMSG_WEATHER, 9); BuildWeatherPacket(&data, m_currentEffect, m_currentDensity); sWorld.SendZoneMessage(&data, m_zoneId, 0); } void WeatherInfo::SendUpdate(Player *plr) //Updates weather for player's zone-change only if new zone weather differs { if(plr->m_lastSeenWeather == m_currentEffect) //return if weather is same as previous zone return; plr->m_lastSeenWeather = m_currentEffect; WorldPacket data(SMSG_WEATHER, 9); BuildWeatherPacket(&data, m_currentEffect, m_currentDensity); plr->GetSession()->SendPacket( &data ); }
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 5, 273 ] ], [ [ 2, 4 ] ] ]
cec4c589a1b670de1e2f09d82b240255903ecb71
d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546
/hlsdk-2.3-p3/multiplayer/dmc/dlls/multiplay_gamerules.cpp
289a858a9480223e17a6d6f9b178d227abc73d82
[]
no_license
joropito/amxxgroup
637ee71e250ffd6a7e628f77893caef4c4b1af0a
f948042ee63ebac6ad0332f8a77393322157fa8f
refs/heads/master
2021-01-10T09:21:31.449489
2010-04-11T21:34:27
2010-04-11T21:34:27
47,087,485
1
0
null
null
null
null
UTF-8
C++
false
false
41,647
cpp
/*** * * Copyright (c) 1996-2002, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // teamplay_gamerules.cpp // #include "extdll.h" #include "util.h" #include "cbase.h" #include "player.h" #include "weapons.h" #include "gamerules.h" #include "skill.h" #include "game.h" #include "items.h" #include "hltv.h" #define INTERMISSION_TIME 60 class CDMCGameMgrHelper : public IVoiceGameMgrHelper { public: virtual bool CanPlayerHearPlayer(CBasePlayer *pPlayer1, CBasePlayer *pPlayer2) { return true; } }; static CDMCGameMgrHelper g_GameMgrHelper; bool g_bHaveMOTD; extern DLL_GLOBAL CGameRules *g_pGameRules; extern DLL_GLOBAL BOOL g_fGameOver; extern int gmsgDeathMsg; // client dll messages extern int gmsgScoreInfo; extern int gmsgMOTD; extern int gmsgServerName; #define ITEM_RESPAWN_TIME 30 #define WEAPON_RESPAWN_TIME 20 #define AMMO_RESPAWN_TIME 20 char *g_szDeathType; //********************************************************* // Rules for the half-life multiplayer game. //********************************************************* CHalfLifeMultiplay :: CHalfLifeMultiplay() { m_VoiceGameMgr.Init(&g_GameMgrHelper, gpGlobals->maxClients); int length; char * pFileList = (char*)LOAD_FILE_FOR_ME( "motd.txt", &length ); if ( pFileList ) g_bHaveMOTD = true; else g_bHaveMOTD = false; RefreshSkillData(); m_flIntermissionEndTime = 0; m_flGameEndTime = 0.0; // 11/8/98 // Modified by YWB: Server .cfg file is now a cvar, so that // server ops can run multiple game servers, with different server .cfg files, // from a single installed directory. // Mapcyclefile is already a cvar. // 3/31/99 // Added lservercfg file cvar, since listen and dedicated servers should not // share a single config file. (sjb) if ( IS_DEDICATED_SERVER() ) { // dedicated server char *servercfgfile = (char *)CVAR_GET_STRING( "servercfgfile" ); if ( servercfgfile && servercfgfile[0] ) { char szCommand[256]; ALERT( at_console, "Executing dedicated server config file\n" ); sprintf( szCommand, "exec %s\n", servercfgfile ); SERVER_COMMAND( szCommand ); } } else { // listen server char *lservercfgfile = (char *)CVAR_GET_STRING( "lservercfgfile" ); if ( lservercfgfile && lservercfgfile[0] ) { char szCommand[256]; ALERT( at_console, "Executing listen server config file\n" ); sprintf( szCommand, "exec %s\n", lservercfgfile ); SERVER_COMMAND( szCommand ); } } } //========================================================= //========================================================= void CHalfLifeMultiplay::RefreshSkillData( void ) { // load all default values CGameRules::RefreshSkillData(); // override some values for multiplay. // suitcharger gSkillData.suitchargerCapacity = 30; // Crowbar whack gSkillData.plrDmgCrowbar = 25; // Glock Round gSkillData.plrDmg9MM = 12; // 357 Round gSkillData.plrDmg357 = 40; // MP5 Round gSkillData.plrDmgMP5 = 12; // M203 grenade gSkillData.plrDmgM203Grenade = 100; // Shotgun buckshot gSkillData.plrDmgBuckshot = 20;// fewer pellets in deathmatch // Crossbow gSkillData.plrDmgCrossbowClient = 20; // RPG gSkillData.plrDmgRPG = 120; // Egon gSkillData.plrDmgEgonWide = 20; gSkillData.plrDmgEgonNarrow = 10; // Hand Grendade gSkillData.plrDmgHandGrenade = 100; // Satchel Charge gSkillData.plrDmgSatchel = 120; // Tripmine gSkillData.plrDmgTripmine = 150; // hornet gSkillData.plrDmgHornet = 10; } // longest the intermission can last, in seconds #define MAX_INTERMISSION_TIME 120 BOOL CHalfLifeMultiplay::ClientCommand( CBasePlayer *pPlayer, const char *pcmd ) { if(m_VoiceGameMgr.ClientCommand(pPlayer, pcmd)) return TRUE; return CGameRules::ClientCommand(pPlayer, pcmd); } extern cvar_t mp_chattime; extern cvar_t timeleft, fragsleft; //========================================================= //========================================================= void CHalfLifeMultiplay :: Think ( void ) { m_VoiceGameMgr.Update(gpGlobals->frametime); ///// Check game rules ///// static int last_frags; static int last_time; int frags_remaining = 0; int time_remaining = 0; if ( g_fGameOver ) // someone else quit the game already { // bounds check int time = (int)CVAR_GET_FLOAT( "mp_chattime" ); if ( time < 1 ) CVAR_SET_STRING( "mp_chattime", "1" ); else if ( time > INTERMISSION_TIME ) CVAR_SET_STRING( "mp_chattime", UTIL_dtos1( INTERMISSION_TIME ) ); m_flIntermissionEndTime = m_flIntermissionStartTime + mp_chattime.value; // check to see if we should change levels now if ( m_flIntermissionEndTime < gpGlobals->time ) { if ( m_iEndIntermissionButtonHit // check that someone has pressed a key, or the max intermission time is over || ( ( m_flIntermissionStartTime + INTERMISSION_TIME ) < gpGlobals->time) ) ChangeLevel(); // intermission is over } return; } if ( m_flGameEndTime != 0.0 && m_flGameEndTime <= gpGlobals->time ) { GoToIntermission(); m_flGameEndTime = 0.0; return; } float flTimeLimit = timelimit.value * 60; float flFragLimit = fraglimit.value; time_remaining = (int)(flTimeLimit ? ( flTimeLimit - gpGlobals->time ) : 0); if ( flTimeLimit != 0 && gpGlobals->time >= flTimeLimit && m_flGameEndTime == 0.0 ) { GoToIntermission(); return; } if ( flFragLimit && m_flGameEndTime == 0.0 ) { int bestfrags = 9999; int remain; // check if any player is over the frag limit for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseEntity *pPlayer = UTIL_PlayerByIndex( i ); if ( pPlayer && pPlayer->pev->frags >= flFragLimit ) { m_flGameEndTime = gpGlobals->time + 1.5; return; } if ( pPlayer ) { remain = flFragLimit - pPlayer->pev->frags; if ( remain < bestfrags ) { bestfrags = remain; } } } frags_remaining = bestfrags; } // Updates when frags change if ( frags_remaining != last_frags ) { g_engfuncs.pfnCvar_DirectSet( &fragsleft, UTIL_VarArgs( "%i", frags_remaining ) ); } // Updates once per second if ( timeleft.value != last_time ) { g_engfuncs.pfnCvar_DirectSet( &timeleft, UTIL_VarArgs( "%i", time_remaining ) ); } last_frags = frags_remaining; last_time = time_remaining; } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::IsMultiplayer( void ) { return TRUE; } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::IsDeathmatch( void ) { return TRUE; } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::IsCoOp( void ) { return gpGlobals->coop; } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::FShouldSwitchWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ) { if ( !pWeapon->CanDeploy() ) { // that weapon can't deploy anyway. return FALSE; } if ( !pPlayer->m_pActiveItem ) { // player doesn't have an active item! return TRUE; } if ( !pPlayer->m_pActiveItem->CanHolster() ) { // can't put away the active item. return FALSE; } if ( pWeapon->iWeight() > pPlayer->m_pActiveItem->iWeight() ) { return TRUE; } return FALSE; } BOOL CHalfLifeMultiplay :: GetNextBestWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon ) { CBasePlayerItem *pCheck; CBasePlayerItem *pBest;// this will be used in the event that we don't find a weapon in the same category. int iBestWeight; int i; iBestWeight = -1;// no weapon lower than -1 can be autoswitched to pBest = NULL; if ( !pCurrentWeapon->CanHolster() ) { // can't put this gun away right now, so can't switch. return FALSE; } for ( i = 0 ; i < MAX_ITEM_TYPES ; i++ ) { pCheck = pPlayer->m_rgpPlayerItems[ i ]; while ( pCheck ) { if ( pCheck->iWeight() > -1 && pCheck->iWeight() == pCurrentWeapon->iWeight() && pCheck != pCurrentWeapon ) { // this weapon is from the same category. if ( pCheck->CanDeploy() ) { if ( pPlayer->SwitchWeapon( pCheck ) ) { return TRUE; } } } else if ( pCheck->iWeight() > iBestWeight && pCheck != pCurrentWeapon )// don't reselect the weapon we're trying to get rid of { //ALERT ( at_console, "Considering %s\n", STRING( pCheck->pev->classname ) ); // we keep updating the 'best' weapon just in case we can't find a weapon of the same weight // that the player was using. This will end up leaving the player with his heaviest-weighted // weapon. if ( pCheck->CanDeploy() ) { // if this weapon is useable, flag it as the best iBestWeight = pCheck->iWeight(); pBest = pCheck; } } pCheck = pCheck->m_pNext; } } // if we make it here, we've checked all the weapons and found no useable // weapon in the same catagory as the current weapon. // if pBest is null, we didn't find ANYTHING. Shouldn't be possible- should always // at least get the crowbar, but ya never know. if ( !pBest ) { return FALSE; } pPlayer->SwitchWeapon( pBest ); return TRUE; } //========================================================= //========================================================= BOOL CHalfLifeMultiplay :: ClientConnected( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ) { m_VoiceGameMgr.ClientConnected(pEntity); return TRUE; } extern int gmsgSayText; extern int gmsgGameMode; void CHalfLifeMultiplay :: UpdateGameMode( CBasePlayer *pPlayer ) { MESSAGE_BEGIN( MSG_ONE, gmsgGameMode, NULL, pPlayer->edict() ); WRITE_BYTE( 0 ); // game mode none MESSAGE_END(); } void CHalfLifeMultiplay :: InitHUD( CBasePlayer *pl ) { // notify other clients of player joining the game UTIL_ClientPrintAll( HUD_PRINTNOTIFY, UTIL_VarArgs( "%s has joined the game\n", ( pl->pev->netname && STRING(pl->pev->netname)[0] != 0 ) ? STRING(pl->pev->netname) : "unconnected" ) ); UTIL_LogPrintf( "\"%s<%i><%s><%i>\" entered the game\n", STRING( pl->pev->netname ), GETPLAYERUSERID( pl->edict() ), GETPLAYERAUTHID( pl->edict() ), GETPLAYERUSERID( pl->edict() ) ); UpdateGameMode( pl ); // sending just one score makes the hud scoreboard active; otherwise // it is just disabled for single play MESSAGE_BEGIN( MSG_ONE, gmsgScoreInfo, NULL, pl->edict() ); WRITE_BYTE( ENTINDEX(pl->edict()) ); WRITE_SHORT( 0 ); WRITE_SHORT( 0 ); WRITE_SHORT( 0 ); MESSAGE_END(); SendMOTDToClient( pl->edict() ); // loop through all active players and send their score info to the new client for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { // FIXME: Probably don't need to cast this just to read m_iDeaths CBasePlayer *plr = (CBasePlayer *)UTIL_PlayerByIndex( i ); if ( plr ) { MESSAGE_BEGIN( MSG_ONE, gmsgScoreInfo, NULL, pl->edict() ); WRITE_BYTE( i ); // client number WRITE_SHORT( plr->pev->frags ); WRITE_SHORT( plr->m_iDeaths ); WRITE_SHORT( plr->pev->team ); MESSAGE_END(); } } if ( g_fGameOver ) { MESSAGE_BEGIN( MSG_ONE, SVC_INTERMISSION, NULL, pl->edict() ); MESSAGE_END(); } } //========================================================= //========================================================= void CHalfLifeMultiplay :: ClientDisconnected( edict_t *pClient ) { if ( pClient ) { CBasePlayer *pPlayer = (CBasePlayer *)CBaseEntity::Instance( pClient ); if ( pPlayer ) { FireTargets( "game_playerleave", pPlayer, pPlayer, USE_TOGGLE, 0 ); UTIL_LogPrintf( "\"%s<%i><%s><%i>\" disconnected\n", STRING( pPlayer->pev->netname ), GETPLAYERUSERID( pPlayer->edict() ), GETPLAYERAUTHID( pPlayer->edict() ), GETPLAYERUSERID( pPlayer->edict() ) ); pPlayer->RemoveAllItems( TRUE );// destroy all of the players weapons and items } } } //========================================================= //========================================================= float CHalfLifeMultiplay :: FlPlayerFallDamage( CBasePlayer *pPlayer ) { int iFallDamage = (int)CVAR_GET_FLOAT("mp_falldamage"); switch ( iFallDamage ) { case 1://progressive pPlayer->m_flFallVelocity -= PLAYER_MAX_SAFE_FALL_SPEED; return pPlayer->m_flFallVelocity * DAMAGE_FOR_FALL_SPEED; break; default: case 0:// fixed return 5; break; } } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::FPlayerCanTakeDamage( CBasePlayer *pPlayer, CBaseEntity *pAttacker ) { return TRUE; } //========================================================= //========================================================= void CHalfLifeMultiplay :: PlayerThink( CBasePlayer *pPlayer ) { if ( g_fGameOver ) { // check for button presses if ( pPlayer->m_afButtonPressed & ( IN_DUCK | IN_ATTACK | IN_ATTACK2 | IN_USE | IN_JUMP ) ) m_iEndIntermissionButtonHit = TRUE; // clear attack/use commands from player pPlayer->m_afButtonPressed = 0; pPlayer->pev->button = 0; pPlayer->m_afButtonReleased = 0; } } //========================================================= //========================================================= void CHalfLifeMultiplay :: PlayerSpawn( CBasePlayer *pPlayer ) { BOOL addDefault; CBaseEntity *pWeaponEntity = NULL; pPlayer->pev->weapons |= (1<<IT_AXE); addDefault = TRUE; while ( pWeaponEntity = UTIL_FindEntityByClassname( pWeaponEntity, "game_player_equip" )) { pWeaponEntity->Touch( pPlayer ); addDefault = FALSE; } if ( addDefault ) { // Start with init ammoload pPlayer->m_iAmmoShells = 25; // Start with shotgun and axe pPlayer->GiveNamedItem( "weapon_quakegun" ); pPlayer->m_iQuakeItems |= (IT_SHOTGUN | IT_AXE); pPlayer->m_iQuakeWeapon = pPlayer->W_BestWeapon(); pPlayer->W_SetCurrentAmmo(); } } //========================================================= //========================================================= BOOL CHalfLifeMultiplay :: FPlayerCanRespawn( CBasePlayer *pPlayer ) { return TRUE; } //========================================================= //========================================================= float CHalfLifeMultiplay :: FlPlayerSpawnTime( CBasePlayer *pPlayer ) { return gpGlobals->time;//now! } BOOL CHalfLifeMultiplay :: AllowAutoTargetCrosshair( void ) { return ( CVAR_GET_FLOAT( "mp_autocrosshair" ) != 0 ); } //========================================================= // IPointsForKill - how many points awarded to anyone // that kills this player? //========================================================= int CHalfLifeMultiplay :: IPointsForKill( CBasePlayer *pAttacker, CBasePlayer *pKilled ) { return 1; } void CHalfLifeMultiplay::ClientUserInfoChanged( CBasePlayer *pPlayer, char *infobuffer ) { pPlayer->m_iFOV = atoi( g_engfuncs.pfnInfoKeyValue( infobuffer, "cl_fov" ) ); pPlayer->m_iAutoWepSwitch = atoi( g_engfuncs.pfnInfoKeyValue( infobuffer, "cl_autowepswitch" ) ); } //========================================================= // PlayerKilled - someone/something killed this player //========================================================= void CHalfLifeMultiplay :: PlayerKilled( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ) { DeathNotice( pVictim, pKiller, pInflictor ); pVictim->m_iDeaths += 1; FireTargets( "game_playerdie", pVictim, pVictim, USE_TOGGLE, 0 ); CBasePlayer *peKiller = NULL; CBaseEntity *ktmp = CBaseEntity::Instance( pKiller ); if ( ktmp && (ktmp->Classify() == CLASS_PLAYER) ) peKiller = (CBasePlayer*)ktmp; if ( pVictim->pev == pKiller ) { // killed self pKiller->frags -= 1; } else if ( ktmp && ktmp->IsPlayer() ) { // if a player dies in a deathmatch game and the killer is a client, award the killer some points pKiller->frags += IPointsForKill( peKiller, pVictim ); FireTargets( "game_playerkill", ktmp, ktmp, USE_TOGGLE, 0 ); } else { // killed by the world pVictim->pev->frags -= 1; } // update the scores // killed scores MESSAGE_BEGIN( MSG_ALL, gmsgScoreInfo ); WRITE_BYTE( ENTINDEX(pVictim->edict()) ); WRITE_SHORT( pVictim->pev->frags ); WRITE_SHORT( pVictim->m_iDeaths ); WRITE_SHORT( pVictim->pev->team ); MESSAGE_END(); // killers score, if it's a player CBaseEntity *ep = CBaseEntity::Instance( pKiller ); if ( ep && ep->Classify() == CLASS_PLAYER ) { CBasePlayer *PK = (CBasePlayer*)ep; MESSAGE_BEGIN( MSG_ALL, gmsgScoreInfo ); WRITE_BYTE( ENTINDEX(PK->edict()) ); WRITE_SHORT( PK->pev->frags ); WRITE_SHORT( PK->m_iDeaths ); WRITE_SHORT( PK->pev->team ); MESSAGE_END(); // let the killer paint another decal as soon as he'd like. PK->m_flNextDecalTime = gpGlobals->time; } } //========================================================= // Deathnotice. //========================================================= void CHalfLifeMultiplay::DeathNotice( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pevInflictor ) { // Work out what killed the player, and send a message to all clients about it CBaseEntity *Killer = CBaseEntity::Instance( pKiller ); const char *killer_weapon_name = "world"; // by default, the player is killed by the world int killer_index = 0; // Hack to fix name change char *tau = "tau_cannon"; char *gluon = "gluon gun"; // QUAKECLASSIC // Might have overridden if (g_szDeathType) { killer_weapon_name = g_szDeathType; } else { if ( pKiller->flags & FL_CLIENT ) { killer_index = ENTINDEX(ENT(pKiller)); if ( pevInflictor ) { if ( pevInflictor == pKiller ) { // If the inflictor is the killer, then it must be their current weapon doing the damage CBasePlayer *pPlayer = (CBasePlayer*)CBaseEntity::Instance( pKiller ); switch( pPlayer->m_iQuakeWeapon ) { case IT_AXE: killer_weapon_name = "weapon_axe"; break; case IT_SHOTGUN: killer_weapon_name = "weapon_shotgun"; break; case IT_SUPER_SHOTGUN: killer_weapon_name = "weapon_doubleshotgun"; break; case IT_NAILGUN: killer_weapon_name = "weapon_nailgun"; break; case IT_SUPER_NAILGUN: killer_weapon_name = "weapon_supernail"; break; case IT_GRENADE_LAUNCHER: killer_weapon_name = "weapon_grenadel"; break; case IT_ROCKET_LAUNCHER: killer_weapon_name = "weapon_rocketl"; break; case IT_LIGHTNING: killer_weapon_name = "weapon_lightning"; break; default: killer_weapon_name = "Empty"; } } else { killer_weapon_name = STRING( pevInflictor->classname ); // it's just that easy } } } else { killer_weapon_name = STRING( pevInflictor->classname ); } // strip the monster_* or weapon_* from the inflictor's classname if ( strncmp( killer_weapon_name, "weapon_", 7 ) == 0 ) killer_weapon_name += 7; else if ( strncmp( killer_weapon_name, "monster_", 8 ) == 0 ) killer_weapon_name += 8; else if ( strncmp( killer_weapon_name, "func_", 5 ) == 0 ) killer_weapon_name += 5; } MESSAGE_BEGIN( MSG_ALL, gmsgDeathMsg ); WRITE_BYTE( killer_index ); // the killer WRITE_BYTE( ENTINDEX(pVictim->edict()) ); // the victim WRITE_STRING( killer_weapon_name ); // what they were killed by (should this be a string?) MESSAGE_END(); // replace the code names with the 'real' names if ( !strcmp( killer_weapon_name, "egon" ) ) killer_weapon_name = gluon; else if ( !strcmp( killer_weapon_name, "gauss" ) ) killer_weapon_name = tau; if ( pVictim->pev == pKiller ) { // killed self UTIL_LogPrintf( "\"%s<%i><%s><%i>\" committed suicide with \"%s\"\n", STRING( pVictim->pev->netname ), GETPLAYERUSERID( pVictim->edict() ), GETPLAYERAUTHID( pVictim->edict() ), GETPLAYERUSERID( pVictim->edict() ), killer_weapon_name ); } else if ( pKiller->flags & FL_CLIENT ) { UTIL_LogPrintf( "\"%s<%i><%s><%i>\" killed \"%s<%i><%s><%i>\" with \"%s\"\n", STRING( pKiller->netname ), GETPLAYERUSERID( ENT(pKiller) ), GETPLAYERAUTHID( ENT(pKiller) ), GETPLAYERUSERID( ENT(pKiller) ), STRING( pVictim->pev->netname ), GETPLAYERUSERID( pVictim->edict() ), GETPLAYERAUTHID( pVictim->edict() ), GETPLAYERUSERID( pVictim->edict() ), killer_weapon_name ); } else { // killed by the world UTIL_LogPrintf( "\"%s<%i><%s><%i>\" committed suicide with \"%s\" (world)\n", STRING( pVictim->pev->netname ), GETPLAYERUSERID( pVictim->edict() ), GETPLAYERAUTHID( pVictim->edict() ), GETPLAYERUSERID( pVictim->edict() ), killer_weapon_name ); } g_szDeathType = NULL; // HLTV event msg MESSAGE_BEGIN( MSG_SPEC, SVC_DIRECTOR ); WRITE_BYTE ( 9 ); // command length in bytes WRITE_BYTE ( DRC_CMD_EVENT ); // player killed WRITE_SHORT( ENTINDEX(pVictim->edict()) ); // index number of primary entity if (pevInflictor) WRITE_SHORT( ENTINDEX(ENT(pevInflictor)) ); // index number of secondary entity else WRITE_SHORT( ENTINDEX(ENT(pKiller)) ); // index number of secondary entity WRITE_LONG( 7 | DRC_FLAG_DRAMATIC); // eventflags (priority and flags) MESSAGE_END(); // Print a standard message // TODO: make this go direct to console return; // just remove for now } //========================================================= // PlayerGotWeapon - player has grabbed a weapon that was // sitting in the world //========================================================= void CHalfLifeMultiplay :: PlayerGotWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ) { } //========================================================= // FlWeaponRespawnTime - what is the time in the future // at which this weapon may spawn? //========================================================= float CHalfLifeMultiplay :: FlWeaponRespawnTime( CBasePlayerItem *pWeapon ) { if ( CVAR_GET_FLOAT("mp_weaponstay") > 0 ) { // make sure it's only certain weapons if ( !(pWeapon->iFlags() & ITEM_FLAG_LIMITINWORLD) ) { return gpGlobals->time + 0; // weapon respawns almost instantly } } return gpGlobals->time + WEAPON_RESPAWN_TIME; } // when we are within this close to running out of entities, items // marked with the ITEM_FLAG_LIMITINWORLD will delay their respawn #define ENTITY_INTOLERANCE 100 //========================================================= // FlWeaponRespawnTime - Returns 0 if the weapon can respawn // now, otherwise it returns the time at which it can try // to spawn again. //========================================================= float CHalfLifeMultiplay :: FlWeaponTryRespawn( CBasePlayerItem *pWeapon ) { if ( pWeapon && pWeapon->m_iId && (pWeapon->iFlags() & ITEM_FLAG_LIMITINWORLD) ) { if ( NUMBER_OF_ENTITIES() < (gpGlobals->maxEntities - ENTITY_INTOLERANCE) ) return 0; // we're past the entity tolerance level, so delay the respawn return FlWeaponRespawnTime( pWeapon ); } return 0; } //========================================================= // VecWeaponRespawnSpot - where should this weapon spawn? // Some game variations may choose to randomize spawn locations //========================================================= Vector CHalfLifeMultiplay :: VecWeaponRespawnSpot( CBasePlayerItem *pWeapon ) { return pWeapon->pev->origin; } //========================================================= // WeaponShouldRespawn - any conditions inhibiting the // respawning of this weapon? //========================================================= int CHalfLifeMultiplay :: WeaponShouldRespawn( CBasePlayerItem *pWeapon ) { if ( pWeapon->pev->spawnflags & SF_NORESPAWN ) { return GR_WEAPON_RESPAWN_NO; } return GR_WEAPON_RESPAWN_YES; } //========================================================= // CanHaveWeapon - returns FALSE if the player is not allowed // to pick up this weapon //========================================================= BOOL CHalfLifeMultiplay::CanHavePlayerItem( CBasePlayer *pPlayer, CBasePlayerItem *pItem ) { if ( CVAR_GET_FLOAT("mp_weaponstay") > 0 ) { if ( pItem->iFlags() & ITEM_FLAG_LIMITINWORLD ) return CGameRules::CanHavePlayerItem( pPlayer, pItem ); // check if the player already has this weapon for ( int i = 0 ; i < MAX_ITEM_TYPES ; i++ ) { CBasePlayerItem *it = pPlayer->m_rgpPlayerItems[i]; while ( it != NULL ) { if ( it->m_iId == pItem->m_iId ) { return FALSE; } it = it->m_pNext; } } } return CGameRules::CanHavePlayerItem( pPlayer, pItem ); } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::CanHaveItem( CBasePlayer *pPlayer, CItem *pItem ) { return TRUE; } //========================================================= //========================================================= void CHalfLifeMultiplay::PlayerGotItem( CBasePlayer *pPlayer, CItem *pItem ) { } //========================================================= //========================================================= int CHalfLifeMultiplay::ItemShouldRespawn( CItem *pItem ) { if ( pItem->pev->spawnflags & SF_NORESPAWN ) { return GR_ITEM_RESPAWN_NO; } return GR_ITEM_RESPAWN_YES; } //========================================================= // At what time in the future may this Item respawn? //========================================================= float CHalfLifeMultiplay::FlItemRespawnTime( CItem *pItem ) { return gpGlobals->time + ITEM_RESPAWN_TIME; } //========================================================= // Where should this item respawn? // Some game variations may choose to randomize spawn locations //========================================================= Vector CHalfLifeMultiplay::VecItemRespawnSpot( CItem *pItem ) { return pItem->pev->origin; } //========================================================= //========================================================= void CHalfLifeMultiplay::PlayerGotAmmo( CBasePlayer *pPlayer, char *szName, int iCount ) { } //========================================================= //========================================================= BOOL CHalfLifeMultiplay::IsAllowedToSpawn( CBaseEntity *pEntity ) { // if ( pEntity->pev->flags & FL_MONSTER ) // return FALSE; return TRUE; } //========================================================= //========================================================= int CHalfLifeMultiplay::AmmoShouldRespawn( CBasePlayerAmmo *pAmmo ) { if ( pAmmo->pev->spawnflags & SF_NORESPAWN ) { return GR_AMMO_RESPAWN_NO; } return GR_AMMO_RESPAWN_YES; } //========================================================= //========================================================= float CHalfLifeMultiplay::FlAmmoRespawnTime( CBasePlayerAmmo *pAmmo ) { return gpGlobals->time + AMMO_RESPAWN_TIME; } //========================================================= //========================================================= Vector CHalfLifeMultiplay::VecAmmoRespawnSpot( CBasePlayerAmmo *pAmmo ) { return pAmmo->pev->origin; } //========================================================= //========================================================= float CHalfLifeMultiplay::FlHealthChargerRechargeTime( void ) { return 60; } float CHalfLifeMultiplay::FlHEVChargerRechargeTime( void ) { return 30; } //========================================================= //========================================================= int CHalfLifeMultiplay::DeadPlayerWeapons( CBasePlayer *pPlayer ) { return GR_PLR_DROP_GUN_ACTIVE; } //========================================================= //========================================================= int CHalfLifeMultiplay::DeadPlayerAmmo( CBasePlayer *pPlayer ) { return GR_PLR_DROP_AMMO_ACTIVE; } edict_t *CHalfLifeMultiplay::GetPlayerSpawnSpot( CBasePlayer *pPlayer ) { edict_t *pentSpawnSpot = CGameRules::GetPlayerSpawnSpot( pPlayer ); if ( IsMultiplayer() && pentSpawnSpot->v.target ) { FireTargets( STRING(pentSpawnSpot->v.target), pPlayer, pPlayer, USE_TOGGLE, 0 ); } return pentSpawnSpot; } //========================================================= //========================================================= int CHalfLifeMultiplay::PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ) { // half life deathmatch has only enemies return GR_NOTTEAMMATE; } BOOL CHalfLifeMultiplay :: PlayFootstepSounds( CBasePlayer *pl, float fvol ) { return FALSE; if ( g_footsteps && g_footsteps->value == 0 ) return FALSE; if ( pl->IsOnLadder() || pl->pev->velocity.Length2D() > 220 ) return TRUE; // only make step sounds in multiplayer if the player is moving fast enough return FALSE; } BOOL CHalfLifeMultiplay :: FAllowFlashlight( void ) { return CVAR_GET_FLOAT( "mp_flashlight" ) != 0; } //========================================================= //========================================================= BOOL CHalfLifeMultiplay :: FAllowMonsters( void ) { return ( CVAR_GET_FLOAT( "mp_allowmonsters" ) != 0 ); } //========================================================= //======== CHalfLifeMultiplay private functions =========== void CHalfLifeMultiplay :: GoToIntermission( void ) { if ( g_fGameOver ) return; // intermission has already been triggered, so ignore. MESSAGE_BEGIN(MSG_ALL, SVC_INTERMISSION); MESSAGE_END(); // bounds check int time = (int)CVAR_GET_FLOAT( "mp_chattime" ); if ( time < 1 ) CVAR_SET_STRING( "mp_chattime", "1" ); else if ( time > INTERMISSION_TIME ) CVAR_SET_STRING( "mp_chattime", UTIL_dtos1( INTERMISSION_TIME ) ); m_flIntermissionEndTime = gpGlobals->time + ( (int)mp_chattime.value ); m_flIntermissionStartTime = gpGlobals->time; g_fGameOver = TRUE; m_iEndIntermissionButtonHit = FALSE; } #define MAX_RULE_BUFFER 1024 typedef struct mapcycle_item_s { struct mapcycle_item_s *next; char mapname[ 32 ]; int minplayers, maxplayers; char rulebuffer[ MAX_RULE_BUFFER ]; } mapcycle_item_t; typedef struct mapcycle_s { struct mapcycle_item_s *items; struct mapcycle_item_s *next_item; } mapcycle_t; /* ============== DestroyMapCycle Clean up memory used by mapcycle when switching it ============== */ void DestroyMapCycle( mapcycle_t *cycle ) { mapcycle_item_t *p, *n, *start; p = cycle->items; if ( p ) { start = p; p = p->next; while ( p != start ) { n = p->next; delete p; p = n; } delete cycle->items; } cycle->items = NULL; cycle->next_item = NULL; } static char com_token[ 1500 ]; /* ============== COM_Parse Parse a token out of a string ============== */ char *COM_Parse (char *data) { int c; int len; len = 0; com_token[0] = 0; if (!data) return NULL; // skip whitespace skipwhite: while ( (c = *data) <= ' ') { if (c == 0) return NULL; // end of file; data++; } // skip // comments if (c=='/' && data[1] == '/') { while (*data && *data != '\n') data++; goto skipwhite; } // handle quoted strings specially if (c == '\"') { data++; while (1) { c = *data++; if (c=='\"' || !c) { com_token[len] = 0; return data; } com_token[len] = c; len++; } } // parse single characters if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c == ',' ) { com_token[len] = c; len++; com_token[len] = 0; return data+1; } // parse a regular word do { com_token[len] = c; data++; len++; c = *data; if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c == ',' ) break; } while (c>32); com_token[len] = 0; return data; } /* ============== COM_TokenWaiting Returns 1 if additional data is waiting to be processed on this line ============== */ int COM_TokenWaiting( char *buffer ) { char *p; p = buffer; while ( *p && *p!='\n') { if ( !isspace( *p ) || isalnum( *p ) ) return 1; p++; } return 0; } /* ============== ReloadMapCycleFile Parses mapcycle.txt file into mapcycle_t structure ============== */ int ReloadMapCycleFile( char *filename, mapcycle_t *cycle ) { char szBuffer[ MAX_RULE_BUFFER ]; char szMap[ 32 ]; int length; char *pFileList; char *aFileList = pFileList = (char*)LOAD_FILE_FOR_ME( filename, &length ); int hasbuffer; mapcycle_item_s *item, *newlist = NULL, *next; if ( pFileList && length ) { // the first map name in the file becomes the default while ( 1 ) { hasbuffer = 0; memset( szBuffer, 0, MAX_RULE_BUFFER ); pFileList = COM_Parse( pFileList ); if ( strlen( com_token ) <= 0 ) break; strcpy( szMap, com_token ); // Any more tokens on this line? if ( COM_TokenWaiting( pFileList ) ) { pFileList = COM_Parse( pFileList ); if ( strlen( com_token ) > 0 ) { hasbuffer = 1; strcpy( szBuffer, com_token ); } } // Check map if ( IS_MAP_VALID( szMap ) ) { // Create entry char *s; item = new mapcycle_item_s; strcpy( item->mapname, szMap ); item->minplayers = 0; item->maxplayers = 0; memset( item->rulebuffer, 0, MAX_RULE_BUFFER ); if ( hasbuffer ) { s = g_engfuncs.pfnInfoKeyValue( szBuffer, "minplayers" ); if ( s && s[0] ) { item->minplayers = atoi( s ); item->minplayers = max( item->minplayers, 0 ); item->minplayers = min( item->minplayers, gpGlobals->maxClients ); } s = g_engfuncs.pfnInfoKeyValue( szBuffer, "maxplayers" ); if ( s && s[0] ) { item->maxplayers = atoi( s ); item->maxplayers = max( item->maxplayers, 0 ); item->maxplayers = min( item->maxplayers, gpGlobals->maxClients ); } // Remove keys // g_engfuncs.pfnInfo_RemoveKey( szBuffer, "minplayers" ); g_engfuncs.pfnInfo_RemoveKey( szBuffer, "maxplayers" ); strcpy( item->rulebuffer, szBuffer ); } item->next = cycle->items; cycle->items = item; } else { ALERT( at_console, "Skipping %s from mapcycle, not a valid map\n", szMap ); } } FREE_FILE( aFileList ); } // Fixup circular list pointer item = cycle->items; // Reverse it to get original order while ( item ) { next = item->next; item->next = newlist; newlist = item; item = next; } cycle->items = newlist; item = cycle->items; // Didn't parse anything if ( !item ) { return 0; } while ( item->next ) { item = item->next; } item->next = cycle->items; cycle->next_item = item->next; return 1; } /* ============== CountPlayers Determine the current # of active players on the server for map cycling logic ============== */ int CountPlayers( void ) { int num = 0; for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBaseEntity *pEnt = UTIL_PlayerByIndex( i ); if ( pEnt ) { num = num + 1; } } return num; } /* ============== ExtractCommandString Parse commands/key value pairs to issue right after map xxx command is issued on server level transition ============== */ void ExtractCommandString( char *s, char *szCommand ) { // Now make rules happen char pkey[512]; char value[512]; // use two buffers so compares // work without stomping on each other char *o; if ( *s == '\\' ) s++; while (1) { o = pkey; while ( *s != '\\' ) { if ( !*s ) return; *o++ = *s++; } *o = 0; s++; o = value; while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; strcat( szCommand, pkey ); if ( strlen( value ) > 0 ) { strcat( szCommand, " " ); strcat( szCommand, value ); } strcat( szCommand, "\n" ); if (!*s) return; s++; } } /* ============== ChangeLevel Server is changing to a new level, check mapcycle.txt for map name and setup info ============== */ void CHalfLifeMultiplay :: ChangeLevel( void ) { static char szPreviousMapCycleFile[ 256 ]; static mapcycle_t mapcycle; char szNextMap[32]; char szFirstMapInList[32]; char szCommands[ 1500 ]; char szRules[ 1500 ]; int minplayers = 0, maxplayers = 0; strcpy( szFirstMapInList, "hldm1" ); // the absolute default level is hldm1 int curplayers; BOOL do_cycle = TRUE; // find the map to change to char *mapcfile = (char*)CVAR_GET_STRING( "mapcyclefile" ); ASSERT( mapcfile != NULL ); szCommands[ 0 ] = '\0'; szRules[ 0 ] = '\0'; curplayers = CountPlayers(); // Has the map cycle filename changed? if ( stricmp( mapcfile, szPreviousMapCycleFile ) ) { strcpy( szPreviousMapCycleFile, mapcfile ); DestroyMapCycle( &mapcycle ); if ( !ReloadMapCycleFile( mapcfile, &mapcycle ) || ( !mapcycle.items ) ) { ALERT( at_console, "Unable to load map cycle file %s\n", mapcfile ); do_cycle = FALSE; } } if ( do_cycle && mapcycle.items ) { BOOL keeplooking = FALSE; BOOL found = FALSE; mapcycle_item_s *item; // Assume current map strcpy( szNextMap, STRING(gpGlobals->mapname) ); strcpy( szFirstMapInList, STRING(gpGlobals->mapname) ); // Traverse list for ( item = mapcycle.next_item; item->next != mapcycle.next_item; item = item->next ) { keeplooking = FALSE; ASSERT( item != NULL ); if ( item->minplayers != 0 ) { if ( curplayers >= item->minplayers ) { found = TRUE; minplayers = item->minplayers; } else { keeplooking = TRUE; } } if ( item->maxplayers != 0 ) { if ( curplayers <= item->maxplayers ) { found = TRUE; maxplayers = item->maxplayers; } else { keeplooking = TRUE; } } if ( keeplooking ) continue; found = TRUE; break; } if ( !found ) { item = mapcycle.next_item; } // Increment next item pointer mapcycle.next_item = item->next; // Perform logic on current item strcpy( szNextMap, item->mapname ); ExtractCommandString( item->rulebuffer, szCommands ); strcpy( szRules, item->rulebuffer ); } if ( !IS_MAP_VALID(szNextMap) ) { strcpy( szNextMap, szFirstMapInList ); } g_fGameOver = TRUE; ALERT( at_console, "CHANGE LEVEL: %s\n", szNextMap ); if ( minplayers || maxplayers ) { ALERT( at_console, "PLAYER COUNT: min %i max %i current %i\n", minplayers, maxplayers, curplayers ); } if ( strlen( szRules ) > 0 ) { ALERT( at_console, "RULES: %s\n", szRules ); } CHANGE_LEVEL( szNextMap, NULL ); if ( strlen( szCommands ) > 0 ) { SERVER_COMMAND( szCommands ); } } #define MAX_MOTD_CHUNK 60 #define MAX_MOTD_LENGTH (MAX_MOTD_CHUNK * 4) void CHalfLifeMultiplay :: SendMOTDToClient( edict_t *client ) { // read from the MOTD.txt file int length, char_count = 0; char *pFileList; char *aFileList = pFileList = (char*)LOAD_FILE_FOR_ME( "motd.txt", &length ); // send the server name MESSAGE_BEGIN( MSG_ONE, gmsgServerName, NULL, client ); WRITE_STRING( CVAR_GET_STRING("hostname") ); MESSAGE_END(); // Send the message of the day // read it chunk-by-chunk, and send it in parts while ( pFileList && *pFileList && char_count < MAX_MOTD_LENGTH ) { char chunk[MAX_MOTD_CHUNK+1]; if ( strlen( pFileList ) < MAX_MOTD_CHUNK ) { strcpy( chunk, pFileList ); } else { strncpy( chunk, pFileList, MAX_MOTD_CHUNK ); chunk[MAX_MOTD_CHUNK] = 0; // strncpy doesn't always append the null terminator } char_count += strlen( chunk ); if ( char_count < MAX_MOTD_LENGTH ) pFileList = aFileList + char_count; else *pFileList = 0; MESSAGE_BEGIN( MSG_ONE, gmsgMOTD, NULL, client ); WRITE_BYTE( *pFileList ? FALSE : TRUE ); // FALSE means there is still more message to come WRITE_STRING( chunk ); MESSAGE_END(); } FREE_FILE( aFileList ); }
[ "joropito@23c7d628-c96c-11de-a380-73d83ba7c083" ]
[ [ [ 1, 1614 ] ] ]
3cac62c8f194de1f72a65dfb820384967548a0b9
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/src/pthread_once.cpp
c57818a0944933f37810fae51ba91d141a5622d1
[]
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,433
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 mutexes on Symbian * */ #include "mutextypes.h" EXPORT_C int pthread_once(pthread_once_t * once_control, thread_init_routine init_routine) { #ifndef NOUSE_INTERNALS void* tlsPtr; // Get the TLS pointer tlsPtr = _pthread_getTls(); if(!tlsPtr) { return ENOMEM; } #endif if(!once_control || !init_routine) { return EINVAL; } if (*once_control == _EDone) { return 0; } #ifndef NOUSE_INTERNALS _pthread_atomicMutexLock(tlsPtr); #endif if(*once_control == _EDone) { #ifndef NOUSE_INTERNALS _pthread_atomicMutexUnlock(tlsPtr); #endif return 0; } *once_control = _EDoing; init_routine(); *once_control = _EDone; #ifndef NOUSE_INTERNALS _pthread_atomicMutexUnlock(tlsPtr); #endif return 0; } // End of File
[ "none@none" ]
[ [ [ 1, 69 ] ] ]
6319314415865c1a5ab4c316ee2e5c563d060d37
7396ad6c1980808aba6716515ecf28390786d879
/codigos/Linhas.h
9618a00f7b44d8978609d71b7f1483fe63606ecd
[]
no_license
dairansc/linhasmetro
9ee1a422a713d0ae9ad46402f67fef6f2aa4c162
2edcb9ffd7b6e7f7aaf098ba283bfa6bec17fa77
refs/heads/master
2021-01-10T12:44:18.286271
2010-10-07T19:36:32
2010-10-07T19:36:32
50,470,441
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
h
//#include <iostream> //#include <string> //#include "Conexoes.h" //using namespace std; class Linhas { public: void inicializa (string , GLcor); void add_conexao (int, int, int, Conexoes*); void add_trem (Trens*, Conexoes*); void desenha(Conexoes*); int id; string nome; int conexoes[LINHA_CON_QNT_MAX]; int qnt_conexoes; int trens[LINHA_TREM_QNT_MAX]; int qnt_trens; GLcor cor; }; void Linhas::desenha(Conexoes *cons){ /*for (int i = 0; i<this->qnt_conexoes; i++){ cons[this->conexoes[i]].desenha(); }*/ } void Linhas::inicializa(string n, GLcor c){ this->id = LINHA_QNT; LINHA_QNT++; this->nome = n; this->cor = c; this->qnt_conexoes = 0; this->qnt_trens = 0; cout << "Nova Linha " << this->nome << "["<< this->id << "]" << endl; } void Linhas::add_conexao(int de, int para, int tipoConexao, Conexoes *cons){ this->conexoes[this->qnt_conexoes] = CON_QNT; this->qnt_conexoes++; cons[CON_QNT].inicializa(de, para, tipoConexao, this->cor); cout << "\tLinha " << this->nome << "[" << this->id << "], com conexões: "; for (int i = 0; i<this->qnt_conexoes; i++){ cout << this->conexoes[i] << " "; } cout << endl; } void Linhas::add_trem(Trens *t, Conexoes *cons){ this->trens[this->qnt_trens] = TREM_QNT; this->qnt_trens++; t[TREM_QNT].inicializa(this->id, cons[ this->conexoes[0] ].de_plataforma_id, this->cor); cout << "\tLinha " << this->nome << "[" << this->id << "], com trens: "; for (int i = 0; i<this->qnt_trens; i++){ cout << this->trens[i] << " "; } cout << endl; } /* void chama_ini(de, para, tipoConexao, this->cor){ }*/
[ [ [ 1, 65 ] ] ]
5b2e875e813000c57bb997d6ef5b592d7cfc3730
58ef4939342d5253f6fcb372c56513055d589eb8
/CloverDemo/source/ImageLib/src/LMSvgUtil.cpp
aaeb060de4c5c992ea31de1772e19382019dd9a9
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,358
cpp
#include <aknutils.h> #include <COEMAIN.H> #include <eikapp.h> #include <eikenv.h> #include "LMSvgUtil.h" #include "Utils.h" #ifdef EKA2 #include "IconFileProvider.h" #include "CloverDemoDocument.h" #endif _LIT(KIconBasename, "CloverDemo.mbm"); LMSvgUtil::~LMSvgUtil() { } LMSvgUtil::LMSvgUtil() { } TInt LMSvgUtil::SetIconSize(CFbsBitmap* aBitmap, const TSize& aSize) { #ifdef EKA2 return AknIconUtils::SetSize(aBitmap, aSize, EAspectRatioNotPreserved); #else //aBitmap->Resize(aSize); return 0; #endif } CFbsBitmap* LMSvgUtil::GetImageFromResourceL(TInt aId) { TFileName filename; CFbsBitmap* image= NULL; GetAppPath(filename); #ifdef __WINS__ filename[0] = 'z'; #endif #ifdef EKA2 CCloverDemoDocument* document = (CCloverDemoDocument*)((CEikAppUi*)(CEikonEnv::Static()->AppUi()))->Document(); CIconFileProvider* iconProvider = document->GetIconFileProvider(); if (iconProvider == NULL) { filename.Append(KIconBasename); iconProvider = CIconFileProvider::NewL(CEikonEnv::Static()->FsSession(), filename); CleanupStack::PushL(iconProvider); document->SetIconFileProvider(iconProvider); CleanupStack::Pop(); } image = AknIconUtils::CreateIconL(*iconProvider, aId); image->SetDisplayMode(EColor64K); #else filename.Append( KIconBasename ); image = CEikonEnv::Static()->CreateBitmapL( filename, aId ); #endif return image; } void LMSvgUtil::GetImageAndMaskFormResourceL(CFbsBitmap*& aBitmap, CFbsBitmap*& aBitmapMask, TInt aBitmapId, TInt aMaskId) { TFileName filename; GetAppPath(filename); #ifdef __WINS__ filename[0] = 'z'; #endif #ifdef EKA2 CCloverDemoDocument* document = (CCloverDemoDocument*)((CEikAppUi*)(CEikonEnv::Static()->AppUi()))->Document(); CIconFileProvider* iconProvider = document->GetIconFileProvider(); if (iconProvider == NULL) { filename.Append(KIconBasename); iconProvider = CIconFileProvider::NewL(CEikonEnv::Static()->FsSession(), filename); CleanupStack::PushL(iconProvider); document->SetIconFileProvider(iconProvider); CleanupStack::Pop(); } AknIconUtils::CreateIconL(aBitmap, aBitmapMask, *iconProvider, aBitmapId, aMaskId); aBitmap->SetDisplayMode(EColor64K); //aBitmapMask->SetDisplayMode(EColor64K); #else filename.Append( KIconBasename ); #endif }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 92 ] ] ]
021038f9ed56da9466a5f31d8d93617444679d91
256022d2e1ae66e89ba06804690f5bae09914c86
/pa4/Robot.h
48a7ec4e16f6168db9ab0082e707bf982ed79557
[]
no_license
elingg/cognitive-dissonance
d7a6da49d48cb3119aa20541a9504b2cfc09703b
156a869cf9605632a33e65303fecad09fa625c51
refs/heads/master
2021-01-01T17:57:42.187178
2009-03-21T06:51:21
2009-03-21T06:51:21
40,203,227
0
0
null
null
null
null
UTF-8
C++
false
false
3,155
h
#ifndef _ROBOT_H #define _ROBOT_H #include <vector> #include "Maps.h" using namespace std; /* CS 221 Students */ /* --------------- */ /* Not all of the information in the file is relevent to what you are * doing. Probably the only thing you'd need to know about in this * file is the GetInitialPosition() method in the RobotSimulation * class. */ // an action is basically just a change in coordinates... typedef MapCoord Action; /* LaserArraySensorReading */ /* overglorified array of four doubles representing the distances * that the laser rangefinder found at a given position. */ typedef struct LaserArraySensorReading { double dist[NUM_DIRECTIONS]; } LaserArraySensorReading; /* LogEntry */ /* Stores exactly what the log file gave us... which is the dead * reckoning position, the 'true position', and the laser readings */ typedef struct LogEntry { Point ptDeadReckon; Point ptActual; LaserArraySensorReading lsr; } LogEntry; /* RobotState */ /* basically stores the action that a robot is going to take, and the * sensor readings it recorded at that time. */ typedef struct RobotState { Point deltaPos; Action action; Point ptActual; Point ptDeadReckon; LaserArraySensorReading lsr; } RobotState; /* RobotSimulation */ /* --------------- */ /* The robot simulation class basically is where the history of the * robot is stored. The class is responsible for reading in the log * file. It directly dumps all of that information into the fullLog * vector. We then process this log and place a more useful version * of it inside of the states vector. * * CS 221 students: The only thing you might need from the * RobotSimulation class is the GetInitialPosition() method, which * returns the map coordinates of where the robot starts out. * * It would also be good to understand that these robot "states" * basically store the action the robot thinks it is taking, and the * sensor readings that it recorded at that time. * * You don't need to read the rest of the comments about processing... * go code :) * * In this processing, two things happen: * 1. We only pull every 'logEntriesPerState' number of log entries to * generate one state. We do this because there really are too many * log entries for the robot's history, and each are taken at very * very small time steps. * 2. We calculate an "action" that the robot thinks it is taking to get * from one state to the next. To do this, we simply look at two * states' positions, see what grid cells that would correspond to * inside of a belief map, and find the delta x and delta y that gives * that takes the robot from one state to the next. */ class RobotSimulation { protected: vector<LogEntry*> fullLog; MapCoord initialPosition; public: RobotSimulation(){} vector<RobotState*> states; bool ReadLogFile(const char *filename); bool GenerateStates(int logEntriesPerState, BeliefMap *bmap); MapCoord GetInitialPosition() const { return initialPosition; }; }; #endif
[ "elingg@257f2f30-e9bf-11dd-b00f-9fabb4b2ff13" ]
[ [ [ 1, 100 ] ] ]
17a02ab61beb2156698ba4322ba22ce874b26dcf
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/test/test/test_tools_test.cpp
e54c3813801bd4f6dd532e5596a586c6c0218659
[ "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
23,944
cpp
// (C) Copyright Gennadiy Rozental 2001-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/test for the library home page. // // File : $RCSfile: test_tools_test.cpp,v $ // // Version : $Revision: 1.34 $ // // Description : tests all Test Tools but output_test_stream // *************************************************************************** // Boost.Test #include <boost/test/unit_test.hpp> #include <boost/test/unit_test_result.hpp> using namespace boost::unit_test; using boost::test_toolbox::extended_predicate_value; // BOOST #include <boost/bind.hpp> // STL #include <iostream> #include <iomanip> #include <list> #include <typeinfo> #include <cassert> //____________________________________________________________________________// #define CHECK_TOOL_USAGE( tool_usage, check ) \ { \ boost::test_toolbox::output_test_stream output; \ \ unit_test_log::instance().set_log_stream( output ); \ { unit_test_result_saver saver; \ tool_usage; \ } \ unit_test_log::instance().set_log_stream( std::cout ); \ BOOST_CHECK( check ); \ } //____________________________________________________________________________// #define CHECK_CRITICAL_TOOL_USAGE( tool_usage, nothrow_check, throw_check ) \ { \ boost::test_toolbox::output_test_stream output; \ \ unit_test_log::instance().set_log_stream( output ); \ try { \ { unit_test_result_saver saver; \ tool_usage; \ } \ unit_test_log::instance().set_log_stream( std::cout ); \ BOOST_CHECK( nothrow_check ); \ } catch( boost::test_toolbox::tt_detail::test_tool_failed const&) { \ unit_test_log::instance().set_log_stream( std::cout ); \ BOOST_CHECK( throw_check ); \ } \ } //____________________________________________________________________________// char set_unix_slash( char in ) { return in == '\\' ? '/' : in; } static std::string const& normalize_file_name( char const* f ) { static std::string buffer; buffer = f; std::transform( buffer.begin(), buffer.end(), buffer.begin(), &set_unix_slash ); return buffer; } #ifdef BOOST_TEST_SHIFTED_LINE #define CHECK_PATTERN( msg, shift ) \ (boost::wrap_stringstream().ref() << normalize_file_name( __FILE__ ) << "(" << (__LINE__-shift) << "): " << msg).str() #else #define CHECK_PATTERN( msg, shift ) \ (boost::wrap_stringstream().ref() << normalize_file_name( __FILE__ ) << "(" << __LINE__ << "): " << msg).str() #endif //____________________________________________________________________________// class bool_convertible { struct Tester {}; public: operator Tester*() { return static_cast<Tester*>( 0 ) + 1; } }; void test_BOOST_CHECK() { #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); CHECK_TOOL_USAGE( BOOST_CHECK( true ), output.is_empty() ); bool_convertible bc; CHECK_TOOL_USAGE( BOOST_CHECK( bc ), output.is_empty() ); CHECK_TOOL_USAGE( BOOST_CHECK( false ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test false failed\n", 2 ) ) ); CHECK_TOOL_USAGE( BOOST_CHECK( 1==2 ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test 1==2 failed\n", 2 ) ) ); int i=2; CHECK_TOOL_USAGE( BOOST_CHECK( i==1 ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test i==1 failed\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_successful_tests ); CHECK_TOOL_USAGE( BOOST_CHECK( i==2 ), output.is_equal( CHECK_PATTERN( "info: test i==2 passed\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_all_errors ); } //____________________________________________________________________________// void test_BOOST_REQUIRE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_REQUIRE" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( true ), true, false ); CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( false ), false, true ); int j = 3; CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( j > 5 ), false, output.is_equal( CHECK_PATTERN( "fatal error in " TEST_CASE_NAME ": test j > 5 failed\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_successful_tests ); CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE( j < 5 ), output.is_equal( CHECK_PATTERN( "info: test j < 5 passed\n", 1 ) ) , false ); unit_test_log::instance().set_log_threshold_level( log_all_errors ); } //____________________________________________________________________________// struct A { friend std::ostream& operator<<( std::ostream& str, A const& a ) { str << "struct A"; return str;} }; void test_BOOST_MESSAGE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_REQUIRE" << '\"' << unit_test_log::instance().set_log_threshold_level( log_messages ); CHECK_TOOL_USAGE( BOOST_MESSAGE( "still testing" ), output.is_equal( "still testing\n" ) ); CHECK_TOOL_USAGE( BOOST_MESSAGE( "1+1=" << 2 ), output.is_equal( "1+1=2\n" ) ); int i = 2; CHECK_TOOL_USAGE( BOOST_MESSAGE( i << "+" << i << "=" << (i+i) ), output.is_equal( "2+2=4\n" ) ); A a = A(); CHECK_TOOL_USAGE( BOOST_MESSAGE( a ), output.is_equal( "struct A\n" ) ); #if !defined(BOOST_NO_STD_LOCALE) && BOOST_WORKAROUND(BOOST_MSVC, >= 1310) CHECK_TOOL_USAGE( BOOST_MESSAGE( std::hex << std::showbase << 20 ), output.is_equal( "0x14\n" ) ); #endif CHECK_TOOL_USAGE( BOOST_MESSAGE( std::setw( 4 ) << 20 ), output.is_equal( " 20\n" ) ); } //____________________________________________________________________________// void test_BOOST_WARN() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_WARN" << '\"' << unit_test_log::instance().set_log_threshold_level( log_warnings ); CHECK_TOOL_USAGE( BOOST_WARN( sizeof(int) == sizeof(short) ), output.is_equal( CHECK_PATTERN( "warning in " TEST_CASE_NAME ": condition sizeof(int) == sizeof(short) is not satisfied\n", 3 ) ) ); } //____________________________________________________________________________// class bad_func_container : public test_case { public: bad_func_container() : test_case( "test_BOOST_CHECKPOINT", true, 1 ) {} void do_run() { throw "some error"; } } bad; void test_BOOST_CHECKPOINT() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECKPOINT" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); BOOST_CHECKPOINT( "Going to do a silly things" ); CHECK_TOOL_USAGE( bad.run(), output.is_equal( (boost::wrap_stringstream().ref() << "Exception in " TEST_CASE_NAME ": C string: some error\n" << normalize_file_name( __FILE__ ) << "(" << 270 << "): " << "last checkpoint: Going to do a silly things\n").str() ) ); } //____________________________________________________________________________// void test_BOOST_WARN_MESSAGE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_WARN_MESSAGE" << '\"' << unit_test_log::instance().set_log_threshold_level( log_warnings ); CHECK_TOOL_USAGE( BOOST_WARN_MESSAGE( sizeof(int) == sizeof(short), "memory won't be used efficiently" ), output.is_equal( CHECK_PATTERN( "warning in " TEST_CASE_NAME ": memory won't be used efficiently\n", 2 ) ) ); int obj_size = 33; CHECK_TOOL_USAGE( BOOST_WARN_MESSAGE( obj_size <= 8, "object size " << obj_size << " too big to be efficiently passed by value" ), output.is_equal( CHECK_PATTERN( "warning in " TEST_CASE_NAME ": object size 33 too big to be efficiently passed by value\n", 3 ) ) ); } //____________________________________________________________________________// void test_BOOST_CHECK_MESSAGE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_MESSAGE" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); CHECK_TOOL_USAGE( BOOST_CHECK_MESSAGE( 2+2 == 5, "Well, may be that what I belive in" ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": Well, may be that what I belive in\n", 2 ) ) ); } //____________________________________________________________________________// void test_BOOST_REQUIRE_MESSAGE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_REQUIRE_MESSAGE" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_MESSAGE( false, "Here we should stop" ), false, output.is_equal( CHECK_PATTERN( "fatal error in " TEST_CASE_NAME ": Here we should stop" << "\n", 3 ) ) ); } //____________________________________________________________________________// struct B { B( int i ) : m_i( i ) {} friend bool operator==( B const& b1, B const& b2 ) { return b1.m_i == b2.m_i; } friend std::ostream& operator<<( std::ostream& str, B const& b ) { str << "B(" << b.m_i << ")"; return str; } int m_i; }; void test_BOOST_CHECK_EQUAL() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_EQUAL" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); int i=1; int j=2; CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL( i, j ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test i == j failed [1 != 2]\n", 2 ) ) ); char const* str1 = "test1"; char const* str2 = "test12"; CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL( str1, str2 ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test str1 == str2 failed [test1 != test12]\n", 2 ) ) ); str1 = NULL; str2 = NULL; CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL( str1, str2 ), output.is_empty() ); str1 = "test"; str2 = NULL; CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL( str1, str2 ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test str1 == str2 failed [test != null string]\n", 2 ) ) ); B b1(1); B b2(2); CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL( b1, b2 ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test b1 == b2 failed [B(1) != B(2)]\n", 2 ) ) ); } //____________________________________________________________________________// bool is_even( int i ) { return i%2 == 0; } int foo( int arg, int mod ) { return arg % mod; } BOOST_TEST_DONT_PRINT_LOG_VALUE( std::list<int> ) extended_predicate_value compare_lists( std::list<int> const& l1, std::list<int> const& l2 ) { if( l1.size() != l2.size() ) { extended_predicate_value res( false ); res.p_message.reset( new boost::wrap_stringstream ); *res.p_message << " Different sizes [" << l1.size() << "!=" << l2.size() << "]"; return res; } return true; } void test_BOOST_CHECK_PREDICATE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_PREDICATE" << '\"' << CHECK_TOOL_USAGE( BOOST_CHECK_PREDICATE( &is_even, 1, (14) ), output.is_empty() ); int i = 17; CHECK_TOOL_USAGE( BOOST_CHECK_PREDICATE( &is_even, 1, (i) ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test &is_even(i) failed for 17\n", 2 ) ) ); CHECK_TOOL_USAGE( BOOST_CHECK_PREDICATE( std::not_equal_to<int>(), 2, (i,17) ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test std::not_equal_to<int>()(i, 17) failed for (17, 17)\n", 2 ) ) ); CHECK_TOOL_USAGE( BOOST_CHECK_PREDICATE( boost::bind( &is_even, boost::bind( &foo, _1, _2 ) ), 2, (i,15) ), output.is_empty() ); std::list<int> l1, l2, l3; l1.push_back( 1 ); l3.push_back( 1 ); l1.push_back( 2 ); l3.push_back( 3 ); CHECK_TOOL_USAGE( BOOST_CHECK_PREDICATE( &compare_lists, 2, (l1,l2) ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test &compare_lists(l1, l2) failed for (, ) Different sizes [2!=0]\n", 2 ) ) ); } //____________________________________________________________________________// void test_BOOST_REQUIRE_PREDICATE() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_REQUIRE_PREDICATE" << '\"' << int arg1 = 1; int arg2 = 2; CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_PREDICATE( std::less_equal<int>(), 2, ( arg1, arg2 ) ), output.is_empty(), false ); CHECK_CRITICAL_TOOL_USAGE( BOOST_REQUIRE_PREDICATE( std::less_equal<int>(), 2, ( arg2, arg1 ) ), false, output.is_equal( CHECK_PATTERN( "fatal error in " TEST_CASE_NAME ": test std::less_equal<int>()(arg2, arg1) " "failed for (" << arg2 << ", " << arg1 << ")\n", 4 ) ) ); } //____________________________________________________________________________// void test_BOOST_ERROR() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_ERROR" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); CHECK_TOOL_USAGE( BOOST_ERROR( "Fail to miss an error" ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": Fail to miss an error\n", 2 ) ) ); CHECK_CRITICAL_TOOL_USAGE( BOOST_FAIL( "No! No! Show must go on." ), false, output.is_equal( CHECK_PATTERN( "fatal error in " TEST_CASE_NAME ": No! No! Show must go on.\n", 2 ) ) ); } //____________________________________________________________________________// struct my_exception { explicit my_exception( int ec = 0 ) : m_error_code( ec ) {} int m_error_code; }; bool is_critical( my_exception const& ex ) { return ex.m_error_code < 0; } void test_BOOST_CHECK_THROW() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_THROW" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); int i=0; CHECK_TOOL_USAGE( BOOST_CHECK_THROW( i++, my_exception ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": exception my_exception is expected\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_successful_tests ); CHECK_TOOL_USAGE( BOOST_CHECK_THROW( throw my_exception(), my_exception ), output.is_equal( CHECK_PATTERN( "info: exception my_exception is caught\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_all_errors ); } //____________________________________________________________________________// void test_BOOST_CHECK_EXCEPTION() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_EXCEPTION" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); CHECK_TOOL_USAGE( BOOST_CHECK_EXCEPTION( throw my_exception( 1 ), my_exception, is_critical ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": incorrect exception my_exception is caught\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_successful_tests ); CHECK_TOOL_USAGE( BOOST_CHECK_EXCEPTION( throw my_exception( -1 ), my_exception, is_critical ), output.is_equal( CHECK_PATTERN( "info: incorrect exception my_exception is caught\n", 2 ) ) ); unit_test_log::instance().set_log_threshold_level( log_all_errors ); } //____________________________________________________________________________// void test_BOOST_CHECK_NO_THROW() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_NO_THROW" << '\"' << int i=0; CHECK_TOOL_USAGE( BOOST_CHECK_NO_THROW( i++ ), output.is_empty() ); CHECK_TOOL_USAGE( BOOST_CHECK_NO_THROW( throw my_exception() ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": exception was thrown by throw my_exception()\n", 2 ) ) ); } //____________________________________________________________________________// void test_BOOST_CHECK_EQUAL_COLLECTIONS() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_EQUAL_COLLECTIONS" << '\"' << unit_test_log::instance().set_log_threshold_level( log_all_errors ); int pattern [] = { 1, 2, 3, 4, 5, 6, 7 }; std::list<int> testlist; testlist.push_back( 1 ); testlist.push_back( 2 ); testlist.push_back( 4 ); // 3 testlist.push_back( 4 ); testlist.push_back( 5 ); testlist.push_back( 7 ); // 6 testlist.push_back( 7 ); #if !defined(__BORLANDC__) CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL_COLLECTIONS( testlist.begin(), testlist.end(), pattern ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test {testlist.begin(), testlist.end()} == {pattern, ...} failed in a position 2 [4 != 3]\n" << normalize_file_name( __FILE__ ) << "(" << __LINE__ << "): " << "error in " TEST_CASE_NAME ": test {testlist.begin(), testlist.end()} == {pattern, ...} failed in a position 5 [7 != 6]\n" , 6 ) ) ); #else CHECK_TOOL_USAGE( BOOST_CHECK_EQUAL_COLLECTIONS( testlist.begin(), testlist.end(), pattern ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test {testlist.begin(), testlist.end()} == {pattern, ...} failed in a position 2 [4 != 3]\n" << normalize_file_name( __FILE__ ) << "(" << (__LINE__-6) << "): " << "error in " TEST_CASE_NAME ": test {testlist.begin(), testlist.end()} == {pattern, ...} failed in a position 5 [7 != 6]\n" , 6 ) ) ); #endif } //____________________________________________________________________________// void test_BOOST_IS_DEFINED() { #define SYMBOL1 #define SYMBOL2 std::cout #define ONE_ARG( arg ) arg #define TWO_ARG( arg1, arg2 ) BOOST_JOIN( arg1, arg2 ) BOOST_CHECK( BOOST_IS_DEFINED(SYMBOL1) ); BOOST_CHECK( BOOST_IS_DEFINED(SYMBOL2) ); BOOST_CHECK( !BOOST_IS_DEFINED( SYMBOL3 ) ); BOOST_CHECK( BOOST_IS_DEFINED( ONE_ARG(arg1) ) ); BOOST_CHECK( !BOOST_IS_DEFINED( ONE_ARG1(arg1) ) ); BOOST_CHECK( BOOST_IS_DEFINED( TWO_ARG(arg1,arg2) ) ); BOOST_CHECK( !BOOST_IS_DEFINED( TWO_ARG1(arg1,arg2) ) ); } //____________________________________________________________________________// void test_BOOST_BITWISE_EQUAL() { #undef TEST_CASE_NAME #define TEST_CASE_NAME << '\"' << "test_BOOST_BITWISE_EQUAL" << '\"' << CHECK_TOOL_USAGE( BOOST_BITWISE_EQUAL( 0x16, 0x16 ), output.is_empty() ); CHECK_TOOL_USAGE( BOOST_BITWISE_EQUAL( (char)0x06, (char)0x16 ), output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test (char)0x06 =.= (char)0x16 in the position 4 failed\n", 2 ) ) ); CHECK_TOOL_USAGE( BOOST_BITWISE_EQUAL( (char)0x26, (char)0x04 ), output.is_equal( std::string( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test (char)0x26 =.= (char)0x04 in the position 1 failed\n", 4 ) ) .append( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test (char)0x26 =.= (char)0x04 in the position 5 failed\n", 4 ) ) ) ); } //____________________________________________________________________________// test_suite* init_unit_test_suite( int /*argc*/, char* /*argv*/[] ) { test_suite* test = BOOST_TEST_SUITE("Test Tools test"); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK ) ); test->add( BOOST_TEST_CASE( &test_BOOST_REQUIRE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_MESSAGE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_WARN ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECKPOINT ) ); test->add( BOOST_TEST_CASE( &test_BOOST_WARN_MESSAGE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_MESSAGE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_REQUIRE_MESSAGE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_EQUAL ) ); test->add( BOOST_TEST_CASE( &test_BOOST_ERROR ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_THROW ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_NO_THROW ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_EXCEPTION ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_EQUAL_COLLECTIONS ) ); test->add( BOOST_TEST_CASE( &test_BOOST_IS_DEFINED ) ); test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_PREDICATE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_REQUIRE_PREDICATE ) ); test->add( BOOST_TEST_CASE( &test_BOOST_BITWISE_EQUAL ) ); return test; } //____________________________________________________________________________// // *************************************************************************** // Revision History : // // $Log: test_tools_test.cpp,v $ // Revision 1.34 2004/10/05 01:46:33 rogeeff // borland fix // // Revision 1.33 2004/10/01 10:55:43 rogeeff // some test errors workarrounds // // Revision 1.32 2004/06/07 07:34:23 rogeeff // detail namespace renamed // // Revision 1.31 2004/05/27 06:30:48 rogeeff // no message // // Revision 1.30 2004/05/21 06:26:11 rogeeff // licence update // // Revision 1.29 2004/05/11 11:05:06 rogeeff // basic_cstring introduced and used everywhere // class properties reworked // namespace names shortened // // Revision 1.28 2003/12/23 13:23:35 johnmaddock // Added patch for gcc2.95.3 (and no new iostreams). // // Revision 1.27 2003/12/01 00:42:38 rogeeff // prerelease cleaning // // *************************************************************************** // EOF
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 743 ] ] ]
4eca77e261c13c17c78d01510a791a6b4178f5ad
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/Scripting/ScriptWrapper.h
23b5d0a0f72ed90d68eb1b3b126284d264e7fc7d
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,659
h
#ifndef SCRIPTWRAPPER_H #define SCRIPTWRAPPER_H extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include "luabind/luabind.hpp" namespace HovUni { /** * The Script Manager. This class functions as a wrapper * around basic Lua-C++ functionality. * @author Dirk Delahaye */ class ScriptWrapper { private: /** * The Lua State. */ lua_State* mLuaState; public: /** * Constructor. */ ScriptWrapper(); /** * Destructor. */ virtual ~ScriptWrapper(); /** * Retrieve the Lua State. * Needed for defining functions in Lua. * @return Pointer to the lua_State object. */ lua_State* getLuaState(); /** * Register a C++ function for use in Lua. In the Lua script, this * function can then be called using the given name. * @param name The function name in the script. * @param function The C++ function to be bound. (Function pointer) */ void registerFunction( std::string name, void (*function)(int)); /** * Execute a function defined in the Lua script. * TODO: This method will just execute a function with integer * return value and no arguments. Maybe add more options or * include template? * @param function The function call in Lua. */ int execute(const std::string function); /** * Load a Lua Script file. * @param filename The location of the Lua script. */ void load(const std::string filename); /** * "Do" a string in the Lua State. * @param theString Do this string. */ void doString(const std::string theString); }; } #endif //SCRIPTWRAPPER_H
[ "dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 74 ] ] ]
017433c25d7d30cc7f8319c73b85aede70e8551c
c1eae8224c4d3d380cc83ff6b218ba2a9df8d687
/Source Codes/LineConner/Main/MeshEigenConner.cpp
2b7846c66b987b938dc3c3a507a1e3435fdf6f26
[]
no_license
pizibing/noise-removal
15bad5c0fe1b3b5fb3f8b775040fc3dfeb48e49b
c087356bfa07305ce7ac6cce8745b1e676d6dc42
refs/heads/master
2016-09-06T17:40:15.754799
2010-03-05T06:47:59
2010-03-05T06:47:59
34,849,474
1
0
null
null
null
null
UTF-8
C++
false
false
1,824
cpp
#include "stdafx.h" #include "MeshEigenConner.h" #include "../Common/watchtime.h" CMeshConner::CMeshConner() { p_comData = new CommonData; p_criPoint = new CriticalPoint(*p_comData); p_drawer = new MeshDrawer(*p_comData); p_removal = new NoiseRemoval(*p_comData); } CMeshConner::~CMeshConner() { if(p_removal) delete p_removal; if(p_drawer) delete p_drawer; if(p_criPoint) delete p_criPoint; if(p_comData) delete p_comData; } void CMeshConner::Attach(MeshModel* pModel) { ASSERT(pModel != NULL); Global::mesh = pModel; Global::p_coord = &(Global::mesh->m_Kernel.GetVertexInfo().GetCoord()); Global::p_adjVtxArray = &(Global::mesh->m_Kernel.GetVertexInfo().GetAdjVertices()); Global::vtxNum = Global::p_coord->size(); Global::faceNum = Global::mesh->m_Kernel.GetFaceInfo().GetIndex().size(); Global::mesh->m_Kernel.GetModelInfo().GetBoundingSphere(Global::bCenter,Global::bRadius); Global::maxLineLength = 2*Global::bRadius; p_comData->clear(); } bool CMeshConner::LoadEigenField(string filename) { SystemWatchTime t; bool rst=p_criPoint->LoadEigenField(filename); t.print_elapsed_time(); return rst; } void CMeshConner::setDrawMode(Global::DrawMode mode) { p_drawer->setMode(mode); } void CMeshConner::Draw() { p_drawer->DrawMesh(); } void CMeshConner::SaveMEConnLine(string filename) { } bool CMeshConner::IsRemoveNoise() { return false; } void CMeshConner::RemoveNoise() { SystemWatchTime t; printf("begin to remove noise...\n"); p_removal->CalPersistence(); p_removal->RemoveNoise(); t.print_elapsed_time(); p_drawer->setBadPaths(p_removal->GetBadPaths()); } void CMeshConner::clear() { if(p_drawer) p_drawer->clear(); if(p_criPoint) p_criPoint->clear(); if(p_comData) p_comData->clear(); }
[ "weihongyu1987@f7207f0a-2814-11df-8e46-3928208ddfa0" ]
[ [ [ 1, 81 ] ] ]
f144f8027865e578c0a2eeaaddc6ca4904b67ca9
51e4aeb0d5e29ae1e8a9d8cf467797da2054b0f1
/src/stateRouter.hpp
82987be9352425938f376798b28ea32e99ef7ac0
[]
no_license
vashero/tachyon-game
b3340272ee58c11077eef077485f8a01e4c81881
5fc2daac314c0b3b19b7336f8eb29d81a5e05729
refs/heads/master
2016-09-09T23:47:14.315285
2009-05-10T17:47:53
2009-05-10T17:47:53
32,647,791
0
0
null
null
null
null
UTF-8
C++
false
false
3,266
hpp
/*============================================================== * Copyright (c) 2009 Blake Fisher. All Rights Reserved. * * This software is released under the BSD License * <http://www.opensource.org/licenses/bsd-license.php> *============================================================== */ #pragma once #include <vector> using namespace std; /** Defines a class that can pass various events to registered listeners based on some state S is the state class SM is the state machine class L is the listener class */ template <class S, class SM, class L> class StateRouter { public: /** The default constructor */ StateRouter() { mStateMachine = NULL; } /** The destructor */ ~StateRouter(){} /** Set the state machine @param sm The state machine that will be used to redirect events */ void set_state_machine(SM *sm) { mStateMachine = sm; } /** Register to receive events when the state machine is in the provided state @param l The listener to receive events @param s The listener will only receive events when the state machine is in this state @return Whether or not the listener was successfully registered */ bool register_listener(L *l, S s) { // Find out if we already have a listener for the passed state if (this->get_state_idx(s) != -1) { // We already have a listener, so fail return false; } // Add to our list of listeners mListeners.push_back(l); mListenerStates.push_back(s); return true; } /** Stop sending frame information to the listener registered on the passed state @param s The state to remove a listener from */ void unregister_listener(S s) { // Find the relevant state int idx = this->get_state_idx(s); // Remove the relevant listener and state if (idx != -1) { mListeners.erase(mListeners.begin() + idx); mListenerStates.erase(mListenerStates.begin() + idx); } } protected: // Variables -------------------- /** The state machine */ SM *mStateMachine; /** Registered listeners */ vector<L*> mListeners; /** The corresponding state of each listener */ vector<S> mListenerStates; // Methods -------------------- /** Get the listener for the passed state @param s The relevant state @return The listener. NULL if there is none */ L *get_listener(S s) { int idx = this->get_state_idx(s); if (idx == -1) { return NULL; } else { return mListeners[idx]; } } L *get_listener() { if (!mStateMachine) { return NULL; } return this->get_listener(mStateMachine->get_current_state()); } /** Get the index into the state that's been registered @param s The relevant state @return An index into our mListeners and mListenerStates vectors. -1 if there is no listener for the passed state */ int get_state_idx(S s) { // Find the relevant state typename vector<S>::iterator foundState; foundState = find(mListenerStates.begin(), mListenerStates.end(), s); if (foundState == mListenerStates.end()) { return -1; } else { return foundState - mListenerStates.begin(); } } };
[ "[email protected]@b90cb52e-2f47-11de-8816-6191455234fe" ]
[ [ [ 1, 134 ] ] ]
21ca1c7d272dd783ea9f0f38146a5d3ab7b61e97
00b979f12f13ace4e98e75a9528033636dab021d
/branches/zfs/tools/noise/src/opt.cc
d4054ce8452751734c95dad5101c998524fbc90f
[]
no_license
BackupTheBerlios/ziahttpd-svn
812e4278555fdd346b643534d175546bef32afd5
8c0b930d3f4a86f0622987776b5220564e89b7c8
refs/heads/master
2016-09-09T20:39:16.760554
2006-04-13T08:44:28
2006-04-13T08:44:28
40,819,288
0
0
null
null
null
null
UTF-8
C++
false
false
188
cc
// // opt.cc for in // // Made by texane // Login <[email protected]> // // Started on Thu Feb 23 09:55:43 2006 texane // Last update Thu Feb 23 09:55:44 2006 texane //
[ "texane@754ce95b-6e01-0410-81d0-8774ba66fe44" ]
[ [ [ 1, 11 ] ] ]
3ba2ff29390d46eac81334349a90dfe784ed5a32
1960e1ee431d2cfd2f8ed5715a1112f665b258e3
/src/util/taskscheduler.cpp
911b9cc6772786846cc34cb55ee087bb62fa0c98
[]
no_license
BackupTheBerlios/bvr20983
c26a1379b0a62e1c09d1428525f3b4940d5bb1a7
b32e92c866c294637785862e0ff9c491705c62a5
refs/heads/master
2021-01-01T16:12:42.021350
2009-11-01T22:38:40
2009-11-01T22:38:40
39,518,214
0
0
null
null
null
null
UTF-8
C++
false
false
4,278
cpp
/* * $Id$ * * A class for handling Windows task. * * Copyright (C) 2009 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 <shlobj.h> #include "util/taskscheduler.h" #include "util/logstream.h" #include "util/guid.h" #include "util/combuffer.h" #include "exception/lasterrorexception.h" #include "exception/comexception.h" #include <sstream> using namespace bvr20983; namespace bvr20983 { namespace util { /** * */ Task::Task(TaskScheduler& taskScheduler) : m_taskScheduler(taskScheduler) { } /** * */ Task::~Task() { } /** * */ void Task::NewTask(LPCTSTR taskName) { THROW_COMEXCEPTION( m_taskScheduler.GetTaskScheduler()->NewWorkItem(taskName,CLSID_CTask,IID_ITask,(LPUNKNOWN*)&m_task) ); } // of Task::NewTask() /** * */ void Task::Commit() { if( !m_task.IsNULL() ) { COMPtr<IPersistFile> pPersistFile; THROW_COMEXCEPTION( m_task->QueryInterface(IID_IPersistFile,(LPVOID*)&pPersistFile) ); THROW_COMEXCEPTION( pPersistFile->Save(NULL,TRUE) ); } // of if } // of Task::Commit() /** * */ TaskScheduler::TaskScheduler() : m_taskScheduler(CLSID_CTaskScheduler,IID_ITaskScheduler,CLSCTX_INPROC_SERVER) { } /** * */ TaskScheduler::~TaskScheduler() { } /** * */ void TaskScheduler::CreateTask(Task& task,LPCTSTR taskName,LPCTSTR parameters,HINSTANCE hDll,LPCTSTR comment) { TCHAR path[MAX_PATH]; ::SHGetFolderPath(NULL,CSIDL_SYSTEM , NULL,SHGFP_TYPE_CURRENT,path); TString rundll32Path(path); rundll32Path += _T("\\rundll32.exe"); ::GetModuleFileName(hDll,path,MAX_PATH); TString completeParameters(path); completeParameters += parameters; task.NewTask(taskName); THROW_COMEXCEPTION( task.GetTask()->SetApplicationName(rundll32Path.c_str()) ); THROW_COMEXCEPTION( task.GetTask()->SetParameters(completeParameters.c_str()) ); THROW_COMEXCEPTION( task.GetTask()->SetFlags(TASK_FLAG_RUN_ONLY_IF_LOGGED_ON) ); //THROW_COMEXCEPTION( task.GetTask()->SetFlags(TASK_FLAG_DISABLED | TASK_FLAG_RUN_ONLY_IF_LOGGED_ON) ); ::SHGetFolderPath(NULL,CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL,SHGFP_TYPE_CURRENT,path); THROW_COMEXCEPTION( task.GetTask()->SetWorkingDirectory(path) ); THROW_COMEXCEPTION( task.GetTask()->SetComment(comment) ); TASK_TRIGGER pTrigger; ::ZeroMemory(&pTrigger, sizeof (TASK_TRIGGER)); // Add code to set trigger structure? pTrigger.wBeginDay =1; // Required pTrigger.wBeginMonth =1; // Required pTrigger.wBeginYear =1999; // Required pTrigger.cbTriggerSize = sizeof (TASK_TRIGGER); pTrigger.wStartHour = 13; pTrigger.TriggerType = TASK_TIME_TRIGGER_DAILY; pTrigger.Type.Daily.DaysInterval = 1; COMPtr<ITaskTrigger> taskTrigger; WORD piNewTrigger=0; THROW_COMEXCEPTION( task.GetTask()->CreateTrigger(&piNewTrigger,&taskTrigger) ); THROW_COMEXCEPTION( taskTrigger->SetTrigger(&pTrigger) ); } // of TaskScheduler::CreateTask() /** * */ void TaskScheduler::RemoveTask(LPCTSTR taskName) { GetTaskScheduler()->Delete(taskName); } // of TaskScheduler::RemoveTask() } // of namespace util } // of namespace bvr20983 /*==========================END-OF-FILE===================================*/
[ "dwachmann@01137330-e44e-0410-aa50-acf51430b3d2" ]
[ [ [ 1, 137 ] ] ]
ee3907be86901194f4c3b3700404dfe67b14c71d
c2abb873c8b352d0ec47757031e4a18b9190556e
/src/MyGUIEngine/src/MyGUI_XmlDocument.cpp
b8a4b1c5b99b036fccdb376b4f310c63fdc3c21c
[]
no_license
twktheainur/vortex-ee
70b89ec097cd1c74cde2b75f556448965d0d345d
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
refs/heads/master
2021-01-10T02:26:21.913972
2009-01-30T12:53:21
2009-01-30T12:53:21
44,046,528
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
17,158
cpp
/*! @file @author Albert Semenov @date 11/2007 @module */ #include "MyGUI_XmlDocument.h" namespace MyGUI { namespace xml { //----------------------------------------------------------------------// // class xmlNodeIterator //----------------------------------------------------------------------// xmlNodeIterator::xmlNodeIterator(VectorNode::iterator _start, VectorNode::iterator _end) : m_first(true), m_current(_start), m_end(_end) { } bool xmlNodeIterator::nextNode() { if (m_current == m_end) return false; else if (m_first) { m_first = false; return true; } ++ m_current; if (m_current == m_end) return false; return true; } bool xmlNodeIterator::nextNode(const std::string & _name) { while (nextNode()) { if ((*m_current)->getName() == _name) return true; }; return false; } //----------------------------------------------------------------------// // class xmlNode //----------------------------------------------------------------------// xmlNode::xmlNode(const std::string &_name, xmlNodePtr _parent, xmlNodeType _type, const std::string & _body) : mName(_name), mBody(_body), mParent(_parent), mType(_type) { } xmlNode::~xmlNode() { for (VectorNode::iterator iter=mChilds.begin(); iter!=mChilds.end(); ++iter) { delete *iter; } mChilds.clear(); } void xmlNode::save(std::ofstream & _stream, size_t _level) { // сначала табуляции намутим for (size_t tab=0; tab<_level; ++tab) _stream << " "; // теперь заголовок тега if (mType == XML_NODE_TYPE_INFO) _stream << "<?"; else _stream << "<"; _stream << mName; for (VectorAttributes::iterator iter = mAttributes.begin(); iter != mAttributes.end(); ++iter) { _stream << " " << iter->first << "=\"" << iter->second << "\""; } bool empty = mChilds.empty(); // если детей нет то закрываем if (empty && mBody.empty()) { if (mType == XML_NODE_TYPE_INFO) _stream << "?>\n"; else _stream << "/>\n"; } else { _stream << ">"; if (!empty) _stream << "\n"; // если есть тело то сначало оно if (!mBody.empty()) { if (!empty) { for (size_t tab=0; tab<=_level; ++tab) _stream << " "; _stream << mBody << "\n"; } else _stream << mBody; } // если есть детишки путь сохранятся for (size_t child=0; child<mChilds.size(); child++) { mChilds[child]->save(_stream, _level + 1); } if (!empty) {for (size_t tab=0; tab<_level; ++tab) _stream << " ";} _stream << "</" << mName << ">\n"; } } xmlNodePtr xmlNode::createChild(const std::string & _name, const std::string & _body) { xmlNodePtr node = new xmlNode(_name, this, XML_NODE_TYPE_NORMAL, _body); mChilds.push_back(node); return node; } void xmlNode::clear() { for (VectorNode::iterator iter = mChilds.begin(); iter != mChilds.end(); ++iter) delete *iter; mChilds.clear(); mBody.clear(); mAttributes.clear(); } bool xmlNode::findAttribute(const std::string & _name, std::string & _value) { for (VectorAttributes::iterator iter=mAttributes.begin(); iter!=mAttributes.end(); ++iter) { if ( (*iter).first == _name) { _value = (*iter).second; return true; } } return false; } std::string xmlNode::findAttribute(const std::string & _name) { for (VectorAttributes::iterator iter=mAttributes.begin(); iter!=mAttributes.end(); ++iter) { if ( (*iter).first == _name) return (*iter).second; } return ""; } //----------------------------------------------------------------------// // class xmlDocument //----------------------------------------------------------------------// xmlDocument::xmlDocument(): mRoot(0), mInfo(0), mLastError(xml::errors::XML_ERROR_NONE), mLastErrorFile(""), mLine(0), mCol(0) { } xmlDocument::~xmlDocument() { clear(); } bool xmlDocument::open(const Ogre::DataStreamPtr& stream) { clear(); mLastErrorFile = stream->getName(); // это текущая строка для разбора std::string line; // это строка из файла std::string read; // текущий узел для разбора xmlNodePtr currentNode = 0; while (false == stream->eof()) { // берем новую строку read = stream->getLine (false); mLine ++; mCol = 0; // потом проверить на многострочных тэгах if (read.empty()) continue; // текущая строка для разбора и то что еще прочитали line += read; // крутимся пока в строке есть теги while (true) { // сначала ищем по угловым скобкам size_t start = find(line, '<'); if (start == line.npos) break; size_t end = find(line, '>', start+1); if (end == line.npos) break; // проверяем на наличее тела size_t body = line.find_first_not_of(" \t<"); if (body < start) { std::string body_str = line.substr(0, start); // текущий символ mCol = body_str.find_first_not_of(" \t"); utility::trim(body_str); if (currentNode != 0) currentNode->addBody(body_str); } // вырезаем наш тэг и парсим if (false == parseTag(currentNode, line.substr(start+1, end-start-1))) { // ошибка установится внутри return false; } // и обрезаем текущую строку разбора line = line.substr(end+1); }; // while (true) }; // while (!stream.eof()) if (currentNode) { mLastError = xml::errors::XML_ERROR_NON_CLOSE_ALL_TAGS; return false; } return true; } bool xmlDocument::open(const std::string & _name) { clear(); std::ifstream stream(_name.c_str()); mLastErrorFile = _name; if (false == stream.is_open()) { mLastError = xml::errors::XML_ERROR_OPEN_FILE; return false; } // это текущая строка для разбора std::string line; // это строка из файла std::string read; // текущий узел для разбора xmlNodePtr currentNode = 0; while (false == stream.eof()) { // берем новую строку std::getline(stream, read); mLine ++; mCol = 0; // потом проверить на многострочных тэгах if (read.empty()) continue; // текущая строка для разбора и то что еще прочитали line += read; // крутимся пока в строке есть теги while (true) { // сначала ищем по угловым скобкам size_t start = find(line, '<'); if (start == line.npos) break; size_t end = find(line, '>', start+1); if (end == line.npos) break; // проверяем на наличее тела size_t body = line.find_first_not_of(" \t<"); if (body < start) { std::string body_str = line.substr(0, start); // текущий символ mCol = body_str.find_first_not_of(" \t"); utility::trim(body_str); if (currentNode != 0) currentNode->addBody(body_str); } // вырезаем наш тэг и парсим if (false == parseTag(currentNode, line.substr(start+1, end-start-1))) { // ошибка установится внутри stream.close(); return false; } // и обрезаем текущую строку разбора line = line.substr(end+1); }; // while (true) }; // while (!stream.eof()) if (currentNode) { mLastError = xml::errors::XML_ERROR_NON_CLOSE_ALL_TAGS; stream.close(); return false; } stream.close(); return true; } // сохраняет файл bool xmlDocument::save(const std::string & _name) { if (!mInfo) { mLastError = xml::errors::XML_ERROR_DOCUMENT_IS_EMPTY; mLastErrorFile = _name; return false; } std::ofstream stream(_name.c_str()); if (!stream.is_open()) { mLastError = xml::errors::XML_ERROR_CREATE_FILE; mLastErrorFile = _name; return false; } // заголовок utf8 stream << (char)0xEF; stream << (char)0xBB; stream << (char)0xBF; mInfo->save(stream, 0); if (mRoot) mRoot->save(stream, 0); stream.close(); return true; } void xmlDocument::clear() { clearInfo(); clearRoot(); mLine = 0; mCol = 0; } const std::string xmlDocument::getLastError() { if (0 == mLastError) return ""; // текстовое описание ошибок static const char * errorNamesString[xml::errors::XML_ERROR_COUNT] = { "XML_ERROR_NONE", "XML_ERROR_OPEN_FILE", "XML_ERROR_CREATE_FILE", "XML_ERROR_BODY_NON_CORRECT", "XML_ERROR_NON_CLOSE_ALL_TAGS", "XML_ERROR_DOCUMENT_IS_EMPTY", "XML_ERROR_CLOSE_TAG_NOT_FOUND_START_TAG", "XML_ERROR_OPEN_CLOSE_NOT_EQVIVALENT", "XML_ERROR_INFO_IS_EXIST", "XML_ERROR_ROOT_IS_EXIST", "XML_ERROR_ATTRIBUTE_NON_CORRECT", }; std::ostringstream stream; stream << "'" << errorNamesString[mLastError] << "' " << mLastErrorFile; if (xml::errors::XML_ERROR_OPEN_FILE != mLastError) stream << ", "<< "line=" << (unsigned int)mLine << " , col=" << (unsigned int)mCol; return stream.str(); } bool xmlDocument::parseTag(xmlNodePtr &_currentNode, std::string _body) { // убераем лишнее utility::trim(_body); if (_body.empty()) { // создаем пустой тег if (_currentNode) _currentNode = _currentNode->createChild(""); else { _currentNode = new xmlNode("", 0); // если это первый то запоминаем if (!mRoot) mRoot = _currentNode; } return true; } char simbol = _body[0]; bool tag_info = false; if (simbol == '!') return true; // проверяем на коментарии if (simbol == '?') { // проверяем на информационный тег tag_info = true; _body.erase(0, 1); // удаляем первый символ } size_t start, end; // проверяем на закрытие тега if (simbol == '/') { if (_currentNode == 0) { // чета мы закрывам а ниче даже и не открыто if (!mRoot) { mLastError = xml::errors::XML_ERROR_CLOSE_TAG_NOT_FOUND_START_TAG; return false; } } // обрезаем имя тэга start = _body.find_first_not_of(" \t", 1); if (start == _body.npos) { // тег пустой _body.clear(); } else { end = _body.find_last_not_of(" \t"); _body = _body.substr(start, end - start+1); } // проверяем соответствие открывающего и закрывающего тегов if (_currentNode->getName() != _body) { mLastError = xml::errors::XML_ERROR_OPEN_CLOSE_NOT_EQVIVALENT; return false; } // а теперь снижаем текущий узел вниз _currentNode = _currentNode->getParent(); } else { // выделяем имя до первого пробела или закрывающего тега std::string cut = _body; start = _body.find_first_of(" \t/?", 1); // << превед if (start != _body.npos) { cut = _body.substr(0, start); _body = _body.substr(start); } else _body.clear(); if (_currentNode) _currentNode = _currentNode->createChild(cut); else { if (tag_info) { // информационный тег if (mInfo) { mLastError = xml::errors::XML_ERROR_INFO_IS_EXIST; return false; } _currentNode = new xmlNode(cut, 0, XML_NODE_TYPE_INFO); mInfo = _currentNode; } else { // рутовый тег if (mRoot) { mLastError = xml::errors::XML_ERROR_ROOT_IS_EXIST; return false; } _currentNode = new xmlNode(cut, 0, XML_NODE_TYPE_NORMAL); mRoot = _currentNode; } } // проверим на пустоту start = _body.find_last_not_of(" \t"); if (start == _body.npos) return true; // сразу отделим закрывающийся тэг bool close = false; if ((_body[start] == '/') || (_body[start] == '?')) { close = true; // не будем резать строку, просто поставим пробел _body[start] = ' '; // проверим на пустоту start = _body.find_last_not_of(" \t"); if (start == _body.npos) { // возвращаем все назад и уходим _currentNode = _currentNode->getParent(); return true; } } // а вот здесь уже в цикле разбиваем на атрибуты while (true) { // ищем равно start = _body.find('='); if (start == _body.npos) { mLastError = xml::errors::XML_ERROR_ATTRIBUTE_NON_CORRECT; return false; } // ищем вторые ковычки end = _body.find('\"', start+1); if (end == _body.npos) { mLastError = xml::errors::XML_ERROR_ATTRIBUTE_NON_CORRECT; return false; } end = _body.find('\"', end+1); if (end == _body.npos) { mLastError = xml::errors::XML_ERROR_ATTRIBUTE_NON_CORRECT; return false; } std::string key = _body.substr(0, start); std::string value = _body.substr(start+1, end-start); // проверка на валидность if (! checkPair(key, value)) { mLastError = xml::errors::XML_ERROR_ATTRIBUTE_NON_CORRECT; return false; } // добавляем пару в узел _currentNode->addAttributes(key, value); // следующий кусок _body = _body.substr(end+1); // в строке не осталось символов start = _body.find_first_not_of(" \t"); if (start == _body.npos) break; mCol += start; }; // был закрывающий тег для текущего тега if (close) { // не проверяем имена, потому что это наш тэг _currentNode = _currentNode->getParent(); } } return true; } bool xmlDocument::checkPair(std::string &_key, std::string &_value) { // в ключе не должно быть ковычек и пробелов utility::trim(_key); if (_key.empty()) return false; size_t start = _key.find_first_of(" \t\"\'"); if (start != _key.npos) return false; // в значении, ковычки по бокам utility::trim(_value); if (_value.size() < 2) return false; if ((_value[0] != '"') || (_value[_value.length()-1] != '"')) return false; _value.erase(0, 1); _value.erase(_value.length() - 1); return true; } // ищет символ без учета ковычек size_t xmlDocument::find(const std::string & _text, char _char, size_t _start) { // ковычки bool kov = false; // буфер для поиска char buff[16] = "\"_\0"; buff[1] = _char; size_t pos = _start; while (true) { pos = _text.find_first_of(buff, pos); // если уже конец, то досвидания if (pos == _text.npos) break; // нашли ковычку else if (_text[pos] == '"') { kov = !kov; pos ++; } // если мы в ковычках, то идем дальше else if (kov) pos ++; // мы не в ковычках else break; }; // while (true) { return pos; } void xmlDocument::clearInfo() { if (mInfo) { delete mInfo; mInfo = 0; } } void xmlDocument::clearRoot() { if (mRoot) { delete mRoot; mRoot = 0; } } xmlNodePtr xmlDocument::createInfo(const std::string & _version, const std::string & _encoding) { clearInfo(); mInfo = new xmlNode("xml", 0, XML_NODE_TYPE_INFO); mInfo->addAttributes("version", _version); mInfo->addAttributes("encoding", _encoding); return mInfo; } xmlNodePtr xmlDocument::createRoot(const std::string & _name) { clearRoot(); mRoot = new xmlNode(_name, 0, XML_NODE_TYPE_NORMAL); return mRoot; } } // namespace xml } // namespace MyGUI
[ "twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83" ]
[ [ [ 1, 600 ] ] ]
9719fecd15fb5ae7657ce8a56b1a0dd8156bee57
68bfdfc18f1345d1ff394b8115681110644d5794
/Examples/Example01/TextureManager.cpp
116431179a4f454e6f82d169a18810cea2739627
[]
no_license
y-gupta/glwar3
43afa1efe475d937ce0439464b165c745e1ec4b1
bea5135bd13f9791b276b66490db76d866696f9a
refs/heads/master
2021-05-28T12:20:41.532727
2010-12-09T07:52:12
2010-12-09T07:52:12
32,911,819
1
0
null
null
null
null
UTF-8
C++
false
false
3,793
cpp
//+----------------------------------------------------------------------------- //| Included files //+----------------------------------------------------------------------------- #include "TextureManager.h" //+----------------------------------------------------------------------------- //| Global objects //+----------------------------------------------------------------------------- TEXTURE_MANAGER TextureManager; //+----------------------------------------------------------------------------- //| Constructor //+----------------------------------------------------------------------------- TEXTURE_MANAGER::TEXTURE_MANAGER() { InvalidTexture = NULL; } //+----------------------------------------------------------------------------- //| Destructor //+----------------------------------------------------------------------------- TEXTURE_MANAGER::~TEXTURE_MANAGER() { Clear(); } //+----------------------------------------------------------------------------- //| Clears all textures //+----------------------------------------------------------------------------- VOID TEXTURE_MANAGER::Clear() { for (INT i=0; i<TextureContainer.GetTotalSize(); i++) { if (TextureContainer.ValidIndex(i)) { delete TextureContainer[i]; } } TextureContainer.Clear(); } //+----------------------------------------------------------------------------- //| Clears all textures including replaceable textures //+----------------------------------------------------------------------------- BOOL TEXTURE_MANAGER::LoadAllReplaceableTextures() { InvalidTexture = InternalLoad("Textures\\BTNtempW.blp"); if (InvalidTexture == NULL) return FALSE; return TRUE; } //+----------------------------------------------------------------------------- //| Clears all textures except for for the replacealbe textures //+----------------------------------------------------------------------------- VOID TEXTURE_MANAGER::UnLoadAllReplaceableTextures() { SAFE_DELETE(InvalidTexture); } //+----------------------------------------------------------------------------- //| Loads a texture //+----------------------------------------------------------------------------- BOOL TEXTURE_MANAGER::Load(const std::string &FileName) { INT Index; TEXTURE* Texture; Index = TextureContainer.GetIndex(FileName); if (Index != INVALID_INDEX) return TRUE; Texture = InternalLoad(FileName); if (Texture == NULL) return FALSE; if (!TextureContainer.Add(FileName, Texture)) { Error.SetMessage("Unable to load \"" + FileName + "\", unable to add texture!"); delete Texture; return FALSE; } return TRUE; } //+----------------------------------------------------------------------------- //| Returns a texture //+----------------------------------------------------------------------------- TEXTURE* TEXTURE_MANAGER::GetTexture(CONST std::string &FileName) { INT Index; Index = TextureContainer.GetIndex(FileName); if (Index == INVALID_INDEX) return InvalidTexture; return TextureContainer[Index]; } //+----------------------------------------------------------------------------- //| Loads a texture //+----------------------------------------------------------------------------- TEXTURE* TEXTURE_MANAGER::InternalLoad(const std::string &FileName) { BUFFER Buffer; TEXTURE* Texture; Texture = new TEXTURE(); if (Texture == NULL) { Error.SetMessage("Unable to load \"" + FileName + "\", memory allocation failed!"); return NULL; } if (!FileLoader.Load(FileName, Buffer)) { delete Texture; return NULL; } if (!ResourceLoader.LoadTexture((*Texture), FileName, Buffer)) { delete Texture; return NULL; } return Texture; }
[ "sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83" ]
[ [ [ 1, 134 ] ] ]
0ae30021700e960252d2ea73c89b3c9625aa0436
842997c28ef03f8deb3422d0bb123c707732a252
/src/uslsext/USDataIOTask.h
ba6585e157701dcc10f0789268ba5def1c9ca41b
[]
no_license
bjorn/moai-beta
e31f600a3456c20fba683b8e39b11804ac88d202
2f06a454d4d94939dc3937367208222735dd164f
refs/heads/master
2021-01-17T11:46:46.018377
2011-06-10T07:33:55
2011-06-10T07:33:55
1,837,561
2
1
null
null
null
null
UTF-8
C++
false
false
950
h
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #ifndef USDATAIOTASK_H #define USDATAIOTASK_H #include <uslsext/USTask.h> #include <uslsext/USData.h> //================================================================// // USDataIOTask //================================================================// class USDataIOTask : public USTask < USDataIOTask > { private: enum { IDLE, LOADING, SAVING, }; STLString mFilename; USData* mData; u32 mState; //----------------------------------------------------------------// void Execute (); public: SET ( cc8*, Filename, mFilename ) GET_SET ( USData*, Data, mData ) //----------------------------------------------------------------// void LoadData ( cc8* filename, USData& target ); void SaveData ( cc8* filename, USData& target ); USDataIOTask (); ~USDataIOTask (); }; #endif
[ [ [ 1, 42 ] ] ]
6e9cd18c933ae730607cadfc39b96653c4986b3d
81e051c660949ac0e89d1e9cf286e1ade3eed16a
/quake3ce/code/game/q_math.cpp
160a43a45d9fb986d1d89e9e7312164659639f32
[]
no_license
crioux/q3ce
e89c3b60279ea187a2ebcf78dbe1e9f747a31d73
5e724f55940ac43cb25440a65f9e9e12220c9ada
refs/heads/master
2020-06-04T10:29:48.281238
2008-11-16T15:00:38
2008-11-16T15:00:38
32,103,416
5
0
null
null
null
null
UTF-8
C++
false
false
40,844
cpp
/* =========================================================================== Copyright (C) 1999-2005 Id Software, Inc. This file is part of Quake III Arena source code. Quake III Arena source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Quake III Arena source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #include "q_shared.h" // // q_math.c -- stateless support routines that are included in each code module vec3_t vec3_origin = {GFIXED_0,GFIXED_0,GFIXED_0}; vec3_t axisDefault[3] = { { GFIXED_1, GFIXED_0, GFIXED_0 }, { GFIXED_0, GFIXED_1, GFIXED_0 }, { GFIXED_0, GFIXED_0, GFIXED_1 } }; avec3_t avec3_origin = {AFIXED_0,AFIXED_0,AFIXED_0}; avec3_t aaxisDefault[3] = { { AFIXED_1, AFIXED_0, AFIXED_0 }, { AFIXED_0, AFIXED_1, AFIXED_0 }, { AFIXED_0, AFIXED_0, AFIXED_1 } }; bvec3_t bvec3_origin = {BFIXED_0,BFIXED_0,BFIXED_0}; bvec3_t baxisDefault[3] = { { BFIXED_1, BFIXED_0, BFIXED_0 }, { BFIXED_0, BFIXED_1, BFIXED_0 }, { BFIXED_0, BFIXED_0, BFIXED_1 } }; vec4_t colorBlack = {GFIXED_0, GFIXED_0, GFIXED_0, GFIXED_1}; vec4_t colorRed = {GFIXED_1, GFIXED_0, GFIXED_0, GFIXED_1}; vec4_t colorGreen = {GFIXED_0, GFIXED_1, GFIXED_0, GFIXED_1}; vec4_t colorBlue = {GFIXED_0, GFIXED_0, GFIXED_1, GFIXED_1}; vec4_t colorYellow = {GFIXED_1, GFIXED_1, GFIXED_0, GFIXED_1}; vec4_t colorMagenta= {GFIXED_1, GFIXED_0, GFIXED_1, GFIXED_1}; vec4_t colorCyan = {GFIXED_0, GFIXED_1, GFIXED_1, GFIXED_1}; vec4_t colorWhite = {GFIXED_1, GFIXED_1, GFIXED_1, GFIXED_1}; vec4_t colorLtGrey = {GFIXED(0,75), GFIXED(0,75), GFIXED(0,75), GFIXED_1}; vec4_t colorMdGrey = {GFIXED(0,5), GFIXED(0,5), GFIXED(0,5), GFIXED_1}; vec4_t colorDkGrey = {GFIXED(0,25), GFIXED(0,25), GFIXED(0,25), GFIXED_1}; vec4_t g_color_table[8] = { {GFIXED_0, GFIXED_0, GFIXED_0, GFIXED_1}, {GFIXED_1, GFIXED_0, GFIXED_0, GFIXED_1}, {GFIXED_0, GFIXED_1, GFIXED_0, GFIXED_1}, {GFIXED_1, GFIXED_1, GFIXED_0, GFIXED_1}, {GFIXED_0, GFIXED_0, GFIXED_1, GFIXED_1}, {GFIXED_0, GFIXED_1, GFIXED_1, GFIXED_1}, {GFIXED_1, GFIXED_0, GFIXED_1, GFIXED_1}, {GFIXED_1, GFIXED_1, GFIXED_1, GFIXED_1}, }; avec3_t bytedirs[NUMVERTEXNORMALS] = { {-AFIXED(0,525731), AFIXED(0,000000), AFIXED(0,850651)}, {-AFIXED(0,442863), AFIXED(0,238856), AFIXED(0,864188)}, {-AFIXED(0,295242), AFIXED(0,000000), AFIXED(0,955423)}, {-AFIXED(0,309017), AFIXED(0,500000), AFIXED(0,809017)}, {-AFIXED(0,162460), AFIXED(0,262866), AFIXED(0,951056)}, {AFIXED(0,000000), AFIXED(0,000000), AFIXED(1,000000)}, {AFIXED(0,000000), AFIXED(0,850651), AFIXED(0,525731)}, {-AFIXED(0,147621), AFIXED(0,716567), AFIXED(0,681718)}, {AFIXED(0,147621), AFIXED(0,716567), AFIXED(0,681718)}, {AFIXED(0,000000), AFIXED(0,525731), AFIXED(0,850651)}, {AFIXED(0,309017), AFIXED(0,500000), AFIXED(0,809017)}, {AFIXED(0,525731), AFIXED(0,000000), AFIXED(0,850651)}, {AFIXED(0,295242), AFIXED(0,000000), AFIXED(0,955423)}, {AFIXED(0,442863), AFIXED(0,238856), AFIXED(0,864188)}, {AFIXED(0,162460), AFIXED(0,262866), AFIXED(0,951056)}, {-AFIXED(0,681718), AFIXED(0,147621), AFIXED(0,716567)}, {-AFIXED(0,809017), AFIXED(0,309017), AFIXED(0,500000)},{-AFIXED(0,587785), AFIXED(0,425325), AFIXED(0,688191)}, {-AFIXED(0,850651), AFIXED(0,525731), AFIXED(0,000000)},{-AFIXED(0,864188), AFIXED(0,442863), AFIXED(0,238856)}, {-AFIXED(0,716567), AFIXED(0,681718), AFIXED(0,147621)},{-AFIXED(0,688191), AFIXED(0,587785), AFIXED(0,425325)}, {-AFIXED(0,500000), AFIXED(0,809017), AFIXED(0,309017)}, {-AFIXED(0,238856), AFIXED(0,864188), AFIXED(0,442863)}, {-AFIXED(0,425325), AFIXED(0,688191), AFIXED(0,587785)}, {-AFIXED(0,716567), AFIXED(0,681718), -AFIXED(0,147621)}, {-AFIXED(0,500000), AFIXED(0,809017), -AFIXED(0,309017)}, {-AFIXED(0,525731), AFIXED(0,850651), AFIXED(0,000000)}, {AFIXED(0,000000), AFIXED(0,850651), -AFIXED(0,525731)}, {-AFIXED(0,238856), AFIXED(0,864188), -AFIXED(0,442863)}, {AFIXED(0,000000), AFIXED(0,955423), -AFIXED(0,295242)}, {-AFIXED(0,262866), AFIXED(0,951056), -AFIXED(0,162460)}, {AFIXED(0,000000), AFIXED(1,000000), AFIXED(0,000000)}, {AFIXED(0,000000), AFIXED(0,955423), AFIXED(0,295242)}, {-AFIXED(0,262866), AFIXED(0,951056), AFIXED(0,162460)}, {AFIXED(0,238856), AFIXED(0,864188), AFIXED(0,442863)}, {AFIXED(0,262866), AFIXED(0,951056), AFIXED(0,162460)}, {AFIXED(0,500000), AFIXED(0,809017), AFIXED(0,309017)}, {AFIXED(0,238856), AFIXED(0,864188), -AFIXED(0,442863)},{AFIXED(0,262866), AFIXED(0,951056), -AFIXED(0,162460)}, {AFIXED(0,500000), AFIXED(0,809017), -AFIXED(0,309017)},{AFIXED(0,850651), AFIXED(0,525731), AFIXED(0,000000)}, {AFIXED(0,716567), AFIXED(0,681718), AFIXED(0,147621)}, {AFIXED(0,716567), AFIXED(0,681718), -AFIXED(0,147621)}, {AFIXED(0,525731), AFIXED(0,850651), AFIXED(0,000000)}, {AFIXED(0,425325), AFIXED(0,688191), AFIXED(0,587785)}, {AFIXED(0,864188), AFIXED(0,442863), AFIXED(0,238856)}, {AFIXED(0,688191), AFIXED(0,587785), AFIXED(0,425325)}, {AFIXED(0,809017), AFIXED(0,309017), AFIXED(0,500000)}, {AFIXED(0,681718), AFIXED(0,147621), AFIXED(0,716567)}, {AFIXED(0,587785), AFIXED(0,425325), AFIXED(0,688191)}, {AFIXED(0,955423), AFIXED(0,295242), AFIXED(0,000000)}, {AFIXED(1,000000), AFIXED(0,000000), AFIXED(0,000000)}, {AFIXED(0,951056), AFIXED(0,162460), AFIXED(0,262866)}, {AFIXED(0,850651), -AFIXED(0,525731), AFIXED(0,000000)},{AFIXED(0,955423), -AFIXED(0,295242), AFIXED(0,000000)}, {AFIXED(0,864188), -AFIXED(0,442863), AFIXED(0,238856)}, {AFIXED(0,951056), -AFIXED(0,162460), AFIXED(0,262866)}, {AFIXED(0,809017), -AFIXED(0,309017), AFIXED(0,500000)}, {AFIXED(0,681718), -AFIXED(0,147621), AFIXED(0,716567)}, {AFIXED(0,850651), AFIXED(0,000000), AFIXED(0,525731)}, {AFIXED(0,864188), AFIXED(0,442863), -AFIXED(0,238856)}, {AFIXED(0,809017), AFIXED(0,309017), -AFIXED(0,500000)}, {AFIXED(0,951056), AFIXED(0,162460), -AFIXED(0,262866)}, {AFIXED(0,525731), AFIXED(0,000000), -AFIXED(0,850651)}, {AFIXED(0,681718), AFIXED(0,147621), -AFIXED(0,716567)}, {AFIXED(0,681718), -AFIXED(0,147621), -AFIXED(0,716567)},{AFIXED(0,850651), AFIXED(0,000000), -AFIXED(0,525731)}, {AFIXED(0,809017), -AFIXED(0,309017), -AFIXED(0,500000)}, {AFIXED(0,864188), -AFIXED(0,442863), -AFIXED(0,238856)}, {AFIXED(0,951056), -AFIXED(0,162460), -AFIXED(0,262866)}, {AFIXED(0,147621), AFIXED(0,716567), -AFIXED(0,681718)}, {AFIXED(0,309017), AFIXED(0,500000), -AFIXED(0,809017)}, {AFIXED(0,425325), AFIXED(0,688191), -AFIXED(0,587785)}, {AFIXED(0,442863), AFIXED(0,238856), -AFIXED(0,864188)}, {AFIXED(0,587785), AFIXED(0,425325), -AFIXED(0,688191)}, {AFIXED(0,688191), AFIXED(0,587785), -AFIXED(0,425325)}, {-AFIXED(0,147621), AFIXED(0,716567), -AFIXED(0,681718)}, {-AFIXED(0,309017), AFIXED(0,500000), -AFIXED(0,809017)}, {AFIXED(0,000000), AFIXED(0,525731), -AFIXED(0,850651)}, {-AFIXED(0,525731), AFIXED(0,000000), -AFIXED(0,850651)}, {-AFIXED(0,442863), AFIXED(0,238856), -AFIXED(0,864188)}, {-AFIXED(0,295242), AFIXED(0,000000), -AFIXED(0,955423)}, {-AFIXED(0,162460), AFIXED(0,262866), -AFIXED(0,951056)}, {AFIXED(0,000000), AFIXED(0,000000), -AFIXED(1,000000)}, {AFIXED(0,295242), AFIXED(0,000000), -AFIXED(0,955423)}, {AFIXED(0,162460), AFIXED(0,262866), -AFIXED(0,951056)}, {-AFIXED(0,442863), -AFIXED(0,238856), -AFIXED(0,864188)}, {-AFIXED(0,309017), -AFIXED(0,500000), -AFIXED(0,809017)}, {-AFIXED(0,162460), -AFIXED(0,262866), -AFIXED(0,951056)}, {AFIXED(0,000000), -AFIXED(0,850651), -AFIXED(0,525731)}, {-AFIXED(0,147621), -AFIXED(0,716567), -AFIXED(0,681718)}, {AFIXED(0,147621), -AFIXED(0,716567), -AFIXED(0,681718)}, {AFIXED(0,000000), -AFIXED(0,525731), -AFIXED(0,850651)}, {AFIXED(0,309017), -AFIXED(0,500000), -AFIXED(0,809017)}, {AFIXED(0,442863), -AFIXED(0,238856), -AFIXED(0,864188)}, {AFIXED(0,162460), -AFIXED(0,262866), -AFIXED(0,951056)}, {AFIXED(0,238856), -AFIXED(0,864188), -AFIXED(0,442863)}, {AFIXED(0,500000), -AFIXED(0,809017), -AFIXED(0,309017)}, {AFIXED(0,425325), -AFIXED(0,688191), -AFIXED(0,587785)}, {AFIXED(0,716567), -AFIXED(0,681718), -AFIXED(0,147621)}, {AFIXED(0,688191), -AFIXED(0,587785), -AFIXED(0,425325)}, {AFIXED(0,587785), -AFIXED(0,425325), -AFIXED(0,688191)}, {AFIXED(0,000000), -AFIXED(0,955423), -AFIXED(0,295242)}, {AFIXED(0,000000), -AFIXED(1,000000), AFIXED(0,000000)}, {AFIXED(0,262866), -AFIXED(0,951056), -AFIXED(0,162460)}, {AFIXED(0,000000), -AFIXED(0,850651), AFIXED(0,525731)}, {AFIXED(0,000000), -AFIXED(0,955423), AFIXED(0,295242)}, {AFIXED(0,238856), -AFIXED(0,864188), AFIXED(0,442863)}, {AFIXED(0,262866), -AFIXED(0,951056), AFIXED(0,162460)}, {AFIXED(0,500000), -AFIXED(0,809017), AFIXED(0,309017)}, {AFIXED(0,716567), -AFIXED(0,681718), AFIXED(0,147621)}, {AFIXED(0,525731), -AFIXED(0,850651), AFIXED(0,000000)}, {-AFIXED(0,238856), -AFIXED(0,864188), -AFIXED(0,442863)}, {-AFIXED(0,500000), -AFIXED(0,809017), -AFIXED(0,309017)}, {-AFIXED(0,262866), -AFIXED(0,951056), -AFIXED(0,162460)}, {-AFIXED(0,850651), -AFIXED(0,525731), AFIXED(0,000000)}, {-AFIXED(0,716567), -AFIXED(0,681718), -AFIXED(0,147621)}, {-AFIXED(0,716567), -AFIXED(0,681718), AFIXED(0,147621)}, {-AFIXED(0,525731), -AFIXED(0,850651), AFIXED(0,000000)}, {-AFIXED(0,500000), -AFIXED(0,809017), AFIXED(0,309017)}, {-AFIXED(0,238856), -AFIXED(0,864188), AFIXED(0,442863)}, {-AFIXED(0,262866), -AFIXED(0,951056), AFIXED(0,162460)}, {-AFIXED(0,864188), -AFIXED(0,442863), AFIXED(0,238856)}, {-AFIXED(0,809017), -AFIXED(0,309017), AFIXED(0,500000)}, {-AFIXED(0,688191), -AFIXED(0,587785), AFIXED(0,425325)}, {-AFIXED(0,681718), -AFIXED(0,147621), AFIXED(0,716567)}, {-AFIXED(0,442863), -AFIXED(0,238856), AFIXED(0,864188)}, {-AFIXED(0,587785), -AFIXED(0,425325), AFIXED(0,688191)}, {-AFIXED(0,309017), -AFIXED(0,500000), AFIXED(0,809017)}, {-AFIXED(0,147621), -AFIXED(0,716567), AFIXED(0,681718)}, {-AFIXED(0,425325), -AFIXED(0,688191), AFIXED(0,587785)}, {-AFIXED(0,162460), -AFIXED(0,262866), AFIXED(0,951056)}, {AFIXED(0,442863), -AFIXED(0,238856), AFIXED(0,864188)}, {AFIXED(0,162460), -AFIXED(0,262866), AFIXED(0,951056)}, {AFIXED(0,309017), -AFIXED(0,500000), AFIXED(0,809017)}, {AFIXED(0,147621), -AFIXED(0,716567), AFIXED(0,681718)}, {AFIXED(0,000000), -AFIXED(0,525731), AFIXED(0,850651)}, {AFIXED(0,425325), -AFIXED(0,688191), AFIXED(0,587785)}, {AFIXED(0,587785), -AFIXED(0,425325), AFIXED(0,688191)}, {AFIXED(0,688191), -AFIXED(0,587785), AFIXED(0,425325)}, {-AFIXED(0,955423), AFIXED(0,295242), AFIXED(0,000000)}, {-AFIXED(0,951056), AFIXED(0,162460), AFIXED(0,262866)}, {-AFIXED(1,000000), AFIXED(0,000000), AFIXED(0,000000)}, {-AFIXED(0,850651), AFIXED(0,000000), AFIXED(0,525731)}, {-AFIXED(0,955423), -AFIXED(0,295242), AFIXED(0,000000)}, {-AFIXED(0,951056), -AFIXED(0,162460), AFIXED(0,262866)}, {-AFIXED(0,864188), AFIXED(0,442863), -AFIXED(0,238856)}, {-AFIXED(0,951056), AFIXED(0,162460), -AFIXED(0,262866)}, {-AFIXED(0,809017), AFIXED(0,309017), -AFIXED(0,500000)}, {-AFIXED(0,864188), -AFIXED(0,442863), -AFIXED(0,238856)}, {-AFIXED(0,951056), -AFIXED(0,162460), -AFIXED(0,262866)}, {-AFIXED(0,809017), -AFIXED(0,309017), -AFIXED(0,500000)}, {-AFIXED(0,681718), AFIXED(0,147621), -AFIXED(0,716567)}, {-AFIXED(0,681718), -AFIXED(0,147621), -AFIXED(0,716567)}, {-AFIXED(0,850651), AFIXED(0,000000), -AFIXED(0,525731)}, {-AFIXED(0,688191), AFIXED(0,587785), -AFIXED(0,425325)}, {-AFIXED(0,587785), AFIXED(0,425325), -AFIXED(0,688191)}, {-AFIXED(0,425325), AFIXED(0,688191), -AFIXED(0,587785)}, {-AFIXED(0,425325), -AFIXED(0,688191), -AFIXED(0,587785)}, {-AFIXED(0,587785), -AFIXED(0,425325), -AFIXED(0,688191)}, {-AFIXED(0,688191), -AFIXED(0,587785), -AFIXED(0,425325)} }; //============================================================== int Q_rand( int *seed ) { *seed = (69069 * (*seed) + 1); return *seed; } gfixed Q_random( int *seed ) { #ifdef FIXED_IS_FLOAT return (MAKE_GFIXED(Q_rand( seed ) & 65535))/65536.0f; #else return gfixed::FromRep(Q_rand( seed ) & ((1<<gfixed::prec)-1)); #endif } afixed Q_arandom( int *seed ) { #ifdef FIXED_IS_FLOAT return (MAKE_AFIXED(Q_rand( seed ) & 1048575))/1048576.0f; #else return afixed::FromRep(Q_rand( seed ) & ((1<<afixed::prec)-1)); #endif } bfixed Q_brandom( int *seed ) { #ifdef FIXED_IS_FLOAT return (MAKE_BFIXED(Q_rand( seed ) & 65535))/65536.0f; #else return bfixed::FromRep(Q_rand( seed ) & ((1<<bfixed::prec)-1)); #endif } gfixed Q_crandom( int *seed ) { return GFIXED(2,0) * ( Q_random( seed ) - GFIXED(0,5) ); } afixed Q_acrandom( int *seed ) { return AFIXED(2,0) * ( Q_arandom( seed ) - AFIXED(0,5) ); } bfixed Q_bcrandom( int *seed ) { return BFIXED(2,0) * ( Q_brandom( seed ) - BFIXED(0,5) ); } #ifdef __LCC__ int VectorCompare( const bvec3_t v1, const bvec3_t v2 ) { if (v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2]) { return 0; } return 1; } bvec_t FIXED_VEC3LEN( const bvec3_t v ) { return (bvec_t)sqrt (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); } bvec_t FIXED_VEC3LEN_SQ( const bvec3_t v ) { return (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); } bvec_t Distance( const bvec3_t p1, const bvec3_t p2 ) { bvec3_t v; VectorSubtract (p2, p1, v); return FIXED_VEC3LEN( v ); } bvec_t DistanceSquared( const bvec3_t p1, const bvec3_t p2 ) { bvec3_t v; VectorSubtract (p2, p1, v); return v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; } // fast vector normalize routine that does not check to make sure // that length != 0, nor does it return length, uses rsqrt approximation void FIXED_FAST_VEC3NORM( bvec3_t v ) { FIXED_FASTVEC3NORM(v); } void VectorInverse( bvec3_t v ){ v[0] = -v[0]; v[1] = -v[1]; v[2] = -v[2]; } void CrossProduct( const bvec3_t v1, const bvec3_t v2, bvec3_t cross ) { cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; } #endif //======================================================= signed char ClampChar( int i ) { if ( i < -128 ) { return -128; } if ( i > 127 ) { return 127; } return i; } signed short ClampShort( int i ) { if ( i < -32768 ) { return -32768; } if ( i > 0x7fff ) { return 0x7fff; } return i; } // this isn't a real cheap function to call! int DirToByte( bvec3_t dir ) { int i, best; afixed d, bestd; if ( !dir ) { return 0; } avec3_t adir; adir[0]=MAKE_AFIXED(dir[0]);adir[1]=MAKE_AFIXED(dir[1]);adir[2]=MAKE_AFIXED(dir[2]); bestd = AFIXED_0; best = 0; for (i=0 ; i<NUMVERTEXNORMALS ; i++) { d = FIXED_VEC3DOT (adir, bytedirs[i]); if (d > bestd) { bestd = d; best = i; } } return best; } #ifndef FIXED_IS_FLOAT int DirToByte( avec3_t dir ) { int i, best; afixed d, bestd; if ( !dir ) { return 0; } bestd = AFIXED_0; best = 0; for (i=0 ; i<NUMVERTEXNORMALS ; i++) { d = FIXED_VEC3DOT (dir, bytedirs[i]); if (d > bestd) { bestd = d; best = i; } } return best; } #endif void ByteToDir( int b, avec3_t dir ) { if ( b < 0 || b >= NUMVERTEXNORMALS ) { VectorCopy( avec3_origin, dir ); return; } dir[0]=bytedirs[b][0]; dir[1]=bytedirs[b][1]; dir[2]=bytedirs[b][2]; } unsigned ColorBytes3 (gfixed r, gfixed g, gfixed b) { unsigned i; ( (byte *)&i )[0] = FIXED_INT32SCALE(255,r); ( (byte *)&i )[1] = FIXED_INT32SCALE(255,g); ( (byte *)&i )[2] = FIXED_INT32SCALE(255,b); return i; } unsigned ColorBytes4 (gfixed r, gfixed g, gfixed b, gfixed a) { unsigned i; ( (byte *)&i )[0] = FIXED_INT32SCALE(255,r); ( (byte *)&i )[1] = FIXED_INT32SCALE(255,g); ( (byte *)&i )[2] = FIXED_INT32SCALE(255,b); ( (byte *)&i )[3] = FIXED_INT32SCALE(255,a); return i; } gfixed NormalizeColor( const vec3_t in, vec3_t out ) { gfixed max; max = in[0]; if ( in[1] > max ) { max = in[1]; } if ( in[2] > max ) { max = in[2]; } if ( FIXED_IS_ZERO(max) ) { VectorClear( out ); } else { out[0] = in[0] / max; out[1] = in[1] / max; out[2] = in[2] / max; } return max; } /* ===================== PlaneFromPoints Returns false if the triangle is degenrate. The normal will point out of the clock for clockwise ordered points ===================== */ qboolean PlaneFromPoints( avec3_t planenormal, bfixed &planedist, const bvec3_t a, const bvec3_t b, const bvec3_t c ) { bvec3_t d1, d2; bvec3_t tmp; VectorSubtract( b, a, d1 ); VectorSubtract( c, a, d2 ); CrossProduct( d2, d1, tmp); if ( FIXED_IS_ZERO(VectorNormalizeB2A(tmp, planenormal ))) { return qfalse; } planedist = FIXED_VEC3DOT( a, planenormal ); return qtrue; } /* =============== RotatePointAroundVector This is not implemented very well... =============== */ void RotatePointAroundVector( bvec3_t dst, const avec3_t dir, const bvec3_t point, afixed degrees ) { afixed m[3][3]; afixed im[3][3]; afixed zrot[3][3]; afixed tmpmat[3][3]; afixed rot[3][3]; int i; avec3_t vr, vup, vf; afixed rad; vf[0] = dir[0]; vf[1] = dir[1]; vf[2] = dir[2]; PerpendicularVector( vr, dir ); CrossProduct( vr, vf, vup ); m[0][0] = vr[0]; m[1][0] = vr[1]; m[2][0] = vr[2]; m[0][1] = vup[0]; m[1][1] = vup[1]; m[2][1] = vup[2]; m[0][2] = vf[0]; m[1][2] = vf[1]; m[2][2] = vf[2]; memcpy( im, m, sizeof( im ) ); im[0][1] = m[1][0]; im[0][2] = m[2][0]; im[1][0] = m[0][1]; im[1][2] = m[2][1]; im[2][0] = m[0][2]; im[2][1] = m[1][2]; memset( zrot, 0, sizeof( zrot ) ); zrot[0][0] = zrot[1][1] = zrot[2][2] = AFIXED_1; rad = DEG2RAD_A( degrees ); zrot[0][0] = FIXED_COS( rad ); zrot[0][1] = FIXED_SIN( rad ); zrot[1][0] = -FIXED_SIN( rad ); zrot[1][1] = FIXED_COS( rad ); MatrixMultiply( m, zrot, tmpmat ); MatrixMultiply( tmpmat, im, rot ); for ( i = 0; i < 3; i++ ) { dst[i] = rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2]; } } #ifndef FIXED_IS_FLOAT /* =============== RotatePointAroundVector This is not implemented very well... =============== */ void RotatePointAroundVector( avec3_t dst, const avec3_t dir, const avec3_t point, afixed degrees ) { afixed m[3][3]; afixed im[3][3]; afixed zrot[3][3]; afixed tmpmat[3][3]; afixed rot[3][3]; int i; avec3_t vr, vup, vf; afixed rad; vf[0] = dir[0]; vf[1] = dir[1]; vf[2] = dir[2]; PerpendicularVector( vr, dir ); CrossProduct( vr, vf, vup ); m[0][0] = vr[0]; m[1][0] = vr[1]; m[2][0] = vr[2]; m[0][1] = vup[0]; m[1][1] = vup[1]; m[2][1] = vup[2]; m[0][2] = vf[0]; m[1][2] = vf[1]; m[2][2] = vf[2]; memcpy( im, m, sizeof( im ) ); im[0][1] = m[1][0]; im[0][2] = m[2][0]; im[1][0] = m[0][1]; im[1][2] = m[2][1]; im[2][0] = m[0][2]; im[2][1] = m[1][2]; memset( zrot, 0, sizeof( zrot ) ); zrot[0][0] = zrot[1][1] = zrot[2][2] = AFIXED_1; rad = DEG2RAD_A( degrees ); zrot[0][0] = FIXED_COS( rad ); zrot[0][1] = FIXED_SIN( rad ); zrot[1][0] = -FIXED_SIN( rad ); zrot[1][1] = FIXED_COS( rad ); MatrixMultiply( m, zrot, tmpmat ); MatrixMultiply( tmpmat, im, rot ); for ( i = 0; i < 3; i++ ) { dst[i] = rot[i][0] * point[0] + rot[i][1] * point[1] + rot[i][2] * point[2]; } } #endif /* =============== RotateAroundDirection =============== */ void RotateAroundDirection( avec3_t axis[3], afixed yaw ) { // create an arbitrary axis[1] PerpendicularVector( axis[1], axis[0] ); // rotate it around axis[0] by yaw if ( FIXED_NOT_ZERO(yaw) ) { avec3_t temp; VectorCopy( axis[1], temp ); RotatePointAroundVector( axis[1], axis[0], temp, yaw ); } // cross to get axis[2] CrossProduct( axis[0], axis[1], axis[2] ); } void vectoangles( const bvec3_t value1, avec3_t angles ) { bfixed forward; afixed yaw, pitch; if ( FIXED_IS_ZERO(value1[1]) && FIXED_IS_ZERO(value1[0])) { yaw = AFIXED_0; if ( value1[2] > BFIXED_0 ) { pitch = AFIXED(90,0); } else { pitch = AFIXED(270,0); } } else { if ( FIXED_NOT_ZERO(value1[0]) ) { yaw = MAKE_AFIXED( FIXED_ATAN2 ( value1[1], value1[0] )) * AFIXED(180,0) / AFIXED_PI ; } else if ( value1[1] > BFIXED_0 ) { yaw = AFIXED(90,0); } else { yaw = AFIXED(270,0); } if ( yaw < AFIXED_0 ) { yaw += AFIXED(360,0); } forward = FIXED_VEC2LEN(value1); pitch = MAKE_AFIXED( FIXED_ATAN2(value1[2], forward)) * AFIXED(180,0) / AFIXED_PI ; if ( pitch < AFIXED_0 ) { pitch += AFIXED(360,0); } } angles[PITCH] = -pitch; angles[YAW] = yaw; angles[ROLL] = AFIXED_0; } #ifndef FIXED_IS_FLOAT void vectoangles( const avec3_t value1, avec3_t angles ) { afixed forward; afixed yaw, pitch; if ( FIXED_IS_ZERO(value1[1]) && FIXED_IS_ZERO(value1[0])) { yaw = AFIXED_0; if ( value1[2] > AFIXED_0 ) { pitch = AFIXED(90,0); } else { pitch = AFIXED(270,0); } } else { if ( FIXED_NOT_ZERO(value1[0]) ) { yaw = MAKE_AFIXED( FIXED_ATAN2 ( value1[1], value1[0] )) * AFIXED(180,0) / AFIXED_PI ; } else if ( value1[1] > AFIXED_0 ) { yaw = AFIXED(90,0); } else { yaw = AFIXED(270,0); } if ( yaw < AFIXED_0 ) { yaw += AFIXED(360,0); } forward = FIXED_VEC2LEN(value1); pitch = MAKE_AFIXED( FIXED_ATAN2(value1[2], forward)) * AFIXED(180,0) / AFIXED_PI ; if ( pitch < AFIXED_0 ) { pitch += AFIXED(360,0); } } angles[PITCH] = -pitch; angles[YAW] = yaw; angles[ROLL] = AFIXED_0; } #endif /* ================= AnglesToAxis ================= */ void AnglesToAxis( const avec3_t angles, avec3_t axis[3] ) { avec3_t right; // angle vectors returns "right" instead of "y axis" AngleVectors( angles, axis[0], right, axis[2] ); VectorSubtract( avec3_origin, right, axis[1] ); } void AxisClear( avec3_t axis[3] ) { axis[0][0] = AFIXED_1; axis[0][1] = AFIXED_0; axis[0][2] = AFIXED_0; axis[1][0] = AFIXED_0; axis[1][1] = AFIXED_1; axis[1][2] = AFIXED_0; axis[2][0] = AFIXED_0; axis[2][1] = AFIXED_0; axis[2][2] = AFIXED_1; } void AxisCopy( avec3_t in[3], avec3_t out[3] ) { VectorCopy( in[0], out[0] ); VectorCopy( in[1], out[1] ); VectorCopy( in[2], out[2] ); } void ProjectPointOnPlane( bvec3_t dst, const bvec3_t p, const avec3_t normal ) { bfixed d; avec3_t n; afixed inv_denom; inv_denom = FIXED_VEC3LEN_SQ( normal ); if(FIXED_NOT_ZERO(inv_denom)) { inv_denom = AFIXED_1 / inv_denom; } #ifdef _DEBUG else { DebugBreak(); } #endif d = (p[0]*normal[0]+p[1]*normal[1]+p[2]*normal[2]) * inv_denom; n[0] = normal[0] * inv_denom; n[1] = normal[1] * inv_denom; n[2] = normal[2] * inv_denom; dst[0] = p[0] - d * n[0]; dst[1] = p[1] - d * n[1]; dst[2] = p[2] - d * n[2]; } #ifndef FIXED_IS_FLOAT void ProjectPointOnPlane( avec3_t dst, const avec3_t p, const avec3_t normal ) { afixed d; avec3_t n; afixed inv_denom; inv_denom = FIXED_VEC3LEN_SQ( normal ); if(FIXED_NOT_ZERO(inv_denom)) { inv_denom = AFIXED_1 / inv_denom; } #ifdef _DEBUG else { DebugBreak(); } #endif d = (p[0]*normal[0]+p[1]*normal[1]+p[2]*normal[2]) * inv_denom; n[0] = normal[0] * inv_denom; n[1] = normal[1] * inv_denom; n[2] = normal[2] * inv_denom; dst[0] = p[0] - d * n[0]; dst[1] = p[1] - d * n[1]; dst[2] = p[2] - d * n[2]; } #endif /* ================ MakeNormalVectors Given a normalized forward vector, create two other perpendicular vectors ================ */ void MakeNormalVectors( const bvec3_t forward, bvec3_t right, bvec3_t up) { bfixed d; // this rotate and negate guarantees a vector // not colinear with the original right[1] = -forward[0]; right[2] = forward[1]; right[0] = forward[2]; d = FIXED_VEC3DOT (right, forward); FIXED_VEC3MA (right, -d, forward, right); VectorNormalize (right); CrossProduct (right, forward, up); } #ifndef FIXED_IS_FLOAT void MakeNormalVectors( const avec3_t forward, avec3_t right, avec3_t up) { afixed d; // this rotate and negate guarantees a vector // not colinear with the original right[1] = -forward[0]; right[2] = forward[1]; right[0] = forward[2]; d = FIXED_VEC3DOT (right, forward); FIXED_VEC3MA (right, -d, forward, right); VectorNormalize (right); CrossProduct (right, forward, up); } #endif void VectorRotate( bvec3_t in, bvec3_t matrix[3], bvec3_t out ) { out[0] = FIXED_VEC3DOT( in, matrix[0] ); out[1] = FIXED_VEC3DOT( in, matrix[1] ); out[2] = FIXED_VEC3DOT( in, matrix[2] ); } #ifndef FIXED_IS_FLOAT void VectorRotate( bvec3_t in, avec3_t matrix[3], bvec3_t out ) { out[0] = FIXED_VEC3DOT( in, matrix[0] ); out[1] = FIXED_VEC3DOT( in, matrix[1] ); out[2] = FIXED_VEC3DOT( in, matrix[2] ); } void VectorRotate( avec3_t in, avec3_t matrix[3], avec3_t out ) { out[0] = FIXED_VEC3DOT( in, matrix[0] ); out[1] = FIXED_VEC3DOT( in, matrix[1] ); out[2] = FIXED_VEC3DOT( in, matrix[2] ); } #endif //============================================================ /* =============== LerpAngle =============== */ afixed LerpAngle (afixed from, afixed to, afixed frac) { afixed a; if ( (to - from) > AFIXED(180,0) ) { to -= AFIXED(360,0); } if ( (to - from) < -AFIXED(180,0) ) { to += AFIXED(360,0); } a = from + frac * (to - from); return a; } /* ================= AngleSubtract Always returns a value from -180 to 180 ================= */ afixed AngleSubtract( afixed a1, afixed a2 ) { afixed a; a = a1 - a2; while ( a > AFIXED(180,0) ) { a -= AFIXED(360,0); } while ( a < -AFIXED(180,0) ) { a += AFIXED(360,0); } return a; } void AnglesSubtract( avec3_t v1, avec3_t v2, avec3_t v3 ) { v3[0] = AngleSubtract( v1[0], v2[0] ); v3[1] = AngleSubtract( v1[1], v2[1] ); v3[2] = AngleSubtract( v1[2], v2[2] ); } /* ================= AngleNormalize360 returns angle normalized to the range [0 <= angle < 360] ================= */ afixed AngleNormalize360 ( afixed angle ) { return FIXED_MOD_CLAMP(angle,AFIXED(360,0)); } /* ================= AngleNormalize180 returns angle normalized to the range [-180 < angle <= 180] ================= */ afixed AngleNormalize180 ( afixed angle ) { angle = AngleNormalize360( angle ); if ( angle > AFIXED(180,0) ) { angle -= AFIXED(360,0); } return angle; } /* ================= AngleDelta returns the normalized delta from angle1 to angle2 ================= */ afixed AngleDelta ( afixed angle1, afixed angle2 ) { return AngleNormalize180( angle1 - angle2 ); } //============================================================ /* ================= SetPlaneSignbits ================= */ void SetPlaneSignbits (cplane_t *out) { int bits, j; // for fast box on planeside test bits = 0; for (j=0 ; j<3 ; j++) { if (out->normal[j] < AFIXED_0) { bits |= 1<<j; } } out->signbits = bits; } /* ================== BoxOnPlaneSide Returns 1, 2, or 1 + 2 */ /* // this is the slow, general version int BoxOnPlaneSide (bvec3_t emins, bvec3_t emaxs, struct cplane_s *p) { int i; bfixed dist1, dist2; int sides; bvec3_t corners[2]; for (i=0 ; i<3 ; i++) { if (p->normal[i] < AFIXED_0) { corners[0][i] = emins[i]; corners[1][i] = emaxs[i]; } else { corners[1][i] = emins[i]; corners[0][i] = emaxs[i]; } } dist1 = FIXED_VEC3DOT_R (p->normal, corners[0]) - p->dist; dist2 = FIXED_VEC3DOT_R (p->normal, corners[1]) - p->dist; sides = 0; if (dist1 >= BFIXED_0) sides = 1; if (dist2 < BFIXED_0) sides |= 2; return sides; } */ int BoxOnPlaneSide (bvec3_t emins, bvec3_t emaxs, struct cplane_s *p) { bfixed dist1, dist2; int sides; // fast axial cases if (p->type < 3) { if (p->dist <= emins[p->type]) return 1; if (p->dist >= emaxs[p->type]) return 2; return 3; } // general case switch (p->signbits) { case 0: dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; break; case 1: dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; break; case 2: dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; break; case 3: dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; break; case 4: dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; dist2 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; break; case 5: dist1 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emins[2]; dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emaxs[2]; break; case 6: dist1 = p->normal[0]*emaxs[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; dist2 = p->normal[0]*emins[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; break; case 7: dist1 = p->normal[0]*emins[0] + p->normal[1]*emins[1] + p->normal[2]*emins[2]; dist2 = p->normal[0]*emaxs[0] + p->normal[1]*emaxs[1] + p->normal[2]*emaxs[2]; break; default: dist1 = dist2 = BFIXED_0; // shut up compiler break; } sides = 0; if (dist1 >= p->dist) sides = 1; if (dist2 < p->dist) sides |= 2; return sides; } /* ================= RadiusFromBounds ================= */ gfixed RadiusFromBounds( const vec3_t mins, const vec3_t maxs ) { int i; vec3_t corner; gfixed a, b; for (i=0 ; i<3 ; i++) { a = FIXED_ABS( mins[i] ); b = FIXED_ABS( maxs[i] ); corner[i] = (a > b) ? a : b; } return FIXED_VEC3LEN (corner); } #ifndef FIXED_IS_FLOAT bfixed RadiusFromBounds( const bvec3_t mins, const bvec3_t maxs ) { int i; bvec3_t corner; bfixed a, b; for (i=0 ; i<3 ; i++) { a = FIXED_ABS( mins[i] ); b = FIXED_ABS( maxs[i] ); corner[i] = (a > b) ? a : b; } return FIXED_VEC3LEN (corner); } #endif void ClearBounds( vec3_t mins, vec3_t maxs ) { mins[0] = mins[1] = mins[2] = GFIXED(32767,0);//GFIXED(99999,0); maxs[0] = maxs[1] = maxs[2] = -GFIXED(32767,0);//-GFIXED(99999,0); } #ifndef FIXED_IS_FLOAT void ClearBounds( bvec3_t mins, bvec3_t maxs ) { mins[0] = mins[1] = mins[2] = BFIXED(99999,0); maxs[0] = maxs[1] = maxs[2] = -BFIXED(99999,0); } #endif void AddPointToBounds( const vec3_t v, vec3_t mins, vec3_t maxs ) { if ( v[0] < mins[0] ) { mins[0] = v[0]; } if ( v[0] > maxs[0]) { maxs[0] = v[0]; } if ( v[1] < mins[1] ) { mins[1] = v[1]; } if ( v[1] > maxs[1]) { maxs[1] = v[1]; } if ( v[2] < mins[2] ) { mins[2] = v[2]; } if ( v[2] > maxs[2]) { maxs[2] = v[2]; } } #ifndef FIXED_IS_FLOAT void AddPointToBounds( const bvec3_t v, bvec3_t mins, bvec3_t maxs ) { if ( v[0] < mins[0] ) { mins[0] = v[0]; } if ( v[0] > maxs[0]) { maxs[0] = v[0]; } if ( v[1] < mins[1] ) { mins[1] = v[1]; } if ( v[1] > maxs[1]) { maxs[1] = v[1]; } if ( v[2] < mins[2] ) { mins[2] = v[2]; } if ( v[2] > maxs[2]) { maxs[2] = v[2]; } } #endif bfixed VectorNormalizeB2A(const bvec3_t bv, avec3_t av) { lfixed length, lvec[3]; lvec[0]=MAKE_LFIXED(bv[0]);lvec[1]=MAKE_LFIXED(bv[1]);lvec[2]=MAKE_LFIXED(bv[2]); length = FIXED_VEC3LEN(lvec); if (FIXED_NOT_ZERO(length)) { av[0] = MAKE_AFIXED(lvec[0]/length); av[1] = MAKE_AFIXED(lvec[1]/length); av[2] = MAKE_AFIXED(lvec[2]/length); } else { VectorClear( av ); } return MAKE_BFIXED(length); } afixed VectorNormalizeA2B(const avec3_t av, bvec3_t bv) { lfixed length, lvec[3]; lvec[0]=MAKE_LFIXED(av[0]);lvec[1]=MAKE_LFIXED(av[1]);lvec[2]=MAKE_LFIXED(av[2]); length = FIXED_VEC3LEN(lvec); if (FIXED_NOT_ZERO(length)) { bv[0] = MAKE_BFIXED(lvec[0]/length); bv[1] = MAKE_BFIXED(lvec[1]/length); bv[2] = MAKE_BFIXED(lvec[2]/length); } else { VectorClear( bv ); } return MAKE_AFIXED(length); } lfixed VectorNormalizeLong2( const vec3_t v, vec3_t out) { lfixed length, lvec[3]; lvec[0]=MAKE_LFIXED(v[0]);lvec[1]=MAKE_LFIXED(v[1]);lvec[2]=MAKE_LFIXED(v[2]); length = FIXED_VEC3LEN(lvec); if (FIXED_NOT_ZERO(length)) { out[0] = MAKE_GFIXED(lvec[0]/length); out[1] = MAKE_GFIXED(lvec[1]/length); out[2] = MAKE_GFIXED(lvec[2]/length); } else { VectorClear( out ); } return length; } #ifndef FIXED_IS_FLOAT lfixed VectorNormalizeLong2( const avec3_t v, avec3_t out) { lfixed length,lvec[3]; lvec[0]=MAKE_LFIXED(v[0]);lvec[1]=MAKE_LFIXED(v[1]);lvec[2]=MAKE_LFIXED(v[2]); length = FIXED_VEC3LEN(lvec); if (FIXED_NOT_ZERO(length)) { out[0] = MAKE_AFIXED(lvec[0]/length); out[1] = MAKE_AFIXED(lvec[1]/length); out[2] = MAKE_AFIXED(lvec[2]/length); } else { VectorClear( out ); } return length; } lfixed VectorNormalizeLong2( const bvec3_t v, bvec3_t out) { lfixed length,lvec[3]; lvec[0]=MAKE_LFIXED(v[0]);lvec[1]=MAKE_LFIXED(v[1]);lvec[2]=MAKE_LFIXED(v[2]); length = FIXED_VEC3LEN(lvec); if (FIXED_NOT_ZERO(length)) { out[0] = MAKE_BFIXED(lvec[0]/length); out[1] = MAKE_BFIXED(lvec[1]/length); out[2] = MAKE_BFIXED(lvec[2]/length); } else { VectorClear( out ); } return length; } #endif int Q_log2( int val ) { int answer; answer = 0; while ( ( val>>=1 ) != 0 ) { answer++; } return answer; } /* ================= PlaneTypeForNormal ================= */ /* int PlaneTypeForNormal (bvec3_t normal) { if ( normal[0] == GFIXED_1 ) return PLANE_X; if ( normal[1] == GFIXED_1 ) return PLANE_Y; if ( normal[2] == GFIXED_1 ) return PLANE_Z; return PLANE_NON_AXIAL; } */ /* ================ MatrixMultiply ================ */ void MatrixMultiply(bmat_33 &in1, bmat_33 &in2, bmat_33 &out) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + in1[0][2] * in2[2][2]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + in1[1][2] * in2[2][2]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + in1[2][2] * in2[2][2]; } #ifndef FIXED_IS_FLOAT /* ================ MatrixMultiply ================ */ void MatrixMultiply(amat_33 &in1, amat_33 &in2, amat_33 &out) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + in1[0][2] * in2[2][2]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + in1[1][2] * in2[2][2]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + in1[2][2] * in2[2][2]; } void MatrixMultiply(bmat_33 &in1, amat_33 &in2, bmat_33 &out) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + in1[0][2] * in2[2][2]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + in1[1][2] * in2[2][2]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + in1[2][2] * in2[2][2]; } #endif void AngleVectors( const avec3_t angles, avec3_t forward, avec3_t right, avec3_t up) { afixed angle; static afixed sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs angle = angles[YAW] * (AFIXED_PI * AFIXED(2,0) / AFIXED(360,0)); sy = FIXED_SIN(angle); cy = FIXED_COS(angle); angle = angles[PITCH] * (AFIXED_PI * AFIXED(2,0) / AFIXED(360,0)); sp = FIXED_SIN(angle); cp = FIXED_COS(angle); angle = angles[ROLL] * (AFIXED_PI * AFIXED(2,0) / AFIXED(360,0)); sr = FIXED_SIN(angle); cr = FIXED_COS(angle); if (forward) { forward[0] = (cp*cy); forward[1] = (cp*sy); forward[2] = -(sp); } if (right) { right[0] = (((-AFIXED_1)*sr*sp*cy+(-AFIXED_1)*cr*-sy)); right[1] = (((-AFIXED_1)*sr*sp*sy+(-AFIXED_1)*cr*cy)); right[2] = (-AFIXED_1*sr*cp); } if (up) { up[0] = ((cr*sp*cy+-sr*-sy)); up[1] = ((cr*sp*sy+-sr*cy)); up[2] = (cr*cp); } } void AngleVectors( const avec3_t angles, bvec3_t forward, bvec3_t right, bvec3_t up) { afixed angle; static afixed sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs angle = angles[YAW] * (AFIXED_PI * AFIXED(2,0) / AFIXED(360,0)); sy = FIXED_SIN(angle); cy = FIXED_COS(angle); angle = angles[PITCH] * (AFIXED_PI * AFIXED(2,0) / AFIXED(360,0)); sp = FIXED_SIN(angle); cp = FIXED_COS(angle); angle = angles[ROLL] * (AFIXED_PI * AFIXED(2,0) / AFIXED(360,0)); sr = FIXED_SIN(angle); cr = FIXED_COS(angle); if (forward) { forward[0] = MAKE_BFIXED(cp*cy); forward[1] = MAKE_BFIXED(cp*sy); forward[2] = -MAKE_BFIXED(sp); } if (right) { right[0] = MAKE_BFIXED(((-AFIXED_1)*sr*sp*cy+(-AFIXED_1)*cr*-sy)); right[1] = MAKE_BFIXED(((-AFIXED_1)*sr*sp*sy+(-AFIXED_1)*cr*cy)); right[2] = MAKE_BFIXED(-AFIXED_1*sr*cp); } if (up) { up[0] = MAKE_BFIXED((cr*sp*cy+-sr*-sy)); up[1] = MAKE_BFIXED((cr*sp*sy+-sr*cy)); up[2] = MAKE_BFIXED(cr*cp); } } void PerpendicularVector( bvec3_t dst, const bvec3_t src ) { int pos; int i; bfixed minelem = BFIXED_1; avec3_t tempvec; /* ** find the smallest magnitude axially aligned vector */ for ( pos = -1, i = 0; i < 3; i++ ) { if ( pos==-1 || FIXED_ABS( src[i] ) < minelem ) { pos = i; minelem = FIXED_ABS( src[i] ); } } tempvec[0] = tempvec[1] = tempvec[2] = AFIXED_0; tempvec[pos] = AFIXED_1; /* ** project the point onto the plane defined by src */ avec3_t asrc; VectorNormalizeB2A(src,asrc); avec3_t adst; ProjectPointOnPlane( adst, tempvec, asrc ); /* ** normalize the result */ VectorNormalizeA2B( adst, dst ); } #ifndef FIXED_IS_FLOAT void PerpendicularVector( avec3_t dst, const avec3_t src ) { int pos; int i; afixed minelem = AFIXED_1; avec3_t tempvec; /* ** find the smallest magnitude axially aligned vector */ for ( pos = -1, i = 0; i < 3; i++ ) { if ( pos==-1 || FIXED_ABS( src[i] ) < minelem ) { pos = i; minelem = FIXED_ABS( src[i] ); } } tempvec[0] = tempvec[1] = tempvec[2] = AFIXED_0; tempvec[pos] = AFIXED_1; /* ** project the point onto the plane defined by src */ ProjectPointOnPlane( dst, tempvec, src ); /* ** normalize the result */ VectorNormalize( dst ); } #endif
[ "jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac", "crioux@684fc592-8442-0410-8ea1-df6b371289ac" ]
[ [ [ 1, 1355 ], [ 1393, 1467 ] ], [ [ 1356, 1392 ] ] ]
75c0d66c07d94fdf643e12a360e567dbb9d9e17f
378a7d9a253f484e4e8169aa44940ae80ce6ae2c
/Functions.cpp
1004a6c06a9891b02cd0d0f45d30d179e5f6832e
[]
no_license
Konnekt/kLock
38e52f418daa8d84774fa6091a2324fe75f98c82
1414160cb19e81f6a1ac5fbfdf5fc4658123218a
refs/heads/master
2020-12-24T12:04:28.786638
2007-06-05T13:51:02
2007-06-05T13:51:02
3,440,011
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,391
cpp
/* * License - http://www.gnu.org/licenses/lgpl.txt */ #include "StdAfx.h" #include "Includes.h" namespace kLock { //funkcja obsługująca wiadomości głównego okna Konnekta LRESULT CALLBACK konnektWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { static Controller* IMCtrl; if(!IMCtrl) IMCtrl = Controller::getInstance(); if(GETINT(kLock::CFG::lockState) && GETINT(kLock::CFG::lockMainWindow)) { switch(iMsg) { case WM_WINDOWPOSCHANGED: { IMLOG("[konnektWindowProc:] iMsg = WM_WINDOWPOSCHANGED"); //chowamy okienko ShowWindow(hWnd, SW_HIDE); return 0; } case WM_USER+1086: { //sprawdzamy jaki to notify i decydujemy, czy dopuścić dalej, czy nie if(lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP) { IMLOG("[konnektWindowProc:] iMsg = WM_USER+1086, lParam = WM_LBUTTONUP|WM_RBUTTONUP"); IMCtrl->lock(L_Unlock); return 0; } else if(lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN || lParam == WM_MOUSEMOVE || lParam == WM_LBUTTONDBLCLK) { IMLOG("[konnektWindowProc:] iMsg = WM_USER+1086, lParam = WM_LBUTTONDOWN|WM_RBUTTONDOWN|WM_MOUSEMOVE|WM_LBUTTONDBLCLK"); return 0; } break; } } } return CallWindowProc(IMCtrl->konnektWindowOldProc, hWnd, iMsg, wParam, lParam); } }
[ [ [ 1, 50 ] ] ]
2e148a26a782ff95acfe8c14be3732fa835c3ea7
a716154c367938cbfa067df9966a6f8436d45589
/JACC/JACCConv.cpp
400b1705d6c565ee265bc97b1ed6849161a25df2
[]
no_license
alkz/JAC
6150cf35008922fc05ab4c4254e42df7908ea309
7c96440bfb5f43d3afb4091948c2b7e9c029b61e
refs/heads/master
2021-01-01T17:00:53.740880
2011-11-05T14:50:29
2011-11-05T14:50:29
2,713,051
0
0
null
null
null
null
UTF-8
C++
false
false
5,411
cpp
///----------------------------------------------------------------- /// /// @file JACCConv.cpp /// @author Alessandro /// Created: 09/02/2011 1.15.15 /// @section DESCRIPTION /// JACCConv class implementation /// ///------------------------------------------------------------------ #include "JACCConv.h" //Do not add custom headers between //Header Include Start and Header Include End //wxDev-C++ designer will remove them ////Header Include Start #include "Images/Self_JACCConv_XPM.xpm" ////Header Include End //---------------------------------------------------------------------------- // JACCConv //---------------------------------------------------------------------------- //Add Custom Events only in the appropriate block. //Code added in other places will be removed by wxDev-C++ ////Event Table Start BEGIN_EVENT_TABLE(JACCConv,wxFrame) ////Manual Code Start EVT_SOCKET(CLIENT_ID, JACCConv::OnClientEvent) ////Manual Code End EVT_CLOSE(JACCConv::OnClose) EVT_BUTTON(ID_WXBUTTON1,JACCConv::WxButton1Click) END_EVENT_TABLE() ////Event Table End JACCConv::JACCConv(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style) : wxFrame(parent, id, title, position, size, style) { CreateGUIControls(); } JACCConv::~JACCConv() { } void JACCConv::CreateGUIControls() { //Do not add custom code between //GUI Items Creation Start and GUI Items Creation End //wxDev-C++ designer will remove them. //Add the custom code before or after the blocks ////GUI Items Creation Start WxPanel1 = new wxPanel(this, ID_WXPANEL1, wxPoint(-8, 0), wxSize(420, 380)); WxPanel1->SetBackgroundColour(wxColour(192,222,250)); WxButton1 = new wxButton(WxPanel1, ID_WXBUTTON1, wxT("Send"), wxPoint(300, 344), wxSize(75, 20), 0, wxDefaultValidator, wxT("WxButton1")); WxButton1->Enable(false); WxMemo1 = new wxTextCtrl(WxPanel1, ID_WXMEMO1, wxEmptyString, wxPoint(30, 24), wxSize(360, 273), wxTE_MULTILINE, wxDefaultValidator, wxT("WxMemo1")); WxMemo1->SetMaxLength(0); WxMemo1->SetFocus(); WxMemo1->SetInsertionPointEnd(); WxEdit1 = new wxTextCtrl(WxPanel1, ID_WXEDIT1, wxT("Scrivi il tuo messaggio..."), wxPoint(45, 320), wxSize(330, 24), 0, wxDefaultValidator, wxT("WxEdit1")); WxEdit1->Enable(false); SetTitle(wxT("JACC Conversation")); SetIcon(Self_JACCConv_XPM); SetSize(8,8,420,408); Center(); ////GUI Items Creation End } void JACCConv::OnClose(wxCloseEvent& event) { if(sockClient) { sockClient->Notify(false); sockClient->Destroy(); sockClient = NULL; } fMain->n_conv += 1; Destroy(); } void JACCConv::connectToDest(wxString d) { dest = d; WxMemo1->AppendText("Connecting to " + dest + "..."); char sql[255] = "SELECT nickname, IP, state FROM UsersOnLine WHERE nickname = '"; strcat(sql, dest.c_str()); strcat(sql, "';"); mysql_query(fLogin->sock, sql); MYSQL_RES *res = mysql_store_result(fLogin->sock); MYSQL_ROW row; if(res) row = mysql_fetch_row(res); addr.Hostname((wxString)row[1]); addr.Service(CONNECT_PORT); wxSocketClient *sock = new wxSocketClient(); /*char s[9]; itoa((int)addr.Service(), s, 10); wxMessageBox("Mi connetto a: " + addr.Hostname() + ":" + (wxString)s, "yo");*/ if(sock->Connect(addr)) { WxMemo1->AppendText("Connected!\n\n"); SetClient(true, sock); WxEdit1->Enable(); WxButton1->Enable(); } } /* * WxButton1Click */ void JACCConv::WxButton1Click(wxCommandEvent& event) { char tmp[SIZE_BUFFER] = "\0"; strcat(tmp, fLogin->MyUser->nickname); strcat(tmp, ": "); strcat(tmp, WxEdit1->GetValue()); sockClient->Write(tmp, SIZE_BUFFER); WxMemo1->AppendText(wxString(tmp) + "\n"); } void JACCConv::OnClientEvent(wxSocketEvent &event) { if (event.GetSocketEvent() == wxSOCKET_CONNECTION) { wxSocketBase* sock = event.GetSocket(); WxMemo1->AppendText("Connected!\n\n"); SetClient(true, sock); WxEdit1->Enable(); WxButton1->Enable(); } if(event.GetSocketEvent() == wxSOCKET_INPUT) { char tmp[SIZE_BUFFER]; sockClient->Read(tmp, SIZE_BUFFER); WxMemo1->AppendText((wxString)tmp + "\n"); } if(event.GetSocketEvent() == wxSOCKET_LOST) { if(client) WxMemo1->AppendText("\n" + dest + " has disconnected"); else WxMemo1->AppendText("\n" + client_connected + " has disconnected"); } } void JACCConv::SetClient(bool c, wxSocketBase *sock) { client = c; sockClient = sock; sockClient->SetEventHandler(*this, CLIENT_ID); sockClient->SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG); sockClient->Notify(true); char tmp[100]; if(!client) { sockClient->Read(tmp, sizeof(tmp)); WxMemo1->AppendText((wxString)tmp + "\n"); char *ye = strtok(tmp, " "); client_connected = ye; } else { strcpy(tmp, fLogin->MyUser->nickname); strcat(tmp, " has connected\n"); sockClient->Write(tmp, sizeof(tmp)); } }
[ [ [ 1, 193 ] ] ]
8b01b35a620805bc3cd580685a8e2bd9ee9cd2cb
8aa65aef3daa1a52966b287ffa33a3155e48cc84
/Source/Graphics/Texture.cpp
5d490317c5e0fbee5f167457afff957b0cec792d
[]
no_license
jitrc/p3d
da2e63ef4c52ccb70023d64316cbd473f3bd77d9
b9943c5ee533ddc3a5afa6b92bad15a864e40e1e
refs/heads/master
2020-04-15T09:09:16.192788
2009-06-29T04:45:02
2009-06-29T04:45:02
37,063,569
1
0
null
null
null
null
UTF-8
C++
false
false
5,838
cpp
#include "Includes.h" #include "Texture.h" namespace P3D { namespace Graphics { Logger TextureManager::logger(L"Graphics.TextureManager"); // indices are TexelFormat enums static int BytesPerTexel[] = { 3, 4, 3, 4, 1 }; static int OpenGLTexelFomat[] = { GL_RGB, GL_RGBA, GL_BGR, GL_BGRA, GL_LUMINANCE }; TextureManager::TextureManager() : _defaultTexture(0) { // init DevIL ilInit(); ilutInit(); // say that we are using OpenGL ilutRenderer(ILUT_OPENGL); // OpenGL image origin mode ilEnable(IL_ORIGIN_SET); ilSetInteger(IL_ORIGIN_MODE, IL_ORIGIN_UPPER_LEFT); // keep DDS compressed ilSetInteger(IL_KEEP_DXTC_DATA, 1); // do not event decompress it ilSetInteger(IL_DO_NOT_DECOMPRESS_DXTC, 1); ilutEnable(ILUT_GL_USE_S3TC); } TextureManager::~TextureManager() { // remove all textures for (TexturesMap::iterator it = _textures.begin(); it != _textures.end(); ++it) it->second->Release(); _textures.clear(); } /* Load texture from file. */ Texture* TextureManager::LoadTexture(const wchar* file) { logger.info() << L"Loading texture from '" << file << L"'..."; // search among loaded TexturesMap::const_iterator it = _textures.find(file); if (it != _textures.end()) { // found! logger.info() << L"Already loaded."; it->second->AddRef(); return it->second; } ILint image = ilGenImage(); ILboolean result = ilLoad(IL_TYPE_UNKNOWN, file); if (!result) { ilDeleteImage(image); logger.error() << L"Error while loading '" << file << L"': " << ToUTF16((const char*)iluErrorString(ilGetError())); _defaultTexture.AddRef(); return &_defaultTexture; } else { Texture* texture = NULL; GLuint id = ilutGLBindTexImage(); texture = new Texture(id); texture->AddRef(); _textures[file] = texture; return texture; } } void TextureManager::UnloadUnusedTextures() { std::vector<TexturesMap::iterator> toRemove; for (TexturesMap::iterator it = _textures.begin(); it != _textures.end(); ++it) { if (it->second->AddRef() == 2) { toRemove.push_back(it); it->second->Release(); } it->second->Release(); } for (std::vector<TexturesMap::iterator>::iterator it = toRemove.begin(); it != toRemove.end(); ++it) _textures.erase(*it); } CustomTexture* TextureManager::CreateCustomTexture(uint width, uint height, TexelFormat format) { GLuint id = 0; glGenTextures(1, &id); return new CustomTexture(id, width, height, format); } Texture::Texture(GLuint id) { _id = id; } Texture::~Texture() { glDeleteTextures(1, &_id); } CustomTexture::CustomTexture(GLuint id, uint width, uint height, TexelFormat format) : Texture(id) { _updateX = 0; _updateY = 0; _updateWidth = 0; _updateHeight = 0; _format = format; Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, BytesPerTexel[_format], width, height, 0, OpenGLTexelFomat[_format], GL_UNSIGNED_BYTE, NULL); } byte* CustomTexture::Lock(uint x, uint y, uint width, uint height) { ASSERT(_pixelBuffer == NULL); ASSERT(_updateWidth == 0 && _updateHeight == 0); ASSERT(width != 0 && height != 0); _updateX = x; _updateY = y; _updateWidth = width; _updateHeight = height; _pixelBuffer.Attach(new PixelUnpackBuffer()); _pixelBuffer->Element.Size = BytesPerTexel[_format]; _pixelBuffer->Initialize(width * height, BUFFER_STATIC); return (byte*)_pixelBuffer->Lock(); } void CustomTexture::Unlock() { ASSERT(_updateWidth != 0 && _updateHeight != 0); ASSERT(_pixelBuffer != NULL); _pixelBuffer->Unlock(); Bind(); glTexSubImage2D(GL_TEXTURE_2D, 0, _updateX, _updateY, _updateWidth, _updateHeight, OpenGLTexelFomat[_format], GL_UNSIGNED_BYTE, 0); _pixelBuffer->Unbind(); _updateX = 0; _updateY = 0; _updateWidth = 0; _updateHeight = 0; _pixelBuffer = NULL; } } }
[ "vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1" ]
[ [ [ 1, 185 ] ] ]
8b489dca7b940d883ede1d0ec14c34ffccdb0d4d
0b66a94448cb545504692eafa3a32f435cdf92fa
/branches/kyr/cbear.berlios.de/windows/registry/value.hpp
4779f7350ad644866576358679b625749c017ff5
[ "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
816
hpp
#ifndef CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_VALUE_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_VALUE_HPP_INCLUDED #include <cbear.berlios.de/windows/registry/data.hpp> namespace cbear_berlios_de { namespace windows { namespace registry { template<class Char> class value: public std::pair<base::basic_string<Char>, data<Char> > { public: typedef Char char_type; typedef base::basic_string<char_type> string_type; typedef data<char_type> data_type; typedef std::pair<string_type, data_type> base_type; value() { } template<class DataType> explicit value(const DataType &data): base_type(string_type(), data) { } template<class DataType > value(const string_type &name, const DataType &data): base_type(name, data) { } }; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 43 ] ] ]
98fc5ee58c85538b552f792ba9c094e2b8921e5f
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/FriendListCtrl.h
bee1f1988a1140d2f8e74402cdeeb4c3963e3b92
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
2,065
h
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #include "MuleListCtrl.h" class CFriend; class CFriendListCtrl : public CMuleListCtrl { DECLARE_DYNAMIC(CFriendListCtrl) friend class CFriendList; public: CFriendListCtrl(); virtual ~CFriendListCtrl(); void Init(); void Localize(); void UpdateList(); protected: void SetAllIcons(); void AddFriend(const CFriend* pFriend); void RemoveFriend(const CFriend* pFriend); void RefreshFriend(const CFriend* pFriend); void UpdateFriend(int iItem, const CFriend* pFriend); void ShowFriendDetails(const CFriend* pFriend); static int CALLBACK SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort); virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); virtual BOOL PreTranslateMessage(MSG* pMsg); DECLARE_MESSAGE_MAP() afx_msg void OnContextMenu(CWnd *pWnd, CPoint point); afx_msg void OnLvnColumnClick(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnNmDblClk(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnSysColorChange(); // MORPH START - Added by Commander, Friendlinks [emulEspaa] - added by zz_fly public: bool AddEmfriendsMetToList(const CString& strFile); // MORPH END - Added by Commander, Friendlinks [emulEspaa] };
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 57 ] ] ]
c18d7c7e19e14eae8f1245b01fe2850165dc8609
3435b4ba763f2b184969e99f1c2e256251793694
/CurtainClothSim/TPhysic/TPhysic/Vector3D.h
ea04839a6180e0dda38db5c8052122de13dac81a
[]
no_license
diegopiacc/CodeExamples
6ae837789c20a02c30d61ab9ccf7b8008888f239
a8d7beffa7f456c8b1c35dcf52c777abc94dd3c4
refs/heads/master
2016-09-06T21:25:10.927518
2011-11-06T18:05:57
2011-11-06T18:05:57
2,702,115
0
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
#ifndef _VECTOR3D_H_ #define _VECTOR3D_H_ #include "math.h" class Vector3D { public: float x, y, z; bool anchor; Vector3D(){ x = 0.0f; y = 0.0f; z = 0.0f; anchor = false; }; Vector3D(float x, float y, float z): x(x), y(y), z(z){ }; void setAnchor(bool a) { anchor = a; }; bool isAnchor() { return anchor; }; Vector3D& operator= (Vector3D v){ x = v.x; y = v.y; z = v.z; return *this; }; Vector3D operator+ (Vector3D v) { return Vector3D(x + v.x, y + v.y, z + v.z); }; Vector3D operator- (Vector3D v) { return Vector3D(x - v.x, y - v.y, z - v.z); }; Vector3D operator* (float value){ return Vector3D(x * value, y * value, z * value); }; Vector3D operator/ (float value){ return Vector3D(x / value, y / value, z / value); }; Vector3D operator- (float value){ return Vector3D(x - value, y - value, z - value); }; Vector3D& operator+= (Vector3D v){ x += v.x; y += v.y; z += v.z; return *this; }; Vector3D& operator-= (Vector3D v){ x -= v.x; y -= v.y; z -= v.z; return *this; }; BOOL operator!= (Vector3D v){ if (x != v.x || y != v.y || z != v.z) return true; else return false; }; BOOL operator== (Vector3D v){ if (x == v.x || y == v.y || z == v.z) return true; else return false; }; Vector3D& operator*= (float value){ x *= value; y *= value; z *= value; return *this; }; Vector3D& operator/= (float value){ x /= value; y /= value; z /= value; return *this; }; Vector3D operator- (){ return Vector3D(-x, -y, -z); }; float length(){ return sqrtf(x*x + y*y + z*z); }; float length(Vector3D v){ return sqrtf(pow(x-v.x,2) + pow(y-v.y,2) + pow(z-v.z,2)); }; float innerProduct(Vector3D v){ return x*v.x + y*v.y + z*v.z; }; void init(){ this->x = 0.0; this->y = 0.0; this->z = 0.0; }; void normalize(){ float length = this->length(); if (length == 0) return; x /= length; y /= length; z /= length; }; protected: }; #endif
[ [ [ 1, 132 ] ] ]
1cb11441c43bed56f9f54eedd0c6619d5c223da2
4f913cc1a50e8e649fd40313631a161234e3c59d
/NokomoSystem/Stream.h
d75098d7e208f4cc09e210b6b415557f307a1e50
[]
no_license
autch/kpiadx.kpi
abb1f084163478796e202196a7411a049a76116c
f482c3871d948e71a3b3839e9066f845ecdb5915
refs/heads/master
2021-12-16T01:22:32.824315
2010-12-15T06:34:48
2010-12-15T06:34:48
1,170,398
1
0
null
null
null
null
UTF-8
C++
false
false
1,025
h
#pragma once #include "NokomoSystem.h" namespace Nokomo { namespace Stream { class IAuStream { public: virtual ~IAuStream() {} virtual BOOL Seek(const QWORD qwPosition) = 0; virtual QWORD GetPosition() = 0; }; class IAuReadOnlyStream: public IAuStream { public: virtual ~IAuReadOnlyStream() {} virtual BOOL Read(VOID* pBuffer, const DWORD dwBytesToRead, DWORD& dwBytesRead) = 0; }; class IAuWriteOnlyStream: public IAuStream { public: virtual ~IAuWriteOnlyStream() {} virtual BOOL Write(const VOID* pBuffer, const DWORD dwBytesToWrite, DWORD& dwBytesWritten) = 0; }; class IAuReadWriteStream: public IAuStream { public: virtual ~IAuReadWriteStream() {} virtual BOOL Read(VOID* pBuffer, const DWORD dwBytesToRead, DWORD& dwBytesRead) = 0; virtual BOOL Write(const VOID* pBuffer, const DWORD dwBytesToWrite, DWORD& dwBytesWritten) = 0; }; }; };
[ "autch@f88602a7-bc0e-0410-bfba-c07ee007e53c" ]
[ [ [ 1, 41 ] ] ]
7dc884d955a79a11ca6167ca1a3b3d965c6cc0f2
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/SQLCEHelper/Source/Command.cpp
0b79da82107a8f2f10276acea9f3eacde08ec6d7
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
10,146
cpp
#include "stdafx.h" using namespace OLEDBCLI; // CCommand::CCommand // // Constructor - builds the CCommand from the CSession object // CCommand::CCommand(OLEDBCLI::CSession &session) : m_pCommand (NULL), m_nParams (0), m_pszParamNames (NULL), m_pBoundParam (NULL), m_pBuffer (NULL), m_nRowSize (0), m_pBindStatus (NULL), m_hParamAccessor(NULL), m_pParam (NULL), m_pParamInfo (NULL) { IUnknown* pUnknown = session; CComPtr<IDBCreateCommand> spCreateCommand; HRESULT hr; hr = pUnknown->QueryInterface(IID_IDBCreateCommand, (void**)&spCreateCommand); if(SUCCEEDED(hr)) { hr = spCreateCommand->CreateCommand(NULL, IID_ICommandText, (IUnknown**)&m_pCommand); if(FAILED(hr)) m_pCommand = NULL; } } // CCommand::~CCommand // // Destructor // CCommand::~CCommand() { ClearParameters(); if(m_pCommand != NULL) { m_pCommand->Release(); m_pCommand = NULL; } } void CCommand::ClearBinding() { if(m_pBuffer != NULL) { delete [] m_pBuffer; m_pBuffer = NULL; m_nRowSize = 0; } if(m_pBoundParam != NULL) { delete [] m_pBoundParam; m_pBoundParam = NULL; } if(m_pBindStatus != NULL) { delete [] m_pBindStatus; m_pBindStatus = NULL; } if(m_hParamAccessor != NULL) { CComPtr<IAccessor> spAccessor; HRESULT hr = m_pCommand->QueryInterface(IID_IAccessor, (void**)&spAccessor); if(SUCCEEDED(hr)) { spAccessor->ReleaseAccessor(m_hParamAccessor, NULL); m_hParamAccessor = NULL; } } } // CCommand::ClearParameters // // Frees all parameter info. // void CCommand::ClearParameters() { ClearBinding(); if(m_pszParamNames != NULL) { CoTaskMemFree(m_pszParamNames); m_pszParamNames = NULL; } if(m_pParamInfo != NULL) { CoTaskMemFree(m_pParamInfo); m_pParamInfo = NULL; } if(m_pParam != NULL) delete [] m_pParam; m_pParam = NULL; m_nParams = 0; } // CCommand::SetText // // Sets the command text // HRESULT CCommand::SetText(LPCTSTR pszText) { HRESULT hr; ATLASSERT(m_pCommand != NULL); ATLASSERT(pszText != NULL); hr = m_pCommand->SetCommandText(DBGUID_DEFAULT, pszText); return hr; } // CCommand::RebindParameters // // Checks if the parameter buffer increased since last Bind. // Must return true for first execution. // bool CCommand::RebindParameters() { ULONG iParam; ULONG nSize = 0; for(iParam = 0; iParam < m_nParams; ++iParam) { nSize += sizeof(DBSTATUS) + sizeof(ULONG); if(m_pParam[iParam].GetType() == DBTYPE_WSTR) nSize += m_pParam[iParam].GetLength() * sizeof(wchar_t); else nSize += m_pParam[iParam].GetLength(); } return nSize > m_nRowSize; } // CCommand::BindParameters // // Binds command parameters // HRESULT CCommand::BindParameters() { HRESULT hr; CComPtr<IAccessor> spAccessor; DBBINDING* pBinding = NULL; BOUNDCOLUMN* pBoundParam = NULL; ULONG iParam; CBindingArray binding; DBPARAMINFO* pParamInfo = m_pParamInfo; // Check if we need to bind the parameters if(!RebindParameters()) return S_OK; // Start the binding process by allocating the binding array if(!binding.Allocate(m_nParams)) return E_OUTOFMEMORY; // Allocate the BOUNDCOLUMN array for parameters m_pBoundParam = new BOUNDCOLUMN[m_nParams]; if(m_pBoundParam == NULL) return E_OUTOFMEMORY; pBinding = binding[0]; pBoundParam = m_pBoundParam; for(iParam = 0; iParam < m_nParams; ++iParam, ++pParamInfo, ++pBinding, ++pBoundParam) { ULONG nParamSize = m_pParam[iParam].GetLength(); DBTYPE wType = pParamInfo->wType; DWORD dwFlags = pParamInfo->dwFlags; if(wType == DBTYPE_STR) ++nParamSize; // Add the NULL terminator // If this is a UNICODE string, correct the size and allow for the NULL terminator if(wType == DBTYPE_WSTR) nParamSize = (nParamSize + 1) * sizeof(wchar_t); pBinding->iOrdinal = pParamInfo->iOrdinal; pBinding->wType = wType; pBinding->bPrecision = pParamInfo->bPrecision; pBinding->bScale = pParamInfo->bScale; pBinding->dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS; pBinding->dwMemOwner = DBMEMOWNER_CLIENTOWNED; pBinding->cbMaxLen = nParamSize; pBinding->pObject = NULL; if(dwFlags & DBPARAMFLAGS_ISINPUT) pBinding->eParamIO |= DBPARAMIO_INPUT; if(dwFlags & DBPARAMFLAGS_ISOUTPUT) pBinding->eParamIO |= DBPARAMIO_OUTPUT; pBinding->obLength = m_nRowSize; m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG)); pBinding->obStatus = m_nRowSize; m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG)); pBinding->obValue = m_nRowSize; m_nRowSize = AddOffset(m_nRowSize, nParamSize); pBoundParam->bPrecision = pBinding->bPrecision; pBoundParam->bScale = pBinding->bScale; pBoundParam->dwFlags = dwFlags; pBoundParam->iAccessor = 0; pBoundParam->iOrdinal = pBinding->iOrdinal; pBoundParam->obLength = pBinding->obLength; pBoundParam->obStatus = pBinding->obStatus; pBoundParam->obValue = pBinding->obValue; pBoundParam->pwszName = pParamInfo->pwszName; pBoundParam->ulColumnSize = nParamSize; pBoundParam->wType = wType; } // Allocate the data buffer m_pBuffer = new BYTE[m_nRowSize]; if(m_pBuffer == NULL) return E_OUTOFMEMORY; // Allocate the DBBINDSTATUS array. We own this memory. m_pBindStatus = new DBBINDSTATUS[m_nParams]; if(m_pBindStatus == NULL) return E_OUTOFMEMORY; hr = m_pCommand->QueryInterface(IID_IAccessor, (void**)&spAccessor); if(FAILED(hr)) return hr; hr = spAccessor->CreateAccessor(DBACCESSOR_PARAMETERDATA, m_nParams, binding[0], m_nRowSize, &m_hParamAccessor, m_pBindStatus); return hr; } // CCommand::SetAllParameters // // Copies all parameter values from the staging array to the parameter buffer // void CCommand::SetAllParameters() { ULONG iParam; BOUNDCOLUMN* pBoundParam = m_pBoundParam; for(iParam = 0; iParam < m_nParams; ++iParam, ++pBoundParam) { CDbValue& value = m_pParam[iParam]; DBSTATUS* pStatus = (DBSTATUS*) (m_pBuffer + pBoundParam->obStatus); ULONG* pLength = (ULONG*) (m_pBuffer + pBoundParam->obLength); BYTE* pValue = (BYTE*) (m_pBuffer + pBoundParam->obValue); *pStatus = value.GetStatus(); *pLength = value.GetType() == DBTYPE_WSTR ? value.GetLength() * sizeof(wchar_t) : value.GetLength(); if(*pStatus == DBSTATUS_S_OK && *pLength > 0) memcpy(pValue, value.GetDataPtr(), *pLength); } } // CCommand::CreateParameters // // Creates te parameter value array to buffer data // HRESULT CCommand::CreateParameters(DBPARAMINFO* pParamInfo) { ULONG iParam; m_pParam = new CDbValue[m_nParams]; if(m_pParam == NULL) return E_OUTOFMEMORY; for(iParam = 0; iParam < m_nParams; ++iParam, ++pParamInfo) { bool bIsLong = pParamInfo->ulParamSize > 8192; ULONG nParamSize = bIsLong ? 1024 : pParamInfo->ulParamSize; m_pParam[iParam].Initialize(pParamInfo->wType, nParamSize, nParamSize, bIsLong); } return S_OK; } // CCommand::Prepare // // Prepares the command for execution (compiles an execution plan) // HRESULT CCommand::Prepare(ULONG cExpectedRuns) { CComPtr<ICommandPrepare> spCommandPrepare; CComPtr<ICommandWithParameters> spCommandParams; HRESULT hr; ATLASSERT(m_pCommand != NULL); hr = m_pCommand->QueryInterface(IID_ICommandPrepare, (void**)&spCommandPrepare); if(FAILED(hr)) return hr; hr = spCommandPrepare->Prepare(cExpectedRuns); if(FAILED(hr)) return hr; // Retrieve the command parameters, if any hr = m_pCommand->QueryInterface(IID_ICommandWithParameters, (void**)&spCommandParams); if(SUCCEEDED(hr)) { ClearParameters(); hr = spCommandParams->GetParameterInfo(&m_nParams, &m_pParamInfo, &m_pszParamNames); if(SUCCEEDED(hr) && m_nParams) { hr = CreateParameters(m_pParamInfo); if(SUCCEEDED(hr)) hr = BindParameters(); } } return hr; } // CCommand::Unprepare // // Unprepares the command (releases the compiled execution plan) // HRESULT CCommand::Unprepare() { CComPtr<ICommandPrepare> spCommandPrepare; HRESULT hr; ATLASSERT(m_pCommand != NULL); hr = m_pCommand->QueryInterface(IID_ICommandPrepare, (void**)&spCommandPrepare); if(FAILED(hr)) return hr; hr = spCommandPrepare->Unprepare(); if(SUCCEEDED(hr)) ClearParameters(); return hr; } // CCommand::Execute // // Executes the command without returning a rowset. // Use for DDL commands. // HRESULT CCommand::Execute(LONG *pcRowsAffected) { HRESULT hr; DBPARAMS dbParams; DBPARAMS* pParams = NULL; ATLASSERT(m_pCommand != NULL); hr = BindParameters(); if(FAILED(hr)) return hr; SetAllParameters(); if(m_nParams) { dbParams.cParamSets = 1; dbParams.hAccessor = m_hParamAccessor; dbParams.pData = m_pBuffer; pParams = &dbParams; } hr = m_pCommand->Execute(NULL, IID_NULL, &dbParams, pcRowsAffected, NULL); return hr; } // CCommand::Execute // // Executes the command and returns a rowset. // HRESULT CCommand::Execute(CRowset &rowset, LONG *pcRowsAffected) { HRESULT hr; IRowset* pRowset = NULL; DBPARAMS dbParams; DBPARAMS* pParams = NULL; ATLASSERT(m_pCommand != NULL); hr = BindParameters(); if(FAILED(hr)) return hr; SetAllParameters(); if(m_nParams) { dbParams.cParamSets = 1; dbParams.hAccessor = m_hParamAccessor; dbParams.pData = m_pBuffer; pParams = &dbParams; } hr = m_pCommand->Execute(NULL, IID_IRowset, pParams, pcRowsAffected, (IUnknown**)&pRowset); if(FAILED(hr)) return hr; hr = rowset.Open(pRowset); return hr; } // CCommand::FindParameter // // Returns a parameter entry index from the given ordinal or NULL if not found // ULONG CCommand::FindParameter(ULONG iOrdinal) { ULONG i; BOUNDCOLUMN* p; for(i = 0, p = m_pBoundParam; i < m_nParams; ++i, ++p) { if(p->iOrdinal == iOrdinal) return i; } return (ULONG)-1; }
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 450 ] ] ]
16f0d7b84745ffac9f6e6eaffb6062a43b74d01a
a57be8cbf86a415ab5c36967db580f552e60a09d
/src/windowproc.cpp
5a9cd2cf84ce62a33ccd2c7680d29258027caefd
[]
no_license
rehno-lindeque/osi-linglkernel
0f6cd8669e0b9fb19260b971216ce9d314dab188
8dae64e7d1a4416c390b3814c40008f0207d8979
refs/heads/master
2020-05-20T13:31:07.991935
2011-01-29T09:58:20
2011-01-29T09:58:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
831
cpp
////////////////////////////////////////////////////////////////////////////// // // WINDOWPROC.CPP // // Copyright © 2007, Rehno Lindeque. All rights reserved. // ////////////////////////////////////////////////////////////////////////////// /* INCLUDES */ #include "api.h" //#include <windows.h> /* IMPLEMENTATION */ /* LRESULT CALLBACK WinGLKernel::Kernel::windowProc(HWND hWnd, uint uiMsg, WPARAM wParam, LPARAM lParam) { /* *pWindow = (*)GetWindowLong(hWnd, GWL_USERDATA); if(pThis) return pThis->processMessage(hWnd, uiMsg, wParam, lParam); else return DefWindowProc(hWnd, uiMsg, wParam, lParam);* return DefWindowProc(hWnd, uiMsg, wParam, lParam); } */
[ [ [ 1, 25 ] ] ]
6e9c4331632d1238027a663e188602255f28fadb
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/hitlnew/fgsimulator.cpp
07b846f824bb10d5051015bb1a70b72f1300ec33
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,465
cpp
/** ****************************************************************************** * * @file flightgearbridge.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup HITLPlugin HITL Plugin * @{ * @brief The Hardware In The Loop plugin *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "fgsimulator.h" #include "extensionsystem/pluginmanager.h" #include "coreplugin/icore.h" #include "coreplugin/threadmanager.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif const float FGSimulator::FT2M = 0.3048; const float FGSimulator::KT2MPS = 0.514444444; const float FGSimulator::INHG2KPA = 3.386; const float FGSimulator::FPS2CMPS = 30.48; //FGSimulator::FGSimulator(QString hostAddr, int outPort, int inPort, bool manual, QString binPath, QString dataPath) : // Simulator(hostAddr, outPort, inPort, manual, binPath, dataPath), // fgProcess(NULL) //{ // // Note: Only tested on windows 7 //#if defined(Q_WS_WIN) // cmdShell = QString("c:/windows/system32/cmd.exe"); //#else // cmdShell = QString("bash"); //#endif //} FGSimulator::FGSimulator(const SimulatorSettings& params) : Simulator(params) { } FGSimulator::~FGSimulator() { disconnect(simProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(processReadyRead())); } void FGSimulator::setupUdpPorts(const QString& host, int inPort, int outPort) { inSocket->bind(QHostAddress(host), inPort); } bool FGSimulator::setupProcess() { QMutexLocker locker(&lock); // Copy FlightGear generic protocol configuration file to the FG protocol directory // NOTE: Not working on Windows 7, if FG is installed in the "Program Files", // likelly due to permissions. The file should be manually copied to data/Protocol/opfgprotocol.xml // QFile xmlFile(":/flightgear/genericprotocol/opfgprotocol.xml"); // xmlFile.open(QIODevice::ReadOnly | QIODevice::Text); // QString xml = xmlFile.readAll(); // xmlFile.close(); // QFile xmlFileOut(pathData + "/Protocol/opfgprotocol.xml"); // xmlFileOut.open(QIODevice::WriteOnly | QIODevice::Text); // xmlFileOut.write(xml.toAscii()); // xmlFileOut.close(); Qt::HANDLE mainThread = QThread::currentThreadId(); qDebug() << "setupProcess Thread: "<< mainThread; simProcess = new QProcess(); simProcess->setReadChannelMode(QProcess::MergedChannels); connect(simProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(processReadyRead())); // Note: Only tested on windows 7 #if defined(Q_WS_WIN) QString cmdShell("c:/windows/system32/cmd.exe"); #else QString cmdShell("bash"); #endif // Start shell (Note: Could not start FG directly on Windows, only through terminal!) simProcess->start(cmdShell); if (simProcess->waitForStarted() == false) { emit processOutput("Error:" + simProcess->errorString()); return false; } // Setup arguments // Note: The input generic protocol is set to update at a much higher rate than the actual updates are sent by the GCS. // If this is not done then a lag will be introduced by FlightGear, likelly because the receive socket buffer builds up during startup. QString args("--fg-root=\"" + settings.dataPath + "\" " + "--timeofday=noon " + "--httpd=5400 " + "--enable-hud " + "--in-air " + "--altitude=3000 " + "--vc=100 " + "--generic=socket,out,50,localhost," + QString::number(settings.inPort) + ",udp,opfgprotocol"); if(!settings.manual) { args.append(" --generic=socket,in,400,localhost," + QString::number(settings.outPort) + ",udp,opfgprotocol"); } // Start FlightGear QString cmd("\"" + settings.binPath + "\" " + args + "\n"); simProcess->write(cmd.toAscii()); return true; } void FGSimulator::processReadyRead() { QByteArray bytes = simProcess->readAllStandardOutput(); QString str(bytes); if ( !str.contains("Error reading data") ) // ignore error { emit processOutput(str); } } void FGSimulator::transmitUpdate() { // Read ActuatorDesired from autopilot ActuatorDesired::DataFields actData = actDesired->getData(); float ailerons = actData.Roll; float elevator = -actData.Pitch; float rudder = actData.Yaw; float throttle = actData.Throttle; // Send update to FlightGear QString cmd; cmd = QString("%1,%2,%3,%4\n") .arg(ailerons) .arg(elevator) .arg(rudder) .arg(throttle); QByteArray data = cmd.toAscii(); outSocket->writeDatagram(data, QHostAddress(settings.hostAddress), settings.outPort); } void FGSimulator::processUpdate(const QByteArray& inp) { static char once=0; // Split QString data(inp); QStringList fields = data.split(","); // Get xRate (deg/s) // float xRate = fields[0].toFloat() * 180.0/M_PI; // Get yRate (deg/s) // float yRate = fields[1].toFloat() * 180.0/M_PI; // Get zRate (deg/s) // float zRate = fields[2].toFloat() * 180.0/M_PI; // Get xAccel (m/s^2) // float xAccel = fields[3].toFloat() * FT2M; // Get yAccel (m/s^2) // float yAccel = fields[4].toFloat() * FT2M; // Get xAccel (m/s^2) // float zAccel = fields[5].toFloat() * FT2M; // Get pitch (deg) float pitch = fields[6].toFloat(); // Get pitchRate (deg/s) // float pitchRate = fields[7].toFloat(); // Get roll (deg) float roll = fields[8].toFloat(); // Get rollRate (deg/s) // float rollRate = fields[9].toFloat(); // Get yaw (deg) float yaw = fields[10].toFloat(); // Get yawRate (deg/s) // float yawRate = fields[11].toFloat(); // Get latitude (deg) float latitude = fields[12].toFloat(); // Get longitude (deg) float longitude = fields[13].toFloat(); // Get heading (deg) float heading = fields[14].toFloat(); // Get altitude (m) float altitude = fields[15].toFloat() * FT2M; // Get altitudeAGL (m) float altitudeAGL = fields[16].toFloat() * FT2M; // Get groundspeed (m/s) float groundspeed = fields[17].toFloat() * KT2MPS; // Get airspeed (m/s) // float airspeed = fields[18].toFloat() * KT2MPS; // Get temperature (degC) float temperature = fields[19].toFloat(); // Get pressure (kpa) float pressure = fields[20].toFloat() * INHG2KPA; // Get VelocityActual Down (cm/s) float velocityActualDown = fields[21].toFloat() * FPS2CMPS; // Get VelocityActual East (cm/s) float velocityActualEast = fields[22].toFloat() * FPS2CMPS; // Get VelocityActual Down (cm/s) float velocityActualNorth = fields[23].toFloat() * FPS2CMPS; //run once HomeLocation::DataFields homeData = posHome->getData(); if(!once) { memset(&homeData, 0, sizeof(HomeLocation::DataFields)); // Update homelocation homeData.Latitude = latitude * 10e6; homeData.Longitude = longitude * 10e6; homeData.Altitude = 0; double LLA[3]; LLA[0]=latitude; LLA[1]=longitude; LLA[2]=0; double ECEF[3]; double RNE[9]; Utils::CoordinateConversions().RneFromLLA(LLA,(double (*)[3])RNE); for (int t=0;t<9;t++) { homeData.RNE[t]=RNE[t]; } Utils::CoordinateConversions().LLA2ECEF(LLA,ECEF); homeData.ECEF[0]=ECEF[0]*100; homeData.ECEF[1]=ECEF[1]*100; homeData.ECEF[2]=ECEF[2]*100; homeData.Be[0]=0; homeData.Be[1]=0; homeData.Be[2]=0; posHome->setData(homeData); once=1; } // Update VelocityActual.{Nort,East,Down} VelocityActual::DataFields velocityActualData; memset(&velocityActualData, 0, sizeof(VelocityActual::DataFields)); velocityActualData.North = velocityActualNorth; velocityActualData.East = velocityActualEast; velocityActualData.Down = velocityActualDown; velActual->setData(velocityActualData); // Update PositionActual.{Nort,East,Down} PositionActual::DataFields positionActualData; memset(&positionActualData, 0, sizeof(PositionActual::DataFields)); positionActualData.North = 0; //Currently hardcoded as there is no way of setting up a reference point to calculate distance positionActualData.East = 0; //Currently hardcoded as there is no way of setting up a reference point to calculate distance positionActualData.Down = (altitude * 100); //Multiply by 100 because positionActual expects input in Centimeters. posActual->setData(positionActualData); // Update AltitudeActual object BaroAltitude::DataFields altActualData; memset(&altActualData, 0, sizeof(BaroAltitude::DataFields)); altActualData.Altitude = altitudeAGL; altActualData.Temperature = temperature; altActualData.Pressure = pressure; altActual->setData(altActualData); // Update attActual object AttitudeActual::DataFields attActualData; memset(&attActualData, 0, sizeof(AttitudeActual::DataFields)); attActualData.Roll = roll; attActualData.Pitch = pitch; attActualData.Yaw = yaw; attActualData.q1 = 0; attActualData.q2 = 0; attActualData.q3 = 0; attActualData.q4 = 0; attActual->setData(attActualData); // Update gps objects GPSPosition::DataFields gpsData; memset(&gpsData, 0, sizeof(GPSPosition::DataFields)); gpsData.Altitude = altitude; gpsData.Heading = heading; gpsData.Groundspeed = groundspeed; gpsData.Latitude = latitude*1e7; gpsData.Longitude = longitude*1e7; gpsData.Satellites = 10; gpsData.Status = GPSPosition::STATUS_FIX3D; gpsPos->setData(gpsData); float NED[3]; double LLA[3] = {(double) gpsData.Latitude / 1e7, (double) gpsData.Longitude / 1e7, (double) (gpsData.GeoidSeparation + gpsData.Altitude)}; // convert from cm back to meters double ECEF[3] = {(double) (homeData.ECEF[0] / 100), (double) (homeData.ECEF[1] / 100), (double) (homeData.ECEF[2] / 100)}; Utils::CoordinateConversions().LLA2Base(LLA, ECEF, (float (*)[3]) homeData.RNE, NED); positionActualData.North = NED[0]*100; //Currently hardcoded as there is no way of setting up a reference point to calculate distance positionActualData.East = NED[1]*100; //Currently hardcoded as there is no way of setting up a reference point to calculate distance positionActualData.Down = NED[2]*100; //Multiply by 100 because positionActual expects input in Centimeters. posActual->setData(positionActualData); }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 304 ] ] ]
beca3a680effdc11135040ff1b483fb2f31876c4
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct2D/D2DCustom.cpp
721305066ae885e0b1ae6e82b7e1eab092569414
[]
no_license
midnite8177/phever
f9a55a545322c9aff0c7d0c45be3d3ddd6088c97
45529e80ebf707e7299887165821ca360aa1907d
refs/heads/master
2020-05-16T21:59:24.201346
2010-07-12T23:51:53
2010-07-12T23:51:53
34,965,829
3
2
null
null
null
null
UTF-8
C++
false
false
16,428
cpp
// Copyright (c) Microsoft Corporation. All rights reserved. #include "stdafx.h" #include "CommonUtils.h" #include "LibraryLoader.h" #include "DirectWrite/DWriteRenderingParams.h" using namespace System::Runtime::InteropServices; typedef HRESULT (*D2D1CreateFactoryFuncPtr)( D2D1_FACTORY_TYPE factoryType, REFIID riid, const D2D1_FACTORY_OPTIONS *pFactoryOptions, void **ppIFactory ); namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct2D1 { namespace D2D = Microsoft::WindowsAPICodePack::DirectX::Direct2D1; D2DFactory ^ D2DFactory::CreateFactory() { return CreateFactory(D2DFactoryType::SingleThreaded, FactoryOptions(DebugLevel::None)); }; D2DFactory ^ D2DFactory::CreateFactory( D2DFactoryType factoryType ) { return CreateFactory(factoryType, FactoryOptions(DebugLevel::None)); }; D2DFactory ^ D2DFactory::CreateFactory( D2DFactoryType factoryType, FactoryOptions factoryOptions ) { D2D1CreateFactoryFuncPtr createFuncPtr = (D2D1CreateFactoryFuncPtr) LibraryLoader::Instance()->GetFunctionfromDll( D2DLibrary, "D2D1CreateFactory"); ID2D1Factory *pIFactory = NULL; D2D1_FACTORY_OPTIONS factoryOptionsCopy; factoryOptions.CopyTo(&factoryOptionsCopy); CommonUtils::VerifyResult( (*createFuncPtr)( static_cast<D2D1_FACTORY_TYPE>(factoryType), __uuidof(ID2D1Factory), &factoryOptionsCopy, (void**)&pIFactory)); return pIFactory ? gcnew D2DFactory(pIFactory) : nullptr; }; DrawingStateBlock ^ D2DFactory::CreateDrawingStateBlock( DrawingStateDescription drawingStateDescription, RenderingParams^ textRenderingParams ) { D2D1_DRAWING_STATE_DESCRIPTION drawingStateDescriptionCopy; drawingStateDescription.CopyTo(&drawingStateDescriptionCopy); ID2D1DrawingStateBlock * ptr = NULL; CommonUtils::VerifyResult( GetInterface<ID2D1Factory>()->CreateDrawingStateBlock( &drawingStateDescriptionCopy, textRenderingParams == nullptr ? NULL : textRenderingParams->GetInterface<IDWriteRenderingParams>(), &ptr )); return ptr ? gcnew DrawingStateBlock(ptr) : nullptr; } DrawingStateBlock ^ D2DFactory::CreateDrawingStateBlock( DrawingStateDescription drawingStateDescription ) { D2D1_DRAWING_STATE_DESCRIPTION drawingStateDescriptionCopy; drawingStateDescription.CopyTo(&drawingStateDescriptionCopy); ID2D1DrawingStateBlock * ptr = NULL; CommonUtils::VerifyResult( GetInterface<ID2D1Factory>()->CreateDrawingStateBlock( &drawingStateDescriptionCopy, NULL, &ptr )); return ptr ? gcnew DrawingStateBlock(ptr) : nullptr; } DrawingStateBlock ^ D2DFactory::CreateDrawingStateBlock( ) { ID2D1DrawingStateBlock * ptr = NULL; CommonUtils::VerifyResult( GetInterface<ID2D1Factory>()->CreateDrawingStateBlock( NULL, NULL, &ptr )); return ptr ? gcnew DrawingStateBlock(ptr) : nullptr; } // // Implement methods for sink interfaces // void Geometry::Simplify( GeometrySimplificationOption simplificationOption, ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance, Matrix3x2F pWorldTransform ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; D2D1_MATRIX_3X2_F copyWorldTransform; pWorldTransform.CopyTo(&copyWorldTransform); try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Simplify( static_cast<D2D1_GEOMETRY_SIMPLIFICATION_OPTION>(simplificationOption), &copyWorldTransform, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Simplify( GeometrySimplificationOption simplificationOption, ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Simplify( static_cast<D2D1_GEOMETRY_SIMPLIFICATION_OPTION>(simplificationOption), NULL, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Simplify( GeometrySimplificationOption simplificationOption, ISimplifiedGeometrySink ^ pIGeometrySink ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Simplify( static_cast<D2D1_GEOMETRY_SIMPLIFICATION_OPTION>(simplificationOption), NULL, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::CombineWithGeometry( Geometry ^ pInputGeometry, CombineMode combineMode, ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance, Matrix3x2F pInputGeometryTransform ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; D2D1_MATRIX_3X2_F copyInputGeometryTransform; pInputGeometryTransform.CopyTo(&copyInputGeometryTransform); try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->CombineWithGeometry( pInputGeometry->GetInterface<ID2D1Geometry>(), static_cast<D2D1_COMBINE_MODE>(combineMode), &copyInputGeometryTransform, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::CombineWithGeometry( Geometry ^ pInputGeometry, CombineMode combineMode, ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->CombineWithGeometry( pInputGeometry->GetInterface<ID2D1Geometry>(), static_cast<D2D1_COMBINE_MODE>(combineMode), NULL, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::CombineWithGeometry( Geometry ^ pInputGeometry, CombineMode combineMode, ISimplifiedGeometrySink ^ pIGeometrySink ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->CombineWithGeometry( pInputGeometry->GetInterface<ID2D1Geometry>(), static_cast<D2D1_COMBINE_MODE>(combineMode), NULL, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Outline( ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance, Matrix3x2F pWorldTransform ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; D2D1_MATRIX_3X2_F copyWorldTransform; pWorldTransform.CopyTo(&copyWorldTransform); try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Outline( &copyWorldTransform, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Outline( ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Outline( NULL, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Outline( ISimplifiedGeometrySink ^ pIGeometrySink ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Outline( NULL, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Widen( FLOAT strokeWidth, StrokeStyle ^ pIStrokeStyle, ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance, Matrix3x2F pWorldTransform ) { D2D1_MATRIX_3X2_F copyWorldTransform; D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; pWorldTransform.CopyTo(&copyWorldTransform); try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Widen( strokeWidth, pIStrokeStyle->GetInterface<ID2D1StrokeStyle>(), &copyWorldTransform, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Widen( FLOAT strokeWidth, StrokeStyle ^ pIStrokeStyle, ISimplifiedGeometrySink ^ pIGeometrySink, FLOAT flatteningTolerance ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Widen( strokeWidth, pIStrokeStyle->GetInterface<ID2D1StrokeStyle>(), NULL, flatteningTolerance, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Widen( FLOAT strokeWidth, StrokeStyle ^ pIStrokeStyle, ISimplifiedGeometrySink ^ pIGeometrySink ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Widen( strokeWidth, pIStrokeStyle->GetInterface<ID2D1StrokeStyle>(), NULL, pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } void Geometry::Tessellate( ITessellationSink ^ pITessellationSink, FLOAT flatteningTolerance, Matrix3x2F pWorldTransform ) { D2D::TessellationSinkCallback *pTessellationSinkCallback = NULL; D2D1_MATRIX_3X2_F copyWorldTransform; pWorldTransform.CopyTo(&copyWorldTransform); try { pTessellationSinkCallback = new D2D::TessellationSinkCallback( pITessellationSink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Tessellate( &copyWorldTransform, flatteningTolerance, pTessellationSinkCallback )); } __finally { ReleaseInterface(pTessellationSinkCallback); } } void Geometry::Tessellate( ITessellationSink ^ pITessellationSink, FLOAT flatteningTolerance ) { D2D::TessellationSinkCallback *pTessellationSinkCallback = NULL; try { pTessellationSinkCallback = new D2D::TessellationSinkCallback( pITessellationSink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Tessellate( NULL, flatteningTolerance, pTessellationSinkCallback )); } __finally { ReleaseInterface(pTessellationSinkCallback); } } void Geometry::Tessellate( ITessellationSink ^ pITessellationSink ) { D2D::TessellationSinkCallback *pTessellationSinkCallback = NULL; try { pTessellationSinkCallback = new D2D::TessellationSinkCallback( pITessellationSink ); CommonUtils::VerifyResult(GetInterface<ID2D1Geometry>()->Tessellate( NULL, pTessellationSinkCallback )); } __finally { ReleaseInterface(pTessellationSinkCallback); } } void PathGeometry::Stream( IGeometrySink ^ pIGeometrySink ) { D2D::GeometrySinkCallback *pGeometrySinkCallback = NULL; try { pGeometrySinkCallback = new D2D::GeometrySinkCallback( pIGeometrySink ); CommonUtils::VerifyResult(GetInterface<ID2D1PathGeometry>()->Stream( pGeometrySinkCallback )); } __finally { ReleaseInterface(pGeometrySinkCallback); } } } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 572 ] ] ]
24045c7dfcba7792521d4395b053963f4d7f5caf
b738fc6ffa2205ea210d10c395ae47b25ba26078
/TUDT/tudtnew/ThreadConnnectTo.cpp
49657746dfaf68e99bd91f5ef9dec25c663b9130
[]
no_license
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
UTF-8
C++
false
false
598
cpp
#include ".\threadconnnectto.h" #include "debug.h" #include "NPeerMng.h" ThreadConnnectTo::ThreadConnnectTo(NPeerMng *pMng,T_PEERID iDistPeerID,T_PEERID iMyId, UDTSOCKET u,const sockaddr *name,int namelen) { m_pMng = pMng; ASSERT(m_pMng); m_iDistPeerID = iDistPeerID; m_iMyId = iMyId; m_socket = u; m_name = *name; m_namelen = namelen; } ThreadConnnectTo::~ThreadConnnectTo(void) { } void * ThreadConnnectTo::Thread() { ThreadStarted(); int iRes = UDT::connect(m_socket,&m_name,m_namelen); m_pMng->OnConnectExFinish(this,iRes); return NULL; }
[ "tantianzuo@159e4f46-9839-11de-8efd-97b2a7529d09" ]
[ [ [ 1, 29 ] ] ]
f2ca2ead9c86936b687b97a43580d889d5270aa7
46c766a3da1fbfb390613f8d4aeaea079180d739
/arraySort.cpp
f93c2f0eab8fea144204b5d80c194591f457f96a
[]
no_license
laosland/CSCE350_final_project
c72cf43905b76dbd0fd429b0f359df3cf19134b8
90e4a85f96497be5e3f52e1468b70e19c2679d77
refs/heads/master
2021-01-10T19:09:01.746106
2011-10-25T22:10:19
2011-10-25T22:10:19
2,621,820
0
0
null
null
null
null
UTF-8
C++
false
false
9,092
cpp
#include "arraySort.h" using namespace std; const float ZVALUE_95 = 1.96; const float ZVALUE_99 = 2.58; const float STANDARD_ERROR = 0.05; const float SAMPLE_PROPORTION = .95; //number of items within 95% of the true mean; const float PERCENTAGE_PICK_CHOICE = .5; const int LARGEST_INT = numeric_limits<int>::max(); const int NUMBER_OF_RUNS = 15; int quickSort = 1, selectSort = 2; arraySort::arraySort() { int sample = 0, counter = 0; randomArraySize = arraySizeCalibration(); // quicksortTimes = new int[randomArraySize]; // selectsortTimes = new int[randomArraySize]; generateRandomArray(randomArraySize); int numberOfSamplings = statisticsGenerator.calculateNumberofSamplings(SAMPLE_PROPORTION, randomArraySize); //cout << "numberOfSamplings= " << numberOfSamplings <<endl; //cout << "randomArraySize= "<<randomArraySize<<endl; while (counter < NUMBER_OF_RUNS) { numberOfSamplings = statisticsGenerator.calculateNumberofSamplings(SAMPLE_PROPORTION, randomArraySize); sample = 0; while (sample < numberOfSamplings) { ///perform sorting and place it's runtime in an array at index "sample". //cout << "segfault test" << endl; testDo(); ///delete current random array clearRandomArray(); ///create new random array using //cout << "segfault test2" << endl; generateRandomArray(randomArraySize); ///increment the sample being taken ++sample; } storeStatistics(selectsortTimes, numberOfSamplings, selectSort); storeStatistics(quicksortTimes, numberOfSamplings, quickSort); ///increase the size of the random array randomArraySize += 2000; ++counter; } //printArray(selectsortTimes, randomArraySize); //send the sort times for the selectsort to a file; sendArrayToFile(quicksortTimes); sendStatisticsToFile(quicksortRunStatistics, "quickSort"); sendStatisticsToScreen(quicksortRunStatistics); sendStatisticsToCSV(quicksortRunStatistics, "quickSort"); sendStatisticsToFile(selectsortRunStatistics, "selectSort"); sendStatisticsToScreen(selectsortRunStatistics); sendStatisticsToCSV(selectsortRunStatistics, "selectSort"); } arraySort::~arraySort() { //dtor } arraySort::arraySort(const arraySort& other) { //copy ctor } arraySort& arraySort::operator=(const arraySort& rhs) { if (this == &rhs) return *this; // handle self assignment //assignment operator return *this; } void arraySort::testDo() { ///perform select sort on the randomArray. //cout << "segfault test in testDo" << endl; // selectsort ss(randomArray); ///add the runtime for the ss to the select sort runtimes array ///using the passed int "iteration" to set index. //selectsortTimes.push_back(ss.getSortTime()); quicksort qs(randomArray); quicksortTimes.push_back(qs.getSortTime()); } void arraySort::generateRandomArray(int arraySize) { srand(static_cast<unsigned>(time(NULL))); // cout << "arraySize is: "<< arraySize <<endl; for (int i = 0; i < arraySize; ++i) { randomArray.push_back(rand()); } } int arraySort::arraySizeCalibration() { int testArraySize = 0; long arrayTestResults=0; quicksort calibrate_quicksort; //selectsort calibrate_selectsort; while (arrayTestResults <= 0.0) { testArraySize +=1000; generateRandomArray(testArraySize); //calibrate_quicksort = new quicksort(); calibrate_quicksort.doSort(randomArray); //calibrate_selectsort.doSort(randomArray); arrayTestResults = calibrate_quicksort.getSortTime(); //arrayTestResults = calibrate_selectsort.getSortTime(); clearRandomArray(); //run arraysort over and over until get sort time > 0 } return testArraySize; } void arraySort::printArray(const vector<int> &passedArray) { for (unsigned int i = 0; i < passedArray.size() -1; ++i) { cout << "element:" << i << " is:" << passedArray[i] << "**" <<endl; } } void arraySort::sendArrayToFile(const vector<long> &passedArray) { outputFile.open("testfile.txt"); for (unsigned int i = 0; i < passedArray.size() -1; ++i) { outputFile << "element:" << i << " is:" << passedArray[i] << endl; } outputFile.close(); } void arraySort::sendStatisticsToFile(const vector<sortStats> &statisticsArray, string sortType) { string filename = "statstest_"+ sortType + ".txt"; outputFile.open(filename.c_str()); for (unsigned int i = 0; i < statisticsArray.size(); ++i) { outputFile << "Mean for test " << i << " is:" << statisticsArray[i].mean << endl; outputFile << "Standard Deviation for test " << i << " is:" << statisticsArray[i].standardDeviation << endl; outputFile << "Variance test " << i << " is:" << statisticsArray[i].variance << endl; outputFile << "Zvalue for test " << i << " is:" << statisticsArray[i].Zvalue << endl; outputFile << "***********************************************************" << endl; } outputFile.close(); } void arraySort::sendStatisticsToScreen(const vector<sortStats> &statisticsArray) { for (unsigned int i = 0; i < statisticsArray.size(); ++i) { cout << "***********************************************************"<< endl; cout << "Mean for test " << i << " is:" << statisticsArray[i].mean << endl; cout << "Standard Deviation for test " << i << " is:" << statisticsArray[i].standardDeviation << endl; cout << "Variance test " << i << " is:" << statisticsArray[i].variance << endl; cout << "Zvalue for test " << i << " is:" << statisticsArray[i].Zvalue << endl; cout << "***********************************************************" << endl; } } void arraySort::sendStatisticsToCSV(const vector<sortStats> &statisticsArray, string sortType) { string filename = "statstest_"+ sortType + ".csv"; outputFile.open(filename.c_str()); outputFile << "\"Mean\",\"Standard Deviation\",\"Variance\",\"ZValue\",\"ArraySize\",\"Sample Size\",\"Test Number\"" <<endl; for (unsigned int i = 0; i < statisticsArray.size(); ++i) { outputFile << statisticsArray[i].mean <<","<<statisticsArray[i].standardDeviation<<","<< statisticsArray[i].variance<<","<<statisticsArray[i].Zvalue<<","<<statisticsArray[i].arraySize<< ","<<statisticsArray[i].sampleSize<<","<<i+1<<endl; } outputFile.close(); } void arraySort::clearRandomArray() { // cout << " clearRandomArray is problem?" << endl; randomArray.clear(); } void arraySort::storeStatistics(vector<long> &passedStats, int numberOfSamplings, int sortType) { sortStats tempElement; // cout << "starting stats calculations for counter: "<< counter <<" of "<< NUMBER_OF_RUNS << endl; if (sortType == quickSort) { ///calculate the current array size's mean and store it in testRunStatistics tempElement.mean = statisticsGenerator.calculateMean(quicksortTimes); ///calculate the current array size's Standard Deviation and store it in testRunStatistics tempElement.standardDeviation = statisticsGenerator.calculateStandardDeviation(quicksortTimes, tempElement.mean); ///calculate the current array size's variance and store it in testRunStatistics tempElement.variance = statisticsGenerator.calculateVariance(tempElement.standardDeviation); ///calculate the current array size's Z score and store it in testRunStatistics tempElement.Zvalue = 0.0; tempElement.arraySize = passedStats.size(); tempElement.sampleSize = numberOfSamplings; //testRunStatistics[counter].Zvalue = statisticsGenerator.calculateZvalue(); quicksortRunStatistics.push_back(tempElement); } if (sortType == selectSort) { ///calculate the current array size's mean and store it in testRunStatistics tempElement.mean = statisticsGenerator.calculateMean(selectsortTimes); ///calculate the current array size's Standard Deviation and store it in testRunStatistics tempElement.standardDeviation = statisticsGenerator.calculateStandardDeviation(selectsortTimes, tempElement.mean); ///calculate the current array size's variance and store it in testRunStatistics tempElement.variance = statisticsGenerator.calculateVariance(tempElement.standardDeviation); ///calculate the current array size's Z score and store it in testRunStatistics tempElement.Zvalue = 0.0; tempElement.arraySize = randomArraySize; tempElement.sampleSize = numberOfSamplings; //testRunStatistics[counter].Zvalue = statisticsGenerator.calculateZvalue(); selectsortRunStatistics.push_back(tempElement); } }
[ [ [ 1, 253 ] ] ]
d865279c9a2e515dbf234fd0fa1a4cb8c2939ee7
84f06293f8d797a6be92a5cbdf81e6992717cc9d
/touch_tracker/tbeta/app/nuigroup/ofxCore_VS2005/src/rect2d.h
26f70d16492f7ffb5e800d575ccc328c8495e80f
[]
no_license
emailtoan/touchapi
bd7b8fa140741051670137d1b93cae61e1c7234a
54e41d3f1a05593e943129ef5b2c63968ff448b9
refs/heads/master
2016-09-07T18:43:51.754299
2008-10-17T06:18:43
2008-10-17T06:18:43
40,374,104
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,172
h
#ifndef __TOUCHLIB_RECT2D__ #define __TOUCHLIB_RECT2D__ //#include <vector2d.h> #include "vector2d.h" // The following code was originally written by Nikolaus Gebhardt as part of Irrlicht. // See www.irrlicht3d.org // The Irrlicht Engine License // Copyright © 2002-2005 Nikolaus Gebhardt // 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. //! Rectangle template. template <class T> class rect { public: rect() : upperLeftCorner(0,0), lowerRightCorner(0,0) {}; rect(T x, T y, T x2, T y2) : upperLeftCorner(x,y), lowerRightCorner(x2,y2) {}; rect(const vector2d<T>& upperLeft, const vector2d<T>& lowerRight) : upperLeftCorner(upperLeft), lowerRightCorner(lowerRight) {}; inline void addPoint(const vector2d<T> &pt) { if(upperLeftCorner == vector2d<T>(0,0) && lowerRightCorner == vector2d<T>(0,0)) { upperLeftCorner = pt; lowerRightCorner = pt; return; } if(pt.X < upperLeftCorner.X) upperLeftCorner.X = pt.X; if(pt.Y < upperLeftCorner.Y) upperLeftCorner.Y = pt.Y; if(pt.X > lowerRightCorner.X) lowerRightCorner.X = pt.X; if(pt.Y > lowerRightCorner.Y) lowerRightCorner.Y = pt.Y; }; inline void addPoint(T x, T y) { if(upperLeftCorner == vector2d<T>(0,0) && lowerRightCorner == vector2d<T>(0,0)) { upperLeftCorner.X = x; upperLeftCorner.Y = y; lowerRightCorner.X = x; lowerRightCorner.Y = y; return; } if(x < upperLeftCorner.X) upperLeftCorner.X = x; if(y < upperLeftCorner.Y) upperLeftCorner.Y = y; if(x > lowerRightCorner.X) lowerRightCorner.X = x; if(y > lowerRightCorner.Y) lowerRightCorner.Y = y; }; void reset(const vector2d<T> &pt) { upperLeftCorner = pt; lowerRightCorner = pt; } bool isPointInside(const vector2d<T>& pos) const { return upperLeftCorner.X <= pos.X && upperLeftCorner.Y <= pos.Y && lowerRightCorner.X >= pos.X && lowerRightCorner.Y >= pos.Y; } //! Returns if the rectangle collides with an other rectangle. bool isRectCollided(const rect<T>& other) const { return (lowerRightCorner.Y > other.upperLeftCorner.Y && upperLeftCorner.Y < other.lowerRightCorner.Y && lowerRightCorner.X > other.upperLeftCorner.X && upperLeftCorner.X < other.lowerRightCorner.X); } //! Returns if the rectangle collides with an other rectangle. bool isBoxInside(const rect<T>& other) const { //return (this->isPointInside(other.upperLeftCorner) && this->isPointInside(other.lowerRightCorner)); return (other.upperLeftCorner.Y >= upperLeftCorner.Y && other.upperLeftCorner.X >= upperLeftCorner.X && other.lowerRightCorner.Y <= lowerRightCorner.Y && other.lowerRightCorner.X <= lowerRightCorner.X); } //! Returns width of rectangle. T getWidth() const { return lowerRightCorner.X - upperLeftCorner.X; } //! Returns height of rectangle. T getHeight() const { return lowerRightCorner.Y - upperLeftCorner.Y; } //! Returns the center of the rectangle vector2d<T> getCenter() const { return vector2d<T>((upperLeftCorner.X + lowerRightCorner.X) / 2, (upperLeftCorner.Y + lowerRightCorner.Y) / 2); } T getArea() const { return getHeight() * getWidth(); } //! Clips this rectangle with another one. void clipAgainst(const rect<T>& other) { if (other.lowerRightCorner.X < lowerRightCorner.X) lowerRightCorner.X = other.lowerRightCorner.X; if (other.lowerRightCorner.Y < lowerRightCorner.Y) lowerRightCorner.Y = other.lowerRightCorner.Y; if (other.upperLeftCorner.X > upperLeftCorner.X) upperLeftCorner.X = other.upperLeftCorner.X; if (other.upperLeftCorner.Y > upperLeftCorner.Y) upperLeftCorner.Y = other.upperLeftCorner.Y; // correct possible invalid rect resulting from clipping if (upperLeftCorner.Y > lowerRightCorner.Y) upperLeftCorner.Y = lowerRightCorner.Y; if (upperLeftCorner.X > lowerRightCorner.X) upperLeftCorner.X = lowerRightCorner.X; } vector2d<T> upperLeftCorner; vector2d<T> lowerRightCorner; }; //! Typedef for float 2d vector. typedef rect<float> rect2df; #endif
[ "cerupcat@5e10ba55-a837-0410-a92f-dfacd3436b42" ]
[ [ [ 1, 168 ] ] ]
cbdf3ec2d861350db1789b76f257fce81000fc7e
e8d9619e262531453688550db22d0e78f1b51dab
/meta2/proto.cpp
8b2ca83313aba66ef11d0ecf4bae9ebc07ab3011
[]
no_license
sje397/sje-miranda-plugins
e9c562f402daef2cfbe333ce9a8a888cd81c9573
effb7ea736feeab1c68db34a86da8a2be2b78626
refs/heads/master
2016-09-05T16:42:34.162442
2011-05-22T14:48:15
2011-05-22T14:48:15
1,784,020
2
1
null
null
null
null
UTF-8
C++
false
false
18,567
cpp
#include "common.h" #include "proto.h" #include "resource.h" #include "core_functions.h" #include "api.h" #include "priorities.h" bool firstSetOnline = true; DWORD status = ID_STATUS_OFFLINE; UINT_PTR setStatusTimerId = 0; DWORD next_meta_id = 1; #define EVENTTYPE_STATUSCHANGE 25368 HANDLE NewMetaContact() { HANDLE hMeta = (HANDLE) CallService(MS_DB_CONTACT_ADD, 0, 0); DBWriteContactSettingDword(hMeta, MODULE, META_ID, next_meta_id++); CallService( MS_PROTO_ADDTOCONTACT, ( WPARAM )hMeta, ( LPARAM )MODULE); return hMeta; } INT_PTR GetCaps(WPARAM wParam,LPARAM lParam) { INT_PTR ret = 0; switch (wParam) { case PFLAGNUM_1: ret = PF1_NUMERICUSERID | PF1_IM | PF1_MODEMSGRECV | PF1_FILESEND; break; case PFLAGNUM_2: ret = PF2_ONLINE | PF2_INVISIBLE | PF2_SHORTAWAY | PF2_LONGAWAY | PF2_LIGHTDND | PF2_HEAVYDND | PF2_FREECHAT | PF2_OUTTOLUNCH | PF2_ONTHEPHONE; break; case PFLAGNUM_3: ret = PF2_ONLINE | PF2_INVISIBLE | PF2_SHORTAWAY | PF2_LONGAWAY | PF2_LIGHTDND | PF2_HEAVYDND | PF2_FREECHAT | PF2_OUTTOLUNCH | PF2_ONTHEPHONE; break; case PFLAGNUM_4: ret = PF4_SUPPORTTYPING | PF4_AVATARS | PF4_SUPPORTIDLE | PF4_IMSENDUTF | PF4_IMSENDOFFLINE; break; case PFLAGNUM_5: ret = PF2_ONLINE | PF2_INVISIBLE | PF2_SHORTAWAY | PF2_LONGAWAY | PF2_LIGHTDND | PF2_HEAVYDND | PF2_FREECHAT | PF2_OUTTOLUNCH | PF2_ONTHEPHONE; break; case PFLAG_UNIQUEIDTEXT: ret = (INT_PTR) Translate("Meta ID"); break; case PFLAG_MAXLENOFMESSAGE: ret = 2048; break; case PFLAG_UNIQUEIDSETTING: ret = (INT_PTR) META_ID; break; } return ret; } INT_PTR GetName(WPARAM wParam,LPARAM lParam) { char *name = (char *)Translate(MODULE); size_t size = min(strlen(name),wParam-1); // copy only the first size bytes. if(strncpy((char *)lParam,name,size)==NULL) return 1; ((char *)lParam)[size]='\0'; return 0; } INT_PTR LoadIcon(WPARAM wParam,LPARAM lParam) { UINT id; switch (wParam & 0xFFFF) { case PLI_PROTOCOL: id = IDI_MCMENU; break; case PLI_ONLINE: id = IDI_MCMENU; break; case PLI_OFFLINE: id = IDI_MCMENUOFF; break; default: return 0; } return (INT_PTR) LoadImage(hInst, MAKEINTRESOURCE(id), IMAGE_ICON, GetSystemMetrics(wParam & PLIF_SMALL ? SM_CXSMICON : SM_CXICON), GetSystemMetrics(wParam & PLIF_SMALL ? SM_CYSMICON : SM_CYICON), 0); return 0; } INT_PTR ProtoGetInfo(WPARAM wParam,LPARAM lParam) { CCSDATA *ccs = ( CCSDATA* )lParam; ccs->hContact = Meta_GetActive(ccs->hContact); char *proto = ContactProto(ccs->hContact); if(!proto) return 1; char szServiceName[256]; mir_snprintf(szServiceName, 256, "%s%s", proto, PSS_GETINFO); if (ServiceExists(szServiceName)) { return CallContactService(ccs->hContact, PSS_GETINFO, ccs->wParam, ccs->lParam); } return 1; } INT_PTR ProtoGetAwayMsg(WPARAM wParam, LPARAM lParam) { CCSDATA *ccs = ( CCSDATA* )lParam; ccs->hContact = Meta_GetMostOnlineSupporting(ccs->hContact, PFLAGNUM_1, PF1_MODEMSGRECV); char *proto = ContactProto(ccs->hContact); if(!proto) return 0; char szServiceName[256]; mir_snprintf(szServiceName, 256, "%s%s", proto, PSS_GETAWAYMSG); if (ServiceExists(szServiceName)) { return CallContactService(ccs->hContact, PSS_GETAWAYMSG, ccs->wParam, ccs->lParam); } return 0; } void CALLBACK SetStatusProc(HWND hWnd, UINT msg, UINT_PTR id, DWORD dw) { int previousMode = status; status = (int)ID_STATUS_ONLINE; ProtoBroadcastAck(MODULE, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)previousMode, status); KillTimer(0, setStatusTimerId); } INT_PTR SetStatus(WPARAM wParam,LPARAM lParam) { // firstSetOnline starts out true - used to delay metacontact's 'onlineness' to prevent double status notifications on startup if(status == ID_STATUS_OFFLINE && firstSetOnline) { // causes crash on exit if miranda is closed in under options.set_status_from_offline milliseconds! //CloseHandle( CreateThread( NULL, 0, SetStatusThread, (void *)wParam, 0, 0 )); setStatusTimerId = SetTimer(0, 0, 10000, SetStatusProc); firstSetOnline = FALSE; } else { int previousMode = status; status = (int)wParam; ProtoBroadcastAck(MODULE, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)previousMode, status); } return 0; } INT_PTR GetStatus(WPARAM wParam,LPARAM lParam) { return status; } INT_PTR ProtoSendMessage(WPARAM wParam, LPARAM lParam) { CCSDATA *ccs = (CCSDATA *) lParam; char *message = (char *)ccs->lParam; int flags = ccs->wParam; char *buff = 0, *proto = 0; HANDLE hMeta = ccs->hContact; HANDLE hSendTo = (HANDLE)MetaAPI_GetActiveContact((WPARAM)hMeta, 0); proto = ContactProto(hSendTo); //DBWriteContactSettingDword(hMeta, MODULE, "TempDefault", (DWORD)hSendTo); char szServiceName[256]; mir_snprintf(szServiceName, 256, "%s", PSS_MESSAGE); if((flags & PREF_UNICODE) && proto != 0) { char szTemp[256]; mir_snprintf(szTemp, 256, "%s%sW", proto, PSS_MESSAGE); if (ServiceExists(szTemp)) strncpy(szServiceName, PSS_MESSAGE "W", sizeof(szServiceName)); } // subcontact does not support utf - convert to old ascii/wide format if((flags & PREF_UTF) && (proto == 0 || !(CallProtoService(proto, PS_GETCAPS, PFLAGNUM_4, 0) & PF4_IMSENDUTF))) { ccs->wParam &= ~PREF_UTF; ccs->wParam |= PREF_UNICODE; wchar_t *unicode = mir_utf8decodeW(message); char *ascii = mir_u2a_cp(unicode, codepage); char *buff = new char[strlen(ascii) + 1 + (wcslen(unicode) + 1) * sizeof(wchar_t)]; strcpy(buff, ascii); wcscpy((wchar_t *)(buff + strlen(ascii) + 1), unicode); mir_free(unicode); mir_free(ascii); ccs->lParam = (LPARAM)buff; } INT_PTR ret = (INT_PTR)CallContactService(hSendTo, szServiceName, ccs->wParam, ccs->lParam); if(buff) { // undo our utf8 conversion changes ccs->lParam = (LPARAM)message; delete[] buff; } return ret; } INT_PTR ProtoSendMessageW(WPARAM wParam, LPARAM lParam) { CCSDATA *ccs = (CCSDATA *) lParam; if(!(ccs->wParam & PREF_UTF)) ccs->wParam |= PREF_UNICODE; return ProtoSendMessage(wParam, lParam); } INT_PTR ProtoRecvMessage(WPARAM wParam, LPARAM lParam) { CCSDATA *ccs = (CCSDATA *) lParam; PROTORECVEVENT *pre = (PROTORECVEVENT *) ccs->lParam; // use the subcontact's protocol to add to the db (AIMOSCAR removes HTML here!) HANDLE most_online = Meta_GetActive(ccs->hContact); char *proto = ContactProto(most_online); if(proto) { char service[256]; mir_snprintf(service, 256, "%s%s", proto, PSR_MESSAGE); if(ServiceExists(service)) return CallService(service, wParam, lParam); } return 0; } int RedirectACKs(WPARAM wParam, LPARAM lParam) { ACKDATA *ack = (ACKDATA*) lParam; HANDLE hMeta; if(ack->hContact == 0 || (hMeta = (HANDLE)DBGetContactSettingDword(ack->hContact, MODULE, "Handle", 0)) == 0) return 0; // Can't find the MetaID, let through the protocol chain if(!strcmp(ack->szModule, MODULE)) { return 0; // don't rebroadcast our own acks } // if it's for something we don't support, ignore if(ack->type != ACKTYPE_MESSAGE && ack->type != ACKTYPE_CHAT && ack->type != ACKTYPE_FILE && ack->type != ACKTYPE_AWAYMSG && ack->type != ACKTYPE_AVATAR && ack->type != ACKTYPE_GETINFO) { return 0; } // change the hContact in the avatar info struct, if it's the avatar we're using - else drop it if(ack->type == ACKTYPE_AVATAR) { if(ack->result == ACKRESULT_SUCCESS || ack->result == ACKRESULT_FAILED || ack->result == ACKRESULT_STATUS) { if(ack->hContact == 0) { return 0; } if(ack->hProcess) { PROTO_AVATAR_INFORMATION AI; memcpy(&AI, (PROTO_AVATAR_INFORMATION *)ack->hProcess, sizeof(PROTO_AVATAR_INFORMATION)); if(AI.hContact) AI.hContact = hMeta; return ProtoBroadcastAck(MODULE,hMeta,ack->type,ack->result, (HANDLE)&AI, ack->lParam); } else return ProtoBroadcastAck(MODULE,hMeta,ack->type,ack->result, 0, ack->lParam); } } return ProtoBroadcastAck(MODULE, hMeta, ack->type, ack->result, ack->hProcess, ack->lParam); } INT_PTR ProtoGetAvatarInfo(WPARAM wParam, LPARAM lParam) { PROTO_AVATAR_INFORMATION *AI = (PROTO_AVATAR_INFORMATION *) lParam; HANDLE hMeta = AI->hContact; // find the most online contact supporting avatars, according to priorities HANDLE most_online = (HANDLE)Meta_GetMostOnlineSupporting(hMeta, PFLAGNUM_4, PF4_AVATARS); char *most_online_proto = ContactProto(most_online); AI->hContact = most_online; char szServiceName[100]; mir_snprintf(szServiceName, sizeof(szServiceName), "%s%s", most_online_proto, PS_GETAVATARINFO); int result = CallService(szServiceName, wParam, lParam); AI->hContact = hMeta; if (result != CALLSERVICE_NOTFOUND) return result; return GAIR_NOAVATAR; // fail } INT_PTR ProtoFileSend(WPARAM wParam, LPARAM lParam) { CCSDATA *ccs = (CCSDATA *) lParam; HANDLE hMeta = ccs->hContact; // find the most online contact supporting file send, according to priorities HANDLE most_online = (HANDLE)Meta_GetMostOnlineSupporting(hMeta, PFLAGNUM_1, PF1_FILESEND); if(ContactStatus(most_online, ContactProto(most_online)) == ID_STATUS_OFFLINE) most_online = (HANDLE)Meta_GetMostOnlineSupporting(hMeta, PFLAGNUM_4, PF4_OFFLINEFILES); int result = CallContactService(most_online, PSS_FILE, ccs->wParam, ccs->lParam); if(result != CALLSERVICE_NOTFOUND) return result; return 0; // fail } INT_PTR ProtoUserIsTyping(WPARAM wParam, LPARAM lParam) { HANDLE hMeta = (HANDLE)wParam; // find the most online contact supporting typing notifications, according to priorities HANDLE most_online = (HANDLE)Meta_GetMostOnlineSupporting(hMeta, PFLAGNUM_4, PF4_SUPPORTTYPING); char *most_online_proto = ContactProto(most_online); char szServiceName[256]; mir_snprintf(szServiceName, sizeof(szServiceName), "%s%s", most_online_proto, PSS_USERISTYPING); CallService(szServiceName, (WPARAM)most_online, lParam); return 0; } int EventContactIsTyping(WPARAM wParam, LPARAM lParam) { HANDLE hMeta; if((hMeta = (HANDLE)DBGetContactSettingDword((HANDLE)wParam, MODULE, "Handle", 0)) != 0 && MetaEnabled()) { // try to remove any clist events added for subcontact CallServiceSync(MS_CLIST_REMOVEEVENT, wParam, (LPARAM) 1); CallService(MS_PROTO_CONTACTISTYPING, (WPARAM)hMeta, lParam); // stop processing of event return 1; } return 0; } INT_PTR SendNudge(WPARAM wParam,LPARAM lParam) { HANDLE hMeta = (HANDLE)wParam, hSubContact = Meta_GetActive(hMeta); char servicefunction[256]; char *protoName = ContactProto(hSubContact); mir_snprintf(servicefunction, 256, "%s/SendNudge", protoName); return CallService(servicefunction, (WPARAM)hSubContact, lParam); } int ContactDeleted(WPARAM wParam, LPARAM lParam) { HANDLE hContact = (HANDLE)wParam; if(IsSubcontact(hContact)) { Meta_Remove(hContact); } else if(IsMetacontact(hContact)) { SubcontactList::Iterator i = metaMap[hContact].start(); HANDLE hSub; while(i.has_val()) { // same functionality as Meta_Remove - except the meta is not deleted when all subcontacts are removed here since it's already happening, // and the 'subcontacts changed' event isn't fired hSub = i.val().handle(); DBDeleteContactSetting(hSub, MODULE, "ParentMetaID"); // deleting these (resident) settings doesn't work :( [25/9/07] DBWriteContactSettingDword(hSub, MODULE, "Handle", 0); DBWriteContactSettingByte(hSub, MODULE, "IsSubcontact", 0); if(!meta_group_hack_disabled) DBWriteContactSettingByte(hSub, "CList", "Hidden", 0); CallService(MS_IGNORE_UNIGNORE, (WPARAM)hSub, (WPARAM)IGNOREEVENT_USERONLINE); i.next(); } metaMap.remove(hContact); } return 0; } int SettingChanged(WPARAM wParam, LPARAM lParam) { if(wParam == 0 || !IsSubcontact((HANDLE)wParam)) return 0; DBCONTACTWRITESETTING *dcws = (DBCONTACTWRITESETTING *)lParam; if(strcmp(dcws->szSetting, "Status") == 0) { // subcontact status has changed Meta_CalcStatus((HANDLE)DBGetContactSettingDword((HANDLE)wParam, MODULE, "Handle", 0)); } // keep subcontacts hidden if the clist doesn't do it for us if(strcmp(dcws->szSetting, "Hidden") == 0 && strcmp(dcws->szModule, "CList") == 0 && MetaEnabled() && !meta_group_hack_disabled) { if(dcws->value.type == DBVT_DELETED || dcws->value.bVal == 0) { DBWriteContactSettingByte((HANDLE)wParam, "CList", "Hidden", 1); } } return 0; } int MetaChanged(WPARAM wParam, LPARAM lParam) { Meta_CalcStatus((HANDLE)wParam); return 0; } int WindowEvent(WPARAM wParam, LPARAM lParam) { MessageWindowEventData *mwed = (MessageWindowEventData *)lParam; bool sub = IsSubcontact(mwed->hContact), meta = IsMetacontact(mwed->hContact); if(sub || meta) { if(mwed->uType == MSG_WINDOW_EVT_OPEN || mwed->uType == MSG_WINDOW_EVT_OPENING) { DBWriteContactSettingByte(mwed->hContact, MODULE, "WindowOpen", 1); if(meta) CallService(MS_CLIST_REMOVEEVENT, (WPARAM)mwed->hContact, (LPARAM)EVENTTYPE_MESSAGE); } else if(mwed->uType == MSG_WINDOW_EVT_CLOSE || mwed->uType == MSG_WINDOW_EVT_CLOSING) { DBWriteContactSettingByte(mwed->hContact, MODULE, "WindowOpen", 0); if(meta) { DBWriteContactSettingDword(mwed->hContact, MODULE, "TempDefault", 0); DBWriteContactSettingDword(mwed->hContact, MODULE, "ForceSend", 0); } } } return 0; } void RegisterProto() { PROTOCOLDESCRIPTOR pd = {0}; pd.cbSize = PROTOCOLDESCRIPTOR_V3_SIZE; //sizeof(pd); pd.szName = MODULE; pd.type = PROTOTYPE_PROTOCOL; CallService(MS_PROTO_REGISTERMODULE,0,(LPARAM)&pd); } // redirect events - works if the contact is both a sub and a meta :) #define DBEF_META 0x2000 int EventFilterAdd(WPARAM wParam, LPARAM lParam) { HANDLE hContact = (HANDLE)wParam; DBEVENTINFO *dbei = (DBEVENTINFO *)lParam; // prevent recursion if(dbei->flags & DBEF_META) return 0; dbei->flags |= DBEF_META; HANDLE hMeta; //events passed up to parent while((hMeta = (HANDLE)DBGetContactSettingDword(hContact, MODULE, "Handle", 0)) != 0) { // subcontact event being added (e.g. by subcontact proto) - add to meta CallService(MS_DB_EVENT_ADD, (WPARAM)hMeta, (LPARAM)dbei); if(dbei->eventType == EVENTTYPE_MESSAGE) { // set default int num = metaMap[hMeta].index_of(hContact); if(num != -1 && num != DBGetContactSettingByte(hMeta, MODULE, "Default", -1)) MetaAPI_SetDefaultContactNum((WPARAM)hMeta, (LPARAM)num); // set meta nick char *proto = ContactProto(hContact); DBVARIANT dbv; if(proto && !DBGetContactSettingUTF8String(0, proto, "Nick", &dbv)) { DBWriteContactSettingUTF8String(0, MODULE, "Nick", dbv.pszVal); DBFreeVariant(&dbv); } // set temp default DBWriteContactSettingDword(hMeta, MODULE, "TempDefault", (DWORD)hContact); } // mark as read if subcontact window not open if((dbei->flags & DBEF_READ) == 0 && (dbei->flags & DBEF_SENT) == 0 && DBGetContactSettingByte(hContact, MODULE, "WindowOpen", 0) == 0) { dbei->flags |= DBEF_READ; } hContact = hMeta; } // events passed down to children hContact = (HANDLE)wParam; // reset to the source event's contact HANDLE hSub; while((hSub = Meta_GetActive(hContact)) != 0) { CallService(MS_DB_EVENT_ADD, (WPARAM)hSub, (LPARAM)dbei); hContact = hSub; } // let original event through return 0; } #define NUM_HOOKS_INTERNAL 10 int hookIndex = 0; HANDLE hHooksInternal[NUM_HOOKS_INTERNAL] = {0}; HANDLE hEventMessageWindow = 0; int ModulesLoadedProto(WPARAM wParam, LPARAM lParam) { hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_MSG_WINDOWEVENT, WindowEvent); Meta_Hide(DBGetContactSettingByte(0, MODULE, "Enabled", 1) == 0); // hooked here so we get it later (than e.g. OTR) hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_DB_EVENT_FILTER_ADD, EventFilterAdd); return 0; } #define NUM_SERVICES 14 HANDLE hServices[NUM_SERVICES] = {0}; void InitProto() { RegisterProto(); // create our services int i = 0; hServices[i++] = CreateProtoServiceFunction(MODULE, PS_GETCAPS, GetCaps); hServices[i++] = CreateProtoServiceFunction(MODULE, PS_GETNAME, GetName); hServices[i++] = CreateProtoServiceFunction(MODULE, PS_LOADICON, LoadIcon); hServices[i++] = CreateProtoServiceFunction(MODULE, PS_SETSTATUS, SetStatus); hServices[i++] = CreateProtoServiceFunction(MODULE, PS_GETSTATUS, GetStatus); hServices[i++] = CreateProtoServiceFunction(MODULE, PSS_GETINFO, ProtoGetInfo); hServices[i++] = CreateProtoServiceFunction(MODULE, PSS_MESSAGE, ProtoSendMessage); hServices[i++] = CreateProtoServiceFunction(MODULE, PSS_MESSAGE"W", ProtoSendMessageW); hServices[i++] = CreateProtoServiceFunction(MODULE, PSR_MESSAGE, ProtoRecvMessage); hServices[i++] = CreateProtoServiceFunction(MODULE, PSS_GETAWAYMSG, ProtoGetAwayMsg); hServices[i++] = CreateProtoServiceFunction(MODULE, PS_GETAVATARINFO, ProtoGetAvatarInfo); hServices[i++] = CreateProtoServiceFunction(MODULE, PSS_FILE, ProtoFileSend); hServices[i++] = CreateProtoServiceFunction(MODULE, PSS_USERISTYPING, ProtoUserIsTyping); // REMEMBER to modify the NUM_SERVICES #define above if you add more services! hServices[i++] = CreateProtoServiceFunction(MODULE, "/SendNudge", SendNudge); hHooksInternal[hookIndex++] = HookEvent(ME_DB_CONTACT_DELETED, ContactDeleted); hHooksInternal[hookIndex++] = HookEvent(ME_DB_CONTACT_SETTINGCHANGED, SettingChanged); hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_MC_DEFAULTTCHANGED, MetaChanged ); hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_MC_FORCESEND, MetaChanged ); hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_MC_UNFORCESEND, MetaChanged ); hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_PROTO_ACK, RedirectACKs); hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_SYSTEM_MODULESLOADED, ModulesLoadedProto); hHooksInternal[hookIndex++] = (HANDLE)HookEvent(ME_PROTO_CONTACTISTYPING, EventContactIsTyping); } void DeinitProto() { for(int i = 0; i < NUM_SERVICES; i++) DestroyServiceFunction(hServices[i]); for(int j = 0; j < NUM_HOOKS_INTERNAL; j++) UnhookEvent(hHooksInternal[j]); }
[ [ [ 1, 529 ] ] ]
f420174c3f227b09fa0fe8d91fefb7089da4190d
b4d726a0321649f907923cc57323942a1e45915b
/CODE/ImpED/ship_select.cpp
b8af63f6ed02a87e68338f5bd57f8a8ffc922a57
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
17,584
cpp
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/FRED2/ship_select.cpp $ * $Revision: 1.2 $ * $Date: 2002/08/15 01:06:34 $ * $Author: penguin $ * * Object selection (marking) dialog box handling code * * $Log: ship_select.cpp,v $ * Revision 1.2 2002/08/15 01:06:34 penguin * Include filename reorg (to coordinate w/ fs2_open) * * Revision 1.1.1.1 2002/07/15 03:11:03 inquisitor * Initial FRED2 Checking * * * 2 10/07/98 6:28p Dave * Initial checkin. Renamed all relevant stuff to be Fred2 instead of * Fred. Globalized mission and campaign file extensions. Removed Silent * Threat specific code. * * 1 10/07/98 3:01p Dave * * 1 10/07/98 3:00p Dave * * 21 2/13/98 11:48a Hoffoss * Fixed up some bugs with object selection when filters are turned off. * * 20 9/16/97 9:41p Hoffoss * Changed Fred code around to stop using Parse_player structure for * player information, and use actual ships instead. * * 19 9/09/97 10:29a Hoffoss * Added support for neutral team, and fixed changes made to how team is * used in ship structure. * * 18 9/06/97 2:13p Mike * Replace support for TEAM_NEUTRAL * * 17 8/26/97 11:08a Hoffoss * Added waypoint paths to object selection dialog. * * 16 7/28/97 5:10p Hoffoss * Removed all occurances of neutral team from Fred. * * 15 7/24/97 2:43p Hoffoss * Made changes whiteside requested. Double clicking acts as clicking ok * button. * * 14 7/24/97 10:24a Mike * Restore support for Unknown team * * 13 7/10/97 11:24a Hoffoss * Fixed bugs in briefing editor system. Make icon button not updating * when selecting ships via list select, and after making icon, it wasn't * being displayed, though it was selected. * * 12 5/26/97 10:30a Hoffoss * Added select wing to object select dialog. * * 11 5/14/97 4:08p Lawrance * removing my_index from game arrays * * 10 3/07/97 4:37p Mike * Make rockeye missile home. * Remove UNKNOWN and NEUTRAL teams. * * 9 2/17/97 5:28p Hoffoss * Checked RCS headers, added them were missing, changing description to * something better, etc where needed. * * $NoKeywords: $ */ #include "stdafx.h" #include "FRED.h" #include "ship_select.h" #include "globalincs/linklist.h" #include "object/object.h" #include "ship/ship.h" #include "Management.h" #include "FREDView.h" #define ACTIVITY_SHIP 1 #define ACTIVITY_WING 2 #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int filter_ships = TRUE; int filter_starts = TRUE; int filter_waypoints = TRUE; int filter_friendly = TRUE; int filter_hostile = TRUE; int filter_neutral = TRUE; int filter_unknown = TRUE; extern int ship_select_down; int activity, list_size, wlist_size, wplist_size; CBrush m_cBrush; HBRUSH m_hBrush; ship_select *ship_select_ptr = NULL; ///////////////////////////////////////////////////////////////////////////// // ship_select dialog ship_select::ship_select(CWnd* pParent /*=NULL*/) : CDialog(ship_select::IDD, pParent) { //{{AFX_DATA_INIT(ship_select) m_filter_ships = TRUE; m_filter_starts = TRUE; m_filter_waypoints = TRUE; m_filter_friendly = TRUE; m_filter_hostile = TRUE; m_filter_neutral = TRUE; m_filter_unknown = TRUE; //}}AFX_DATA_INIT m_filter_ships = filter_ships; m_filter_starts = filter_starts; m_filter_waypoints = filter_waypoints; m_filter_friendly = filter_friendly; m_filter_hostile = filter_hostile; m_filter_neutral = filter_neutral; m_filter_unknown = filter_unknown; activity = 0; ship_select_ptr = this; } void ship_select::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(ship_select) DDX_Control(pDX, IDC_WING_LIST, m_wing_list); DDX_Control(pDX, IDC_SHIP_LIST, m_ship_list); DDX_Check(pDX, IDC_FILTER_SHIPS, m_filter_ships); DDX_Check(pDX, IDC_FILTER_STARTS, m_filter_starts); DDX_Check(pDX, IDC_FILTER_WAYPOINTS, m_filter_waypoints); DDX_Check(pDX, IDC_FILTER_SHIPS_FRIENDLY, m_filter_friendly); DDX_Check(pDX, IDC_FILTER_SHIPS_HOSTILE, m_filter_hostile); DDX_Check(pDX, IDC_FILTER_SHIPS_NEUTRAL, m_filter_neutral); DDX_Check(pDX, IDC_FILTER_SHIPS_UNKNOWN, m_filter_unknown); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(ship_select, CDialog) //{{AFX_MSG_MAP(ship_select) ON_CBN_SELCHANGE(IDC_WING_DISPLAY_FILTER, OnSelchangeWingDisplayFilter) ON_BN_CLICKED(IDC_FILTER_SHIPS, OnFilterShips) ON_BN_CLICKED(IDC_FILTER_STARTS, OnFilterStarts) ON_BN_CLICKED(IDC_FILTER_WAYPOINTS, OnFilterWaypoints) ON_BN_CLICKED(IDC_FILTER_SHIPS_FRIENDLY, OnFilterShipsFriendly) ON_BN_CLICKED(IDC_FILTER_SHIPS_HOSTILE, OnFilterShipsHostile) ON_BN_CLICKED(IDC_FILTER_SHIPS_NEUTRAL, OnFilterShipsNeutral) ON_BN_CLICKED(IDC_FILTER_SHIPS_UNKNOWN, OnFilterShipsUnknown) ON_BN_CLICKED(IDC_CLEAR, OnClear) ON_BN_CLICKED(IDC_ALL, OnAll) ON_BN_CLICKED(IDC_INVERT, OnInvert) ON_LBN_DBLCLK(IDC_SHIP_LIST, OnDblclkShipList) ON_LBN_SELCHANGE(IDC_WING_LIST, OnSelchangeWingList) ON_LBN_SELCHANGE(IDC_SHIP_LIST, OnSelchangeShipList) ON_LBN_DBLCLK(IDC_WING_LIST, OnDblclkWingList) ON_BN_CLICKED(IDC_UPDATE, update_list) ON_WM_TIMER () ON_WM_CTLCOLOR() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // ship_select message handlers void ship_select::OnSelchangeWingDisplayFilter() { UpdateData(TRUE); create_list(); } BOOL ship_select::OnInitDialog() { int i, flags; object *ptr; wlist_size = wplist_size = 0; CDialog::OnInitDialog(); ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { flags = ptr->flags & ~OF_TEMP_MARKED; if (flags & OF_MARKED) flags |= OF_TEMP_MARKED; else flags &= ~OF_TEMP_MARKED; ptr->flags = flags; ptr = GET_NEXT(ptr); } list_size = 0; create_list(); GetDlgItem(IDC_FILTER_SHIPS_FRIENDLY)->EnableWindow(m_filter_ships); GetDlgItem(IDC_FILTER_SHIPS_HOSTILE)->EnableWindow(m_filter_ships); GetDlgItem(IDC_FILTER_SHIPS_NEUTRAL)->EnableWindow(m_filter_ships); GetDlgItem(IDC_FILTER_SHIPS_UNKNOWN)->EnableWindow(m_filter_ships); // Elements 0 - wlist_size are wings, and elements wlist_size - wplist_size are waypoint paths m_wing_list.ResetContent(); wlist_size = 0; for (i=0; i<MAX_WINGS; i++) { if (Wings[i].wave_count) { m_wing_list.AddItem(Wings[i].name, RGB(255,255,0)); //m_wing_list.AddString(Wings[i].name); wing_sel_last[wlist_size] = 0; wing_index[wlist_size++] = i; } } /*wplist_size = wlist_size; for (i=0; i<Num_waypoint_lists; i++) { //m_wing_list.AddString(Waypoint_lists[i].name); wing_sel_last[wplist_size] = 0; wing_index[wplist_size++] = i; }*/ BOOL bRet = m_cBrush.CreateSolidBrush(RGB(0, 0, 0)); m_hBrush = (HBRUSH)m_cBrush; SetTimer(1, 100, 0); return TRUE; } void ship_select::OnTimer(UINT nIDEvent) { // I haven't left any comments in my changing of the Fred code to // suit the purposes of ImpED. Basically because MFC is ugly, nasty // horrible and should have never been unleashed on this planet. // But this is probably particularly nasty. I needed to update the // list of craft when a new one is added. And not knowing anyway // to get a hold of this class outside of it I had to create a timer. // This timer fires every 100 ms to create the craft list. This // is got to be very, very, very bad. Only thing I have to say for // myself is MFC sucks so I don't really care. //update_list(); CDialog::OnTimer(0); } void ship_select::create_list() { char text[512]; int flag; object *ptr; COLORREF color; int pos; pos = m_ship_list.GetCurSel(); update_status(); m_ship_list.ResetContent(); list_size = 0; if (m_filter_starts) { ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if (ptr->type == OBJ_START) { color = RGB(IFF_colors[Ships[ptr->instance].iff][0].red, IFF_colors[Ships[ptr->instance].iff][0].green, IFF_colors[Ships[ptr->instance].iff][0].blue); // stupid hack because here it doesn't seem to think 0 is green and 1 is red if (Ships[ptr->instance].iff == 0) color = RGB(0, 2550, 0); if (Ships[ptr->instance].iff == 1) color = RGB(255, 0, 0); m_ship_list.AddItem(Ships[ptr->instance].ship_name, color); //m_ship_list.AddString(Ships[ptr->instance].ship_name); obj_index[list_size++] = ptr; if (ptr->flags & OF_TEMP_MARKED) m_ship_list.SetSel(list_size - 1); } ptr = GET_NEXT(ptr); } } if (m_filter_ships) { ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if (ptr->type == OBJ_SHIP) { flag = 0; switch (Ships[ptr->instance].team) { case TEAM_FRIENDLY: flag = m_filter_friendly; break; case TEAM_HOSTILE: flag = m_filter_hostile; break; case TEAM_NEUTRAL: flag = m_filter_neutral; break; case TEAM_UNKNOWN: flag = m_filter_unknown; break; default: flag = m_filter_hostile; break; } if (flag) { color = RGB(IFF_colors[Ships[ptr->instance].iff][0].red, IFF_colors[Ships[ptr->instance].iff][0].green, IFF_colors[Ships[ptr->instance].iff][0].blue); if (Ships[ptr->instance].iff == 0) color = RGB(0, 2550, 0); if (Ships[ptr->instance].iff == 1) color = RGB(255, 0, 0); m_ship_list.AddItem(Ships[ptr->instance].ship_name, color); //m_ship_list.AddString(Ships[ptr->instance].ship_name); obj_index[list_size++] = ptr; if (ptr->flags & OF_TEMP_MARKED) m_ship_list.SetSel(list_size - 1); } } ptr = GET_NEXT(ptr); } } if (m_filter_waypoints) { ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if (ptr->type == OBJ_WAYPOINT) { sprintf(text, "%s:%d", Waypoint_lists[ptr->instance / 65536].name, (ptr->instance & 0xffff) + 1); m_ship_list.AddItem(text, RGB(160,154,154)); //m_ship_list.AddString(text); obj_index[list_size++] = ptr; if (ptr->flags & OF_TEMP_MARKED) m_ship_list.SetSel(list_size - 1); } ptr = GET_NEXT(ptr); } } //m_ship_list.SetCurSel(3); } void ship_select::OnOK() { KillTimer(1); object *ptr; unmark_all(); update_status(); ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if (ptr->flags & OF_TEMP_MARKED) mark_object(OBJ_INDEX(ptr)); ptr = GET_NEXT(ptr); } if (query_valid_object() && (Marked == 1) && (Objects[cur_object_index].type == OBJ_POINT)) { Assert(Briefing_dialog); Briefing_dialog->icon_select(Objects[cur_object_index].instance); } else { if (Briefing_dialog) Briefing_dialog->icon_select(-1); } filter_ships = m_filter_ships; filter_starts = m_filter_starts; filter_waypoints = m_filter_waypoints; filter_friendly = m_filter_friendly; filter_hostile = m_filter_hostile; filter_neutral = m_filter_neutral; filter_unknown = m_filter_unknown; ship_select_down = 0; CDialog::OnOK(); } void ship_select::OnCancel() { ship_select_down = 0; CDialog::OnCancel(); } void ship_select::update_status() { int i, z; object *ptr; ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { ptr->flags &= ~OF_TEMP_MARKED; ptr = GET_NEXT(ptr); } for (i=0; i<list_size; i++) { z = m_ship_list.GetSel(i); if (z < 1) obj_index[i]->flags &= ~OF_TEMP_MARKED; else obj_index[i]->flags |= OF_TEMP_MARKED; } OnSelchangeShipList(); } void ship_select::OnFilterShips() { UpdateData(TRUE); create_list(); GetDlgItem(IDC_FILTER_SHIPS_FRIENDLY)->EnableWindow(m_filter_ships); GetDlgItem(IDC_FILTER_SHIPS_HOSTILE)->EnableWindow(m_filter_ships); GetDlgItem(IDC_FILTER_SHIPS_NEUTRAL)->EnableWindow(m_filter_ships); GetDlgItem(IDC_FILTER_SHIPS_UNKNOWN)->EnableWindow(m_filter_ships); } void ship_select::OnFilterStarts() { UpdateData(TRUE); create_list(); } void ship_select::OnFilterWaypoints() { UpdateData(TRUE); create_list(); } void ship_select::OnFilterShipsFriendly() { UpdateData(TRUE); create_list(); } void ship_select::OnFilterShipsHostile() { UpdateData(TRUE); create_list(); } void ship_select::OnFilterShipsNeutral() { UpdateData(TRUE); create_list(); } void ship_select::OnFilterShipsUnknown() { UpdateData(TRUE); create_list(); } void ship_select::OnClear() { int i; object *ptr; ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { ptr->flags &= ~OF_TEMP_MARKED; ptr = GET_NEXT(ptr); } for (i=0; i<list_size; i++) m_ship_list.SetSel(i, FALSE); for (i=0; i<wplist_size; i++) { wing_sel_last[i] = 0; m_wing_list.SetSel(i, FALSE); } } void ship_select::OnAll() { int i; for (i=0; i<list_size; i++) { obj_index[i]->flags |= OF_TEMP_MARKED; m_ship_list.SetSel(i); } for (i=0; i<wplist_size; i++) { wing_sel_last[i] = 1; m_wing_list.SetSel(i, TRUE); } } void ship_select::OnInvert() { int i, z; for (i=0; i<list_size; i++) { z = m_ship_list.GetSel(i); if (z > 0) { obj_index[i]->flags &= ~OF_TEMP_MARKED; m_ship_list.SetSel(i, FALSE); } else { obj_index[i]->flags |= OF_TEMP_MARKED; m_ship_list.SetSel(i); } } OnSelchangeShipList(); } void ship_select::OnDblclkShipList() { OnOK(); /* int i, j, z, wing; z = m_ship_list.GetCaretIndex(); switch (obj_index[z]->type) { case OBJ_SHIP: wing = Ships[obj_index[z]->instance].wingnum; if (wing >= 0) { for (i=0; i<Wings[wing].wave_count; i++) for (j=0; j<list_size; j++) if (OBJ_INDEX(obj_index[j]) == wing_objects[wing][i]) { m_ship_list.SetSel(j); break; } for (i=0; i<wlist_size; i++) if (wing_index[i] == wing) { m_wing_list.SetSel(i); wing_sel_last[i] = 1; break; } } break; case OBJ_WAYPOINT: break; }*/ } void ship_select::OnSelchangeWingList() { int i, j, k, z; if (activity) return; activity = ACTIVITY_WING; for (i=0; i<wlist_size; i++) { z = (m_wing_list.GetSel(i) > 0) ? 1 : 0; if (z != wing_sel_last[i]) { for (j=0; j<Wings[wing_index[i]].wave_count; j++) for (k=0; k<list_size; k++) if (OBJ_INDEX(obj_index[k]) == wing_objects[wing_index[i]][j]) { m_ship_list.SetSel(k, z ? TRUE : FALSE); break; } wing_sel_last[i] = z; } } for (i=wlist_size; i<wplist_size; i++) { z = (m_wing_list.GetSel(i) > 0) ? 1 : 0; if (z != wing_sel_last[i]) { for (j=0; j<Waypoint_lists[wing_index[i]].count; j++) for (k=0; k<list_size; k++) if ((obj_index[k]->type == OBJ_WAYPOINT) && (obj_index[k]->instance == wing_index[i] * 65536 + j)) { m_ship_list.SetSel(k, z ? TRUE : FALSE); break; } wing_sel_last[i] = z; } } activity = 0; } void ship_select::OnSelchangeShipList() { int i, j, k, count; if (activity) return; activity = ACTIVITY_SHIP; for (i=0; i<wlist_size; i++) { count = 0; for (j=0; j<Wings[wing_index[i]].wave_count; j++) for (k=0; k<list_size; k++) if (OBJ_INDEX(obj_index[k]) == wing_objects[wing_index[i]][j]) { if (m_ship_list.GetSel(k)) count++; break; } if (count == Wings[wing_index[i]].wave_count) wing_sel_last[i] = 1; else wing_sel_last[i] = 0; m_wing_list.SetSel(i, wing_sel_last[i] ? TRUE : FALSE); } for (i=wlist_size; i<wplist_size; i++) { count = 0; for (j=0; j<Waypoint_lists[wing_index[i]].count; j++) for (k=0; k<list_size; k++) if ((obj_index[k]->type == OBJ_WAYPOINT) && (obj_index[k]->instance == wing_index[i] * 65536 + j)) { if (m_ship_list.GetSel(k)) count++; break; } if (count == Waypoint_lists[wing_index[i]].count) wing_sel_last[i] = 1; else wing_sel_last[i] = 0; m_wing_list.SetSel(i, wing_sel_last[i] ? TRUE : FALSE); } activity = 0; } void ship_select::OnDblclkWingList() { OnOK(); } void ship_select::update_list() { create_list(); m_wing_list.ResetContent(); wlist_size = 0; for (int i=0; i<MAX_WINGS; i++) { if (Wings[i].wave_count) { m_wing_list.AddItem(Wings[i].name, RGB(255,255,0)); wing_sel_last[wlist_size] = 0; wing_index[wlist_size++] = i; } } } HBRUSH ship_select::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor ) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (pWnd->GetDlgCtrlID() == IDC_SHIP_LIST) { //pDC->SetBkMode(TRANSPARENT); hbr = m_hBrush; } if (pWnd->GetDlgCtrlID() == IDC_WING_LIST) { pDC->SetBkMode(TRANSPARENT); hbr = m_hBrush; } return hbr; }
[ [ [ 1, 738 ] ] ]
7955d35539ae8b89a5990e49c20c62bb9fb318f6
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/SectionMetadata.cpp
a251e8c826746fc1e7ea2aa1c725e9050170e4ca
[]
no_license
danishcake/FusionForever
8fc3b1a33ac47177666e6ada9d9d19df9fc13784
186d1426fe6b3732a49dfc8b60eb946d62aa0e3b
refs/heads/master
2016-09-05T16:16:02.040635
2010-04-24T11:05:10
2010-04-24T11:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,643
cpp
#include "stdafx.h" #include "SectionMetadata.h" #include <map> #include "vmath.h" namespace SectionMetadata { static std::map<std::string, std::vector<std::string> > tags; static std::map<std::string, std::map<std::string, double> > values; static std::map<std::string, std::map<std::string, Vector2d> > coordinates; static std::vector<std::string> section_types; void RegisterSectionTag(std::string _section_type, std::string _tag) { tags[_section_type].push_back(_tag); } void RegisterSectionKeyValue(std::string _section_type, std::string _key, double _value) { values[_section_type][_key] = _value; } void RegisterSectionKeyCoordinate(std::string _section_type, std::string _key, double _x, double _y) { coordinates[_section_type][_key] = Vector2d(_x, _y); } void RegisterSection(const std::string _section_type) { section_types.push_back(_section_type); } std::vector<std::string> GetTags(const std::string _section_type) { if(tags.find(_section_type) != tags.end()) return tags[_section_type]; return std::vector<std::string>(); } std::map<std::string, double> GetValues(const std::string _section_type) { if(values.find(_section_type) != values.end()) return values[_section_type]; return std::map<std::string, double>(); } std::map<std::string, Vector2d> GetCoordinates(const std::string _section_type) { if(coordinates.find(_section_type) != coordinates.end()) return coordinates[_section_type]; return std::map<std::string, Vector2d>(); } std::vector<std::string> GetSections() { return section_types; } }
[ [ [ 1, 58 ] ] ]
ee61d65322171f9d20424c4bffa92eb641ea375b
54319da8732c447b8f196de5e98293083d3acf10
/qt4_src/src/main.cpp
74ff3557ac80361d320ce9a68c620c8990c520fe
[ "curl" ]
permissive
libfetion/libfetion-gui
6c0ed30f9b31669048347352b292fbe02e5505f3
a5912c7ac301830c2953378e58a4d923bc0a0a8d
refs/heads/master
2021-01-13T02:16:46.031301
2010-09-19T10:42:37
2010-09-19T10:42:37
32,465,618
2
0
null
null
null
null
UTF-8
C++
false
false
3,406
cpp
/*************************************************************************** * Copyright (C) 2008 by DDD * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <QApplication> #include <QTranslator> #include <QtPlugin> //@TO FIX remove it affter fixed styleshee's import #include <QFile> #include "appconfig.h" #include "fxmain.h" #include "fxdb.h" #include "fxskinmanage.h" #ifdef HAVE_LOG4QT_DEBUG_ENABLED #include "log4qt/propertyconfigurator.h" /* log4qt configure load */ #endif #ifdef WIN32 #else #include <fcntl.h> #include <sys/types.h> #include <pwd.h> #endif #ifdef WIN32 Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qgif) #else #ifdef Q_OS_MAC //Q_IMPORT_PLUGIN(qgif) #else //linux //Q_IMPORT_PLUGIN(qgif) #endif #endif int main(int argc, char *argv[]) { if (!fx_init()) { fprintf(stderr, "init the libfetion fail \n"); exit(0); } init_db(); #ifdef WIN32 #else //compatible old app's config file moveOldConfigFile(); #endif QApplication app(argc, argv); QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath()); #ifdef HAVE_LOG4QT_DEBUG_ENABLED /*FIXME: real log4qt configuration path */ Log4Qt::PropertyConfigurator::configure( app.applicationDirPath() + "/log4qt.properties"); #endif QTranslator translator_fetion; translator_fetion.load("fetion_utf8_CN", defaultResPath()); QTranslator translator_qt; translator_qt.load("qt_zh_CN", defaultResPath()); app.installTranslator(&translator_fetion); app.installTranslator(&translator_qt); app.setFont(Settings::instance().getCurrentFont()); setSkins(Settings::instance().SkinPath(), Settings::instance().SkinName()); FxMain *mainWin = new FxMain(); app.setQuitOnLastWindowClosed(false); int reslut = app.exec(); if (mainWin) { delete mainWin; } destoy_db(); //destroy the libfetion fx_terminate(); return reslut; }
[ "alsor.zhou@3dff0f8e-6350-0410-ad39-8374e07577ec", "[email protected]@3dff0f8e-6350-0410-ad39-8374e07577ec", "libfetion@3dff0f8e-6350-0410-ad39-8374e07577ec" ]
[ [ [ 1, 45 ], [ 47, 49 ], [ 51, 102 ] ], [ [ 46, 46 ] ], [ [ 50, 50 ] ] ]
dad9d6fe54c862bbb11bbc5e24185e91fb8ab4bb
305f56324b8c1625a5f3ba7966d1ce6c540e9d97
/src/lister/TestButton.h
70ed267aa27ad718e48aa00c98a4d710dc55890e
[]
no_license
radtek/lister
be45f7ac67da72c1c2ac0d7cd878032c9648af7b
71418c72b31823624f545ad86cc804c43b6e9426
refs/heads/master
2021-01-01T19:56:30.878680
2011-06-22T17:04:13
2011-06-22T17:04:13
41,946,076
0
0
null
null
null
null
UTF-8
C++
false
false
456
h
#ifndef _TestButton_h_ #define _TestButton_h_ #include <CtrlLib/CtrlLib.h> using namespace Upp; //============================================================================================== class TestButton : public Button { public: typedef TestButton CLASSNAME; bool wasClicked; TestButton(); // Only called if we use WhenCtrlsAction, NOT WhenCtrlAction. void BeginTest(); }; #endif
[ "jeffshumphreys@97668ed5-8355-0e3d-284e-ab2976d7b0b4" ]
[ [ [ 1, 19 ] ] ]
e57a9d8627e09fcd08d29322a01ec01b61cf142b
7db1ef9796de61dd7fb4b3428c848d3f675828ed
/aniSprite.cpp
3e2d7ea218ea62710e7eeae248fe9b8050631d54
[]
no_license
previsualconsent/Video-Game
d02e5278b280eda8ada1e0133269c27e91ad4507
41b13e0b063347344b91e37942878c4360a120c0
refs/heads/master
2021-01-01T06:10:55.980099
2011-06-22T15:52:30
2011-06-22T15:52:30
1,857,645
0
0
null
null
null
null
UTF-8
C++
false
false
1,271
cpp
#include "aniSprite.h" #include <iostream> using namespace std; aniSprite::aniSprite(int x, int y, string file,int frame_number) : sprite(x,y,file) { /* bitmap = NULL; position.x = x; position.y = y; filename = file; bitmap = al_load_bitmap(filename.c_str()); width = al_get_bitmap_width(bitmap); height = al_get_bitmap_height(bitmap); */ ALLEGRO_BITMAP *tmpBit = NULL; numFrames=frame_number; width = width/numFrames; try { frames = new ALLEGRO_BITMAP*[numFrames]; } catch(...) { frames = 0; } for(int i=0;i<numFrames;i++) { frames[i] = al_create_sub_bitmap(bitmap,width*i,0,width,height); } bitmap = frames[0]; currentFrame=0; } void aniSprite::advanceFrame() { currentFrame++; if(currentFrame == numFrames) { currentFrame=0; } bitmap = frames[currentFrame]; draw(); } void aniSprite::rewindFrame() { currentFrame--; if(currentFrame < 0) { currentFrame+=numFrames; } bitmap = frames[currentFrame]; draw(); } void aniSprite::setFrame(int i) { bitmap = frames[i]; } aniSprite::~aniSprite() { //dtor }
[ [ [ 1, 72 ] ] ]
2189ba31d319139f194662f1a0bbb4b736adf78c
ae8a7d8d43288a2eb30e4c28c53248112f803b46
/gserver.cpp
b2826536db4cc0113af725f1881ed136cf19e21b
[]
no_license
andreisavu/port-redirect
8ebdedde374662d72c9ea62cfae6fa88b4067913
208676a3ea0f2feb1ee9816f768b6da69824e34c
refs/heads/master
2021-01-23T20:13:19.843307
2009-08-24T06:59:36
2009-08-24T06:59:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,290
cpp
/* (c) GarajCode 2005 Simple Multithreaded/Multiclient server Date : 30 iunie 2005 Last date : 31 octombrie 2005 */ /* Change log : 10 august 2005 - adaugat suport pentru optiuni de securitate ( MCSC ) 11 august 2005 - suport pentru trusted ip - suport pentru banned ip 23 august 2005 - finisari 6 septembrie 2005 - modificare interfata clasa 7 septembrie 2005 - utilizare arbori binari la cautare IP 31 octombrie 2005 - WIN9X_HACK */ #include "gserver.h" #include <stdio.h> #include <process.h> // dezactiveaza avertizarile pentru STL #pragma warning(disable:4786) #pragma warning(disable:4786) #define CLOSE_WAIT_TIME 500 // timpul de asteptat pentru a se inchide thread-ul de listen namespace GN { // functie auxiliara - returneaza 1 sau 0 daca un // caracter este intr-un buffer sau nu inline int is_in( char * buffer, char ch ) { char *p = buffer; while( *p ) { if( *p == ch ) return 1; p++; } return 0; /* for( int i=0; i<l; i++) if( buffer[i] == ch ) return 1; return 0; */ } // functie auxiliara folosita pentru impartire string-uri int get_token( char * buffer, char * text, int start, int end, char * sep ) { int k=0; int i = start; // trece peste caracterele initiale while( is_in(sep, text[i]) && i<end ) i++; // transfera continutul in buffer while( !is_in(sep, text[i]) && i < end ) { buffer[k++] = text[i]; i++; } buffer[k] = 0; return i; } // initializare CServer::CServer() : m_listen_thread( NULL ) { } // inchidere automata CServer::~CServer() { close(); } // adauga lista de ip de incredere void CServer::add_tiplist( char * list ) { // proceseaza lista de ip-uri si adauga // in lista de ip-uri de incredere char buffer[50]; char sep[] = "; "; int l = strlen( list ); int st = -1; if( !l ) return; do { st++; st = get_token( buffer, list, st, l, sep); if( strlen(buffer)>= 7 ) add_trusted_ip( pack_ip(buffer) ); }while( st != l ); } // adauga lista de ip-uri interzise void CServer::add_bannedlist( char * list ) { char buffer[50]; char sep[] = "; "; int l = strlen( list ); int st = -1; if( !l ) return; do { st++; st = get_token( buffer, list, st, l, sep); if( strlen(buffer)>= 7 ) add_banned_ip( pack_ip(buffer) ); }while( st != l ); } // informatii necesare pentru thread-ul de server // structura este folosita doar intern pentru // trimiterea de informatii intre thread-uri struct ServerData { CLIENT_LIST *client_list; // client list CSocket *socket; // server or client socket SERVER_PROCEDURE action; // client handler SERVER_EVENT_HANDLER event_handler; // server event handler UINT max_client_number; // max simultanious connections UINT mcsc; // multiple connections from same client UINT utip; // use trusted ip list TRUSTED_IP_LIST *tip_list; // lista de ip-uri in forma impachetata UINT ubip; // use banned ip list BANNED_IP_LIST *bip_list; // lista de ip-uri interzise }; // thread-ul client - fiecare client este gestionat de // un astfel de thread creat de thread-ul de ascultare DWORD WINAPI ClientThread( LPVOID param ) { ServerData *data=(ServerData*)param; // apeleaza functia care sa gestioneze clientul if(data->action) { try { data->action(*(data->client_list),*(data->socket)); } catch( GSTD::CError error ) { if( data->event_handler ) { // semnaleaza eroare aparuta in functia de protocol data->event_handler( SM_CLIENT_ERROR, &error, data->socket ); } } } // extrage adresa din lista data->client_list->remove( data->socket ); // semnaleaza deconectare client if( data->event_handler ) { data->event_handler( SM_CLIENT_DISCONNECTED, NULL, data->socket); } // inchide socket-ul try { data->socket->close(); } catch( GSTD::CError error) { if( data->event_handler ) { // semnaleaza eroare la inchidere data->event_handler( SM_CLIENT_ERROR, &error, data->socket ); } } // elibereaza memoria folosita de client delete data->socket; delete data; return 0; } #ifdef WIN9X_HACK // necesara deoarece exista o problema cu // functia CreateThread pe win9x - returneaza NULL void ClientThread_Hack( void * param ) { ClientThread( param ); } #endif // asteapta sa apara un client si atunci realizeaza un nou // thread pentru fiecare client DWORD WINAPI ListenThread( LPVOID param ) { ServerData *data=(ServerData*)param; ServerData *client; CSocket aux; // semnaleaza pornirea daemonului if( data->event_handler ) { data->event_handler( SM_CREATE, NULL, data->socket); } while( true ) { // asteapta o conexiune try { aux = data->socket->accept(); } catch(GSTD::CError error) { if( data->event_handler) { // semnaleaza problema aparuta data->event_handler( SM_CONNECTION_ERROR, &error, NULL); } break; } // use banned ip if( data->ubip ) { // verifica daca ip-ul se afla in lista // de ip-uri interzise if( data->bip_list->count( aux.get_ip_pack() ) ) { // semnaleaza tentativa de conectare de la un IP // din lista de interzis if( data->event_handler ) { data->event_handler( SM_BIP_ERROR, NULL, &aux ); } aux.close(); continue; } } // use trusted ip if( data->utip ) { // verifica daca ip-ul este in lista // daca nu a fost gasit conexiunea este inchisa si se // asteapta alt client if( !data->tip_list->count( aux.get_ip_pack() ) ) { // semnaleaza eroare if( data->event_handler ) { data->event_handler( SM_TIP_ERROR, NULL, &aux ); } aux.close(); continue; } } // multiple connexions from same client if( !data->mcsc ) { // verifica daca acest client mai este conectat odata for( CLIENT_LIST_ITERATOR it = data->client_list->begin(); it != data->client_list->end(); it++) if( aux.get_ip_pack() == (*it)->get_ip_pack() ) { // semnaleaza eroare if( data->event_handler ) { data->event_handler( SM_MCSC_ERROR, NULL, &aux ); } // inchide conexiune aux.close(); break; } // daca a fost gasit se asteapta o alta conexiune if( it != data->client_list->end() ) continue; } // verifica limita pentru clienti if( data->client_list->size() >= data->max_client_number ) { // semnaleaza depasire limita de conexiuni simultane if(data->event_handler) { data->event_handler(SM_CLIENT_LIMIT_REACHED, NULL, &aux); } // refuza conexiunea curenta try { aux.close(); } catch( GSTD::CError error ) { if( data->event_handler ) { // semnaleaza eroare data->event_handler( SM_CLIENT_ERROR, &error, &aux); } } // asteapta pentru urmatorul client continue; } // semnaleaza conectarea unui nou client si asteapta acceptul conexiunii if( data->event_handler ) { if( !data->event_handler( SM_CLIENT_CONNECTED, NULL, &aux ) ) { // conexiunea a fost refuzata try { aux.close(); } catch( GSTD::CError error ) { if( data->event_handler ) { // semnaleaza eroare data->event_handler( SM_CLIENT_ERROR, &error, &aux); } } // asteapta urmatorul client continue; } } // aloca memorie pentru un nou client if( !(client = new ServerData) ) { // problema interna cu memoria - server-ul nu trebuie inchis // semnaleaza problema if(data->event_handler) { data->event_handler(SM_NO_MEMORY_FOR_CLIENT, NULL, &aux); } // refuza conexiunea curenta din lipsa de resurse try { aux.close(); } catch( GSTD::CError error ) { if( data->event_handler ) { // semnaleaza problema data->event_handler( SM_CLIENT_ERROR, &error, &aux); } continue; } } // seteaza structura client->action = data->action; client->client_list = data->client_list; client->event_handler = data->event_handler; // aloca memorie pentru socket if( !(client->socket = new CSocket) ) { // problema cu memoria - se renunta la acest client if(data->event_handler) { data->event_handler(SM_NO_MEMORY_FOR_CLIENT, NULL, &aux); } try { aux.close(); } catch( GSTD::CError error ) { if( data->event_handler) { // problema de semnalat data->event_handler( SM_CLIENT_ERROR, &error, &aux); } } delete client; continue; } *client->socket = aux; // salveza adresa noului socket in lista data->client_list->push_back(client->socket); #ifndef WIN9X_HACK // creaza un nou thread pentru client HANDLE tmph = CreateThread(NULL,0,ClientThread,client,0,NULL); if( !tmph ) { // nu s-a putut crea thread-ul pentru gestionarea // clientului, conexiunea este refuzata si server-ul // isi vede de treaba mai departe eroare fiind semnalata if( data->event_handler) { data->event_handler( SM_THREAD_ERROR, NULL, &aux); } try { aux.close(); } catch( GSTD::CError error ) { if( data->event_handler ) { // semnaleaza problema data->event_handler( SM_CLIENT_ERROR, &error, &aux ); } } // elibereaza memoria alocata pentru client delete client->socket; delete client; // asteapta urmatoarea conexiune continue; } // inchide handle CloseHandle( tmph ); #endif #ifdef WIN9X_HACK // problema legat de CreateThread - un hack pentru WIN9X if( _beginthread( ClientThread_Hack, 0, client ) == -1L ) { // nu s-a putut crea thread-ul pentru gestionarea // clientului, conexiunea este refuzata si server-ul // isi vede de treaba mai departe eroare fiind semnalata if( data->event_handler) { data->event_handler( SM_THREAD_ERROR, NULL, &aux); } try { aux.close(); } catch( GSTD::CError error ) { if( data->event_handler ) { // semnaleaza problema data->event_handler( SM_CLIENT_ERROR, &error, &aux ); } } // elibereaza memoria alocata pentru client delete client->socket; delete client; // asteapta urmatoarea conexiune continue; } #endif } // inchide toate conexiunile cu clientii si asteapta // ca lista sa devina vida for(CLIENT_LIST_ITERATOR it = data->client_list->begin(); it != data->client_list->end(); it++) { try { (*it)->close(); } catch( GSTD::CError error ) { if( data->event_handler ) { //semnaleaza eroare data->event_handler( SM_CLIENT_ERROR, &error, *it); } } } // asteapta pana toti clienti se inchid // verificare se face la un interval de jumatate // de secunda pentru a evita utilizarea inutila // a procesorului while( data->client_list->size() ) Sleep(500); // semnaleaza inchiderea daemonului if( data->event_handler ) { data->event_handler( SM_CLOSE, NULL, data->socket); } // elibereaza memoria necesara pentru daemon delete data; return 1; } #ifdef WIN9X_HACK // problema cu CreateThread pe WIN9X void ListenThread_Hack( void * param ) { ListenThread( param ); } #endif void CServer::create( SERVER_CREATION_DATA &init_data ) { // verifica daca avem o functie pentru client if( !init_data.server_procedure ) { throw GSTD::CError(0, "No client function" ); } // initializeaza socket-ul de server try { m_listen_socket.create(); m_listen_socket.listen( init_data.port ); } catch(GSTD::CError error) { throw (GSTD::CError)error; } // aloca memorie necesara pentru server ServerData *data; if(!(data=new ServerData)) { m_listen_socket.close(); throw GSTD::CError( GSTD::BAD_ALLOC ); } // seteaza structura care va fi pasata mai departe data->action = init_data.server_procedure; // functia pentru protocol data->event_handler = init_data.server_event_handler; // gestionare evenimente interne data->client_list = &m_client_list; // lista de clienti data->socket = &m_listen_socket; // socket-ul server data->mcsc = init_data.mcsc; // conexiuni multiple de la acelasi IP data->max_client_number = init_data.max_client_number; // numarul maxim de conexiuni simultane data->utip = init_data.utip; // use trusted ip list data->tip_list = &m_tip_list; // lista de ip-uri de incredere data->ubip = init_data.ubip; // use banned ip list data->bip_list = &m_bip_list; // lista de ip-uri interzise // porneste daemonul pentru server #ifndef WIN9X_HACK // versiunea care TEORETIC trebuie sa fie independenta de // versiunea de Windows m_listen_thread = CreateThread(NULL, 0, ListenThread, data, 0, NULL); if( !m_listen_thread ) { // eroare la pornire daemon GSTD::CError error; error.set_code( GetLastError() ); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error.get_code(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Fill error struct error.set_text( (char*)lpMsgBuf ); // Free the buffer. LocalFree( lpMsgBuf ); // elibereaza memoria alocata delete data; // semnaleaza eroare throw (GSTD::CError)error; } #endif #ifdef WIN9X_HACK // foloseste _beginthread // dezavantaj major - nu mai permite folosirea WaitForSingleObject if( _beginthread( ListenThread_Hack, 0, data ) == -1L ) { throw GSTD::CError( 0, "Error creating listen thread - WIN9XHACK" ); } #endif } // inchide server-ul, fiecare client este inchis void CServer::close() { try { m_listen_socket.close(); } catch(GSTD::CError error) { throw (GSTD::CError)error; } #ifndef WIN9X_HACK if(m_listen_thread) { WaitForSingleObject(m_listen_thread, INFINITE); m_listen_thread = NULL; } #endif #ifdef WIN9X_HACK // asteapta pana ce toti clientii se inchide while( m_client_list.size() ) Sleep( 500 ); Sleep( CLOSE_WAIT_TIME ); #endif // elibereaza lista de ip in care se are incredere m_tip_list.clear(); // elibereaza lista de ip-uri interzise m_bip_list.clear(); } }; // namespace GN // (c) GarajCode 2005 - programmed by Savu Andrei
[ [ [ 1, 662 ] ] ]