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
a4613ce930b7a5425ee2fbc0011e7c9061cb8ddc
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/ULLib/include/ULQueueThread.h
a127a9f8611c8ecb8aa82b036316e323a03faa4c
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
1,414
h
///\file ULQueueThread.h ///\brief Заголовочный файл класса потока с очередью(27.08.2007) #pragma once #ifndef __ULQUEUETHREAD__H_ #define __ULQUEUETHREAD__H_ #include "ULMessageMap.inl" #include "ULThread.h" namespace ULThreads { ///\class CULQueueThread ///\brief Класс потока с очередью(27.08.2007) class CULQueueThread:public CULThread { private: ///\brief хэндл события запуска цикла сообщений HANDLE m_hStartedEvent; protected: ///\brief Фукнция потока static DWORD ThreadProc(LPVOID param); ///\brief Объект класса добавления и обработки сообщений. ///Cообщения добавляются в конструкторе класса CULMessageMap<CULQueueThread> MessageMap; public: ///\brief Конструктор CULQueueThread(void); ///\brief Десдруктор virtual ~CULQueueThread(void); ///\brief Создаёт поток ///\param lpThreadAttributes атрибуты доступа ///\param dwStackSize размер стэка ///\param dwCreationFlags флаг ///\return TRUE в случае успеха BOOL Create(LPSECURITY_ATTRIBUTES lpThreadAttributes=NULL, SIZE_T dwStackSize=0, DWORD dwCreationFlags=CREATE_SUSPENDED); }; } #endif//__ULQUEUETHREAD__H_
[ "UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f" ]
[ [ [ 1, 38 ] ] ]
3ae3bc87e0f6229933f5d63e6ad017cb6b4a6e42
01acea32aaabe631ce84ff37340c6f20da3065a6
/lock.h
3b146fbacc85ac53d18b4cfe8404d9e2c2789b48
[]
no_license
olooney/pattern-space
db2804d75249fe42427c15260ecb665bc489e012
dcf07e63a6cb7644452924212ed087d45c301e78
refs/heads/master
2021-01-20T09:38:41.065323
2011-04-20T01:25:58
2011-04-20T01:25:58
1,638,393
0
0
null
null
null
null
UTF-8
C++
false
false
2,559
h
/* Resource, Lock Wraps SDL thread syncronization fuctionality in C++ objects. Resource is a thin wrapper around SDL_Semaphore. Lock implements the RAII idiom: simply instantiate a Lock on a Resource at the beginning of a scope to lock it until the end of the scope (in an exception safe way.) TODO: Resource could be an ABC, becuase there are other ways of implementing resources, even in SDL. Lock depends only on wait() and post(), and that's really the essence of a mutex. Note: if you use tryWait() or waitTimeout(), be prepared to catch a possible ResourceError exception. */ #ifndef PATTERN_SPACE_MUTEX_INCLUSION_GUARD #define PATTERN_SPACE_MUTEX_INCLUSION_GUARD #include <SDL/SDL.h> #include <SDL/SDL_thread.h> namespace PatternSpace { /********************* Resource *********************/ class Resource { public: class ResourceError {}; // exception class // a default of one means one thread can have the lock at a time. Resource(int i=1) { sdl_sem = SDL_CreateSemaphore(i); } ~Resource() { SDL_DestroySemaphore(sdl_sem); } void wait() { SDL_SemWait(sdl_sem); } void post() { SDL_SemPost(sdl_sem); } int value() const { SDL_SemValue(sdl_sem); } bool tryWait() { return boolOrError( SDL_SemTryWait(sdl_sem) ); } bool waitTimeout(int timeout) { return boolOrError( SDL_SemWaitTimeout(sdl_sem, timeout) ); } private: SDL_sem * sdl_sem; // change the SDL error return code to a C++ exception. static bool boolOrError(Uint32 x) { if ( x == 0 ) return true; else if ( x == -1 ) throw ResourceError(); else return false; } }; // end class Resource /********************* Lock *********************/ // RAII for a lock on a Resources class Lock { public: explicit Lock(Resource& target): resource(target) { resource.wait(); // get the resource } ~Lock() { resource.post(); // release the resource } private: Resource& resource; //declare copy and assignment private; Locks shouldn't be copied Lock& operator=(Lock&); Lock(Lock&); }; // end class Lock } // end namespace PatternSpace #endif // PATTERN_SPACE_MUTEX_INCLUSION_GUARD
[ [ [ 1, 81 ] ] ]
334a0ad1a973240ff77e25dfaa60ce70f46288e4
c7120eeec717341240624c7b8a731553494ef439
/src/cplusplus/freezone-samp/src/player_animation.hpp
742bccad9a7b189bab7e24e79700edbd73270fd4
[]
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
3,534
hpp
#ifndef PLAYER_ANIMATION_HPP #define PLAYER_ANIMATION_HPP #include "core/module_h.hpp" #include "player_animation_t.hpp" class player_animation :public application_item ,public createble_i ,public configuradable ,public players_events::on_connect_i { public: player_animation(); virtual ~player_animation(); 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(player_animation); public: // players_events::on_connect_i virtual void on_connect(player_ptr_t const& player_ptr); private: command_arguments_rezult cmd_animation(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_animation_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_special_dance(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_special_handsup(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_special_phone(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_special_pissing(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); // Начиная с 0.3 command_arguments_rezult cmd_special_drink(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); command_arguments_rezult cmd_special_smoke(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params); private: friend class player_animation_item; animation_libs_t animation_libs; int get_total_anims() const; bool is_block_on_jetpack; public: void special_phone_start_impl(player_ptr_t const& player_ptr, messages_pager& pager, messages_sender const& sender); void special_phone_stop_impl(player_ptr_t const& player_ptr, messages_pager& pager, messages_sender const& sender); }; class player_animation_item :public player_item ,public on_timer1000_i ,public player_events::on_request_class_i ,public player_events::on_keystate_change_i ,public player_events::on_update_i { public: typedef std::tr1::shared_ptr<player_animation_item> ptr; protected: friend class player_animation; player_animation_item(player_animation& manager); virtual ~player_animation_item(); public: // player_events::* virtual void on_request_class(int class_id); virtual void on_keystate_change(int keys_new, int keys_old); virtual void on_timer1000(); virtual bool on_update(); private: player_animation& manager; int is_can_preload; bool is_first; void preload_libs(); }; #endif // PLAYER_ANIMATION_HPP
[ "dimonml@19848965-7475-ded4-60a4-26152d85fbc5" ]
[ [ [ 1, 81 ] ] ]
e10edcb9da52db5dbd076306e79ab7abfb60dd22
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/sense/xsens_mti_driver_t.h
dbd0ce98cd3e1863a8de96352e79373251bf11e2
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
1,854
h
#ifndef xsens_mti_driver_t_H_INCLUDED #define xsens_mti_driver_t_H_INCLUDED //--------------------------------------------------------- #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> #include <boost/timer.hpp> //--------------------------------------------------------- #include <string> //--------------------------------------------------------- #include "alcor/sense/xsens_mti_inc.hpp" #include "alcor/math/fast_mti_integral_t.hpp" //--------------------------------------------------------- #include "alcor/math/quaternion_t.hpp" //--------------------------------------------------------- namespace all { namespace sense { //--------------------------------------------------------- /// namespace detail { struct MTi_driver_impl; } //--------------------------------------------------------- /// class xsens_mti_driver_t { public: /// xsens_mti_driver_t(); /// ~xsens_mti_driver_t(); /// bool open(std::string& configfile); /// void reset(tags::heading_reset_t); /// void reset(tags::global_reset_t); /// void reset(tags::object_reset_t); /// void reset(tags::align_reset_t); /// void get_data(float data[]); /// void run_mti(); /// void stop_mti(); ///test void print_calibdata(); private: /// boost::shared_ptr<detail::MTi_driver_impl> impl; /// boost::timer timestamp_; /// void mti_loop_(); /// boost::shared_ptr<boost::thread> loop_thread_; /// all::math::fast_mti_integral_t processor_; /// volatile bool running_; }; //--------------------------------------------------------- }}//all::sense //--------------------------------------------------------- #endif //xsense_mti_driver_t_H_INCLUDED
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 71 ] ] ]
4a1d15438d374d0b848c762af3e5c2718f06e970
9b781f66110d82c4918feffeeee3740d6b9dcc73
/Motion Graphs/Lines/DynamicRenderable.h
4d9b0ae1217a9803e12acbb41bd85fcf4903d3a5
[]
no_license
vanish87/Motion-Graphs
3c41cbb4ae838e2dce1172a56dfa00b8fe8f12cf
6eab48f3625747d838f2f8221705a1dba154d8ca
refs/heads/master
2021-01-23T05:34:56.297154
2011-06-10T09:53:15
2011-06-10T09:53:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,833
h
#include "../stdafx.h" #ifndef DYNAMIC_RENDERABLE_H #define DYNAMIC_RENDERABLE_H #include <OgreSimpleRenderable.h> /// Abstract base class providing mechanisms for dynamically growing hardware buffers. class DynamicRenderable : public Ogre::SimpleRenderable { public: /// Constructor DynamicRenderable(); /// Virtual destructor virtual ~DynamicRenderable(); /** Initializes the dynamic renderable. @remarks This function should only be called once. It initializes the render operation, and calls the abstract function createVertexDeclaration(). @param operationType The type of render operation to perform. @param useIndices Specifies whether to use indices to determine the vertices to use as input. */ void initialize(Ogre::RenderOperation::OperationType operationType, bool useIndices); /// Implementation of Ogre::SimpleRenderable virtual Ogre::Real getBoundingRadius(void) const; /// Implementation of Ogre::SimpleRenderable virtual Ogre::Real getSquaredViewDepth(const Ogre::Camera* cam) const; protected: /// Maximum capacity of the currently allocated vertex buffer. size_t mVertexBufferCapacity; /// Maximum capacity of the currently allocated index buffer. size_t mIndexBufferCapacity; /** Creates the vertex declaration. @remarks Override and set mRenderOp.vertexData->vertexDeclaration here. mRenderOp.vertexData will be created for you before this method is called. */ virtual void createVertexDeclaration() = 0; /** Prepares the hardware buffers for the requested vertex and index counts. @remarks This function must be called before locking the buffers in fillHardwareBuffers(). It guarantees that the hardware buffers are large enough to hold at least the requested number of vertices and indices (if using indices). The buffers are possibly reallocated to achieve this. @par The vertex and index count in the render operation are set to the values of vertexCount and indexCount respectively. @param vertexCount The number of vertices the buffer must hold. @param indexCount The number of indices the buffer must hold. This parameter is ignored if not using indices. */ void prepareHardwareBuffers(size_t vertexCount, size_t indexCount); /** Fills the hardware vertex and index buffers with data. @remarks This function must call prepareHardwareBuffers() before locking the buffers to ensure the they are large enough for the data to be written. Afterwards the vertex and index buffers (if using indices) can be locked, and data can be written to them. */ virtual void fillHardwareBuffers() = 0; }; #endif // DYNAMIC_RENDERABLE_H
[ "onumis@6a9b4378-2129-4827-95b0-0a0a1e71ef92" ]
[ [ [ 1, 71 ] ] ]
73f695b2f5b59cabb20e8f20f431c42d372ee184
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGameVedioUI/VedioUIComponent/src/VedioUIComponent.cpp
d43a905a5d0315e39529686a4ebccef84e0441ce
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,940
cpp
#include "VedioUIComponentStableHeaders.h" #include "VedioUIComponent.h" #include "VedioUIInterface.h" using namespace Orz; VedioUIComponent::VedioUIComponent(void):_vedioInterface(new VedioUIInterface) { using namespace CEGUI; WindowManager& winMgr = WindowManager::getSingleton(); _window= winMgr.createWindow("TaharezLook/StaticImage", "vedio"); _window->setPosition(UVector2(cegui_reldim(0), cegui_reldim( -0.001f))); _window->setSize(UVector2(cegui_reldim(1), cegui_reldim(0.5))); _vedioInterface->load = boost::bind(&VedioUIComponent::load, this, _1); _vedioInterface->play = boost::bind(&VedioUIComponent::play, this); _vedioInterface->getWindow = boost::bind(&VedioUIComponent::getWindow, this); _vedioInterface->isEnd = boost::bind(&VedioUIComponent::isEnd, this); _vedioInterface->reset = boost::bind(&VedioUIComponent::reset, this); } VedioUIComponent::~VedioUIComponent(void) { //using namespace Ogre; //OgreVideoManager* mgr=(OgreVideoManager*) OgreVideoManager::getSingletonPtr(); //mgr->destroyAdvancedTexture("video_material"); //Ogre::TextureManager::getSingleton().getByName("startmovie.ogg"); } CEGUI::Window * VedioUIComponent::getWindow(void) { return _window; } void VedioUIComponent::createTexture(const std::string & filename) { using namespace Ogre; OgreVideoManager* mgr=(OgreVideoManager*) OgreVideoManager::getSingletonPtr(); //createQuad("video_quad","video_material",-0.5,1,1,-0.94); mgr->setInputName(filename); mgr->createDefinedTexture("video_material"); TheoraVideoClip* clip = mgr->getVideoClipByName(filename); clip->pause(); } bool VedioUIComponent::load(const std::string & filename) { _filename = filename; using namespace Ogre; using namespace CEGUI; createTexture(filename); //ImagesetManager::getSingleton().createFromImageFile("abc","10points.png"); //Ogre::TextureManager::getSingleton().load("10points.png",ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().getByName(filename);//createManual("RttTex:"+nam //std::cout<<tex->getName()<<std::endl; CEGUI::OgreTexture& ceguiTex = static_cast<CEGUI::OgreTexture&>(CEGUI::System::getSingleton().getRenderer()->createTexture()); ceguiTex.setOgreTexture(tex); Imageset & iset = ImagesetManager::getSingleton().create("vedio", ceguiTex); iset.defineImage( "vedio", CEGUI::Point( 0.0f, 0.0f ), CEGUI::Size( 640, 480 ), CEGUI::Point( 0.0f, 0.0f ) ); _window->setPosition(UVector2(cegui_reldim(0), cegui_reldim( -0.001f))); _window->setSize(UVector2(cegui_reldim(1), cegui_reldim(1))); // disable frame and standard background _window->setProperty("FrameEnabled", "false"); _window->setProperty("BackgroundEnabled", "false"); _window->setProperty("Image", "set:vedio image:vedio"); //setProperty("Image", "set:vedio_ "+filename+" image:image"); return true; } bool VedioUIComponent::play(void) { using namespace Ogre; OgreVideoManager* mgr=(OgreVideoManager*) OgreVideoManager::getSingletonPtr(); TheoraVideoClip* clip = mgr->getVideoClipByName(_filename); clip->restart(); clip->play(); return true; } ComponentInterface * VedioUIComponent::_queryInterface(const TypeInfo & info) { if(info == TypeInfo(typeid(VedioUIInterface))) return _vedioInterface.get(); return NULL; } bool VedioUIComponent::isEnd(void) { using namespace Ogre; OgreVideoManager* mgr=(OgreVideoManager*) OgreVideoManager::getSingletonPtr(); TheoraVideoClip* clip = mgr->getVideoClipByName(_filename); if(!clip) return false; return clip->isDone(); } void VedioUIComponent::reset(void) { using namespace Ogre; OgreVideoManager* mgr=(OgreVideoManager*) OgreVideoManager::getSingletonPtr(); TheoraVideoClip* clip = mgr->getVideoClipByName(_filename); //clip->stop(); }
[ [ [ 1, 137 ] ] ]
fd41f41decea24536f0e2267507e18bdbb7fa8c0
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aosdesigner/view/ApplicationView.cpp
5a5cc5a84aa1e0fcb3fdcb6cb3e20bfe2f8d4d14
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
734
cpp
#include "view/ApplicationView.hpp" #include <QTimer> #include "view/MainWindow.hpp" #include "view/DesignerActions.hpp" namespace aosd { namespace view { ApplicationView::ApplicationView( int &argc, char **argv ) : QApplication( argc, argv ) , m_main_window( new MainWindow() ) { show_main_window(); } ApplicationView::~ApplicationView() { } void ApplicationView::show_main_window() { m_main_window->show(); } int ApplicationView::run( Callback callback_on_ready ) { QTimer::singleShot(0, this, SLOT(on_ready())); m_on_ready = callback_on_ready; return this->exec(); } void ApplicationView::on_ready() { if( m_on_ready ) m_on_ready(); } } }
[ "klaim@localhost" ]
[ [ [ 1, 47 ] ] ]
69187e9b361c8bfc8ea13dc22c18f6d3a4e34c9c
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/TileEngine/structure.cpp
edfce86a5f63fe33dd3da98e08910b9c1af3b471
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
71,357
cpp
#ifdef PRECOMPILEDHEADERS #include "TileEngine All.h" #else #include <string.h> #include "types.h" #include "wcheck.h" #include "debug.h" #include "FileMan.h" #include "MemMan.h" #include "structure.h" #include "tiledef.h" #include "worlddef.h" #include "worldman.h" #include "interface.h" #include "isometric utils.h" #include "font.h" #include "font control.h" #include "los.h" #include "lighting.h" #include "Smell.h" #include "SaveLoadMap.h" #include "strategicmap.h" #include "sgp_logger.h" #include "Sys Globals.h" //for access to gfEditMode flag //Kris: #ifdef JA2EDITOR #include "Editor Undo.h" //for access to AddToUndoList( iMapIndex ) #endif #include "explosion control.h" #include "Sound Control.h" #include "Buildings.h" #include "Random.h" #include "Tile Animation.h" #endif #ifdef COUNT_PATHS extern UINT32 guiSuccessfulPathChecks; extern UINT32 guiTotalPathChecks; extern UINT32 guiFailedPathChecks; extern UINT32 guiUnsuccessfulPathChecks; #endif void DeleteStructureFromTile( MAP_ELEMENT * pMapElement, STRUCTURE * pStructure ); /* * NB: STRUCTURE_SPECIAL * * Means different things depending on the context. * * WALLNWINDOW SPECIAL - opaque to sight * MULTI SPECIAL - second level (damaged) MULTI structure, should only be deleted if * starting with the deletion of a MULTI SPECIAL structure */ UINT8 AtHeight[PROFILE_Z_SIZE] = { 0x01, 0x02, 0x04, 0x08 }; #define FIRST_AVAILABLE_STRUCTURE_ID (INVALID_STRUCTURE_ID + 2) UINT16 gusNextAvailableStructureID = FIRST_AVAILABLE_STRUCTURE_ID; STRUCTURE_FILE_REF * gpStructureFileRefs; INT32 guiMaterialHitSound[ NUM_MATERIAL_TYPES ] = { -1, S_WOOD_IMPACT1, S_WOOD_IMPACT2, S_WOOD_IMPACT3, S_VEG_IMPACT1, -1, S_PORCELAIN_IMPACT1, -1, -1, -1, -1, S_STONE_IMPACT1, S_STONE_IMPACT1, S_STONE_IMPACT1, S_STONE_IMPACT1, S_RUBBER_IMPACT1, -1, -1, -1, -1, -1, S_METAL_IMPACT1, S_METAL_IMPACT2, S_METAL_IMPACT3, S_STONE_IMPACT1, S_METAL_IMPACT3, }; UINT8 gubMaterialArmour[] = /* index 1-10, organics index 11-20, rocks and concretes index 21-30, metals index 1, dry timber index 2, furniture wood index 3, tree wood index 11, stone masonry index 12, non-reinforced concrete index 13, reinforced concrete index 14, rock index 21, light metal (furniture) index 22, heavy metal (doors etc) index 23, really heavy metal index 24, indestructable stone index 25, indestructable metal */ { // note: must increase; r.c. should block *AP* 7.62mm rounds 0, // nothing 25, // dry timber; wood wall +1/2 20, // furniture wood (thin!) or plywood wall +1/2 30, // wood (live); 1.5x timber 3, // light vegetation 10, // upholstered furniture 47, // porcelain 10, // cactus, hay, bamboo 0, 0, 0, 55, // stone masonry; 3x timber 63, // non-reinforced concrete; 4x timber??? 70, // reinforced concrete; 6x timber 85, // rock? - number invented 9, // rubber - tires 40, // sand 1, // cloth 40, // sandbag 0, 0, 37, // light metal (furniture; NB thin!) 57, // thicker metal (dumpster) 85, // heavy metal (vault doors) - block everything // note that vehicle armour will probably end up in here 127, // rock indestructable 127, // indestructable 57, // like 22 but with screen windows }; // Function operating on a structure tile UINT8 FilledTilePositions( DB_STRUCTURE_TILE * pTile ) { UINT8 ubFilled = 0, ubShapeValue; INT8 bLoopX, bLoopY, bLoopZ; // Loop through all parts of a structure and add up the number of // filled spots for (bLoopX = 0; bLoopX < PROFILE_X_SIZE; bLoopX++) { for (bLoopY = 0; bLoopY < PROFILE_Y_SIZE; bLoopY++) { ubShapeValue = pTile->Shape[bLoopX][bLoopY]; for (bLoopZ = 0; bLoopZ < PROFILE_Z_SIZE; bLoopZ++) { if (ubShapeValue & AtHeight[bLoopZ]) { ubFilled++; } } } } return( ubFilled ); } // // Structure database functions // void FreeStructureFileRef( STRUCTURE_FILE_REF * pFileRef ) { // Frees all of the memory associated with a file reference, including // the file reference structure itself UINT16 usLoop; Assert( pFileRef != NULL ); if (pFileRef->pDBStructureRef != NULL) { for (usLoop = 0; usLoop < pFileRef->usNumberOfStructures; usLoop++) { if (pFileRef->pDBStructureRef[usLoop].ppTile) { MemFree( pFileRef->pDBStructureRef[usLoop].ppTile ); } } MemFree( pFileRef->pDBStructureRef ); } if (pFileRef->pubStructureData != NULL) { MemFree( pFileRef->pubStructureData ); } if (pFileRef->pAuxData != NULL) { MemFree( pFileRef->pAuxData ); if (pFileRef->pTileLocData != NULL) { MemFree( pFileRef->pTileLocData ); } } MemFree( pFileRef ); } void FreeAllStructureFiles( void ) { // Frees all of the structure database! STRUCTURE_FILE_REF * pFileRef; STRUCTURE_FILE_REF * pNextRef; pFileRef = gpStructureFileRefs; while( pFileRef != NULL ) { pNextRef = pFileRef->pNext; FreeStructureFileRef( pFileRef ); pFileRef = pNextRef; } } BOOLEAN FreeStructureFile( STRUCTURE_FILE_REF * pStructureFile ) { CHECKF( pStructureFile ); // unlink the file ref if (pStructureFile->pPrev != NULL) { pStructureFile->pPrev->pNext = pStructureFile->pNext; } else { // freeing the head of the list! gpStructureFileRefs = pStructureFile->pNext; } if (pStructureFile->pNext != NULL) { pStructureFile->pNext->pPrev = pStructureFile->pPrev; } if (pStructureFile->pPrev == NULL && pStructureFile->pNext == NULL) { // toasting the list! gpStructureFileRefs = NULL; } // and free all the structures used! FreeStructureFileRef( pStructureFile ); return( TRUE ); } BOOLEAN LoadStructureData( STR szFileName, STRUCTURE_FILE_REF * pFileRef, UINT32 * puiStructureDataSize ) //UINT8 **ppubStructureData, UINT32 * puiDataSize, STRUCTURE_FILE_HEADER * pHeader ) { // Loads a structure file's data as a honking chunk o' memory HWFILE hInput; STRUCTURE_FILE_HEADER Header; UINT32 uiBytesRead; UINT32 uiDataSize; BOOLEAN fOk; CHECKF( szFileName ); CHECKF( pFileRef ); hInput = FileOpen( szFileName, FILE_ACCESS_READ | FILE_OPEN_EXISTING, FALSE ); if (hInput == 0) { return( FALSE ); } fOk = FileRead( hInput, &Header, sizeof( STRUCTURE_FILE_HEADER ), &uiBytesRead ); if (!fOk || uiBytesRead != sizeof( STRUCTURE_FILE_HEADER ) || strncmp( Header.szId, STRUCTURE_FILE_ID, STRUCTURE_FILE_ID_LEN ) != 0 || Header.usNumberOfStructures == 0) { FileClose( hInput ); return( FALSE ); } pFileRef->usNumberOfStructures = Header.usNumberOfStructures; if (Header.fFlags & STRUCTURE_FILE_CONTAINS_AUXIMAGEDATA) { uiDataSize = sizeof( AuxObjectData ) * Header.usNumberOfImages; pFileRef->pAuxData = (AuxObjectData *) MemAlloc( uiDataSize ); if (pFileRef->pAuxData == NULL) { FileClose( hInput ); return( FALSE ); } fOk = FileRead( hInput, pFileRef->pAuxData, uiDataSize, &uiBytesRead ); if (!fOk || uiBytesRead != uiDataSize) { MemFree( pFileRef->pAuxData ); FileClose( hInput ); return( FALSE ); } if (Header.usNumberOfImageTileLocsStored > 0) { uiDataSize = sizeof( RelTileLoc ) * Header.usNumberOfImageTileLocsStored; pFileRef->pTileLocData = (RelTileLoc *) MemAlloc( uiDataSize ); if (pFileRef->pTileLocData == NULL) { MemFree( pFileRef->pAuxData ); FileClose( hInput ); return( FALSE ); } fOk = FileRead( hInput, pFileRef->pTileLocData, uiDataSize, &uiBytesRead ); if (!fOk || uiBytesRead != uiDataSize) { MemFree( pFileRef->pAuxData ); FileClose( hInput ); return( FALSE ); } } } if (Header.fFlags & STRUCTURE_FILE_CONTAINS_STRUCTUREDATA) { pFileRef->usNumberOfStructuresStored = Header.usNumberOfStructuresStored; uiDataSize = Header.usStructureDataSize; // Determine the size of the data, from the header just read, // allocate enough memory and read it in pFileRef->pubStructureData = (UINT8 *) MemAlloc( uiDataSize ); if (pFileRef->pubStructureData == NULL) { FileClose( hInput ); if (pFileRef->pAuxData != NULL) { MemFree( pFileRef->pAuxData ); if (pFileRef->pTileLocData != NULL) { MemFree( pFileRef->pTileLocData ); } } return( FALSE ); } fOk = FileRead( hInput, pFileRef->pubStructureData, uiDataSize, &uiBytesRead ); if (!fOk || uiBytesRead != uiDataSize) { MemFree( pFileRef->pubStructureData ); if (pFileRef->pAuxData != NULL) { MemFree( pFileRef->pAuxData ); if (pFileRef->pTileLocData != NULL) { MemFree( pFileRef->pTileLocData ); } } FileClose( hInput ); return( FALSE ); } *puiStructureDataSize = uiDataSize; } FileClose( hInput ); return( TRUE ); } BOOLEAN CreateFileStructureArrays( STRUCTURE_FILE_REF * pFileRef, UINT32 uiDataSize ) { // Based on a file chunk, creates all the dynamic arrays for the // structure definitions contained within UINT8 * pCurrent; DB_STRUCTURE_REF * pDBStructureRef; DB_STRUCTURE_TILE ** ppTileArray; UINT16 usLoop; UINT16 usIndex; UINT16 usTileLoop; UINT32 uiHitPoints; pCurrent = pFileRef->pubStructureData; pDBStructureRef = (DB_STRUCTURE_REF *) MemAlloc( pFileRef->usNumberOfStructures * sizeof( DB_STRUCTURE_REF ) ); if (pDBStructureRef == NULL) { return( FALSE ); } memset( pDBStructureRef, 0, pFileRef->usNumberOfStructures * sizeof( DB_STRUCTURE_REF ) ); pFileRef->pDBStructureRef = pDBStructureRef; for (usLoop = 0; usLoop < pFileRef->usNumberOfStructuresStored; usLoop++) { if (pCurrent + sizeof( DB_STRUCTURE ) > pFileRef->pubStructureData + uiDataSize) { // gone past end of file block?! // freeing of memory will occur outside of the function return( FALSE ); } usIndex = ((DB_STRUCTURE *) pCurrent)->usStructureNumber; pDBStructureRef[usIndex].pDBStructure = (DB_STRUCTURE *) pCurrent; ppTileArray = (DB_STRUCTURE_TILE **) MemAlloc( pDBStructureRef[usIndex].pDBStructure->ubNumberOfTiles * sizeof( DB_STRUCTURE_TILE *)); if (ppTileArray == NULL) { // freeing of memory will occur outside of the function return( FALSE ); } pDBStructureRef[usIndex].ppTile = ppTileArray; pCurrent += sizeof( DB_STRUCTURE ); // Set things up to calculate hit points uiHitPoints = 0; for (usTileLoop = 0; usTileLoop < pDBStructureRef[usIndex].pDBStructure->ubNumberOfTiles; usTileLoop++ ) { if (pCurrent + sizeof( DB_STRUCTURE ) > pFileRef->pubStructureData + uiDataSize) { // gone past end of file block?! // freeing of memory will occur outside of the function return( FALSE ); } ppTileArray[usTileLoop] = (DB_STRUCTURE_TILE *) pCurrent; // set the single-value relative position between this tile and the base tile ppTileArray[usTileLoop]->sPosRelToBase = ppTileArray[usTileLoop]->bXPosRelToBase + ppTileArray[usTileLoop]->bYPosRelToBase * WORLD_COLS; uiHitPoints += FilledTilePositions( ppTileArray[usTileLoop] ); pCurrent += sizeof( DB_STRUCTURE_TILE ); } // scale hit points down to something reasonable... uiHitPoints = uiHitPoints * 100 / 255; /* if (uiHitPoints > 255) { uiHitPoints = 255; } */ pDBStructureRef[usIndex].pDBStructure->ubHitPoints = (UINT8) uiHitPoints; /* if (pDBStructureRef[usIndex].pDBStructure->usStructureNumber + 1 == pFileRef->usNumberOfStructures) { break; } */ } return( TRUE ); } #include <vfs/Core/vfs_file_raii.h> #include <vfs/Core/vfs.h> #include "XML_StructureData.hpp" void checkStructureValidity(STRUCTURE_FILE_REF *str1, STRUCTURE_FILE_REF* str2, UINT32 size1, UINT32 size2) { if(str1 == str2 && str1 == NULL) { return; } if(str1->pubStructureData && str2->pubStructureData) { SGP_THROW_IFFALSE( size1 == size2, L""); //SGP_THROW_IFFALSE( 0 == memcmp(str1->pubStructureData, str2->pubStructureData, size1), L"" ); UINT8* ptr1 = str1->pubStructureData; UINT8* ptr2 = str2->pubStructureData; unsigned int count = 0; for(; count < size1 && (*ptr1++ == *ptr2++); count++) {} SGP_THROW_IFFALSE(count == size1, L"bad structure data"); } else if(str1->pubStructureData || str2->pubStructureData) { SGP_THROW(L"bad structure data"); } int count_tiles_1 = 0, count_tiles_2 = 0; if(str1->pAuxData && str2->pAuxData) { SGP_THROW_IFFALSE(str1->usNumberOfStructures == str2->usNumberOfStructures, L""); SGP_THROW_IFFALSE(str1->usNumberOfStructuresStored == str2->usNumberOfStructuresStored, L""); //SGP_THROW_IFFALSE( 0 == memcmp(str1->pAuxData, str2->pAuxData, sizeof(AuxObjectData)*str2->usNumberOfStructures), L"" ); for(int i = 0; i < str2->usNumberOfStructures; ++i) { SGP_THROW_IFFALSE( 0 == memcmp(&str1->pAuxData[i], &str2->pAuxData[i], sizeof(AuxObjectData)), _BS(L"bad aux_image : ") << i << _BS::wget ); } for(int i = 0; i < str1->usNumberOfStructures; ++i){ count_tiles_1 += str1->pAuxData[i].ubNumberOfTiles; } for(int j = 0; j < str2->usNumberOfStructures; ++j){ count_tiles_2 += str2->pAuxData[j].ubNumberOfTiles; } SGP_THROW_IFFALSE(count_tiles_1 == count_tiles_2, L""); } else if(str1->pAuxData || str2->pAuxData) { SGP_THROW(L"bad aux image data"); } if(str1->pTileLocData && str2->pTileLocData) { SGP_THROW_IFFALSE( 0 == memcmp(str1->pTileLocData, str2->pTileLocData, count_tiles_1*sizeof(RelTileLoc)), L"" ); } else if(str1->pTileLocData || str2->pTileLocData) { SGP_THROW(L"bad aux tile data"); } } STRUCTURE_FILE_REF * LoadStructureFile( STR szFileName ) { // NB should be passed in expected number of structures so we can check equality UINT32 uiDataSize = 0; BOOLEAN fOk; STRUCTURE_FILE_REF* pFileRef; bool found_jsd_xml_file = false; extern bool g_bUseXML_Structures; if(g_bUseXML_Structures) { vfs::Path filename = std::string(szFileName) + ".xml"; if(getVFS()->fileExists(filename)) { pFileRef = (STRUCTURE_FILE_REF *) MemAlloc( sizeof( STRUCTURE_FILE_REF ) ); memset( pFileRef, 0, sizeof( STRUCTURE_FILE_REF ) ); CStructureDataReader str_reader(pFileRef); xml_auto::TGenericXMLParser<CStructureDataReader> str_parser(&str_reader); SGP_TRYCATCH_RETHROW( str_parser.parseFile(filename), _BS(L"Could not parse file : ") << filename << _BS::wget); uiDataSize = str_reader.structure_data_size; fOk = TRUE; found_jsd_xml_file = true; } else { } } if(!found_jsd_xml_file) { pFileRef = (STRUCTURE_FILE_REF *) MemAlloc( sizeof( STRUCTURE_FILE_REF ) ); if (pFileRef == NULL) { return( NULL ); } memset( pFileRef, 0, sizeof( STRUCTURE_FILE_REF ) ); if(g_bUseXML_Structures) { } fOk = LoadStructureData( szFileName, pFileRef, &uiDataSize ); } if (!fOk) { SGP_WARNING("Could not load structure file : ") << szFileName << "[.jsd|.xml]" << sgp::endl << sgp::flush; MemFree( pFileRef ); return( NULL ); } if (pFileRef->pubStructureData != NULL) { fOk = CreateFileStructureArrays( pFileRef, uiDataSize ); if (fOk == FALSE) { FreeStructureFileRef( pFileRef ); return( NULL ); } } // Add the file reference to the master list, at the head for convenience if (gpStructureFileRefs != NULL) { gpStructureFileRefs->pPrev = pFileRef; } pFileRef->pNext = gpStructureFileRefs; gpStructureFileRefs = pFileRef; return( pFileRef ); } // // Structure creation functions // STRUCTURE * CreateStructureFromDB( DB_STRUCTURE_REF * pDBStructureRef, UINT8 ubTileNum ) { // Creates a STRUCTURE struct for one tile of a structure STRUCTURE * pStructure; DB_STRUCTURE * pDBStructure; DB_STRUCTURE_TILE * pTile; // set pointers to the DBStructure and Tile CHECKN( pDBStructureRef ); CHECKN( pDBStructureRef->pDBStructure ); pDBStructure = pDBStructureRef->pDBStructure; CHECKN( pDBStructureRef->ppTile ); pTile = pDBStructureRef->ppTile[ubTileNum]; CHECKN( pTile ); // allocate memory... pStructure = (STRUCTURE *) MemAlloc( sizeof( STRUCTURE ) ); CHECKN( pStructure ); memset( pStructure, 0, sizeof( STRUCTURE ) ); // setup pStructure->fFlags = pDBStructure->fFlags; pStructure->pShape = &(pTile->Shape); pStructure->pDBStructureRef = pDBStructureRef; if (pTile->sPosRelToBase == 0) { // base tile pStructure->fFlags |= STRUCTURE_BASE_TILE; pStructure->ubHitPoints = pDBStructure->ubHitPoints; } if (pDBStructure->ubWallOrientation != NO_ORIENTATION) { if (pStructure->fFlags & STRUCTURE_WALL) { // for multi-tile walls, which are only the special corner pieces, // the non-base tile gets no orientation value because this copy // will be skipped if (pStructure->fFlags & STRUCTURE_BASE_TILE) { pStructure->ubWallOrientation = pDBStructure->ubWallOrientation; } } else { pStructure->ubWallOrientation = pDBStructure->ubWallOrientation; } } pStructure->ubVehicleHitLocation = pTile->ubVehicleHitLocation; return( pStructure ); } BOOLEAN OkayToAddStructureToTile( INT32 sBaseGridNo, INT16 sCubeOffset, DB_STRUCTURE_REF * pDBStructureRef, UINT8 ubTileIndex, INT16 sExclusionID, BOOLEAN fIgnorePeople ) { // Verifies whether a structure is blocked from being added to the map at a particular point DB_STRUCTURE * pDBStructure; DB_STRUCTURE_TILE ** ppTile; STRUCTURE * pExistingStructure; STRUCTURE * pOtherExistingStructure; INT8 bLoop, bLoop2; INT32 sGridNo; INT32 sOtherGridNo; ppTile = pDBStructureRef->ppTile; sGridNo = sBaseGridNo + ppTile[ubTileIndex]->sPosRelToBase; if (sGridNo < 0 || sGridNo > WORLD_MAX) { return( FALSE ); } if (gpWorldLevelData[sBaseGridNo].sHeight != gpWorldLevelData[sGridNo].sHeight) { // uneven terrain, one portion on top of cliff and another not! can't add! return( FALSE ); } pDBStructure = pDBStructureRef->pDBStructure; pExistingStructure = gpWorldLevelData[sGridNo].pStructureHead; /* // If adding a mobile structure, always allow addition if the mobile structure tile is passable if ( (pDBStructure->fFlags & STRUCTURE_MOBILE) && (ppTile[ubTileIndex]->fFlags & TILE_PASSABLE) ) { return( TRUE ); } */ while (pExistingStructure != NULL) { if (sCubeOffset == pExistingStructure->sCubeOffset) { // CJC: // If adding a mobile structure, allow addition if existing structure is passable if ( (pDBStructure->fFlags & STRUCTURE_MOBILE) && (pExistingStructure->fFlags & STRUCTURE_PASSABLE) ) { // Skip! pExistingStructure = pExistingStructure->pNext; continue; } if (pDBStructure->fFlags & STRUCTURE_OBSTACLE) { // CJC: NB these next two if states are probably COMPLETELY OBSOLETE but I'm leaving // them in there for now (no harm done) // ATE: // ignore this one if it has the same ID num as exclusion if ( sExclusionID != INVALID_STRUCTURE_ID ) { if ( pExistingStructure->usStructureID == sExclusionID ) { // Skip! pExistingStructure = pExistingStructure->pNext; continue; } } if ( fIgnorePeople ) { // If we are a person, skip! if ( pExistingStructure->usStructureID < TOTAL_SOLDIERS ) { // Skip! pExistingStructure = pExistingStructure->pNext; continue; } } // two obstacle structures aren't allowed in the same tile at the same height // ATE: There is more sophisticated logic for mobiles, so postpone this check if mobile.... if ( ( pExistingStructure->fFlags & STRUCTURE_OBSTACLE ) && !( pDBStructure->fFlags & STRUCTURE_MOBILE ) ) { if ( pExistingStructure->fFlags & STRUCTURE_PASSABLE && !(pExistingStructure->fFlags & STRUCTURE_MOBILE) ) { // no mobiles, existing structure is passable } else { return( FALSE ); } } else if ((pDBStructure->ubNumberOfTiles > 1) && (pExistingStructure->fFlags & STRUCTURE_WALLSTUFF)) { // if not an open door... if ( ! ( (pExistingStructure->fFlags & STRUCTURE_ANYDOOR) && (pExistingStructure->fFlags & STRUCTURE_OPEN) ) ) { // we could be trying to place a multi-tile obstacle on top of a wall; we shouldn't // allow this if the structure is going to be on both sides of the wall for (bLoop = 1; bLoop < 4; bLoop++) { switch( pExistingStructure->ubWallOrientation) { case OUTSIDE_TOP_LEFT: case INSIDE_TOP_LEFT: sOtherGridNo = NewGridNo( sGridNo, DirectionInc( (INT8) (bLoop + 2) ) ); break; case OUTSIDE_TOP_RIGHT: case INSIDE_TOP_RIGHT: sOtherGridNo = NewGridNo( sGridNo, DirectionInc( bLoop ) ); break; default: // @%?@#%?@% sOtherGridNo = NewGridNo( sGridNo, DirectionInc( SOUTHEAST ) ); } for (bLoop2 = 0; bLoop2 < pDBStructure->ubNumberOfTiles; bLoop2++) { if ( sBaseGridNo + ppTile[bLoop2]->sPosRelToBase == sOtherGridNo) { // obstacle will straddle wall! return( FALSE ); } } } } } } else if (pDBStructure->fFlags & STRUCTURE_WALLSTUFF) { // two walls with the same alignment aren't allowed in the same tile if ((pExistingStructure->fFlags & STRUCTURE_WALLSTUFF) && (pDBStructure->ubWallOrientation == pExistingStructure->ubWallOrientation)) { return( FALSE ); } else if ( !(pExistingStructure->fFlags & (STRUCTURE_CORPSE | STRUCTURE_PERSON)) ) { // it's possible we're trying to insert this wall on top of a multitile obstacle for (bLoop = 1; bLoop < 4; bLoop++) { switch( pDBStructure->ubWallOrientation) { case OUTSIDE_TOP_LEFT: case INSIDE_TOP_LEFT: sOtherGridNo = NewGridNo( sGridNo, DirectionInc( (INT8) (bLoop + 2) ) ); break; case OUTSIDE_TOP_RIGHT: case INSIDE_TOP_RIGHT: sOtherGridNo = NewGridNo( sGridNo, DirectionInc( bLoop ) ); break; default: // @%?@#%?@% sOtherGridNo = NewGridNo( sGridNo, DirectionInc( SOUTHEAST ) ); break; } for (ubTileIndex = 0; ubTileIndex < pDBStructure->ubNumberOfTiles; ubTileIndex++) { pOtherExistingStructure = FindStructureByID( sOtherGridNo, pExistingStructure->usStructureID ); if (pOtherExistingStructure) { return( FALSE ); } } } } } if ( pDBStructure->fFlags & STRUCTURE_MOBILE ) { // ATE: // ignore this one if it has the same ID num as exclusion if ( sExclusionID != INVALID_STRUCTURE_ID ) { if ( pExistingStructure->usStructureID == sExclusionID ) { // Skip! pExistingStructure = pExistingStructure->pNext; continue; } } if ( fIgnorePeople ) { // If we are a person, skip! if ( pExistingStructure->usStructureID < TOTAL_SOLDIERS ) { // Skip! pExistingStructure = pExistingStructure->pNext; continue; } } // ATE: Added check here - UNLESS the part we are trying to add is PASSABLE! if ( pExistingStructure->fFlags & STRUCTURE_MOBILE && !(pExistingStructure->fFlags & STRUCTURE_PASSABLE) && !(ppTile[ubTileIndex]->fFlags & TILE_PASSABLE) ) { // don't allow 2 people in the same tile return( FALSE ); } // ATE: Another rule: allow PASSABLE *IF* the PASSABLE is *NOT* MOBILE! if ( !( pExistingStructure->fFlags & STRUCTURE_MOBILE ) && (pExistingStructure->fFlags & STRUCTURE_PASSABLE) ) { // Skip! pExistingStructure = pExistingStructure->pNext; continue; } // ATE: Added here - UNLESS this part is PASSABLE.... // two obstacle structures aren't allowed in the same tile at the same height if ( (pExistingStructure->fFlags & STRUCTURE_OBSTACLE ) && !(ppTile[ubTileIndex]->fFlags & TILE_PASSABLE) ) { return( FALSE ); } } if ((pDBStructure->fFlags & STRUCTURE_OPENABLE)) { if (pExistingStructure->fFlags & STRUCTURE_OPENABLE) { // don't allow two openable structures in the same tile or things will screw // up on an interface level return( FALSE ); } } } pExistingStructure = pExistingStructure->pNext; } return( TRUE ); } BOOLEAN InternalOkayToAddStructureToWorld( INT32 sBaseGridNo, INT8 bLevel, DB_STRUCTURE_REF * pDBStructureRef, INT16 sExclusionID, BOOLEAN fIgnorePeople ) { UINT8 ubLoop; INT16 sCubeOffset; CHECKF( pDBStructureRef ); CHECKF( pDBStructureRef->pDBStructure ); CHECKF( pDBStructureRef->pDBStructure->ubNumberOfTiles > 0 ); CHECKF( pDBStructureRef->ppTile ); /* if (gpWorldLevelData[sGridNo].sHeight != sBaseTileHeight) { // not level ground! return( FALSE ); } */ for (ubLoop = 0; ubLoop < pDBStructureRef->pDBStructure->ubNumberOfTiles; ubLoop++) { if (pDBStructureRef->ppTile[ubLoop]->fFlags & TILE_ON_ROOF) { if (bLevel == 0) { sCubeOffset = PROFILE_Z_SIZE; } else { return( FALSE ); } } else { sCubeOffset = bLevel * PROFILE_Z_SIZE; } if (!OkayToAddStructureToTile( sBaseGridNo, sCubeOffset, pDBStructureRef, ubLoop, sExclusionID, fIgnorePeople )) { return( FALSE ); } } return( TRUE ); } BOOLEAN OkayToAddStructureToWorld( INT32 sBaseGridNo, INT8 bLevel, DB_STRUCTURE_REF * pDBStructureRef, INT16 sExclusionID ) { return( InternalOkayToAddStructureToWorld( sBaseGridNo, bLevel, pDBStructureRef, sExclusionID, (BOOLEAN)(sExclusionID == IGNORE_PEOPLE_STRUCTURE_ID) ) ); } BOOLEAN AddStructureToTile( MAP_ELEMENT * pMapElement, STRUCTURE * pStructure, UINT16 usStructureID ) { // adds a STRUCTURE to a MAP_ELEMENT (adds part of a structure to a location on the map) STRUCTURE * pStructureTail; CHECKF( pMapElement ); CHECKF( pStructure ); pStructureTail = pMapElement->pStructureTail; if (pStructureTail == NULL) { // set the head and tail to the new structure pMapElement->pStructureHead = pStructure; } else { // add to the end of the list pStructure->pPrev = pStructureTail; pStructureTail->pNext = pStructure; } pMapElement->pStructureTail = pStructure; pStructure->usStructureID = usStructureID; if (pStructure->fFlags & STRUCTURE_OPENABLE) { pMapElement->uiFlags |= MAPELEMENT_INTERACTIVETILE; } return( TRUE ); } STRUCTURE * InternalAddStructureToWorld( INT32 sBaseGridNo, INT8 bLevel, DB_STRUCTURE_REF * pDBStructureRef, LEVELNODE * pLevelNode ) { // Adds a complete structure to the world at a location plus all other locations covered by the structure INT32 sGridNo; STRUCTURE ** ppStructure; STRUCTURE * pBaseStructure; DB_STRUCTURE * pDBStructure; DB_STRUCTURE_TILE ** ppTile; UINT8 ubLoop; UINT8 ubLoop2; INT16 sBaseTileHeight=-1; UINT16 usStructureID; CHECKF( pDBStructureRef ); CHECKF( pLevelNode ); pDBStructure = pDBStructureRef->pDBStructure; CHECKF( pDBStructure ); ppTile = pDBStructureRef->ppTile; CHECKF( ppTile ); CHECKF( pDBStructure->ubNumberOfTiles > 0 ); // first check to see if the structure will be blocked if (!OkayToAddStructureToWorld( sBaseGridNo, bLevel, pDBStructureRef, INVALID_STRUCTURE_ID ) ) { return( NULL ); } // We go through a definition stage here and a later stage of // adding everything to the world so that we don't have to untangle // things if we run out of memory. First we create an array of // pointers to point to all of the STRUCTURE elements created in // the first stage. This array gets given to the base tile so // there is an easy way to remove an entire object from the world quickly // NB we add 1 because the 0th element is in fact the reference count! ppStructure = (STRUCTURE **) MemAlloc( pDBStructure->ubNumberOfTiles * sizeof( STRUCTURE * ) ); CHECKF( ppStructure ); memset( ppStructure, 0, pDBStructure->ubNumberOfTiles * sizeof( STRUCTURE * ) ); for (ubLoop = BASE_TILE; ubLoop < pDBStructure->ubNumberOfTiles; ubLoop++) { // for each tile, create the appropriate STRUCTURE struct ppStructure[ubLoop] = CreateStructureFromDB( pDBStructureRef, ubLoop ); if (ppStructure[ubLoop] == NULL) { // Free allocated memory and abort! for (ubLoop2 = 0; ubLoop2 < ubLoop; ubLoop2++) { MemFree( ppStructure[ubLoop2] ); } MemFree( ppStructure ); return( NULL ); } ppStructure[ubLoop]->sGridNo = sBaseGridNo + ppTile[ubLoop]->sPosRelToBase; if (ubLoop != BASE_TILE) { #ifdef JA2EDITOR //Kris: //Added this undo code if in the editor. //It is important to save tiles effected by multitiles. If the structure placement //fails below, it doesn't matter, because it won't hurt the undo code. if( gfEditMode ) AddToUndoList( ppStructure[ ubLoop ]->sGridNo ); #endif ppStructure[ubLoop]->sBaseGridNo = sBaseGridNo; } if (ppTile[ubLoop]->fFlags & TILE_ON_ROOF) { ppStructure[ubLoop]->sCubeOffset = (bLevel + 1) * PROFILE_Z_SIZE; } else { ppStructure[ubLoop]->sCubeOffset = bLevel * PROFILE_Z_SIZE; } if (ppTile[ubLoop]->fFlags & TILE_PASSABLE) { ppStructure[ubLoop]->fFlags |= STRUCTURE_PASSABLE; } if (pLevelNode->uiFlags & LEVELNODE_SOLDIER) { // should now be unncessary ppStructure[ubLoop]->fFlags |= STRUCTURE_PERSON; ppStructure[ubLoop]->fFlags &= ~(STRUCTURE_BLOCKSMOVES); } else if (pLevelNode->uiFlags & LEVELNODE_ROTTINGCORPSE || pDBStructure->fFlags & STRUCTURE_CORPSE) { ppStructure[ubLoop]->fFlags |= STRUCTURE_CORPSE; // attempted check to screen this out for queen creature or vehicle if ( pDBStructure->ubNumberOfTiles < 10 ) { ppStructure[ubLoop]->fFlags |= STRUCTURE_PASSABLE; ppStructure[ubLoop]->fFlags &= ~(STRUCTURE_BLOCKSMOVES); } else { // make sure not transparent ppStructure[ubLoop]->fFlags &= ~(STRUCTURE_TRANSPARENT); } } } if (pLevelNode->uiFlags & LEVELNODE_SOLDIER) { // use the merc's ID as the structure ID for his/her structure usStructureID = pLevelNode->pSoldier->ubID; } else if (pLevelNode->uiFlags & LEVELNODE_ROTTINGCORPSE) { // ATE: Offset IDs so they don't collide with soldiers usStructureID = (UINT16)( TOTAL_SOLDIERS + pLevelNode->pAniTile->uiUserData ); } else { gusNextAvailableStructureID++; if (gusNextAvailableStructureID == 0) { // skip past the #s for soldiers' structures and the invalid structure # gusNextAvailableStructureID = FIRST_AVAILABLE_STRUCTURE_ID; } usStructureID = gusNextAvailableStructureID; } // now add all these to the world! for (ubLoop = BASE_TILE; ubLoop < pDBStructure->ubNumberOfTiles; ubLoop++) { sGridNo = ppStructure[ubLoop]->sGridNo; if (ubLoop == BASE_TILE) { sBaseTileHeight = gpWorldLevelData[sGridNo].sHeight; } else { if (gpWorldLevelData[sGridNo].sHeight != sBaseTileHeight) { // not level ground! abort! for (ubLoop2 = BASE_TILE; ubLoop2 < ubLoop; ubLoop2++) { DeleteStructureFromTile( &(gpWorldLevelData[ppStructure[ubLoop2]->sGridNo]), ppStructure[ubLoop2] ); } MemFree( ppStructure ); return( NULL ); } } if (AddStructureToTile( &(gpWorldLevelData[sGridNo]), ppStructure[ubLoop], usStructureID ) == FALSE) { // error! abort! for (ubLoop2 = BASE_TILE; ubLoop2 < ubLoop; ubLoop2++) { DeleteStructureFromTile( &(gpWorldLevelData[ppStructure[ubLoop2]->sGridNo]), ppStructure[ubLoop2] ); } MemFree( ppStructure ); return( NULL ); } } pBaseStructure = ppStructure[BASE_TILE]; pLevelNode->pStructureData = pBaseStructure; MemFree( ppStructure ); // And we're done! return a pointer to the base structure! return( pBaseStructure ); } BOOLEAN AddStructureToWorld( INT32 sBaseGridNo, INT8 bLevel, DB_STRUCTURE_REF * pDBStructureRef, PTR pLevelN ) { STRUCTURE * pStructure; pStructure = InternalAddStructureToWorld( sBaseGridNo, bLevel, pDBStructureRef, (LEVELNODE *) pLevelN ); if (pStructure == NULL) { return( FALSE ); } return( TRUE ); } // // Structure deletion functions // void DeleteStructureFromTile( MAP_ELEMENT * pMapElement, STRUCTURE * pStructure ) { // removes a STRUCTURE element at a particular location from the world // put location pointer in tile if (pMapElement->pStructureHead == pStructure) { if (pMapElement->pStructureTail == pStructure) { // only element in the list! pMapElement->pStructureHead = NULL; pMapElement->pStructureTail = NULL; } else { // first element in the list of 2+ members pMapElement->pStructureHead = pStructure->pNext; } } else if (pMapElement->pStructureTail == pStructure) { // last element in the list pStructure->pPrev->pNext = NULL; pMapElement->pStructureTail = pStructure->pPrev; } else { // second or later element in the list; it's guaranteed that there is a // previous element but not necessary a next pStructure->pPrev->pNext = pStructure->pNext; if (pStructure->pNext != NULL) { pStructure->pNext->pPrev = pStructure->pPrev; } } if (pStructure->fFlags & STRUCTURE_OPENABLE) { // only one allowed in a tile, so we are safe to do this... pMapElement->uiFlags &= (~MAPELEMENT_INTERACTIVETILE); } MemFree( pStructure ); } BOOLEAN DeleteStructureFromWorld( STRUCTURE * pStructure ) { // removes all of the STRUCTURE elements for a structure from the world MAP_ELEMENT * pBaseMapElement; STRUCTURE * pBaseStructure; DB_STRUCTURE_TILE ** ppTile; STRUCTURE * pCurrent; UINT8 ubLoop, ubLoop2; UINT8 ubNumberOfTiles; INT32 sBaseGridNo, sGridNo; UINT16 usStructureID; BOOLEAN fMultiStructure; BOOLEAN fRecompileMPs; BOOLEAN fRecompileExtraRadius; // for doors... yuck INT32 sCheckGridNo; CHECKF( pStructure ); pBaseStructure = FindBaseStructure( pStructure ); CHECKF( pBaseStructure ); usStructureID = pBaseStructure->usStructureID; fMultiStructure = ( ( pBaseStructure->fFlags & STRUCTURE_MULTI ) != 0 ); fRecompileMPs = ( ( gsRecompileAreaLeft != 0 ) && ! ( ( pBaseStructure->fFlags & STRUCTURE_MOBILE ) != 0 ) ); if (fRecompileMPs) { fRecompileExtraRadius = ( ( pBaseStructure->fFlags & STRUCTURE_WALLSTUFF ) != 0 ); } else { fRecompileExtraRadius = FALSE; } pBaseMapElement = &gpWorldLevelData[pBaseStructure->sGridNo]; ppTile = pBaseStructure->pDBStructureRef->ppTile; sBaseGridNo = pBaseStructure->sGridNo; ubNumberOfTiles = pBaseStructure->pDBStructureRef->pDBStructure->ubNumberOfTiles; // Free all the tiles for (ubLoop = BASE_TILE; ubLoop < ubNumberOfTiles; ubLoop++) { sGridNo = sBaseGridNo + ppTile[ubLoop]->sPosRelToBase; // there might be two structures in this tile, one on each level, but we just want to // delete one on each pass pCurrent = FindStructureByID( sGridNo, usStructureID ); if (pCurrent) { DeleteStructureFromTile( &gpWorldLevelData[sGridNo], pCurrent ); } if ( !gfEditMode && ( fRecompileMPs ) ) { if ( fRecompileMPs ) { AddTileToRecompileArea( sGridNo ); if ( fRecompileExtraRadius ) { // add adjacent tiles too for (ubLoop2 = 0; ubLoop2 < NUM_WORLD_DIRECTIONS; ubLoop2++) { sCheckGridNo = NewGridNo( sGridNo, DirectionInc( ubLoop2 ) ); if (sCheckGridNo != sGridNo) { AddTileToRecompileArea( sCheckGridNo ); } } } } } } return( TRUE ); } STRUCTURE * InternalSwapStructureForPartner( INT32 sGridNo, STRUCTURE * pStructure, BOOLEAN fFlipSwitches, BOOLEAN fStoreInMap ) { // switch structure LEVELNODE * pLevelNode; LEVELNODE * pShadowNode; STRUCTURE * pBaseStructure; STRUCTURE * pNewBaseStructure; DB_STRUCTURE_REF * pPartnerDBStructure; BOOLEAN fDoor; INT8 bDelta; UINT8 ubHitPoints; INT16 sCubeOffset; if (pStructure == NULL) { return( NULL ); } pBaseStructure = FindBaseStructure( pStructure ); CHECKF( pBaseStructure ); if ((pBaseStructure->pDBStructureRef->pDBStructure)->bPartnerDelta == NO_PARTNER_STRUCTURE) { return( NULL ); } fDoor = ((pBaseStructure->fFlags & STRUCTURE_ANYDOOR) > 0); pLevelNode = FindLevelNodeBasedOnStructure( pBaseStructure->sGridNo, pBaseStructure ); if (pLevelNode == NULL) { return( NULL ); } pShadowNode = FindShadow( pBaseStructure->sGridNo, pLevelNode->usIndex ); // record values bDelta = pBaseStructure->pDBStructureRef->pDBStructure->bPartnerDelta; pPartnerDBStructure = pBaseStructure->pDBStructureRef + bDelta; sGridNo = pBaseStructure->sGridNo; ubHitPoints = pBaseStructure->ubHitPoints; sCubeOffset = pBaseStructure->sCubeOffset; // delete the old structure and add the new one if (DeleteStructureFromWorld( pBaseStructure ) == FALSE) { return( NULL ); } pNewBaseStructure = InternalAddStructureToWorld( sGridNo, (INT8) (sCubeOffset / PROFILE_Z_SIZE), pPartnerDBStructure, pLevelNode ); if (pNewBaseStructure == NULL) { return( NULL ); } // set values in the new structure pNewBaseStructure->ubHitPoints = ubHitPoints; if (!fDoor) { // swap the graphics // store removal of previous if necessary if ( fStoreInMap ) { ApplyMapChangesToMapTempFile( TRUE ); RemoveStructFromMapTempFile( sGridNo, pLevelNode->usIndex ); } pLevelNode->usIndex += bDelta; // store removal of new one if necessary if ( fStoreInMap ) { AddStructToMapTempFile( sGridNo, pLevelNode->usIndex ); ApplyMapChangesToMapTempFile( FALSE ); } if (pShadowNode != NULL) { pShadowNode->usIndex += bDelta; } } //if ( (pNewBaseStructure->fFlags & STRUCTURE_SWITCH) && (pNewBaseStructure->fFlags & STRUCTURE_OPEN) ) if ( 0 /*fFlipSwitches*/ ) { if ( pNewBaseStructure->fFlags & STRUCTURE_SWITCH ) { // just turned a switch on! ActivateSwitchInGridNo( NOBODY, sGridNo ); } } return( pNewBaseStructure ); } STRUCTURE * SwapStructureForPartner( INT32 sGridNo, STRUCTURE * pStructure ) { return( InternalSwapStructureForPartner( sGridNo, pStructure, TRUE, FALSE ) ); } STRUCTURE * SwapStructureForPartnerWithoutTriggeringSwitches( INT32 sGridNo, STRUCTURE * pStructure ) { return( InternalSwapStructureForPartner( sGridNo, pStructure, FALSE, FALSE ) ); } STRUCTURE * SwapStructureForPartnerAndStoreChangeInMap( INT32 sGridNo, STRUCTURE * pStructure ) { return( InternalSwapStructureForPartner( sGridNo, pStructure, TRUE, TRUE ) ); } #ifdef JA2UB STRUCTURE * SwapStructureForPartnerForcingGraphicalChange( INT32 sGridNo, STRUCTURE * pStructure ) { return( InternalSwapStructureForPartner( sGridNo, pStructure, FALSE, TRUE ) ); } #endif STRUCTURE * FindStructure( INT32 sGridNo, UINT32 fFlags ) { // finds a structure that matches any of the given flags STRUCTURE * pCurrent; //bug fix for win98 crash when traveling between sectors if ( TileIsOutOfBounds( sGridNo ) ) { return( NULL ); } pCurrent = gpWorldLevelData[sGridNo].pStructureHead; while (pCurrent != NULL) { if ((pCurrent->fFlags & fFlags) != 0) { return( pCurrent ); } pCurrent = pCurrent->pNext; } return( NULL ); } STRUCTURE * FindNextStructure( STRUCTURE * pStructure, UINT32 fFlags ) { STRUCTURE * pCurrent; CHECKF( pStructure ); pCurrent = pStructure->pNext; while (pCurrent != NULL) { if ((pCurrent->fFlags & fFlags) != 0) { return( pCurrent ); } pCurrent = pCurrent->pNext; } return( NULL ); } STRUCTURE * FindStructureByID( INT32 sGridNo, UINT16 usStructureID ) { // finds a structure that matches any of the given flags STRUCTURE * pCurrent; pCurrent = gpWorldLevelData[sGridNo].pStructureHead; while (pCurrent != NULL) { if (pCurrent->usStructureID == usStructureID) { return( pCurrent ); } pCurrent = pCurrent->pNext; } return( NULL ); } STRUCTURE * FindBaseStructure( STRUCTURE * pStructure ) { // finds the base structure for any structure CHECKF( pStructure ); if (pStructure->fFlags & STRUCTURE_BASE_TILE) { return( pStructure ); } return( FindStructureByID( pStructure->sBaseGridNo, pStructure->usStructureID ) ); } STRUCTURE * FindNonBaseStructure( INT32 sGridNo, STRUCTURE * pStructure ) { // finds a non-base structure in a location CHECKF( pStructure ); if (!(pStructure->fFlags & STRUCTURE_BASE_TILE)) { // error! return( NULL ); } return( FindStructureByID( sGridNo, pStructure->usStructureID ) ); } INT16 GetBaseTile( STRUCTURE * pStructure ) { if (pStructure == NULL) { return( -1 ); } if (pStructure->fFlags & STRUCTURE_BASE_TILE) { return( pStructure->sGridNo ); } else { return( pStructure->sBaseGridNo ); } } INT8 StructureHeight( STRUCTURE * pStructure ) { // return the height of an object from 1-4 UINT8 ubLoopX, ubLoopY; PROFILE * pShape; UINT8 ubShapeValue; INT8 bLoopZ; INT8 bGreatestHeight = -1; if (pStructure == NULL || pStructure->pShape == NULL) { return( 0 ); } if (pStructure->ubStructureHeight != 0) { return( pStructure->ubStructureHeight ); } pShape = pStructure->pShape; // loop horizontally on the X and Y planes for (ubLoopX = 0; ubLoopX < PROFILE_X_SIZE; ubLoopX++) { for (ubLoopY = 0; ubLoopY < PROFILE_Y_SIZE; ubLoopY++) { ubShapeValue = (*pShape)[ubLoopX][ubLoopY]; // loop DOWN vertically so that we find the tallest point first // and don't need to check any below it for (bLoopZ = PROFILE_Z_SIZE - 1; bLoopZ > bGreatestHeight; bLoopZ--) { if (ubShapeValue & AtHeight[bLoopZ]) { bGreatestHeight = bLoopZ; if (bGreatestHeight == PROFILE_Z_SIZE - 1) { // store height pStructure->ubStructureHeight = bGreatestHeight + 1; return( bGreatestHeight + 1); } break; } } } } // store height pStructure->ubStructureHeight = bGreatestHeight + 1; return( bGreatestHeight + 1); } INT8 GetTallestStructureHeight( INT32 sGridNo, BOOLEAN fOnRoof ) { STRUCTURE * pCurrent; INT8 iHeight; INT8 iTallest = 0; INT16 sDesiredHeight; if (fOnRoof) { sDesiredHeight = STRUCTURE_ON_ROOF; } else { sDesiredHeight = STRUCTURE_ON_GROUND; } pCurrent = gpWorldLevelData[sGridNo].pStructureHead; while (pCurrent != NULL) { if (pCurrent->sCubeOffset == sDesiredHeight) { iHeight = StructureHeight( pCurrent ); if (iHeight > iTallest) { iTallest = iHeight; } } pCurrent = pCurrent->pNext; } return( iTallest ); } INT8 GetStructureTargetHeight( INT32 sGridNo, BOOLEAN fOnRoof ) { STRUCTURE * pCurrent; INT8 iHeight; INT8 iTallest = 0; INT16 sDesiredHeight; if (fOnRoof) { sDesiredHeight = STRUCTURE_ON_ROOF; } else { sDesiredHeight = STRUCTURE_ON_GROUND; } // prioritize openable structures and doors pCurrent = FindStructure( sGridNo, (STRUCTURE_DOOR | STRUCTURE_OPENABLE ) ); if ( pCurrent ) { // use this structure if ( pCurrent->fFlags & STRUCTURE_DOOR ) { iTallest = 3; // don't aim at the very top of the door } else { iTallest = StructureHeight( pCurrent ); } } else { pCurrent = gpWorldLevelData[sGridNo].pStructureHead; while (pCurrent != NULL) { if (pCurrent->sCubeOffset == sDesiredHeight) { iHeight = StructureHeight( pCurrent ); if (iHeight > iTallest) { iTallest = iHeight; } } pCurrent = pCurrent->pNext; } } return( iTallest ); } INT8 StructureBottomLevel( STRUCTURE * pStructure ) { // return the bottom level of an object, from 1-4 UINT8 ubLoopX, ubLoopY; PROFILE * pShape; UINT8 ubShapeValue; INT8 bLoopZ; INT8 bLowestHeight = PROFILE_Z_SIZE; if (pStructure == NULL || pStructure->pShape == NULL) { return( 0 ); } pShape = pStructure->pShape; // loop horizontally on the X and Y planes for (ubLoopX = 0; ubLoopX < PROFILE_X_SIZE; ubLoopX++) { for (ubLoopY = 0; ubLoopY < PROFILE_Y_SIZE; ubLoopY++) { ubShapeValue = (*pShape)[ubLoopX][ubLoopY]; // loop DOWN vertically so that we find the tallest point first // and don't need to check any below it for (bLoopZ = 0; bLoopZ < bLowestHeight; bLoopZ++) { if (ubShapeValue & AtHeight[bLoopZ]) { bLowestHeight = bLoopZ; if (bLowestHeight == 0) { return( 1 ); } break; } } } } return( bLowestHeight + 1); } BOOLEAN StructureDensity( STRUCTURE * pStructure, UINT8 * pubLevel0, UINT8 * pubLevel1, UINT8 * pubLevel2, UINT8 * pubLevel3 ) { UINT8 ubLoopX, ubLoopY; UINT8 ubShapeValue; PROFILE * pShape; CHECKF( pStructure ); CHECKF( pubLevel0 ); CHECKF( pubLevel1 ); CHECKF( pubLevel2 ); CHECKF( pubLevel3 ); *pubLevel0 = 0; *pubLevel1 = 0; *pubLevel2 = 0; *pubLevel3 = 0; pShape = pStructure->pShape; for (ubLoopX = 0; ubLoopX < PROFILE_X_SIZE; ubLoopX++) { for (ubLoopY = 0; ubLoopY < PROFILE_Y_SIZE; ubLoopY++) { ubShapeValue = (*pShape)[ubLoopX][ubLoopY]; if (ubShapeValue & AtHeight[0]) { (*pubLevel0)++; } if (ubShapeValue & AtHeight[1]) { (*pubLevel1)++; } if (ubShapeValue & AtHeight[2]) { (*pubLevel2)++; } if (ubShapeValue & AtHeight[3]) { (*pubLevel3)++; } } } // convert values to percentages! *pubLevel0 *= 4; *pubLevel1 *= 4; *pubLevel2 *= 4; *pubLevel3 *= 4; return( TRUE ); } BOOLEAN DamageStructure( STRUCTURE * pStructure, UINT8 ubDamage, UINT8 ubReason, INT32 sGridNo, INT16 sX, INT16 sY, UINT8 ubOwner ) { // do damage to a structure; returns TRUE if the structure should be removed STRUCTURE *pBase; UINT8 ubArmour; //LEVELNODE *pNode; CHECKF( pStructure ); if (pStructure->fFlags & STRUCTURE_PERSON || pStructure->fFlags & STRUCTURE_CORPSE) { // don't hurt this structure, it's used for hit detection only! return( FALSE ); } if ( (pStructure->pDBStructureRef->pDBStructure->ubArmour == MATERIAL_INDESTRUCTABLE_METAL) || (pStructure->pDBStructureRef->pDBStructure->ubArmour == MATERIAL_INDESTRUCTABLE_STONE) ) { return( FALSE ); } // Account for armour! if (ubReason == STRUCTURE_DAMAGE_EXPLOSION) { if ( pStructure->fFlags & STRUCTURE_EXPLOSIVE ) { ubArmour = gubMaterialArmour[ pStructure->pDBStructureRef->pDBStructure->ubArmour ] / 3; } else { ubArmour = gubMaterialArmour[ pStructure->pDBStructureRef->pDBStructure->ubArmour ] / 2; } if (ubArmour > ubDamage) { // didn't even scratch the paint return( FALSE ); } else { // did some damage to the structure ubDamage -= ubArmour; } } else { ubDamage = 0; } // OK, Let's check our reason if ( ubReason == STRUCTURE_DAMAGE_GUNFIRE ) { // If here, we have penetrated, check flags // Are we an explodable structure? if ( (pStructure->fFlags & STRUCTURE_EXPLOSIVE) && Random( 2 ) ) { // Remove struct! pBase = FindBaseStructure( pStructure ); // ATE: Set hit points to zero.... pBase->ubHitPoints = 0; // Get LEVELNODE for struct and remove! // pNode = FindLevelNodeBasedOnStructure( pBase->sGridNo, pBase ); //Set a flag indicating that the following changes are to go the the maps temp file // ApplyMapChangesToMapTempFile( TRUE ); // Remove! // RemoveStructFromLevelNode( pBase->sGridNo, pNode ); // ApplyMapChangesToMapTempFile( FALSE ); // Generate an explosion here! IgniteExplosion( ubOwner, sX, sY, 0, sGridNo, STRUCTURE_IGNITE, 0 ); // ATE: Return false here, as we are dealing with deleting the graphic here... return( FALSE ); } // Make hit sound.... if ( pStructure->fFlags & STRUCTURE_CAVEWALL ) { PlayJA2Sample( S_VEG_IMPACT1, RATE_11025, SoundVolume( HIGHVOLUME, sGridNo ), 1, SoundDir( sGridNo ) ); } else { if ( guiMaterialHitSound[ pStructure->pDBStructureRef->pDBStructure->ubArmour ] != -1 ) { PlayJA2Sample( guiMaterialHitSound[ pStructure->pDBStructureRef->pDBStructure->ubArmour ], RATE_11025, SoundVolume( HIGHVOLUME, sGridNo ), 1, SoundDir( sGridNo ) ); } } // Don't update damage HPs.... return( TRUE ); } // OK, LOOK FOR A SAM SITE, UPDATE.... UpdateAndDamageSAMIfFound( gWorldSectorX, gWorldSectorY, gbWorldSectorZ, sGridNo, ubDamage ); // find the base so we can reduce the hit points! pBase = FindBaseStructure( pStructure ); CHECKF( pBase ); if (pBase->ubHitPoints <= ubDamage) { // boom! structure destroyed! return( TRUE ); } else { pBase->ubHitPoints -= ubDamage; //Since the structure is being damaged, set the map element that a structure is damaged gpWorldLevelData[ sGridNo ].uiFlags |= MAPELEMENT_STRUCTURE_DAMAGED; // We are a little damaged.... return( 2 ); } } #define LINE_HEIGHT 20 void DebugStructurePage1( void ) { STRUCTURE * pStructure; STRUCTURE * pBase; //LEVELNODE * pLand; INT32 sGridNo, sDesiredLevel; INT8 bHeight, bDens0, bDens1, bDens2, bDens3; INT8 bStructures; static CHAR16 WallOrientationString[5][15] = { L"None", L"Inside left", L"Inside right", L"Outside left", L"Outside right" }; SetFont( LARGEFONT1 ); gprintf( 0, 0, L"DEBUG STRUCTURES PAGE 1 OF 1" ); if (GetMouseMapPos( &sGridNo ) == FALSE) { return; //gprintf( 0, LINE_HEIGHT * 1, L"No structure selected" ); } if (gsInterfaceLevel == I_GROUND_LEVEL) { sDesiredLevel = STRUCTURE_ON_GROUND; } else { sDesiredLevel = STRUCTURE_ON_ROOF; } gprintf( 320, 0, L"Building %d", gubBuildingInfo[ sGridNo ] ); /* pLand = gpWorldLevelData[sGridNo].pLandHead; gprintf( 320, 0, L"Fake light %d", pLand->ubFakeShadeLevel ); gprintf( 320, LINE_HEIGHT, L"Real light: ground %d roof %d", LightTrueLevel( sGridNo, 0 ), LightTrueLevel( sGridNo, 1 ) ); */ pStructure = gpWorldLevelData[sGridNo].pStructureHead; while (pStructure != NULL) { if (pStructure->sCubeOffset == sDesiredLevel) { break; } pStructure = pStructure->pNext; } if (pStructure != NULL) { if (pStructure->fFlags & STRUCTURE_GENERIC) { gprintf( 0, LINE_HEIGHT * 1, L"Generic structure %x #%d", pStructure->fFlags, pStructure->pDBStructureRef->pDBStructure->usStructureNumber ); } else if (pStructure->fFlags & STRUCTURE_TREE) { gprintf( 0, LINE_HEIGHT * 1, L"Tree"); } else if (pStructure->fFlags & STRUCTURE_WALL) { gprintf( 0, LINE_HEIGHT * 1, L"Wall with orientation %s", WallOrientationString[pStructure->ubWallOrientation] ); } else if (pStructure->fFlags & STRUCTURE_WALLNWINDOW) { gprintf( 0, LINE_HEIGHT * 1, L"Wall with window" ); } else if (pStructure->fFlags & STRUCTURE_VEHICLE) { gprintf( 0, LINE_HEIGHT * 1, L"Vehicle %d", pStructure->pDBStructureRef->pDBStructure->usStructureNumber ); } else if (pStructure->fFlags & STRUCTURE_NORMAL_ROOF) { gprintf( 0, LINE_HEIGHT * 1, L"Roof" ); } else if (pStructure->fFlags & STRUCTURE_SLANTED_ROOF) { gprintf( 0, LINE_HEIGHT * 1, L"Slanted roof" ); } else if (pStructure->fFlags & STRUCTURE_DOOR) { gprintf( 0, LINE_HEIGHT * 1, L"Door with orientation %s", WallOrientationString[pStructure->ubWallOrientation] ); } else if (pStructure->fFlags & STRUCTURE_SLIDINGDOOR) { gprintf( 0, LINE_HEIGHT * 1, L"%s sliding door with orientation %s", (pStructure->fFlags & STRUCTURE_OPEN) ? L"Open" : L"Closed", WallOrientationString[pStructure->ubWallOrientation] ); } else if (pStructure->fFlags & STRUCTURE_DDOOR_LEFT) { gprintf( 0, LINE_HEIGHT * 1, L"DDoorLft with orientation %s", WallOrientationString[pStructure->ubWallOrientation] ); } else if (pStructure->fFlags & STRUCTURE_DDOOR_RIGHT) { gprintf( 0, LINE_HEIGHT * 1, L"DDoorRt with orientation %s", WallOrientationString[pStructure->ubWallOrientation] ); } else { gprintf( 0, LINE_HEIGHT * 1, L"UNKNOWN STRUCTURE! (%x)", pStructure->fFlags ); } bHeight = StructureHeight( pStructure ); pBase = FindBaseStructure( pStructure ); gprintf( 0, LINE_HEIGHT * 2, L"Structure height %d, cube offset %d, armour %d, HP %d", bHeight, pStructure->sCubeOffset, gubMaterialArmour[pStructure->pDBStructureRef->pDBStructure->ubArmour], pBase->ubHitPoints ); if (StructureDensity( pStructure, (UINT8 *)&bDens0, (UINT8 *)&bDens1, (UINT8 *)&bDens2, (UINT8 *)&bDens3 ) == TRUE) { gprintf( 0, LINE_HEIGHT * 3, L"Structure fill %d%%/%d%%/%d%%/%d%% density %d", bDens0, bDens1, bDens2, bDens3, pStructure->pDBStructureRef->pDBStructure->ubDensity ); } #ifndef LOS_DEBUG gprintf( 0, LINE_HEIGHT * 4, L"Structure ID %d", pStructure->usStructureID ); #endif pStructure = gpWorldLevelData[sGridNo].pStructureHead; for ( bStructures = 0; pStructure != NULL; pStructure = pStructure->pNext) { bStructures++; } gprintf( 0, LINE_HEIGHT * 12, L"Number of structures = %d", bStructures ); } #ifdef LOS_DEBUG if (gLOSTestResults.fLOSTestPerformed) { gprintf( 0, LINE_HEIGHT * 4, L"LOS from (%7d,%7d,%7d)", gLOSTestResults.iStartX, gLOSTestResults.iStartY, gLOSTestResults.iStartZ); gprintf( 0, LINE_HEIGHT * 5, L"to (%7d,%7d,%7d)", gLOSTestResults.iEndX, gLOSTestResults.iEndY, gLOSTestResults.iEndZ); if (gLOSTestResults.fOutOfRange) { gprintf( 0, LINE_HEIGHT * 6, L"is out of range" ); } else if (gLOSTestResults.fLOSClear) { gprintf( 0, LINE_HEIGHT * 6, L"is clear!" ); } else { gprintf( 0, LINE_HEIGHT * 6, L"is blocked at (%7d,%7d,%7d)!", gLOSTestResults.iStoppedX, gLOSTestResults.iStoppedY, gLOSTestResults.iStoppedZ ); gprintf( 0, LINE_HEIGHT * 10, L"Blocked at cube level %d", gLOSTestResults.iCurrCubesZ ); } gprintf( 0, LINE_HEIGHT * 7, L"Passed through %d tree bits!", gLOSTestResults.ubTreeSpotsHit ); gprintf( 0, LINE_HEIGHT * 8, L"Maximum range was %7d", gLOSTestResults.iMaxDistance ); gprintf( 0, LINE_HEIGHT * 9, L"actual range was %7d", gLOSTestResults.iDistance ); if (gLOSTestResults.ubChanceToGetThrough <= 100) { gprintf( 0, LINE_HEIGHT * 11, L"Chance to get through was %d", gLOSTestResults.ubChanceToGetThrough ); } } #endif gprintf( 0, LINE_HEIGHT * 13, L"N %d NE %d E %d SE %d", gubWorldMovementCosts[ sGridNo ][ NORTH ][ gsInterfaceLevel ], gubWorldMovementCosts[ sGridNo ][ NORTHEAST ][ gsInterfaceLevel ], gubWorldMovementCosts[ sGridNo ][ EAST ][ gsInterfaceLevel ], gubWorldMovementCosts[ sGridNo ][ SOUTHEAST ][ gsInterfaceLevel ] ); gprintf( 0, LINE_HEIGHT * 14, L"S %d SW %d W %d NW %d", gubWorldMovementCosts[ sGridNo ][ SOUTH ][ gsInterfaceLevel ], gubWorldMovementCosts[ sGridNo ][ SOUTHWEST ][ gsInterfaceLevel ], gubWorldMovementCosts[ sGridNo ][ WEST ][ gsInterfaceLevel ], gubWorldMovementCosts[ sGridNo ][ NORTHWEST ][ gsInterfaceLevel ] ); gprintf( 0, LINE_HEIGHT * 15, L"Ground smell %d strength %d", SMELL_TYPE( gpWorldLevelData[ sGridNo ].ubSmellInfo ), SMELL_STRENGTH( gpWorldLevelData[ sGridNo ].ubSmellInfo ) ); #ifdef COUNT_PATHS if (guiTotalPathChecks > 0) { gprintf( 0, LINE_HEIGHT * 16, L"Total %ld, %%succ %3ld | %%failed %3ld | %%unsucc %3ld", guiTotalPathChecks, 100 * guiSuccessfulPathChecks / guiTotalPathChecks, 100 * guiFailedPathChecks / guiTotalPathChecks, 100 * guiUnsuccessfulPathChecks / guiTotalPathChecks ); } #else gprintf( 0, LINE_HEIGHT * 16, L"Adj soldiers %d", gpWorldLevelData[sGridNo].ubAdjacentSoldierCnt ); #endif } BOOLEAN AddZStripInfoToVObject( HVOBJECT hVObject, STRUCTURE_FILE_REF * pStructureFileRef, BOOLEAN fFromAnimation, INT16 sSTIStartIndex ) { UINT32 uiLoop; UINT8 ubLoop2; UINT8 ubNumIncreasing = 0; UINT8 ubNumStable = 0; UINT8 ubNumDecreasing = 0; BOOLEAN fFound = FALSE; ZStripInfo * pCurr; INT16 sLeftHalfWidth; INT16 sRightHalfWidth; INT16 sOffsetX; INT16 sOffsetY; UINT16 usWidth; UINT16 usHeight; DB_STRUCTURE_REF * pDBStructureRef; DB_STRUCTURE * pDBStructure = NULL; INT16 sSTIStep = 0; INT16 sStructIndex = 0; INT16 sNext; UINT32 uiDestVoIndex; BOOLEAN fCopyIntoVo; BOOLEAN fFirstTime; if (pStructureFileRef->usNumberOfStructuresStored == 0) { return( TRUE ); } for (uiLoop = 0; uiLoop < pStructureFileRef->usNumberOfStructures; uiLoop++) { pDBStructureRef = &(pStructureFileRef->pDBStructureRef[uiLoop]); pDBStructure = pDBStructureRef->pDBStructure; //if (pDBStructure != NULL && pDBStructure->ubNumberOfTiles > 1 && !(pDBStructure->fFlags & STRUCTURE_WALLSTUFF) ) if (pDBStructure != NULL && pDBStructure->ubNumberOfTiles > 1 ) { for (ubLoop2 = 1; ubLoop2 < pDBStructure->ubNumberOfTiles; ubLoop2++) { if (pDBStructureRef->ppTile[ubLoop2]->sPosRelToBase != 0) { // spans multiple tiles! (could be two levels high in one tile) fFound = TRUE; break; } } } } // ATE: Make all corpses use z-strip info.. if ( pDBStructure != NULL && pDBStructure->fFlags & STRUCTURE_CORPSE ) { fFound = TRUE; } if (!fFound) { // no multi-tile images in this vobject; that's okay... return! return( TRUE ); } hVObject->ppZStripInfo = (ZStripInfo **) MemAlloc( sizeof( ZStripInfo * ) * hVObject->usNumberOfObjects ); if (hVObject->ppZStripInfo == NULL) { return( FALSE ); } memset( hVObject->ppZStripInfo, 0, sizeof( ZStripInfo * ) * hVObject->usNumberOfObjects ); if ( fFromAnimation ) { // Determine step index for STI if ( sSTIStartIndex == -1 ) { // one-direction only for this anim structure sSTIStep = hVObject->usNumberOfObjects; sSTIStartIndex = 0; } else { sSTIStep = ( hVObject->usNumberOfObjects / pStructureFileRef->usNumberOfStructures ); } } else { sSTIStep = 1; } sStructIndex = 0; sNext = sSTIStartIndex + sSTIStep; fFirstTime = TRUE; for (uiLoop = (UINT8)sSTIStartIndex; uiLoop < hVObject->usNumberOfObjects; uiLoop++ ) { // Defualt to true fCopyIntoVo = TRUE; // Increment struct index.... if ( uiLoop == (UINT32)sNext ) { sNext = (UINT16)( uiLoop + sSTIStep ); sStructIndex++; } else { if ( fFirstTime ) { fFirstTime = FALSE; } else { fCopyIntoVo = FALSE; } } if ( fFromAnimation ) { uiDestVoIndex = sStructIndex; } else { uiDestVoIndex = uiLoop; } if ( fCopyIntoVo && sStructIndex < pStructureFileRef->usNumberOfStructures ) { pDBStructure = pStructureFileRef->pDBStructureRef[ sStructIndex ].pDBStructure; if (pDBStructure != NULL && ( pDBStructure->ubNumberOfTiles > 1 || ( pDBStructure->fFlags & STRUCTURE_CORPSE ) ) ) //if (pDBStructure != NULL && pDBStructure->ubNumberOfTiles > 1 ) { // ATE: We allow SLIDING DOORS of 2 tile sizes... if ( !(pDBStructure->fFlags & STRUCTURE_ANYDOOR) || ( (pDBStructure->fFlags & ( STRUCTURE_ANYDOOR ) ) && ( pDBStructure->fFlags & STRUCTURE_SLIDINGDOOR ) ) ) { hVObject->ppZStripInfo[ uiDestVoIndex ] = (ZStripInfo *) MemAlloc( sizeof( ZStripInfo ) ); if (hVObject->ppZStripInfo[ uiDestVoIndex ] == NULL) { // augh!! out of memory! free everything allocated and abort for (ubLoop2 = 0; ubLoop2 < uiLoop; ubLoop2++) { if (hVObject->ppZStripInfo[ubLoop2] != NULL) { MemFree(hVObject->ppZStripInfo[uiLoop]); } } MemFree( hVObject->ppZStripInfo ); hVObject->ppZStripInfo = NULL; return( FALSE ); } else { pCurr = hVObject->ppZStripInfo[ uiDestVoIndex ]; ubNumIncreasing = 0; ubNumStable = 0; ubNumDecreasing = 0; // time to do our calculations! sOffsetX = hVObject->pETRLEObject[uiLoop].sOffsetX; sOffsetY = hVObject->pETRLEObject[uiLoop].sOffsetY; usWidth = hVObject->pETRLEObject[uiLoop].usWidth; usHeight = hVObject->pETRLEObject[uiLoop].usHeight; if (pDBStructure->fFlags & (STRUCTURE_MOBILE | STRUCTURE_CORPSE) ) { // adjust for the difference between the animation and structure base tile //if (pDBStructure->fFlags & (STRUCTURE_MOBILE ) ) { sOffsetX = sOffsetX + (WORLD_TILE_X / 2); sOffsetY = sOffsetY + (WORLD_TILE_Y / 2); } // adjust for the tile offset sOffsetX = sOffsetX - pDBStructure->bZTileOffsetX * (WORLD_TILE_X / 2) + pDBStructure->bZTileOffsetY * (WORLD_TILE_X / 2); sOffsetY = sOffsetY - pDBStructure->bZTileOffsetY * (WORLD_TILE_Y / 2); } // figure out how much of the image is on each side of // the bottom corner of the base tile if (sOffsetX <= 0) { // note that the adjustments here by (WORLD_TILE_X / 2) are to account for the X difference // between the blit position and the bottom corner of the base tile sRightHalfWidth = usWidth + sOffsetX - (WORLD_TILE_X / 2); if (sRightHalfWidth >= 0) { // Case 1: negative image offset, image straddles bottom corner // negative of a negative is positive sLeftHalfWidth = -sOffsetX + (WORLD_TILE_X / 2); } else { // Case 2: negative image offset, image all on left side // bump up the LeftHalfWidth to the right edge of the last tile-half, // so we can calculate the size of the leftmost portion accurately // NB subtracting a negative to add the absolute value sLeftHalfWidth = usWidth - (sRightHalfWidth % (WORLD_TILE_X / 2)); sRightHalfWidth = 0; } } else if (sOffsetX < (WORLD_TILE_X / 2)) { sLeftHalfWidth = (WORLD_TILE_X / 2) - sOffsetX; sRightHalfWidth = usWidth - sLeftHalfWidth; if (sRightHalfWidth <= 0) { // Case 3: positive offset < 20, image all on left side // should never happen because these images are multi-tile! sRightHalfWidth = 0; // fake the left width to one half-tile sLeftHalfWidth = (WORLD_TILE_X / 2); } else { // Case 4: positive offset < 20, image straddles bottom corner // all okay? } } else { // Case 5: positive offset, image all on right side // should never happen either sLeftHalfWidth = 0; sRightHalfWidth = usWidth; } if (sLeftHalfWidth > 0) { ubNumIncreasing = sLeftHalfWidth / (WORLD_TILE_X / 2); } if (sRightHalfWidth > 0) { ubNumStable = 1; if (sRightHalfWidth > (WORLD_TILE_X / 2)) { ubNumDecreasing = sRightHalfWidth / (WORLD_TILE_X / 2); } } if (sLeftHalfWidth > 0) { pCurr->ubFirstZStripWidth = sLeftHalfWidth % (WORLD_TILE_X / 2); if (pCurr->ubFirstZStripWidth == 0) { ubNumIncreasing--; pCurr->ubFirstZStripWidth = (WORLD_TILE_X / 2); } } else // right side only; offset is at least 20 (= WORLD_TILE_X / 2) { if (sOffsetX > WORLD_TILE_X) { pCurr->ubFirstZStripWidth = (WORLD_TILE_X / 2) - (sOffsetX - WORLD_TILE_X) % (WORLD_TILE_X / 2); } else { pCurr->ubFirstZStripWidth = WORLD_TILE_X - sOffsetX; } if (pCurr->ubFirstZStripWidth == 0) { ubNumDecreasing--; pCurr->ubFirstZStripWidth = (WORLD_TILE_X / 2); } } // now create the array! pCurr->ubNumberOfZChanges = ubNumIncreasing + ubNumStable + ubNumDecreasing; pCurr->pbZChange = (INT8 *) MemAlloc( pCurr->ubNumberOfZChanges ); if ( pCurr->pbZChange == NULL) { // augh! for (ubLoop2 = 0; ubLoop2 < uiLoop; ubLoop2++) { if (hVObject->ppZStripInfo[ubLoop2] != NULL) { MemFree(hVObject->ppZStripInfo[uiLoop]); } } MemFree( hVObject->ppZStripInfo ); hVObject->ppZStripInfo = NULL; return( FALSE ); } for (ubLoop2 = 0; ubLoop2 < ubNumIncreasing; ubLoop2++) { pCurr->pbZChange[ubLoop2] = 1; } for (; ubLoop2 < ubNumIncreasing + ubNumStable; ubLoop2++) { pCurr->pbZChange[ubLoop2] = 0; } for (; ubLoop2 < pCurr->ubNumberOfZChanges; ubLoop2++) { pCurr->pbZChange[ubLoop2] = -1; } if (ubNumIncreasing > 0) { pCurr->bInitialZChange = -(ubNumIncreasing); } else if (ubNumStable > 0) { pCurr->bInitialZChange = 0; } else { pCurr->bInitialZChange = -(ubNumDecreasing); } } } } } } return( TRUE ); } BOOLEAN InitStructureDB( void ) { gusNextAvailableStructureID = FIRST_AVAILABLE_STRUCTURE_ID; return( TRUE ); } BOOLEAN FiniStructureDB( void ) { gusNextAvailableStructureID = FIRST_AVAILABLE_STRUCTURE_ID; return( TRUE ); } INT8 GetBlockingStructureInfo( INT32 sGridNo, INT8 bDir, INT8 bNextDir, INT8 bLevel, INT8 *pStructHeight, STRUCTURE ** ppTallestStructure, BOOLEAN fWallsBlock ) { STRUCTURE * pCurrent, *pStructure = 0; INT16 sDesiredLevel; BOOLEAN fOKStructOnLevel = FALSE; BOOLEAN fMinimumBlockingFound = FALSE; if ( bLevel == 0) { sDesiredLevel = STRUCTURE_ON_GROUND; } else { sDesiredLevel = STRUCTURE_ON_ROOF; } pCurrent = gpWorldLevelData[sGridNo].pStructureHead; // If no struct, return if ( pCurrent == NULL ) { (*pStructHeight) = StructureHeight( pCurrent ); (*ppTallestStructure) = NULL; return( NOTHING_BLOCKING ); } while (pCurrent != NULL) { // Check level! if (pCurrent->sCubeOffset == sDesiredLevel ) { fOKStructOnLevel = TRUE; pStructure = pCurrent; // Turn off if we are on upper level! if ( pCurrent->fFlags & STRUCTURE_ROOF && bLevel == 1 ) { fOKStructOnLevel = FALSE; } // Don't stop FOV for people if ( pCurrent->fFlags & ( STRUCTURE_CORPSE | STRUCTURE_PERSON ) ) { fOKStructOnLevel = FALSE; } if ( pCurrent->fFlags & ( STRUCTURE_TREE | STRUCTURE_ANYFENCE ) ) { fMinimumBlockingFound = TRUE; } // Default, if we are a wall, set full blocking if ( ( pCurrent->fFlags & STRUCTURE_WALL ) && !fWallsBlock ) { // Return full blocking! // OK! This will be handled by movement costs......! fOKStructOnLevel = FALSE; } // CHECK FOR WINDOW if ( pCurrent->fFlags & STRUCTURE_WALLNWINDOW ) { switch( pCurrent->ubWallOrientation ) { case OUTSIDE_TOP_LEFT: case INSIDE_TOP_LEFT: (*pStructHeight) = StructureHeight( pCurrent ); (*ppTallestStructure) = pCurrent; if ( pCurrent->fFlags & STRUCTURE_OPEN ) { return( BLOCKING_TOPLEFT_OPEN_WINDOW ); } else { return( BLOCKING_TOPLEFT_WINDOW ); } break; case OUTSIDE_TOP_RIGHT: case INSIDE_TOP_RIGHT: (*pStructHeight) = StructureHeight( pCurrent ); (*ppTallestStructure) = pCurrent; if ( pCurrent->fFlags & STRUCTURE_OPEN ) { return( BLOCKING_TOPRIGHT_OPEN_WINDOW ); } else { return( BLOCKING_TOPRIGHT_WINDOW ); } break; } } // Check for door if ( pCurrent->fFlags & STRUCTURE_ANYDOOR ) { // If we are not opem, we are full blocking! if ( !(pCurrent->fFlags & STRUCTURE_OPEN ) ) { (*pStructHeight) = StructureHeight( pCurrent ); (*ppTallestStructure) = pCurrent; return( FULL_BLOCKING ); break; } else { switch( pCurrent->ubWallOrientation ) { case OUTSIDE_TOP_LEFT: case INSIDE_TOP_LEFT: (*pStructHeight) = StructureHeight( pCurrent ); (*ppTallestStructure) = pCurrent; return( BLOCKING_TOPLEFT_DOOR ); break; case OUTSIDE_TOP_RIGHT: case INSIDE_TOP_RIGHT: (*pStructHeight) = StructureHeight( pCurrent ); (*ppTallestStructure) = pCurrent; return( BLOCKING_TOPRIGHT_DOOR ); break; } } } } pCurrent = pCurrent->pNext; } // OK, here, we default to we've seen a struct, reveal just this one if ( fOKStructOnLevel ) { if ( fMinimumBlockingFound ) { (*pStructHeight) = StructureHeight( pStructure ); (*ppTallestStructure) = pStructure; return( BLOCKING_REDUCE_RANGE ); } else { (*pStructHeight) = StructureHeight( pStructure ); (*ppTallestStructure) = pStructure; return( BLOCKING_NEXT_TILE ); } } else { (*pStructHeight) = 0; (*ppTallestStructure) = NULL; return( NOTHING_BLOCKING ); } } UINT8 StructureFlagToType( UINT32 uiFlag ) { UINT8 ubLoop; UINT32 uiBit = STRUCTURE_GENERIC; for ( ubLoop = 8; ubLoop < 32; ubLoop++ ) { if ( (uiFlag & uiBit) != 0 ) { return( ubLoop ); } uiBit = uiBit << 1; } return( 0 ); } UINT32 StructureTypeToFlag( UINT8 ubType ) { UINT32 uiFlag = 0x1; uiFlag = uiFlag << ubType; return( uiFlag ); } STRUCTURE * FindStructureBySavedInfo( INT32 sGridNo, UINT8 ubType, UINT8 ubWallOrientation, INT8 bLevel ) { STRUCTURE * pCurrent; UINT32 uiTypeFlag; uiTypeFlag = StructureTypeToFlag( ubType ); pCurrent = gpWorldLevelData[sGridNo].pStructureHead; while (pCurrent != NULL) { if (pCurrent->fFlags & uiTypeFlag && pCurrent->ubWallOrientation == ubWallOrientation && ( (bLevel == 0 && pCurrent->sCubeOffset == 0) || (bLevel > 0 && pCurrent->sCubeOffset > 0) ) ) { return( pCurrent ); } pCurrent = pCurrent->pNext; } return( NULL ); } UINT32 GetStructureOpenSound( STRUCTURE * pStructure, BOOLEAN fClose ) { UINT32 uiSoundID; switch( pStructure->pDBStructureRef->pDBStructure->ubArmour ) { case MATERIAL_LIGHT_METAL: case MATERIAL_THICKER_METAL: uiSoundID = OPEN_LOCKER; break; case MATERIAL_WOOD_WALL: case MATERIAL_PLYWOOD_WALL: case MATERIAL_FURNITURE: uiSoundID = OPEN_WOODEN_BOX; break; default: uiSoundID = OPEN_DEFAULT_OPENABLE; } if ( fClose ) { uiSoundID++; } return( uiSoundID ); }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 2525 ] ] ]
9e8d64c56a055015e21979dfd0532abc1462f7a2
0468c65f767387da526efe03b37e1d6e8ddd1815
/source/drivers/win/replay.cpp
7703bf06b64137fd807ab336e40363996c652df7
[]
no_license
arntsonl/fc2x
aadc4e1a6c4e1d5bfcc76a3815f1f033b2d7e2fd
57ffbf6bcdf0c0b1d1e583663e4466adba80081b
refs/heads/master
2021-01-13T02:22:19.536144
2011-01-11T22:48:58
2011-01-11T22:48:58
32,103,729
0
0
null
null
null
null
UTF-8
C++
false
false
30,863
cpp
#include <io.h> #include "replay.h" #include "common.h" #include "main.h" #include "window.h" #include "movie.h" #include "archive.h" #include "utils/xstring.h" static const char* fm2ext[] = {"fm2",0}; int MetaPosX,MetaPosY; // Used when deciding to automatically make the stop movie checkbox checked static bool stopframeWasEditedByUser = false; //the comments contained in the currently-displayed movie static std::vector<std::wstring> currComments; //the subtitles contained in the currently-displayed movie static std::vector<std::string> currSubtitles; extern FCEUGI *GameInfo; //retains the state of the readonly checkbox and stopframe value bool replayReadOnlySetting; int replayStopFrameSetting = 0; void RefreshThrottleFPS(); static char* GetReplayPath(HWND hwndDlg) { char* fn=0; char szChoice[MAX_PATH]; LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETCURSEL, 0, 0); LONG lCount = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETCOUNT, 0, 0); // NOTE: lCount-1 is the "Browse..." list item if(lIndex != CB_ERR && lIndex != lCount-1) { LONG lStringLength = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETLBTEXTLEN, (WPARAM)lIndex, 0); if(lStringLength < MAX_PATH) { char szDrive[MAX_PATH]={0}; char szDirectory[MAX_PATH]={0}; char szFilename[MAX_PATH]={0}; char szExt[MAX_PATH]={0}; char szTemp[MAX_PATH]={0}; SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETLBTEXT, (WPARAM)lIndex, (LPARAM)szTemp); if(szTemp[0] && szTemp[1]!=':') sprintf(szChoice, ".\\%s", szTemp); else strcpy(szChoice, szTemp); SetCurrentDirectory(BaseDirectory.c_str()); _splitpath(szChoice, szDrive, szDirectory, szFilename, szExt); if(szDrive[0]=='\0' && szDirectory[0]=='\0') fn=strdup(FCEU_MakePath(FCEUMKF_MOVIE, szChoice).c_str()); // need to make a full path else fn=strdup(szChoice); // given a full path } } return fn; } static std::string GetRecordPath(HWND hwndDlg) { std::string fn; char szChoice[MAX_PATH]; char szDrive[MAX_PATH]={0}; char szDirectory[MAX_PATH]={0}; char szFilename[MAX_PATH]={0}; char szExt[MAX_PATH]={0}; GetDlgItemText(hwndDlg, IDC_EDIT_FILENAME, szChoice, sizeof(szChoice)); _splitpath(szChoice, szDrive, szDirectory, szFilename, szExt); //make sure that there is an extension of fm2 if(stricmp(szExt,".fm2")) { strcpy(szExt,".fm2"); _makepath(szChoice,szDrive,szDirectory,szFilename,szExt); } if(szDrive[0]=='\0' && szDirectory[0]=='\0') fn=FCEU_MakePath(FCEUMKF_MOVIE, szChoice); // need to make a full path else fn= szChoice; // given a full path return fn; } static char* GetSavePath(HWND hwndDlg) { char* fn=0; char szDrive[MAX_PATH]={0}; char szDirectory[MAX_PATH]={0}; char szFilename[MAX_PATH]={0}; char szExt[MAX_PATH]={0}; LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCURSEL, 0, 0); LONG lStringLength = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETLBTEXTLEN, (WPARAM)lIndex, 0); fn = (char*)malloc(lStringLength+1); //CB_GETLBTEXTLEN doesn't include NULL terminator. SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETLBTEXT, (WPARAM)lIndex, (LPARAM)fn); _splitpath(fn, szDrive, szDirectory, szFilename, szExt); if(szDrive[0]=='\0' && szDirectory[0]=='\0') { char* newfn=strdup(FCEU_MakePath(FCEUMKF_STATE, fn).c_str()); // need to make a full path free(fn); fn=newfn; } return fn; } void UpdateReplayCommentsSubs(const char * fname) { MOVIE_INFO info; FCEUFILE *fp = FCEU_fopen(fname,0,"rb",0); fp->stream = fp->stream->memwrap(); bool scanok = FCEUI_MovieGetInfo(fp, info, true); delete fp; if(!scanok) return; currComments = info.comments; currSubtitles = info.subtitles; } void UpdateReplayDialog(HWND hwndDlg) { int doClear=1; char *fn=GetReplayPath(hwndDlg); // remember the previous setting for the read-only checkbox replayReadOnlySetting = (SendDlgItemMessage(hwndDlg, IDC_CHECK_READONLY, BM_GETCHECK, 0, 0) == BST_CHECKED); EnableWindow(GetDlgItem(hwndDlg,IDC_BUTTON_METADATA),FALSE); if(fn) { MOVIE_INFO info; FCEUFILE* fp = FCEU_fopen(fn,0,"rb",0); fp->stream = fp->stream->memwrap(); bool isarchive = FCEU_isFileInArchive(fn); bool ismovie = FCEUI_MovieGetInfo(fp, info, false); delete fp; if(ismovie) { char tmp[256]; double div; sprintf(tmp, "%u", (unsigned)info.num_frames); SetWindowTextA(GetDlgItem(hwndDlg,IDC_LABEL_FRAMES), tmp); // frames SetDlgItemText(hwndDlg,IDC_EDIT_STOPFRAME,tmp); stopframeWasEditedByUser = false; EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_READONLY),TRUE); div = (FCEUI_GetCurrentVidSystem(0,0)) ? 50.006977968268290849 : 60.098813897440515532; // PAL timing double tempCount = (info.num_frames / div) + 0.005; // +0.005s for rounding int num_seconds = (int)tempCount; int fraction = (int)((tempCount - num_seconds) * 100); int seconds = num_seconds % 60; int minutes = (num_seconds / 60) % 60; int hours = (num_seconds / 60 / 60) % 60; sprintf(tmp, "%02d:%02d:%02d.%02d", hours, minutes, seconds, fraction); SetWindowTextA(GetDlgItem(hwndDlg,IDC_LABEL_LENGTH), tmp); // length sprintf(tmp, "%u", (unsigned)info.rerecord_count); SetWindowTextA(GetDlgItem(hwndDlg,IDC_LABEL_UNDOCOUNT), tmp); // rerecord SendDlgItemMessage(hwndDlg,IDC_CHECK_READONLY,BM_SETCHECK,(replayReadOnlySetting ? BST_CHECKED : BST_UNCHECKED), 0); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_RECORDEDFROM),info.poweron ? "Power-On" : (info.reset?"Soft-Reset":"Savestate")); if(isarchive) { EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_READONLY),FALSE); Button_SetCheck(GetDlgItem(hwndDlg,IDC_CHECK_READONLY),BST_CHECKED); } else EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_READONLY),TRUE); //----------- //mbg 5/26/08 - getting rid of old movie formats //if(info.movie_version > 1) //{ char emuStr[128]; SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_ROMUSED),info.name_of_rom_used.c_str()); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_ROMCHECKSUM),md5_asciistr(info.md5_of_rom_used)); char boolstring[4] = "On "; if (!info.pal) strcpy(boolstring, "Off"); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_PALUSED),boolstring); if (info.ppuflag) strcpy(boolstring, "On "); else strcpy(boolstring, "Off"); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_NEWPPUUSED),boolstring); if(info.emu_version_used < 20000 ) sprintf(emuStr, "FCEU %d.%02d.%02d%s", info.emu_version_used/10000, (info.emu_version_used/100)%100, (info.emu_version_used)%100, info.emu_version_used < 9813 ? " (blip)" : ""); else sprintf(emuStr, "FCEUX %d.%02d.%02d", info.emu_version_used/10000, (info.emu_version_used/100)%100, (info.emu_version_used)%100); //else //{ // if(info.emu_version_used == 1) // strcpy(emuStr, "Famtasia"); // else if(info.emu_version_used == 2) // strcpy(emuStr, "Nintendulator"); // else if(info.emu_version_used == 3) // strcpy(emuStr, "VirtuaNES"); // else // { // strcpy(emuStr, "(unknown)"); // char* dot = strrchr(fn,'.'); // if(dot) // { // if(!stricmp(dot,".fmv")) // strcpy(emuStr, "Famtasia? (unknown version)"); // else if(!stricmp(dot,".nmv")) // strcpy(emuStr, "Nintendulator? (unknown version)"); // else if(!stricmp(dot,".vmv")) // strcpy(emuStr, "VirtuaNES? (unknown version)"); // else if(!stricmp(dot,".fcm")) // strcpy(emuStr, "FCEU? (unknown version)"); // } // } //} SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_EMULATORUSED),emuStr); //} //else //{ // SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_ROMUSED),"unknown"); // SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_ROMCHECKSUM),"unknown"); // SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_EMULATORUSED),"FCEU 0.98.10 (blip)"); //} //-------------------- SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_CURRCHECKSUM),md5_asciistr(GameInfo->MD5)); // enable OK and metadata EnableWindow(GetDlgItem(hwndDlg,IDOK),TRUE); EnableWindow(GetDlgItem(hwndDlg,IDC_BUTTON_METADATA),TRUE); currComments = info.comments; currSubtitles = info.subtitles; doClear = 0; } free(fn); } else { EnableWindow(GetDlgItem(hwndDlg,IDC_EDIT_OFFSET),FALSE); EnableWindow(GetDlgItem(hwndDlg,IDC_EDIT_FROM),FALSE); } if(doClear) { SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_LENGTH),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_FRAMES),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_UNDOCOUNT),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_ROMUSED),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_ROMCHECKSUM),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_RECORDEDFROM),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_EMULATORUSED),""); SetWindowText(GetDlgItem(hwndDlg,IDC_LABEL_CURRCHECKSUM),md5_asciistr(GameInfo->MD5)); SetDlgItemText(hwndDlg,IDC_EDIT_STOPFRAME,""); stopframeWasEditedByUser=false; EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_READONLY),FALSE); SendDlgItemMessage(hwndDlg,IDC_CHECK_READONLY,BM_SETCHECK,BST_UNCHECKED,0); EnableWindow(GetDlgItem(hwndDlg,IDOK),FALSE); } } // C:\fceu\movies\bla.fcm + C:\fceu\fceu\ -> C:\fceu\movies\bla.fcm // movies\bla.fcm + fceu\ -> movies\bla.fcm // C:\fceu\movies\bla.fcm + C:\fceu\ -> movies\bla.fcm void AbsoluteToRelative(char *const dst, const char *const dir, const char *const root) { int i, igood=0; for(i = 0 ; ; i++) { int a = tolower(dir[i]); int b = tolower(root[i]); if(a == '/' || a == '\0' || a == '.') a = '\\'; if(b == '/' || b == '\0' || b == '.') b = '\\'; if(a != b) { igood = 0; break; } if(a == '\\') igood = i+1; if(!dir[i] || !root[i]) break; } // if(igood) // sprintf(dst, ".\\%s", dir + igood); // else strcpy(dst, dir + igood); } BOOL CALLBACK ReplayMetadataDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { RECT wrect; switch(uMsg) { case WM_INITDIALOG: { if (MetaPosX==-32000) MetaPosX=0; //Just in case if (MetaPosY==-32000) MetaPosY=0; SetWindowPos(hwndDlg,0,MetaPosX,MetaPosY,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOOWNERZORDER); //setup columns HWND hwndList = GetDlgItem(hwndDlg,IDC_LIST1); ListView_SetExtendedListViewStyleEx(hwndList, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES , LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES ); ListView_SetUnicodeFormat(hwndList,TRUE); RECT listRect; GetClientRect(hwndList,&listRect); LVCOLUMN lvc; int colidx=0; lvc.mask = LVCF_TEXT | LVCF_WIDTH; lvc.pszText = "Key"; lvc.cx = 100; ListView_InsertColumn(hwndList, colidx++, &lvc); lvc.mask = LVCF_TEXT | LVCF_WIDTH; lvc.pszText = "Value"; lvc.cx = listRect.right - 100; ListView_InsertColumn(hwndList, colidx++, &lvc); //Display the Subtitles into the Metadata as well for(uint32 i=0;i<currSubtitles.size();i++) { std::string& subtitle = currSubtitles[i]; size_t splitat = subtitle.find_first_of(' '); std::wstring key, value; //if we can't split it then call it an unnamed key if(splitat == std::string::npos) { value = mbstowcs(subtitle); } else { key = mbstowcs(subtitle.substr(0,splitat)); value = mbstowcs(subtitle.substr(splitat+1)); } LVITEM lvi; lvi.iItem = i; lvi.mask = LVIF_TEXT; lvi.iSubItem = 0; lvi.pszText = (LPSTR)key.c_str(); SendMessageW(hwndList, LVM_INSERTITEMW, 0, (LPARAM)&lvi); lvi.iSubItem = 1; lvi.pszText = (LPSTR)value.c_str(); SendMessageW(hwndList, LVM_SETITEMTEXTW, i, (LPARAM)&lvi); } //Display Subtitle Heading if (currSubtitles.size() > 0) //If no subtitles, don't bother with this heading { std::wstring rHeading = mbstowcs(string("SUBTITLES")); LVITEM lvSubtitle; lvSubtitle.iItem = 0; lvSubtitle.mask = LVIF_TEXT; lvSubtitle.iSubItem = 0; lvSubtitle.pszText = (LPSTR)rHeading.c_str(); SendMessageW(hwndList, LVM_INSERTITEMW, 0, (LPARAM)&lvSubtitle); } //Display the comments in the movie data for(uint32 i=0;i<currComments.size();i++) { std::wstring& comment = currComments[i]; size_t splitat = comment.find_first_of(' '); std::wstring key, value; //if we can't split it then call it an unnamed key if(splitat == std::string::npos) { value = comment; } else { key = comment.substr(0,splitat); value = comment.substr(splitat+1); } LVITEM lvi; lvi.iItem = i; lvi.mask = LVIF_TEXT; lvi.iSubItem = 0; lvi.pszText = (LPSTR)key.c_str(); SendMessageW(hwndList, LVM_INSERTITEMW, 0, (LPARAM)&lvi); lvi.iSubItem = 1; lvi.pszText = (LPSTR)value.c_str(); SendMessageW(hwndList, LVM_SETITEMTEXTW, i, (LPARAM)&lvi); } } break; case WM_MOVE: if (!IsIconic(hwndDlg)) { GetWindowRect(hwndDlg,&wrect); MetaPosX = wrect.left; MetaPosY = wrect.top; #ifdef WIN32 WindowBoundsCheckNoResize(MetaPosX,MetaPosY,wrect.right); #endif } break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDCANCEL: EndDialog(hwndDlg, 0); return TRUE; } break; } return FALSE; } extern char FileBase[]; void HandleScan(HWND hwndDlg, FCEUFILE* file, int& i) { MOVIE_INFO info; bool scanok = FCEUI_MovieGetInfo(file, info, true); if(!scanok) return; //------------ //attempt to match the movie with the rom //first, try matching md5 //then try matching base name char md51 [256]; char md52 [256]; strcpy(md51, md5_asciistr(GameInfo->MD5)); strcpy(md52, md5_asciistr(info.md5_of_rom_used)); if(strcmp(md51, md52)) { unsigned int k, count1=0, count2=0; //mbg merge 7/17/06 changed to uint for(k=0;k<strlen(md51);k++) count1 += md51[k]-'0'; for(k=0;k<strlen(md52);k++) count2 += md52[k]-'0'; if(count1 && count2) return; const char* tlen1=strstr(file->filename.c_str(), " ("); const char* tlen2=strstr(FileBase, " ("); int tlen3=tlen1?(int)(tlen1-file->filename.c_str()):file->filename.size(); int tlen4=tlen2?(int)(tlen2-FileBase):strlen(FileBase); int len=MAX(0,MIN(tlen3,tlen4)); if(strnicmp(file->filename.c_str(), FileBase, len)) { char temp[512]; strcpy(temp,FileBase); temp[len]='\0'; if(!strstr(file->filename.c_str(), temp)) return; } } //------------- //if we get here, then we had a match char relative[MAX_PATH]; AbsoluteToRelative(relative, file->fullFilename.c_str(), BaseDirectory.c_str()); SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_INSERTSTRING, i++, (LPARAM)relative); } BOOL CALLBACK ReplayDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: { bool tasedit = lParam?true:false; //some of the controls are illogical with tasedit //remove them, and rename the window if(tasedit) { SetWindowText(hwndDlg,"Load TasEdit Movie"); ShowWindow(GetDlgItem(hwndDlg,IDC_CHECK_READONLY),SW_HIDE); ShowWindow(GetDlgItem(hwndDlg,IDC_CHECK_STOPMOVIE),SW_HIDE); ShowWindow(GetDlgItem(hwndDlg,IDC_EDIT_STOPFRAME),SW_HIDE); } SendDlgItemMessage(hwndDlg, IDC_CHECK_READONLY, BM_SETCHECK, replayReadOnlySetting?BST_CHECKED:BST_UNCHECKED, 0); SendDlgItemMessage(hwndDlg, IDC_CHECK_STOPMOVIE,BM_SETCHECK, BST_UNCHECKED, 0); char* findGlob[2] = {strdup(FCEU_MakeFName(FCEUMKF_MOVIEGLOB, 0, 0).c_str()), strdup(FCEU_MakeFName(FCEUMKF_MOVIEGLOB2, 0, 0).c_str())}; int items=0; for(int j=0;j<2;j++) { char* temp=0; do { temp=strchr(findGlob[j],'/'); if(temp) *temp = '\\'; } while(temp); // disabled because... apparently something is case sensitive?? // for(i=1;i<strlen(findGlob[j]);i++) // findGlob[j][i] = tolower(findGlob[j][i]); } // FCEU_PrintError(findGlob[0]); // FCEU_PrintError(findGlob[1]); for(int j=0;j<2;j++) { // if the two directories are the same, only look through one of them to avoid adding everything twice if(j==1 && !strnicmp(findGlob[0],findGlob[1],MAX(strlen(findGlob[0]),strlen(findGlob[1]))-6)) continue; char globBase[512]; strcpy(globBase,findGlob[j]); globBase[strlen(globBase)-5]='\0'; //char szFindPath[512]; //mbg merge 7/17/06 removed WIN32_FIND_DATA wfd; HANDLE hFind; memset(&wfd, 0, sizeof(wfd)); hFind = FindFirstFile(findGlob[j], &wfd); if(hFind != INVALID_HANDLE_VALUE) { do { if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; //TODO - a big copy/pasted block below. factor out extension extractor or use another one // filter out everything that's not an extension we like *.fm2 // (because FindFirstFile is too dumb to do that) { std::string ext = getExtension(wfd.cFileName); if(ext != "fm2") if(ext != "zip") if(ext != "rar") if(ext != "7z") continue; } char filename [512]; sprintf(filename, "%s%s", globBase, wfd.cFileName); //replay system requires this to stay put. SetCurrentDirectory(BaseDirectory.c_str()); ArchiveScanRecord asr = FCEUD_ScanArchive(filename); if(!asr.isArchive()) { FCEUFILE* fp = FCEU_fopen(filename,0,"rb",0); fp->stream = fp->stream->memwrap(); if(fp) { HandleScan(hwndDlg,fp ,items); delete fp; } } else { asr.files.FilterByExtension(fm2ext); for(uint32 i=0;i<asr.files.size();i++) { FCEUFILE* fp = FCEU_fopen(filename,0,"rb",0,asr.files[i].index); if(fp) { HandleScan(hwndDlg,fp, items); delete fp; } } } } while(FindNextFile(hFind, &wfd)); FindClose(hFind); } } free(findGlob[0]); free(findGlob[1]); if(items>0) SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_SETCURSEL, items-1, 0); SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_INSERTSTRING, items++, (LPARAM)"Browse..."); UpdateReplayDialog(hwndDlg); } SetFocus(GetDlgItem(hwndDlg, IDC_COMBO_FILENAME)); return FALSE; case WM_COMMAND: if(HIWORD(wParam) == EN_CHANGE) { if (LOWORD(wParam) == IDC_EDIT_STOPFRAME) // Check if Stop movie at value has changed { if (stopframeWasEditedByUser) { HWND hwnd1 = GetDlgItem(hwndDlg,IDC_CHECK_STOPMOVIE); Button_SetCheck(hwnd1,BST_CHECKED); stopframeWasEditedByUser = true; } else stopframeWasEditedByUser = true; } } if(HIWORD(wParam) == CBN_SELCHANGE) { UpdateReplayDialog(hwndDlg); } else if(HIWORD(wParam) == CBN_CLOSEUP) { LONG lCount = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETCOUNT, 0, 0); LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETCURSEL, 0, 0); if (lIndex != CB_ERR && lIndex == lCount-1) SendMessage(hwndDlg, WM_COMMAND, (WPARAM)IDOK, 0); // send an OK notification to open the file browser } else { int wID = LOWORD(wParam); switch(wID) { case IDC_BUTTON_METADATA: DialogBoxParam(fceu_hInstance, "IDD_REPLAY_METADATA", hwndDlg, ReplayMetadataDialogProc, (LPARAM)0); break; case IDOK: { LONG lCount = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETCOUNT, 0, 0); LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_GETCURSEL, 0, 0); if(lIndex != CB_ERR) { if(lIndex == lCount-1) { // pop open a file browser... char *pn=strdup(FCEU_GetPath(FCEUMKF_MOVIE).c_str()); char szFile[MAX_PATH]={0}; OPENFILENAME ofn; //int nRet; //mbg merge 7/17/06 removed memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwndDlg; ofn.lpstrFilter = "FCEUX Movie Files (*.fm2)\0*.fm2\0Archive Files (*.zip,*.rar,*.7z)\0*.zip;*.rar;*.7z\0All Files (*.*)\0*.*\0\0"; ofn.lpstrFile = szFile; ofn.nMaxFile = sizeof(szFile); ofn.lpstrInitialDir = pn; ofn.Flags = OFN_NOCHANGEDIR | OFN_HIDEREADONLY; ofn.lpstrDefExt = "fm2"; ofn.lpstrTitle = "Play Movie from File"; if(GetOpenFileName(&ofn)) { char relative[MAX_PATH*2]; AbsoluteToRelative(relative, szFile, BaseDirectory.c_str()); //replay system requires this to stay put. SetCurrentDirectory(BaseDirectory.c_str()); ArchiveScanRecord asr = FCEUD_ScanArchive(relative); FCEUFILE* fp = FCEU_fopen(relative,0,"rb",0,-1,fm2ext); if(!fp) goto abort; strcpy(relative,fp->fullFilename.c_str()); delete fp; LONG lOtherIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_FINDSTRING, (WPARAM)-1, (LPARAM)relative); if(lOtherIndex != CB_ERR) { // select already existing string SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_SETCURSEL, lOtherIndex, 0); } else { SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_INSERTSTRING, lIndex, (LPARAM)relative); SendDlgItemMessage(hwndDlg, IDC_COMBO_FILENAME, CB_SETCURSEL, lIndex, 0); } // restore focus to the dialog SetFocus(GetDlgItem(hwndDlg, IDC_COMBO_FILENAME)); UpdateReplayDialog(hwndDlg); } abort: free(pn); } else { // user had made their choice // TODO: warn the user when they open a movie made with a different ROM char* fn=GetReplayPath(hwndDlg); //char TempArray[16]; //mbg merge 7/17/06 removed replayReadOnlySetting = (SendDlgItemMessage(hwndDlg, IDC_CHECK_READONLY, BM_GETCHECK, 0, 0) == BST_CHECKED); char offset1Str[32]={0}; SendDlgItemMessage(hwndDlg, IDC_EDIT_STOPFRAME, WM_GETTEXT, (WPARAM)32, (LPARAM)offset1Str); replayStopFrameSetting = (SendDlgItemMessage(hwndDlg, IDC_CHECK_STOPMOVIE, BM_GETCHECK,0,0) == BST_CHECKED)? strtol(offset1Str,0,10):0; EndDialog(hwndDlg, (INT_PTR)fn); } } } return TRUE; case IDCANCEL: EndDialog(hwndDlg, 0); return TRUE; } } case WM_CTLCOLORSTATIC: if((HWND)lParam == GetDlgItem(hwndDlg, IDC_LABEL_CURRCHECKSUM)) { // draw the md5 sum in red if it's different from the md5 of the rom used in the replay HDC hdcStatic = (HDC)wParam; char szMd5Text[35]; GetDlgItemText(hwndDlg, IDC_LABEL_ROMCHECKSUM, szMd5Text, 35); if(!strlen(szMd5Text) || !strcmp(szMd5Text, "unknown") || !strcmp(szMd5Text, "00000000000000000000000000000000") || !strcmp(szMd5Text, md5_asciistr(GameInfo->MD5))) SetTextColor(hdcStatic, RGB(0,0,0)); // use black color for a match (or no comparison) else SetTextColor(hdcStatic, RGB(255,0,0)); // use red for a mismatch SetBkMode((HDC)wParam,TRANSPARENT); return (BOOL)GetSysColorBrush(COLOR_BTNFACE); } else return FALSE; } return FALSE; }; static void UpdateRecordDialog(HWND hwndDlg) { int enable=0; std::string fn=GetRecordPath(hwndDlg); if(fn!="") { if(access(fn.c_str(), F_OK) || !access(fn.c_str(), W_OK)) { LONG lCount = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCOUNT, 0, 0); LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCURSEL, 0, 0); if(lIndex != lCount-1) { enable=1; } } } EnableWindow(GetDlgItem(hwndDlg,IDOK),enable ? TRUE : FALSE); } static void UpdateRecordDialogPath(HWND hwndDlg, const std::string &fname) { char* baseMovieDir = strdup(FCEU_GetPath(FCEUMKF_MOVIE).c_str()); char* fn=0; // display a shortened filename if the file exists in the base movie directory if(!strncmp(fname.c_str(), baseMovieDir, strlen(baseMovieDir))) { char szDrive[MAX_PATH]={0}; char szDirectory[MAX_PATH]={0}; char szFilename[MAX_PATH]={0}; char szExt[MAX_PATH]={0}; _splitpath(fname.c_str(), szDrive, szDirectory, szFilename, szExt); fn=(char*)malloc(strlen(szFilename)+strlen(szExt)+1); _makepath(fn, "", "", szFilename, szExt); } else fn=strdup(fname.c_str()); if(fn) { SetWindowText(GetDlgItem(hwndDlg,IDC_EDIT_FILENAME),fn); // FIXME: make utf-8? free(fn); } } static BOOL CALLBACK RecordDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { static struct CreateMovieParameters* p = NULL; switch(uMsg) { case WM_INITDIALOG: p = (struct CreateMovieParameters*)lParam; UpdateRecordDialogPath(hwndDlg, p->szFilename); p->szFilename = ""; SendMessage(GetDlgItem(hwndDlg,IDC_EDIT_AUTHOR), CCM_SETUNICODEFORMAT, TRUE, 0); // Populate the "record from..." dialog { char* findGlob=strdup(FCEU_MakeFName(FCEUMKF_STATEGLOB, 0, 0).c_str()); WIN32_FIND_DATA wfd; HANDLE hFind; int i=0; SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_INSERTSTRING, i++, (LPARAM)"Start"); SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_INSERTSTRING, i++, (LPARAM)"Now"); memset(&wfd, 0, sizeof(wfd)); hFind = FindFirstFile(findGlob, &wfd); if(hFind != INVALID_HANDLE_VALUE) { do { if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) continue; if (strlen(wfd.cFileName) < 4 || !strcmp(wfd.cFileName + (strlen(wfd.cFileName) - 4), ".fm2")) continue; SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_INSERTSTRING, i++, (LPARAM)wfd.cFileName); } while(FindNextFile(hFind, &wfd)); FindClose(hFind); } free(findGlob); SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_INSERTSTRING, i++, (LPARAM)"Browse..."); SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_SETCURSEL, p->recordFrom, 0); } UpdateRecordDialog(hwndDlg); return TRUE; case WM_COMMAND: if(HIWORD(wParam) == CBN_SELCHANGE) { LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCURSEL, 0, 0); if(lIndex == CB_ERR) { // fix listbox selection SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_SETCURSEL, (WPARAM)0, 0); } UpdateRecordDialog(hwndDlg); return TRUE; } else if(HIWORD(wParam) == CBN_CLOSEUP) { LONG lCount = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCOUNT, 0, 0); LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCURSEL, 0, 0); if (lIndex != CB_ERR && lIndex == lCount-1) { OPENFILENAME ofn; char szChoice[MAX_PATH]={0}; // pop open a file browser to choose the savestate memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwndDlg; ofn.lpstrFilter = "FCEU Save State (*.fc?)\0*.fc?\0\0"; ofn.lpstrFile = szChoice; ofn.lpstrDefExt = "fcs"; ofn.nMaxFile = MAX_PATH; if(GetOpenFileName(&ofn)) { SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_INSERTSTRING, lIndex, (LPARAM)szChoice); SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_SETCURSEL, (WPARAM)lIndex, 0); } else UpdateRecordDialog(hwndDlg); } return TRUE; } else if(HIWORD(wParam) == EN_CHANGE && LOWORD(wParam) == IDC_EDIT_FILENAME) { UpdateRecordDialog(hwndDlg); } else { switch(LOWORD(wParam)) { case IDOK: { LONG lIndex = SendDlgItemMessage(hwndDlg, IDC_COMBO_RECORDFROM, CB_GETCURSEL, 0, 0); p->szFilename = GetRecordPath(hwndDlg); p->recordFrom = (int)lIndex; p->author = GetDlgItemTextW<500>(hwndDlg,IDC_EDIT_AUTHOR); if(lIndex>=2) p->szSavestateFilename = GetSavePath(hwndDlg); EndDialog(hwndDlg, 1); } return TRUE; case IDCANCEL: EndDialog(hwndDlg, 0); return TRUE; case IDC_BUTTON_BROWSEFILE: { OPENFILENAME ofn; char szChoice[MAX_PATH]={0}; // browse button memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwndDlg; ofn.lpstrFilter = "FCEUX Movie File (*.fm2)\0*.fm2\0All Files (*.*)\0*.*\0\0"; ofn.lpstrFile = szChoice; ofn.lpstrDefExt = "fm2"; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT; if(GetSaveFileName(&ofn)) { UpdateRecordDialogPath(hwndDlg,szChoice); } } return TRUE; } } } return FALSE; } //Show the record movie dialog and record a movie. void FCEUD_MovieRecordTo() { static struct CreateMovieParameters p; p.szFilename = strdup(FCEU_MakeFName(FCEUMKF_MOVIE,0,0).c_str()); if(p.recordFrom >= 2) p.recordFrom=1; if(DialogBoxParam(fceu_hInstance, "IDD_RECORDINP", hAppWnd, RecordDialogProc, (LPARAM)&p)) { if(p.recordFrom >= 2) { // attempt to load the savestate // FIXME: pop open a messagebox if this fails FCEUI_LoadState(p.szSavestateFilename.c_str()); { extern int loadStateFailed; if(loadStateFailed) { char str [1024]; sprintf(str, "Failed to load save state \"%s\".\nRecording from current state instead...", p.szSavestateFilename); FCEUD_PrintError(str); } } } EMOVIE_FLAG flags = MOVIE_FLAG_NONE; if(p.recordFrom == 0) flags = MOVIE_FLAG_FROM_POWERON; FCEUI_SaveMovie(p.szFilename.c_str(), flags, p.author); } } void Replay_LoadMovie(bool tasedit) { replayReadOnlySetting = FCEUI_GetMovieToggleReadOnly(); char* fn = (char*)DialogBoxParam(fceu_hInstance, "IDD_REPLAYINP", hAppWnd, ReplayDialogProc, (LPARAM)(tasedit?1:0)); if(fn) { FCEUI_LoadMovie(fn, replayReadOnlySetting, tasedit, replayStopFrameSetting); free(fn); //mbg 6/21/08 - i think this stuff has to get updated in case the movie changed the pal emulation flag pal_emulation = FCEUI_GetCurrentVidSystem(0,0); UpdateCheckedMenuItems(); SetMainWindowStuff(); RefreshThrottleFPS(); } } /// Show movie replay dialog and replay the movie if necessary. void FCEUD_MovieReplayFrom() { Replay_LoadMovie(false); }
[ "Cthulhu32@e9098629-9c10-95be-0fa9-336bad66c20b" ]
[ [ [ 1, 1011 ] ] ]
eb6b7881ef65d1f2734d3ee680cc044321a1d96e
eed0d2db074961e9fa1ff2c58281de679bf734c7
/message.h
f3489c602ee723bca83386a8c9daeb92adc11c8e
[]
no_license
thandav/micron
35eefa22b3e9d698a092b98898510d6a393e2424
349ef537d16970c93569c8de478e1f2addee3d94
refs/heads/master
2016-09-11T09:13:22.733858
2011-09-11T17:37:39
2011-09-11T17:37:39
1,777,980
2
0
null
null
null
null
UTF-8
C++
false
false
592
h
#ifndef MESSAGE_H #define MESSAGE_H #include <sys/socket.h> #include <arpa/inet.h> class Message { public: Message(const char* addr, const char* message); ~Message(); Message(const Message& other); Message& operator=(const Message& other); char* getQueueName() { return m_queueName; } long getSeqId() { return m_seqId; } void print(); protected: private: char* m_queueName; char* m_body; long m_seqId; }; #endif // MESSAGE_H
[ [ [ 1, 30 ] ] ]
f7dcd3ea002f3d15e2ddc9bf9fa906013a8a04fb
50f94444677eb6363f2965bc2a29c09f8da7e20d
/Src/EmptyProject/SequentialIncident.cpp
9bb5a512330fcd68a01e83ec25afe23350addda1
[]
no_license
gasbank/poolg
efd426db847150536eaa176d17dcddcf35e74e5d
e73221494c4a9fd29c3d75fb823c6fb1983d30e5
refs/heads/master
2020-04-10T11:56:52.033568
2010-11-04T19:31:00
2010-11-04T19:31:00
1,051,621
1
0
null
null
null
null
UTF-8
C++
false
false
3,166
cpp
#include "EmptyProjectPCH.h" #include "SequentialIncident.h" #include "Trigger.h" #include "Action.h" #include "ScriptManager.h" #include "BlockingActionIncident.h" SequentialIncident::SequentialIncident( int trigCount ) : Incident( trigCount ) { m_curIncident = 0; m_lastCheck = 1; } bool SequentialIncident::update( double dTime, float fElapsedTime ) { if ( !checkTrigCountRemained() ) return false; if ( !isActivated() ) { if ( m_curSequence != m_sequencer.end() ) if ( !(*m_curSequence)->update( dTime, fElapsedTime ) ) return false; activate(); return true; } else if ( m_curSequence != m_sequencer.end() ) { if ( (*m_curSequence)->isFinished() ) { deactivate(); m_curSequence++; } } if ( isFinished() ) { decreaseTrigCount(); m_curSequence = m_sequencer.begin(); } return false; } void SequentialIncident::addTriggerSequence( Trigger* trigger ) { if ( m_lastCheck == 1 ) m_curIncident = new BlockingActionIncident( getTrigCount() ); m_curIncident->addTrigger( trigger ); m_lastCheck = 0; } void SequentialIncident::addActionSequence( Action* action ) { if ( m_lastCheck == 0 ) { addIncident( m_curIncident ); m_curSequence = m_sequencer.begin(); } m_curIncident->addAction( action ); m_lastCheck = 1; } void SequentialIncident::activate() { Incident::activate(); } void SequentialIncident::deactivate() { Incident::deactivate(); } SequentialIncident::~SequentialIncident() { } void SequentialIncident::release() { EpSafeReleaseAll( m_sequencer ); Incident::release(); } void SequentialIncident::printDebugInfo() const { throw std::runtime_error( "Not implemented yet" ); } void SequentialIncident::printDebugInfoDetailed() const { throw std::runtime_error( "Not implemented yet" ); } ////////////////////////////////////////////////////////////////////////// int EpSequentialIncidentAddTrigger( void* pv1, void* pv2 ) { SequentialIncident* inci = reinterpret_cast<SequentialIncident*>( pv1 ); Trigger* trig = reinterpret_cast<Trigger*>( pv2 ); inci->addTriggerSequence( trig ); return 0; } SCRIPT_CALLABLE_I_PV_PV( EpSequentialIncidentAddTrigger ) int EpSequentialIncidentAddAction( void* pv1, void* pv2 ) { SequentialIncident* inci = reinterpret_cast<SequentialIncident*>( pv1 ); Action* act = reinterpret_cast<Action*>( pv2 ); inci->addActionSequence( act ); return 0; } SCRIPT_CALLABLE_I_PV_PV( EpSequentialIncidentAddAction ) SequentialIncident* EpCreateSequentialIncident( int trigCount ) { if ( trigCount == 0 ) OutputDebugString( _T(" - EpWarn: SequentialIncident with triggering count 0 is created.\n" ) ); return new SequentialIncident( trigCount ); } SCRIPT_CALLABLE_PV_I( EpCreateSequentialIncident ) START_SCRIPT_FACTORY( SequentialIncident ) CREATE_OBJ_COMMAND( EpCreateSequentialIncident ) CREATE_OBJ_COMMAND_NEWNAME( EpSequentialIncidentAddTrigger, "EpAddTriggerToSequence" ) CREATE_OBJ_COMMAND_NEWNAME( EpSequentialIncidentAddAction, "EpAddActionToSequence" ) END_SCRIPT_FACTORY( SequentialIncident )
[ [ [ 1, 5 ], [ 7, 8 ], [ 10, 48 ], [ 50, 68 ], [ 70, 73 ], [ 75, 84 ], [ 97, 97 ], [ 99, 100 ], [ 102, 107 ], [ 109, 109 ], [ 111, 116 ], [ 118, 129 ], [ 132, 132 ] ], [ [ 6, 6 ], [ 9, 9 ], [ 49, 49 ], [ 69, 69 ], [ 74, 74 ], [ 85, 96 ], [ 98, 98 ], [ 101, 101 ], [ 108, 108 ], [ 110, 110 ], [ 117, 117 ], [ 130, 131 ] ] ]
26df7ce7f4fe1ec73b54a5b3f8f3e78da07fa3b5
93088fe67401f51470ea3f9d55d12e0b40f04450
/jni/src/MenuState.cpp
f7e24747f05ce168be307ad73df9935406a6de92
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
4nakin/canabalt-bluegin
f9967891418e07690c270075a1de0386b1d9a456
c68dc378d420e271dd7faa49b89e30c7c87c7233
refs/heads/master
2021-01-24T03:08:39.081279
2011-04-17T06:05:57
2011-04-17T06:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,522
cpp
#include "bluegin/resourcemanager.h" #include "rdv/MenuState.h" #include "rdv/PlayState.h" #include "flx/flxG.h" using namespace ci; using namespace bluegin; using namespace flx; extern FlxGlobal FlxG; void onFade(void*) { FlxG.setState(StatePtr(new PlayState())); } static void onStart(void* data) { FlxG.flash.start(Color(1.0f, 1.0f, 1.0f),0.5f); FlxG.fade.start(Color::black(),1,onFade); } void MenuState::create() { FlxG.score = 0; ResourceManager& res = *(FlxG.resources); t1 = Text::create(FlxG.width/2 - 320, 20, 640, "Rendezvous"); t1->setSize(80.0f); t1->setColor(FlxU::color(0xFF4744)); t1->setAlignment(ALIGN_CENTER); add(t1); TextPtr t1, t2; b1 = Button::create(FlxG.width / 2 - 90, 200, onStart); SpritePtr image = Sprite::create(); image->createGraphic(180, 64, FlxU::color(0x5F5DB7)); SpritePtr imageHi = Sprite::create(); imageHi->createGraphic(image->width, image->height, FlxU::color(0x8482FF)); b1->loadGraphic(image, imageHi); t1 = Text::create(1, 5, 178, "Start"); t1->setColor(Color::white()); t1->setSize(56.0f); t1->setAlignment(ALIGN_CENTER); t2 = Text::create(t1->x,t1->y,t1->width,t1->getText()); t2->setColor(Color::white()); t2->setAlignment(t1->getAlignment()); t2->setSize(t1->getSize()); b1->loadText(t1,t2); add(b1); FlxG.flash.start(Color::black(),1.0f); } void MenuState::update() { State::update(); }
[ [ [ 1, 59 ] ] ]
505beb8c3e58f8fa6e5e06f028363df8e88e15de
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Interface/WndGuildCombat1to1.h
d498a6e27849aa91e19a1cae7390b6f07ad1da13
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
3,778
h
#if __VER >= 11 // __GUILD_COMBAT_1TO1 #ifndef __WNDGUILDCOMBAT1TO1__H #define __WNDGUILDCOMBAT1TO1__H ////////////////////////////////////////////////////////////////////////// // 1:1 GuildCombat Class ////////////////////////////////////////////////////////////////////////// class CWndGuildCombat1to1Selection : public CWndNeuz { protected: multimap<int, CGuildMember*> m_mapSelectPlayer; // 정렬된 길드원 리스트 vector<u_long> m_vecGuildList ; // 길드원 리스트 vector<u_long> m_vecSelectPlayer; // 참가자 리스트 // u_long m_uidDefender; // CTexture m_TexDefender; // int m_nDefenderIndex; // int nMaxJoinMember; // int nMaxWarMember; public: void Reset(); CWndGuildCombat1to1Selection(); virtual ~CWndGuildCombat1to1Selection(); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); virtual void OnDraw( C2DRender* p2DRender ); virtual void OnInitialUpdate(); virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ); virtual void OnSize( UINT nType, int cx, int cy ); virtual void OnLButtonUp( UINT nFlags, CPoint point ); virtual void OnLButtonDown( UINT nFlags, CPoint point ); void EnableFinish( BOOL bFlag ); // void SetDefender( u_long uiPlayer ); void UpDateGuildListBox(); void AddCombatPlayer( u_long uiPlayer ); void AddGuildPlayer( u_long uiPlayer ); void RemoveCombatPlayer( int nIndex ) ; void RemoveGuildPlayer( int nIndex ) ; u_long FindCombatPlayer( u_long uiPlayer ); u_long FindGuildPlayer( u_long uiPlayer ); // void SetMemberSize( int nMaxJoin, int nMaxWar ); }; class CWndGuildCombat1to1Offer : public CWndNeuz { protected: DWORD m_dwReqGold; DWORD m_dwMinGold; DWORD m_dwBackupGold; public: int m_nCombatType; // 0 : 길드대전 , 1 : 1:1길드대전 public: CWndGuildCombat1to1Offer(int nCombatType); virtual ~CWndGuildCombat1to1Offer(); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); virtual void OnDraw( C2DRender* p2DRender ); virtual void OnInitialUpdate(); virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase ); virtual void OnSize( UINT nType, int cx, int cy ); virtual void OnLButtonUp( UINT nFlags, CPoint point ); virtual void OnLButtonDown( UINT nFlags, CPoint point ); virtual void PaintFrame( C2DRender* p2DRender ); void SetGold( DWORD nCost ); // void SetTotalGold( __int64 nCost ); void SetMinGold( DWORD dwMinGold ) { m_dwMinGold = dwMinGold; } void SetReqGold( DWORD dwReqGold ) { m_dwReqGold = dwReqGold; } void SetBackupGold( DWORD dwBackupGold ) { m_dwBackupGold = dwBackupGold; } void EnableAccept( BOOL bFlag ); }; ////////////////////////////////////////////////////////////////////////// // Message Box Class ////////////////////////////////////////////////////////////////////////// class CGuildCombat1to1SelectionResetConfirm : public CWndMessageBox { public: CString m_strMsg; virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD dwWndId = 0 ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); }; class CWndGuildCombat1to1OfferMessageBox : public CWndMessageBox { public: DWORD m_nCost; void SetValue( CString str, DWORD nCost ); virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD dwWndId = 0 ); virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult ); }; #endif //__WNDGUILDCOMBAT1TO1__H #endif //__GUILD_COMBAT_1TO1
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 108 ] ] ]
844d3df4208053c94e6dd11c13ff0860e8004210
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/Syssetup.h
ade6d2000a4be9b10070772d5fa4c854a83e5290
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
UTF-8
C++
false
false
1,568
h
#if !defined(AFX_SYSSETUP_H__3603CBA2_A124_11D4_9426_0080C8E20736__INCLUDED_) #define AFX_SYSSETUP_H__3603CBA2_A124_11D4_9426_0080C8E20736__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Syssetup.h : header file // ///////////////////////////////////////////////////////////////////////////// // CSYSSETUP dialog class CSYSSETUP : public CPropertyPage { DECLARE_DYNCREATE(CSYSSETUP) // Construction public: CSYSSETUP(); ~CSYSSETUP(); CTaiShanDoc *pDoc; // Dialog Data //{{AFX_DATA(CSYSSETUP) enum { IDD = IDD_SZ_SYSTEMINFO }; BOOL m_AlarmSound; BOOL m_AutoOrganizeData; BOOL m_autoclose; BOOL m_autoday; BOOL m_showxline; BOOL m_showyline; BOOL m_autosavezb; BOOL m_cjmxyester; BOOL m_tjxgpower; BOOL m_showinfohq; BOOL m_startalert; BOOL m_volpower; BOOL m_backpower; BOOL m_autominute; int m_kline; int m_fourgraph; //}}AFX_DATA // Overrides // ClassWizard generate virtual function overrides //{{AFX_VIRTUAL(CSYSSETUP) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CSYSSETUP) virtual BOOL OnInitDialog(); afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SYSSETUP_H__3603CBA2_A124_11D4_9426_0080C8E20736__INCLUDED_)
[ [ [ 1, 66 ] ] ]
4285920b163d76b2f164402af17408940ff645ae
075043812c30c1914e012b52c60bc3be2cfe49cc
/src/SDLGUIlibTests/DragAndDropTests.cpp
624684d65efb5554de3b8d5c54423a2416580bb6
[]
no_license
Luke-Vulpa/Shoko-Rocket
8a916d70bf777032e945c711716123f692004829
6f727a2cf2f072db11493b739cc3736aec40d4cb
refs/heads/master
2020-12-28T12:03:14.055572
2010-02-28T11:58:26
2010-02-28T11:58:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,875
cpp
#include "stdafx.h" #include <Widget.h> #include <Event.h> namespace { int drag_start_count = 0; void WidgetDragStart(Widget* /*_widget*/, DragEventArgs* _args) { drag_start_count++; _args->drag_type = 1; //Important - ignored if zero } int drag_reset_count = 0; Vector2i drag_reset_position; void WidgetDragReset(Widget* /*_widget*/, DragEventArgs* _args) { drag_reset_count++; drag_reset_position = Vector2i(_args->x, _args->y); } void WidgetDragEnterRejected(Widget* /*_widget*/, DragEventArgs* _args) { _args->drag_accepted = false; } void WidgetDragEnterAccepted(Widget* /*_widget*/, DragEventArgs* _args) { _args->drag_accepted = true; } int sucessful_landings = 0; void WidgetDragLand(Widget* /*_widget*/, DragEventArgs* _args) { if(_args->drag_type == 1) sucessful_landings++; } } TEST_FIXTURE(SDL_fixture, WidgetDragSources) { CHECK(SDL_init_ok); if(SDL_init_ok) { Widget* widget = new Widget(); CHECK_EQUAL(false, widget->GetAllowDrag()); widget->SetAllowDrag(true); CHECK_EQUAL(true, widget->GetAllowDrag()); Widget::ClearRoot(); } } TEST_FIXTURE(SDL_fixture, WidgetStartDragEvent) { CHECK(SDL_init_ok); if(SDL_init_ok) { drag_start_count = 0; Widget* widget = new Widget(); widget->SetAllowDrag(true); widget->OnDragStart.connect(WidgetDragStart); SDL_Event e; e.type = SDL_MOUSEMOTION; e.motion.x = 10; e.motion.y = 10; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEBUTTONDOWN; e.button.x = 10; e.button.y = 10; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); CHECK_EQUAL(0, drag_start_count); e.type = SDL_MOUSEMOTION; e.motion.x = 11; Widget::DistributeSDLEvents(&e); CHECK_EQUAL(1, drag_start_count); CHECK_EQUAL(widget, Widget::GetDraggedWidget()); Widget::ClearRoot(); } } TEST_FIXTURE(SDL_fixture, WidgetDragResetEventOverSelf) { CHECK(SDL_init_ok); if(SDL_init_ok) { drag_reset_count = 0; drag_start_count = 0; Widget* widget = new Widget(); widget->SetAllowDrag(true); widget->OnDragStart.connect(WidgetDragStart); widget->OnDragReset.connect(WidgetDragReset); SDL_Event e; e.type = SDL_MOUSEMOTION; e.motion.x = 10; e.motion.y = 10; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEBUTTONDOWN; e.button.x = 10; e.button.y = 10; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEMOTION; e.motion.x = 11; Widget::DistributeSDLEvents(&e); //Mouse drop on top of dragged widget results in a reset e.type = SDL_MOUSEBUTTONUP; e.button.x = 12; e.button.y = 10; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); CHECK_EQUAL(1, drag_reset_count); CHECK_EQUAL((Widget*)NULL, Widget::GetDraggedWidget()); CHECK_EQUAL(Vector2i(1, 0), drag_reset_position); Widget::ClearRoot(); } } TEST_FIXTURE(SDL_fixture, WidgetDragResetEventOverEmpty) { CHECK(SDL_init_ok); if(SDL_init_ok) { drag_reset_count = 0; drag_start_count = 0; Widget* widget = new Widget(); widget->SetAllowDrag(true); widget->OnDragStart.connect(WidgetDragStart); widget->OnDragReset.connect(WidgetDragReset); SDL_Event e; e.type = SDL_MOUSEMOTION; e.motion.x = 10; e.motion.y = 10; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEBUTTONDOWN; e.button.x = 10; e.button.y = 10; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEMOTION; e.motion.x = 11; Widget::DistributeSDLEvents(&e); //Mouse drop on top of dragged widget results in a reset e.type = SDL_MOUSEBUTTONUP; e.button.x = 16; e.button.y = 15; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); CHECK_EQUAL(1, drag_reset_count); CHECK_EQUAL((Widget*)NULL, Widget::GetDraggedWidget()); CHECK_EQUAL(Vector2i(5, 5), drag_reset_position); Widget::ClearRoot(); } } TEST_FIXTURE(SDL_fixture, WidgetDragResetEventOverRejectingWidget) { CHECK(SDL_init_ok); if(SDL_init_ok) { drag_reset_count = 0; drag_reset_position = Vector2i(0, 0); drag_start_count = 0; Widget* widget = new Widget(); widget->SetSize(Vector2i(50, 50)); widget->SetAllowDrag(true); widget->OnDragStart.connect(WidgetDragStart); widget->OnDragReset.connect(WidgetDragReset); Widget* widget2 = new Widget(); widget2->SetSize(Vector2i(50, 50)); widget2->SetPosition(Vector2i(50, 0)); widget2->OnDragEnter.connect(WidgetDragEnterRejected); SDL_Event e; e.type = SDL_MOUSEMOTION; e.motion.x = 10; e.motion.y = 10; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEBUTTONDOWN; e.button.x = 10; e.button.y = 10; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEMOTION; e.motion.x = 55; e.motion.y = 10; Widget::DistributeSDLEvents(&e); //Mouse drop on top of dragged widget results in a reset e.type = SDL_MOUSEBUTTONUP; e.button.x = 65; e.button.y = 15; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); CHECK_EQUAL(1, drag_reset_count); CHECK_EQUAL((Widget*)NULL, Widget::GetDraggedWidget()); CHECK_EQUAL(Vector2i(10, 5), drag_reset_position); Widget::ClearRoot(); } } TEST_FIXTURE(SDL_fixture, WidgetDragResetEventOverAccceptingWidget) { CHECK(SDL_init_ok); if(SDL_init_ok) { drag_reset_count = 0; drag_reset_position = Vector2i(0, 0); drag_start_count = 0; sucessful_landings = 0; Widget* widget = new Widget(); widget->SetSize(Vector2i(50, 50)); widget->SetAllowDrag(true); widget->OnDragStart.connect(WidgetDragStart); widget->OnDragReset.connect(WidgetDragReset); Widget* widget2 = new Widget(); widget2->SetSize(Vector2i(50, 50)); widget2->SetPosition(Vector2i(50, 0)); widget2->OnDragEnter.connect(WidgetDragEnterAccepted); widget2->OnDragLand.connect(WidgetDragLand); SDL_Event e; e.type = SDL_MOUSEMOTION; e.motion.x = 10; e.motion.y = 10; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEBUTTONDOWN; e.button.x = 10; e.button.y = 10; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); e.type = SDL_MOUSEMOTION; e.motion.x = 55; e.motion.y = 10; Widget::DistributeSDLEvents(&e); //Mouse drop on top of dragged widget results in a reset e.type = SDL_MOUSEBUTTONUP; e.button.x = 65; e.button.y = 15; e.button.button = SDL_BUTTON_LEFT; Widget::DistributeSDLEvents(&e); CHECK_EQUAL(0, drag_reset_count); CHECK_EQUAL((Widget*)NULL, Widget::GetDraggedWidget()); CHECK_EQUAL(1, sucessful_landings); //TODO accept count & position? Widget::ClearRoot(); } }
[ [ [ 1, 279 ] ] ]
774e50c6a7bb1fb4d64e6eef89f5e368b8873e1d
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonPlayer_2nd/Source/LPTask/src/TimerShutdownTask.cpp
c3636b14b236717b9595b30648c69b52aac3357f
[]
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
GB18030
C++
false
false
1,481
cpp
/* ============================================================================ Name : TimerShutdownTask.cpp Author : zengcity Version : 1.0 Copyright : Your copyright notice Description : CTimerShutdownTask implementation ============================================================================ */ #include "TimerShutdownTask.h" #include "MacroUtil.h" #include "TimeOutTimer.h" CTimerShutdownTask::CTimerShutdownTask() { // No implementation required } CTimerShutdownTask::~CTimerShutdownTask() { SAFE_DELETE_ACTIVE(iTimer); } CTimerShutdownTask* CTimerShutdownTask::NewLC(const TInt aPriority) { CTimerShutdownTask* self = new (ELeave)CTimerShutdownTask(); CleanupStack::PushL(self); self->ConstructL(aPriority); return self; } CTimerShutdownTask* CTimerShutdownTask::NewL(const TInt aPriority) { CTimerShutdownTask* self=CTimerShutdownTask::NewLC(aPriority); CleanupStack::Pop(); // self; return self; } void CTimerShutdownTask::ConstructL(const TInt aPriority) { iTimer = CTimeOutTimer::NewL(aPriority, *this); } void CTimerShutdownTask::TimerExpired() { User::Exit(0); } //开始定时关机 void CTimerShutdownTask::StartTask(TTimeIntervalMicroSeconds32 anInterval) { if (iTimer) { iTimer->After(anInterval); } } //取消定时关机 void CTimerShutdownTask::CancelTask() { if (iTimer) { if (iTimer->IsActive()) iTimer->Cancel(); } }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 68 ] ] ]
b44f2637047e74af96c94f3115ab1b7ed44dd65c
7a4dfb986f5bd5fbee2186fcf37a0a0a74ef6033
/SubtitleGrabber/HTTP.cpp
b406e5258cd924ae44a0b2271bff22571d917b52
[]
no_license
zsjoska/subtitle-grabber
cad96727e73d6d3ec58eb3ad5eb1dfbac0c646bd
8de1a741b2b7fdd2e7899738839516e729d23430
refs/heads/master
2016-09-06T19:14:26.133224
2007-05-30T09:20:55
2007-05-30T09:20:55
32,320,106
0
0
null
null
null
null
UTF-8
C++
false
false
1,400
cpp
#include "StdAfx.h" #include "HTTP.h" #include "HTTPRequest.h" #include "HTTPResponse.h" #include "HTTPTransport.h" const TCHAR CHTTP::CRLF[3]=_T("\r\n"); CHTTP::CHTTP(void) { m_bUseProxy = FALSE; m_strLastServer = _T(""); m_bKeepAlive = FALSE; m_pTransport = new CHTTPTransport; } CHTTP::~CHTTP(void) { if (m_pTransport != NULL) { if (m_bKeepAlive) { m_bKeepAlive = FALSE; m_pTransport->Close(); } delete m_pTransport; m_pTransport = NULL; } } CHTTPResponse * CHTTP::ExecuteRequest(CHTTPRequest * pRequest) { BOOL bCanUseKeepalive = pRequest->CanPersist(); if (m_bKeepAlive && !bCanUseKeepalive) { m_bKeepAlive = FALSE; m_pTransport->Close(); } if (m_bKeepAlive && pRequest->GetServer() != m_strLastServer) { m_bKeepAlive = FALSE; m_pTransport->Close(); } BOOL bConnected = FALSE; if (!m_bKeepAlive) { m_strLastServer = pRequest->GetServer(); bConnected = m_pTransport->Open(m_strLastServer); } if (!bConnected) { return NULL; } CHTTPResponse * pResponse = m_pTransport->DoRequest(pRequest); if (pResponse == NULL) { m_bKeepAlive = FALSE; } else { if (bCanUseKeepalive && pResponse->CanPersist()) { m_bKeepAlive = TRUE; } else { m_bKeepAlive = FALSE; } } if (!m_bKeepAlive) { m_pTransport->Close(); } return pResponse; }
[ "zsjoska@a99920ad-ab31-0410-9f62-6da89933afc0" ]
[ [ [ 1, 83 ] ] ]
657a1ecf04aae88914897610212bd2844ea92771
7a8153e3fde0807462b6b6696b796d772639fa74
/src/game/lifeforms/LifeForm.cpp
8dbc6c2d60f4a9c19fe92979ca85cd3911d8fbcf
[]
no_license
qaze/violetland
7183f9670676d05da3970cd2fbd8cf7e5f5197c2
9f0fc9aff4ca1a4111b45fb105fc33fd9ae97dad
refs/heads/master
2021-01-02T22:38:01.687080
2011-10-10T12:35:36
2011-10-10T12:35:36
32,754,552
2
0
null
null
null
null
UTF-8
C++
false
false
3,197
cpp
#include <sstream> #include "LifeForm.h" using namespace violetland; LifeForm::LifeForm(float x, float y, int w, int h) : Object(x, y, w, h) { std::ostringstream buf; buf << UidGenerator::getInstance()->getId(); Id = buf.str(); Strength = 1.0f; Agility = 1.0f; Vitality = 1.0f; m_health = MaxHealth(); State = LIFEFORM_STATE_ALIVE; m_lastAttackTime = SDL_GetTicks(); TargetX = TargetY = 0.0f; Poisoned = false; m_walking = false; Frozen = 0; Burning = false; Level = 1; Name = "Unknown lifeform"; } void LifeForm::draw() { // nothing } Sound* LifeForm::hit(float damage, bool poison) { setHealth(getHealth() - damage); if (getHealth() == 0 && State == LIFEFORM_STATE_ALIVE) { State = LIFEFORM_STATE_SMITTEN; } return NULL; } void LifeForm::process(int deltaTime) { if (Frozen > 0) { Frozen -= deltaTime; if (Frozen < 0) Frozen = 0; } if (State == LIFEFORM_STATE_ALIVE && Frozen == 0) { setHealth(getHealth() + HealthRegen() * deltaTime); if (Poisoned) setHealth(getHealth() - 0.0004f * deltaTime); if (Burning) { RMask -= 0.02 / MaxHealth(); if (RMask < 0) RMask = 0; GMask -= 0.02 / MaxHealth(); if (GMask < 0) GMask = 0; BMask -= 0.02 / MaxHealth(); if (BMask < 0) BMask = 0; AMask += 0.01 / MaxHealth(); if (AMask > 1) AMask = 1; setHealth(getHealth() - 0.0005f * deltaTime); } if (!m_walking) { Speed -= Acceleration * deltaTime; if (Speed < 0) Speed = 0; } m_walking = false; Object::move(deltaTime); } } void LifeForm::move(float direction, int deltaTime) { if (m_walkDelay > 0) return; m_walking = true; Speed += Acceleration * deltaTime; if (Speed > MaxSpeed()) Speed = MaxSpeed(); turn(direction, MaxSpeed(), deltaTime); } const float LifeForm::MaxHealth() const { return getVitality() > 0.8f ? 1.0f + (getVitality() - 1.0f) * 2.0f + (getStrength() - 1.0f) : 0.4f; } const float LifeForm::ChanceToEvade() const { float chance = (getAgility() - 1.0f) / 4.0f + (getStrength() - 1.0f) / 4.0f; if (chance < 0) chance = 0; return chance; } const bool LifeForm::Attack() { int now = SDL_GetTicks(); if (now - m_lastAttackTime > AttackDelay()) { m_lastAttackTime = now; return true; } else { return false; } } const float LifeForm::Damage() const { return getStrength() / 8.0f; } const int LifeForm::AttackDelay() const { return (1.0f - (getAgility() - 1.0f) / 2.0f) * 1000; } const float LifeForm::MaxSpeed() const { return getAgility() / 5.0f; } const float LifeForm::HealthRegen() const { return getVitality() > 1.0f ? (getVitality() - 1.0f) * 0.000006f : 0.0f; } const float LifeForm::ReloadSpeedMod() const { return 1.0f / getAgility(); } const float LifeForm::WeaponRetForceMod() const { return getStrength() > 1.0f ? 1.0f - (getStrength() - 1.0f) * 1.1f : 1.0f; } const float LifeForm::fixHealth(float health) const { if (health > MaxHealth()) return MaxHealth(); else if (health < 0) return 0; else return health; } LifeForm::~LifeForm() { // nothing }
[ "[email protected]@c5058ba8-c010-11de-a759-a54c9d3330c2", "5253450@c5058ba8-c010-11de-a759-a54c9d3330c2", "[email protected]@c5058ba8-c010-11de-a759-a54c9d3330c2" ]
[ [ [ 1, 2 ], [ 9, 11 ], [ 143, 149 ] ], [ [ 3, 4 ], [ 8, 8 ], [ 12, 21 ], [ 23, 26 ], [ 28, 30 ], [ 32, 40 ], [ 42, 51 ], [ 53, 53 ], [ 71, 82 ], [ 84, 95 ], [ 97, 100 ], [ 105, 106 ], [ 108, 117 ], [ 119, 121 ], [ 123, 125 ], [ 127, 129 ], [ 132, 133 ], [ 135, 137 ], [ 139, 141 ] ], [ [ 5, 7 ], [ 22, 22 ], [ 27, 27 ], [ 31, 31 ], [ 41, 41 ], [ 52, 52 ], [ 54, 70 ], [ 83, 83 ], [ 96, 96 ], [ 101, 104 ], [ 107, 107 ], [ 118, 118 ], [ 122, 122 ], [ 126, 126 ], [ 130, 131 ], [ 134, 134 ], [ 138, 138 ], [ 142, 142 ], [ 150, 154 ] ] ]
eca48bf35ab5490057baaa97471535a1261bbb2f
cd387cba6088f351af4869c02b2cabbb678be6ae
/lib/geometry/algorithms/loop.hpp
05eed371e23e69f02fbdc7a34390e129c2e3fa2e
[ "BSL-1.0" ]
permissive
pedromartins/mew-dev
e8a9cd10f73fbc9c0c7b5bacddd0e7453edd097e
e6384775b00f76ab13eb046509da21d7f395909b
refs/heads/master
2016-09-06T14:57:00.937033
2009-04-13T15:16:15
2009-04-13T15:16:15
32,332,332
0
0
null
null
null
null
UTF-8
C++
false
false
2,735
hpp
// Geometry Library // // Copyright Barend Gehrels, Geodan Holding B.V. Amsterdam, the Netherlands. // Copyright Bruno Lalande 2008 // Use, modification and distribution is subject to 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 _GEOMETRY_LOOP_HPP #define _GEOMETRY_LOOP_HPP #include <geometry/geometries/segment.hpp> namespace geometry { /*! \brief Loops through segments of a container and call specified functor for all segments. \ingroup loop \details for_each like implementation to: - walk over const segments of a linestring/polygon - be able to break out the loop (if the functor returns false) - have a const functor and keep state in separate state-object - we still keep the "functor" here so it might be a function or an object, at this place - in most algorithms the typename F::state_type is used; in those places it must be an object \param v container (vector,list,deque) containing points \param functor functor which is called at each const segment \param state state, specified separately from the strategy functor \return false if the functor returns false, otherwise true \par Template parameters: - \a V container type, for example a vector, linestring, linear_ring - \a F functor type, class or function, not modified by the algorithm - \a S state type, might be modified \par Concepts - \a V - const_iterator begin() - const_iterator end() - value_type - \a F - <em>if it is a function functor</em>: bool \b function (const segment&, state&) - <em>if it is a class functor</em>: bool operator()(const segment&, state&) const - \a S - no specific requirements here, requirments given by F \note Some algorithms from the Geometry Library, for example within, centroid, use this method. \par Examples: First example, using a class functor \dontinclude doxygen_examples.cpp \skip example_loop1 \line { \until //:\\ Second example, using a function functor and latlong coordinates \dontinclude doxygen_examples.cpp \skip example_loop2 \line { \until //:\\ */ template<typename V, typename F, typename S> inline bool loop(const V& v, const F& functor, S& state) { typename V::const_iterator it = v.begin(); if (it != v.end()) { typename V::const_iterator previous = it++; while(it != v.end()) { segment<const typename V::value_type> s(*previous, *it); if (! functor(s, state)) { return false; } previous = it++; } } return true; } } // namespace geometry #endif // _GEOMETRY_LOOP_HPP
[ "fushunpoon@1fd432d8-e285-11dd-b2d9-215335d0b316" ]
[ [ [ 1, 86 ] ] ]
63b19aa23a0cde109c4fc80ce6caa7c75b63352f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/detail/core/matcher/set_matcher.hpp
6c70345d1cc7b6221df9c9144f7be6c99215e0d0
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
3,798
hpp
/////////////////////////////////////////////////////////////////////////////// // set.hpp // // Copyright 2004 Eric Niebler. 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 BOOST_XPRESSIVE_DETAIL_SET_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_DETAIL_SET_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once # pragma warning(push) # pragma warning(disable : 4127) // conditional expression constant # pragma warning(disable : 4100) // unreferenced formal parameter # pragma warning(disable : 4351) // vc8 new behavior: elements of array 'foo' will be default initialized #endif #include <algorithm> #include <boost/mpl/assert.hpp> #include <boost/type_traits/same_traits.hpp> #include <boost/xpressive/detail/detail_fwd.hpp> #include <boost/xpressive/detail/core/quant_style.hpp> #include <boost/xpressive/detail/core/state.hpp> namespace boost { namespace xpressive { namespace detail { /////////////////////////////////////////////////////////////////////////////// // set_matcher // template<typename Traits, int Size> struct set_matcher : quant_style_fixed_width<1> { typedef typename Traits::char_type char_type; char_type set_[ Size ? Size : 1 ]; bool not_; bool icase_; typedef set_matcher<Traits, Size + 1> next_type; friend struct set_matcher<Traits, Size - 1>; set_matcher(Traits const &) : set_() , not_(false) , icase_(false) { } set_matcher(char_type ch, Traits const &traits) : set_() , not_(false) , icase_(false) { BOOST_MPL_ASSERT_RELATION(1, ==, Size); this->set_[0] = traits.translate(ch); } void complement() { this->not_ = !this->not_; } void nocase(Traits const &traits) { this->icase_ = true; for(int i = 0; i < Size; ++i) { this->set_[i] = traits.translate_nocase(this->set_[i]); } } next_type push_back(char_type ch, Traits const &traits) const { return next_type(*this, ch, traits); } char_type const *begin() const { return this->set_; } char_type const *end() const { return this->set_ + Size; } bool in_set(Traits const &traits, char_type ch) const { ch = this->icase_ ? traits.translate_nocase(ch) : traits.translate(ch); if(1 == Size) { return this->set_[0] == ch; } else { return this->end() != std::find(this->begin(), this->end(), ch); } } template<typename BidiIter, typename Next> bool match(state_type<BidiIter> &state, Next const &next) const { if(state.eos() || this->not_ == this->in_set(traits_cast<Traits>(state), *state.cur_)) { return false; } if(++state.cur_, next.match(state)) { return true; } return --state.cur_, false; } private: set_matcher(set_matcher<Traits, Size - 1> const &that, char_type ch, Traits const &traits) : set_() , not_(false) , icase_(that.icase_) { std::copy(that.begin(), that.end(), this->set_); this->set_[ Size - 1 ] = traits.translate(ch); } }; /////////////////////////////////////////////////////////////////////////////// // set_initializer struct set_initializer { }; #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma warning(pop) #endif }}} // namespace boost::xpressive::detail #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 145 ] ] ]
221ab6650748618a1aa12708231678b3b862751b
6c8c4728e608a4badd88de181910a294be56953a
/EnvironmentModule/Sky.cpp
6ba1e105500caa2f2517703b42ca1b15c044ac94
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,672
cpp
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "Foundation.h" #include "OgreRenderingModule.h" #include "EnvironmentModule.h" #include "Sky.h" #include "SceneManager.h" #include "CoreTypes.h" #include "OgreTextureResource.h" #include "NetworkEvents.h" #include "ServiceManager.h" #include "NetworkMessages/NetInMessage.h" namespace Environment { Sky::Sky(EnvironmentModule *owner) : owner_(owner), skyEnabled_(false), type_(OgreRenderer::SKYTYPE_BOX), skyBoxImageCount_(0) { } Sky::~Sky() { } bool Sky::HandleRexGM_RexSky(ProtocolUtilities::NetworkEventInboundData* data) { // HACK ON REX MODE, return false if you have problems // return false; ProtocolUtilities::NetInMessage &msg = *data->message; msg.ResetReading(); msg.SkipToFirstVariableByName("Parameter"); // Variable block begins, should have currently (at least) 4 instances. size_t instance_count = msg.ReadCurrentBlockInstanceCount(); if (instance_count < 4) { EnvironmentModule::LogWarning("Generic message \"RexSky\" did not contain all the necessary data."); return false; } // 1st instance contains the sky type. OgreRenderer::SkyType type = OgreRenderer::SKYTYPE_NONE; type = (OgreRenderer::SkyType)boost::lexical_cast<int>(msg.ReadString()); // 2nd instance contains the texture uuid's std::string image_string = msg.ReadString(); //HACK split() returns vector-struct not a direct vector after verson 6 #if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1 StringVector images_type = Ogre::StringUtil::split(image_string); StringVector images = images_type; #else Ogre::vector<Ogre::String>::type images_type = Ogre::StringUtil::split(image_string); StringVector images; int size = images_type.size(); images.resize(size); for(int i = 0; i < size; ++i) images[i] = images_type[i]; #endif //END HACK //StringVector images = boost::lexical_cast<StringVector>(images_type); // 3rd instance contains the curvature parameter. float curvature = boost::lexical_cast<float>(msg.ReadString()); // 4th instance contains the tiling parameter. float tiling = boost::lexical_cast<float>(msg.ReadString()); UpdateSky(type, images, curvature, tiling); return false; } void Sky::UpdateSky(const OgreRenderer::SkyType &type, std::vector<std::string> images, const float &curvature, const float &tiling) { type_ = type; if (type_ == OgreRenderer::SKYTYPE_NONE) { Scene::EntityPtr sky = GetSkyEntity().lock(); if (sky) { OgreRenderer::EC_OgreSky *sky_component = sky->GetComponent<OgreRenderer::EC_OgreSky>().get(); sky_component->DisableSky(); return; } } // Suffixes are used to identify different texture positions on the skybox. std::map<std::string, int> indexMap; std::map<std::string, int>::const_iterator suffixIter; indexMap["_fr"] = 0; // front indexMap["_bk"] = 1; // back indexMap["_lf"] = 2; // left indexMap["_rt"] = 3; // right indexMap["_up"] = 4; // up indexMap["_dn"] = 5; // down currentSkyBoxImageCount_ = 0; skyBoxImageCount_ = 0; size_t max = std::min(images.size(), (size_t)SKYBOX_TEXTURE_COUNT); for(size_t n = 0; n < max; ++n) { std::string image_str = images[n]; size_t index = n; if (image_str.size() < 4) break; switch(type_) { case OgreRenderer::SKYTYPE_BOX: { std::string suffix = image_str.substr(image_str.size() - 3); suffixIter = indexMap.find(suffix); if (suffixIter == indexMap.end()) break; index = suffixIter->second; image_str = image_str.substr(0, image_str.size() - 3); if (RexTypes::IsNull(image_str)) break; ++skyBoxImageCount_; skyBoxTextures_[index] = image_str; break; } case OgreRenderer::SKYTYPE_DOME: skyDomeTexture_ = image_str; break; case OgreRenderer::SKYTYPE_PLANE: skyPlaneTexture_ = image_str; break; } } RequestSkyTextures(); Scene::EntityPtr sky = GetSkyEntity().lock(); if (sky) //send changes on curvature and tiling to EC_OgreSky. { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); switch(type) { case OgreRenderer::SKYTYPE_BOX: // Noting to send for sky box so we leave this empty. break; case OgreRenderer::SKYTYPE_DOME: { OgreRenderer::SkyDomeParameters param = sky_component->GetSkyDomeParameters(); if(param.curvature != curvature || param.tiling != tiling) { param.curvature = curvature; param.tiling = tiling; sky_component->SetSkyDomeParameters(param); } break; } case OgreRenderer::SKYTYPE_PLANE: { OgreRenderer::SkyPlaneParameters param = sky_component->GetSkyPlaneParameters(); if(param.tiling != tiling) { param.tiling = tiling; sky_component->SetSkyPlaneParameters(param); } break; } } /*OgreRenderer::SkyImageData imageData; //= new OgreRenderer::SkyImageData; //imageData.index = index; imageData.type = type; imageData.curvature = curvature; imageData.tiling = tiling; sky_component->SetSkyParameters(imageData);*/ } emit SkyTypeChanged(); } void Sky::CreateDefaultSky(const bool &show) { type_ = OgreRenderer::SKYTYPE_BOX; Scene::EntityPtr sky = GetSkyEntity().lock(); if (sky) { OgreRenderer::EC_OgreSky *sky_component = sky->GetComponent<OgreRenderer::EC_OgreSky>().get(); assert(sky_component); sky_component->CreateSky(); EnableSky(sky_component->IsSkyEnabled()); std::vector<std::string> items = sky_component->GetMaterialTextureNames(); for(uint i = 0; i < 6; i++) skyBoxTextures_[i] = items[i]; } } void Sky::DisableSky() { Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_component->DisableSky(); EnableSky(sky_component->IsSkyEnabled()); } } bool Sky::IsSkyEnabled() const { return skyEnabled_; } void Sky::RequestSkyTextures() { boost::weak_ptr<OgreRenderer::Renderer> w_renderer = owner_->GetFramework()->GetServiceManager()->GetService <OgreRenderer::Renderer>(Foundation::Service::ST_Renderer); boost::shared_ptr<OgreRenderer::Renderer> renderer = w_renderer.lock(); switch(type_) { case OgreRenderer::SKYTYPE_BOX: for(int i = 0; i < SKYBOX_TEXTURE_COUNT; ++i) skyBoxTextureRequests_[i] = renderer->RequestResource(skyBoxTextures_[i], OgreRenderer::OgreTextureResource::GetTypeStatic()); break; case OgreRenderer::SKYTYPE_DOME: skyDomeTextureRequest_ = renderer->RequestResource(skyDomeTexture_, OgreRenderer::OgreTextureResource::GetTypeStatic()); break; case OgreRenderer::SKYTYPE_PLANE: skyPlaneTextureRequest_ = renderer->RequestResource(skyPlaneTexture_, OgreRenderer::OgreTextureResource::GetTypeStatic()); break; case OgreRenderer::SKYTYPE_NONE: default: break; } } void Sky::OnTextureReadyEvent(Resource::Events::ResourceReady *tex) { assert(tex); Scene::EntityPtr sky = GetSkyEntity().lock(); if (!sky) { EnvironmentModule::LogDebug("Could not get SkyEntityPtr!"); return; } OgreRenderer::EC_OgreSky *sky_component = sky->GetComponent<OgreRenderer::EC_OgreSky>().get(); assert(sky_component); switch(type_) { case OgreRenderer::SKYTYPE_BOX: for(int i = 0; i < SKYBOX_TEXTURE_COUNT; ++i) if (tex->tag_ == skyBoxTextureRequests_[i]) sky_component->SetSkyBoxMaterialTexture(i, tex->id_.c_str(), skyBoxImageCount_); break; case OgreRenderer::SKYTYPE_DOME: if (tex->tag_ == skyDomeTextureRequest_) sky_component->SetSkyDomeMaterialTexture(tex->id_.c_str()); break; case OgreRenderer::SKYTYPE_PLANE: if (tex->tag_ == skyPlaneTextureRequest_) sky_component->SetSkyPlaneMaterialTexture(tex->id_.c_str()); break; default: break; } EnableSky(sky_component->IsSkyEnabled()); } void Sky::SetSkyTexture(const RexAssetID &texture_id) { switch(type_) { case OgreRenderer::SKYTYPE_DOME: skyDomeTexture_ = texture_id; break; case OgreRenderer::SKYTYPE_PLANE: skyPlaneTexture_ = texture_id; break; default: EnvironmentModule::LogError("SetSkyTexture can be used only for SkyDome and SkyPlane!"); break; } } void Sky::SetSkyBoxTextures(const RexAssetID textures[SKYBOX_TEXTURE_COUNT]) { if (type_ != OgreRenderer::SKYTYPE_BOX) { EnvironmentModule::LogError("SetSkyBoxTextures can be used only for SkyBox!"); return; } skyBoxImageCount_ = 0; for(int i = 0; i < SKYBOX_TEXTURE_COUNT; ++i) { if(skyBoxTextures_[i] != textures[i] && textures[i] != "") { skyBoxTextures_[i] = textures[i]; skyBoxImageCount_++; } } } void Sky::FindCurrentlyActiveSky() { Scene::ScenePtr scene = owner_->GetFramework()->GetDefaultWorldScene(); for(Scene::SceneManager::iterator iter = scene->begin(); iter != scene->end(); ++iter) { Scene::Entity &entity = **iter; Foundation::ComponentInterfacePtr sky_component = entity.GetComponent(OgreRenderer::EC_OgreSky::NameStatic()); if (sky_component.get()) cachedSkyEntity_ = scene->GetEntity(entity.GetId()); } } Scene::EntityWeakPtr Sky::GetSkyEntity() { return cachedSkyEntity_; } OgreRenderer::SkyType Sky::GetSkyType() const { return type_; } void Sky::EnableSky(bool enabled) { if(skyEnabled_ != enabled) { skyEnabled_ = enabled; emit SkyEnabled(enabled); } } void Sky::ChangeSkyType(OgreRenderer::SkyType type, bool update_sky) { Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); EnableSky(update_sky); sky_component->SetSkyType(type, update_sky); type_ = type; switch(type_) { case OgreRenderer::SKYTYPE_BOX: for(uint i = 0; i < SKYBOX_TEXTURE_COUNT; i++) skyBoxTextures_[i] = sky_component->GetSkyBoxTextureID(i); break; case OgreRenderer::SKYTYPE_PLANE: skyPlaneTexture_ = sky_component->GetSkyDomeTextureID(); break; case OgreRenderer::SKYTYPE_DOME: skyDomeTexture_ = sky_component->GetSkyDomeTextureID(); break; } emit SkyTypeChanged(); } } RexTypes::RexAssetID Sky::GetSkyTextureID(OgreRenderer::SkyType sky_type, int index) const { if(index < 0) index = 0; else if(index > SKYBOX_TEXTURE_COUNT - 1) index = SKYBOX_TEXTURE_COUNT - 1; if(sky_type == OgreRenderer::SKYTYPE_BOX) { return skyBoxTextures_[index]; } else if(sky_type == OgreRenderer::SKYTYPE_DOME) { return skyDomeTexture_; } else if(sky_type == OgreRenderer::SKYTYPE_PLANE) { return skyPlaneTexture_; } return 0; } OgreRenderer::SkyDomeParameters Sky::GetSkyDomeParameters() { OgreRenderer::SkyDomeParameters sky_dome_param; sky_dome_param.Reset(); Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_dome_param = sky_component->GetSkyDomeParameters(); } return sky_dome_param; } OgreRenderer::SkyPlaneParameters Sky::GetSkyPlaneParameters() { OgreRenderer::SkyPlaneParameters sky_plane_param; sky_plane_param.Reset(); Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_plane_param = sky_component->GetSkyPlaneParameters(); } return sky_plane_param; } OgreRenderer::SkyBoxParameters Sky::GetSkyBoxParameters() { OgreRenderer::SkyBoxParameters sky_param; sky_param.Reset(); Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_param = sky_component->GetBoxSkyParameters(); } return sky_param; } void Sky::SetSkyDomeParameters(const OgreRenderer::SkyDomeParameters &params, bool update_sky) { Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_component->SetSkyDomeParameters(params, update_sky); if(update_sky) { type_ = OgreRenderer::SKYTYPE_DOME; emit SkyTypeChanged(); } } } void Sky::SetSkyPlaneParameters(const OgreRenderer::SkyPlaneParameters &params, bool update_sky) { Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_component->SetSkyPlaneParameters(params, update_sky); if(update_sky) { type_ = OgreRenderer::SKYTYPE_PLANE; emit SkyTypeChanged(); } } } void Sky::SetSkyBoxParameters(const OgreRenderer::SkyBoxParameters &params, bool update_sky) { Scene::EntityPtr sky = GetSkyEntity().lock(); if(sky) { OgreRenderer::EC_OgreSky *sky_component = checked_static_cast<OgreRenderer::EC_OgreSky*>(sky->GetComponent("EC_OgreSky").get()); assert(sky_component); sky_component->SetSkyBoxParameters(params, update_sky); if(update_sky) { type_ = OgreRenderer::SKYTYPE_BOX; emit SkyTypeChanged(); } } } } // namespace RexLogic
[ "jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3", "joosuav@5b2332b8-efa3-11de-8684-7d64432d61a3", "cmayhem@5b2332b8-efa3-11de-8684-7d64432d61a3", "tuoki@5b2332b8-efa3-11de-8684-7d64432d61a3", "cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3", "sempuki1@5b2332b8-efa3-11de-8684-7d64432d61a3", "jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3", "[email protected]@5b2332b8-efa3-11de-8684-7d64432d61a3", "loorni@5b2332b8-efa3-11de-8684-7d64432d61a3", "mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 5 ], [ 14, 14 ], [ 16, 16 ], [ 19, 25 ], [ 27, 27 ], [ 31, 37 ], [ 39, 47 ], [ 49, 49 ], [ 54, 54 ], [ 58, 58 ], [ 64, 69 ], [ 71, 84 ], [ 86, 103 ], [ 105, 127 ], [ 129, 131 ], [ 133, 134 ], [ 136, 141 ], [ 183, 186 ], [ 188, 188 ], [ 193, 193 ], [ 199, 200 ], [ 218, 226 ], [ 229, 231 ], [ 233, 235 ], [ 237, 251 ], [ 253, 255 ], [ 257, 261 ], [ 263, 267 ], [ 269, 276 ], [ 278, 290 ], [ 292, 295 ], [ 297, 297 ], [ 299, 299 ], [ 301, 303 ], [ 314, 317 ], [ 320, 321 ], [ 324, 333 ], [ 487, 487 ] ], [ [ 6, 7 ], [ 11, 11 ], [ 15, 15 ], [ 18, 18 ], [ 38, 38 ], [ 291, 291 ], [ 300, 300 ], [ 318, 318 ] ], [ [ 8, 8 ], [ 189, 190 ], [ 192, 192 ], [ 198, 198 ], [ 319, 319 ], [ 322, 322 ] ], [ [ 9, 9 ], [ 48, 48 ], [ 50, 50 ], [ 53, 53 ], [ 56, 57 ], [ 59, 62 ] ], [ [ 10, 10 ], [ 51, 52 ], [ 55, 55 ], [ 63, 63 ], [ 187, 187 ] ], [ [ 12, 13 ] ], [ [ 17, 17 ], [ 104, 104 ], [ 227, 227 ], [ 262, 262 ], [ 296, 296 ], [ 306, 306 ], [ 362, 362 ], [ 380, 380 ] ], [ [ 26, 26 ], [ 30, 30 ] ], [ [ 28, 29 ], [ 70, 70 ], [ 142, 182 ], [ 194, 197 ], [ 201, 217 ], [ 252, 252 ], [ 268, 268 ], [ 277, 277 ], [ 298, 298 ], [ 304, 305 ], [ 307, 313 ], [ 334, 361 ], [ 363, 379 ], [ 381, 486 ] ], [ [ 85, 85 ], [ 191, 191 ], [ 256, 256 ], [ 323, 323 ] ], [ [ 128, 128 ], [ 132, 132 ], [ 135, 135 ], [ 228, 228 ], [ 232, 232 ], [ 236, 236 ] ] ]
087ce57f6ee227410cd62a131947a618756ea7e8
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/Algorithm/Sort/hkSort.h
98b5fed5cf7f535d1bb15c807c40eb3a9e726bb2
[]
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
3,831
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 HKBASE_HKALGORITHM_H #define HKBASE_HKALGORITHM_H #include <Common/Base/hkBase.h> namespace hkAlgorithm { /// swap the elements template<typename T> HK_FORCE_INLINE void HK_CALL swap(T& x, T& y) { T t(x); x = y; y = t; } /// swap the 16 byte aligned elements template<typename T> HK_FORCE_INLINE void HK_CALL swap16(T& x, T& y) { HK_ALIGN16( T t ) = x; x = y; y = t; } /// function object that routes calls to operator< template<typename T> class less { public: HK_FORCE_INLINE hkBool operator() ( const T& a, const T& b ) { return ( a < b ); } }; /// function object that routes calls to operator> template<typename T> class greater { public: HK_FORCE_INLINE hkBool operator() ( const T& a, const T& b ) { return ( a > b ); } }; /// heap sort. you supply the functor, see hkAlgorithm::less for an example functor. template<typename T, typename L> void HK_CALL heapSort(T *pArr, int iSize, L cmpLess); /// Heap sort for the elements of the specified array. /// /// \param *pArr A pointer to the array to sort. /// \param iSize The size of the array pointed to by *pArr. /// template<typename T> void HK_CALL heapSort(T *pArr, int iSize) { heapSort( pArr, iSize, less<T>() ); } // used by heapSort template<typename T, typename L> void HK_CALL downHeap(T *pArr, int k, int n, L cmpLess); /// quick sort. you supply the functor, see hkAlgorithm::less for an example functor. template<typename T, typename L> HK_FORCE_INLINE void HK_CALL quickSort(T *pArr, int iSize, L cmpLess); /// Quick sort for the elements of the specified array. /// /// \param *pArr A pointer to the data to sort. /// \param iSize The size of the array pointed to by *pArr. /// template<typename T> HK_FORCE_INLINE void HK_CALL quickSort(T *pArr, int iSize) { quickSort( pArr, iSize, less<T>() ); } template< typename T, typename L > void HK_CALL quickSortRecursive(T *pArr, int d, int h, L cmpLess); /// Quick sort using an explicit stack for efficiency reasons. template<typename T> HK_FORCE_INLINE void HK_CALL explicitStackQuickSort(T *pArr, int iSize) { explicitStackQuickSort( pArr, iSize, less<T>() ); } } #if defined(HK_PS2) //|| defined(HK_PLATFORM_PS3) || defined(HK_PLATFORM_PS3SPU) #define hkSort hkAlgorithm::heapSort #else #define hkSort hkAlgorithm::quickSort //#define hkSort hkAlgorithm::explicitStackQuickSort #endif #include <Common/Base/Algorithm/Sort/hkSort.inl> #endif // HKBASE_HKALGORITHM_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, 136 ] ] ]
7b4285e7a2dbfa25f69222e9433bb61e18111752
ca99bc050dbc58be61a92e04f2a80a4b83cb6000
/Game/src/Game/GameManager.h
fe0698784c48c90d4df421746a3addf148b28239
[]
no_license
NicolasBeaudrot/angry-tux
e26c619346c63a468ad3711de786e94f5b78a2f1
5a8259f57ba59db9071158a775948d06e424a9a8
refs/heads/master
2021-01-06T20:41:23.705460
2011-04-14T18:28:04
2011-04-14T18:28:04
32,141,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,490
h
/* Copyright (C) 2010 Nicolas Beaudrot 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/>. */ #ifndef GAMEMANAGER_H #define GAMEMANAGER_H #include <SFML/Graphics.hpp> #include <Box2D/Box2D.h> #include "../Utilities/Config.h" #include "../Entities/EntityManager.h" #include "../Map/MapManager.h" #include "EventManager.h" class GameManager : public CSingleton<GameManager> { public: void init(); void newGame(const std::string world, int map_id); void restart(); protected: private: GameManager(); ~GameManager(); friend class CSingleton<GameManager>; sf::RenderWindow _app; b2World *_world; EventManager *_eventManager; std::string _currentWorld; int _currentMapId; void createWorld(); void destroyWorld(); void run(); }; #endif // GAMEMANAGER_H
[ "nicolas.beaudrot@43db0318-7ac6-f280-19a0-2e79116859ad" ]
[ [ [ 1, 47 ] ] ]
97f100e4ac661ee7d57b6896017588bda721fe91
65fe6f7017f90fa55acf45773470f8f039724748
/antbuster/include/ca/caRect.h
0d16435387efac010e0f89d094749cbdc8652265
[]
no_license
ashivers/antbusterhge
bd37276c29d1bb5b3da8d0058d2a3e8421dfa3ab
575a21c56fa6c8633913b7e2df729767ac8a7850
refs/heads/master
2021-01-20T22:40:19.612909
2007-10-03T10:56:44
2007-10-03T10:56:44
40,769,210
0
0
null
null
null
null
UTF-8
C++
false
false
2,623
h
#ifndef CURVEDANI_Rect_H #define CURVEDANI_Rect_H #include "caPoint2d.h" namespace cAni { template< class T > struct _Rect { _Rect(); _Rect(T _left,T _right, T _top, T _bottom); _Rect(const _Rect &t); T left, right, top, bottom; _Rect & operator &= (const _Rect &clip); // intersect rect _Rect operator & (const _Rect &clip) const; // intersect rect _Rect & operator += (const _Point2<T> &point); // offset rect by point _Rect operator + (const _Point2<T> &point) const; // offset rect by point bool operator & (const _Point2<T> &point) const; // check point in rect bool operator == (const _Rect &o) const; T GetWidth() const; T GetHeight() const; bool Visible(); }; template< class T > inline _Rect<T>::_Rect():left(0),right(0),top(0),bottom(0) { } template< class T > inline _Rect<T>::_Rect(T _left,T _right, T _top, T _bottom): left(_left),right(_right),top(_top),bottom(_bottom) { } template< class T > inline _Rect<T>::_Rect(const _Rect<T> &t):left(t.left),right(t.right),top(t.top),bottom(t.bottom) { } template< class T > inline _Rect<T> & _Rect<T>::operator &= (const _Rect<T> &clip) { if (left<clip.left) left = clip.left; if (top<clip.top) top = clip.top; if (right>clip.right) right = clip.right; if (bottom>clip.bottom) bottom = clip.bottom; return *this; } template< class T > inline _Rect<T> _Rect<T>::operator & (const _Rect<T> &clip) const { _Rect<T> t(*this); t &= clip; return t; } template< class T > inline _Rect<T> & _Rect<T>::operator += (const _Point2<T> &point) { left += point.x; right += point.x; top += point.y; bottom += point.y; return *this; } template< class T > inline _Rect<T> _Rect<T>::operator + (const _Point2<T> &point) const { _Rect<T> t(*this); t += point; return t; } template< class T > inline bool _Rect<T>::operator & (const _Point2<T> &point) const { return point.x >= left && point.x < right && point.y >= top && point.y < bottom; } template< class T > inline bool _Rect<T>::Visible() { return left<right && top<bottom; } template< class T > inline bool _Rect<T>::operator == (const _Rect<T> &o) const { return left == o.left && right == o.right && top == o.top && bottom == o.bottom; } template< class T > inline T _Rect<T>::GetWidth() const { return right - left; } template< class T > inline T _Rect<T>::GetHeight() const { return bottom - top; } typedef _Rect<short> Rect; typedef _Rect<float> Rectf; }; #endif//CURVEDANI_Rect_H
[ "zikaizhang@b4c9a983-0535-0410-ac72-75bbccfdc641" ]
[ [ [ 1, 101 ] ] ]
cd9d1535f4aa4e17e058195c6937a88ad2992853
e03ee4538dce040fe16fc7bb48d495735ac324f4
/Stable/Behaviours/Artillery.cpp
cbd530e7cae4ba48d344fbf863fb62bb48c06297
[]
no_license
vdelgadov/itcvideogame
dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441
5eac60e901b29bff4d844f34cd52f97f4d1407b5
refs/heads/master
2020-05-16T23:43:48.956373
2009-12-01T02:09:08
2009-12-01T02:09:08
42,265,496
0
0
null
null
null
null
UTF-8
C++
false
false
2,729
cpp
#ifndef _ART #define _ART #include "Actor_States.cpp" //InfluenceMap* AIController::s_InfluenceMap = NULL; class ArtEngaging : public AState<Actor>{ private: static const double attacking_range; public: void enter(Actor* a){ cout << "Entering Artillery Engaging" <<endl; //Enemy = null;//Engine.getClosestOrWhatever()... } void execute(Actor* a){ AIController* aic = (AIController*)(a->getController()); CObject* Enemy = aic->getEnemy(); if(!Enemy){ a->getFSM()->changeState("Idle"); return; } Vector3D stf; int x, y; getBestPosition(a, &x, &y); double real_x = (x+0.5)*(/*Engine.getWidth()*/ 100.0 / AIController::s_InfluenceMap->getMapWidth()); double real_y = (y+0.5)*(/*Engine.getWidth()*/ 100.0 / AIController::s_InfluenceMap->getMapHeight()); stf = SteeringBehaviors<Vector3D>::seek(Vector3D(real_x, real_y, a->getVehicle()->getPos().z), a->getVehicle()); stf += a->getVehicle()->getCurrVel(); if((Enemy->getVehicle()->getPos() - a->getVehicle()->getPos()).magnitude() < 1) stf += SteeringBehaviors<Vector3D>::evade(a->getVehicle(), Enemy->getVehicle()); stf.normalize(); a->getVehicle()->setCurrVel(stf); if((a->getVehicle()->getPos() - Enemy->getVehicle()->getPos()).magnitude() < attacking_range){ a->getFSM()->changeState("Attack"); return; } } void exit(Actor* a){ cout << "Exiting Brute Engaging" << endl; } void getBestPosition(Actor* a, int* x, int* y){ int a_x, a_y; AIController::s_InfluenceMap->mapCoords(a->getVehicle()->getPos(), &a_x, &a_y); *x = a_x; *y = a_y; int vr = a->getViewRadius(); int up, down, left, right; up = a_y-vr; down = a_y+vr; left = a_x-vr; right = a_x+vr; while(down >= AIController::s_InfluenceMap->getMapHeight()) down--; while(up< 0) up++; while(left < 0) left++; while(right >= AIController::s_InfluenceMap->getMapWidth()) right--; for(int i=up; i<=down; i++) for(int j=left; j<=right; j++){ if(AIController::s_InfluenceMap->getSpot(i, j) > AIController::s_InfluenceMap->getSpot(*y, *x)){ *x = j; *y = i; } } } }; const double ArtEngaging::attacking_range = 3.0; class ArtAttack : public AState<Actor> { void enter(Actor* a){ cout << "Entering Artillery Attack" << endl; } void execute(Actor* a){ AIController* aic = (AIController*)(a->getController()); CObject* Enemy = aic->getEnemy(); cout << "Fireball <<O " << endl; a->getFSM()->changeState("Engaging"); } void exit(Actor* a){ cout << "Exiting Artillery Attack" << endl; } }; #endif
[ "mrjackinc@972b8bf6-92a2-11de-b72a-e7346c8bff7a", "leamsi.setroc@972b8bf6-92a2-11de-b72a-e7346c8bff7a" ]
[ [ [ 1, 3 ], [ 11, 11 ], [ 14, 25 ], [ 27, 30 ], [ 32, 33 ], [ 37, 60 ], [ 62, 67 ], [ 69, 76 ], [ 78, 91 ], [ 93, 94 ], [ 96, 113 ] ], [ [ 4, 10 ], [ 12, 13 ], [ 26, 26 ], [ 31, 31 ], [ 34, 36 ], [ 61, 61 ], [ 68, 68 ], [ 77, 77 ], [ 92, 92 ], [ 95, 95 ] ] ]
a0c347c22034633999c9827edbe2aa8b1cdc3dc7
de1e5905af557c6155ee50f509758a549e458ef3
/src/ui/ui_search.cpp
732a37ee642b15efc7b64c25bc88638ce276c0a1
[]
no_license
alltom/taps
f15f0a5b234db92447a581f3777dbe143d78da6c
a3c399d932314436f055f147106d41a90ba2fd02
refs/heads/master
2021-01-13T01:46:24.766584
2011-09-03T23:20:12
2011-09-03T23:20:12
2,486,969
1
0
null
null
null
null
UTF-8
C++
false
false
45,267
cpp
//----------------------------------------------------------------------------- // name: ui_search.cpp // desc: birdbrain ui // // authors: Ananya Misra ([email protected]) // Ge Wang ([email protected]) // Perry R. Cook ([email protected]) // Philip Davidson ([email protected]) // EST. April 20, 2006 //----------------------------------------------------------------------------- //#include "birdbrain.h" #include "sceptre.h" #include "ui_search.h" #include "ui_scripting.h" //#include "ui_audio.h" //#include "ui_element.h" //#include "ui_library.h" #include "audicle.h" #include "audicle_utils.h" //#include "audicle_gfx.h" #include "audicle_geometry.h" #include "RegionComparer.h" //UISearch * g_search_face = NULL; // enumeration for ui elements enum UI_ELMENTS { BT_LISTEN = 0, BT_STOP, BT_FIND, BT_ADD, // add to library BT_LOAD_DB, // load feature database BT_ADD_DB, // add template to database BT_TOGGLE_VIEW, // toggle matches view BT_CENTER, // center matches view on selected SL_ROTATE_H, // rotate around y-axis SL_ZOOM, // zoom in? SL_ROTATE_V, // rotate around x-axis SL_NUM_MATCHES, // how many matches to show in 3d view SL_VAL_A, SL_VAL_B, SL_VAL_C, SL_VAL_D, SL_VAL_E, SL_WEI_A, SL_WEI_B, SL_WEI_C, SL_WEI_D, SL_WEI_E, // keep this as last NUM_UI_ELEMENTS }; // names of ui elements static char * ui_str[] = { "listen", "stop", "find", "add-lib", "load-db", "add-db", "view", "center", "rotate", "zoom", "rotate", "show N", "null", "null", "null", "null", "null", "null", "null", "null", "null", "null", }; //----------------------------------------------------------------------------- // name: UISearch() // desc: ... //----------------------------------------------------------------------------- UISearch::UISearch( ) : AudicleFace( ) { if( !this->init( ) ) { fprintf( stderr, "[audicle]: cannot start face...\n" ); return; } } //----------------------------------------------------------------------------- // name: ~UISearch() // desc: ... //----------------------------------------------------------------------------- UISearch::~UISearch( ) { // delete ui_elements // delete bagels // delete library? // anything else? } //----------------------------------------------------------------------------- // name: init() // desc: ... //----------------------------------------------------------------------------- t_CKBOOL UISearch::init( ) { if( !AudicleFace::init() ) return FALSE; int i; // log BB_log( BB_LOG_SYSTEM, "initializing search user interface..." ); // push log BB_pushlog(); // ui elements ui_elements = new UI_Element *[NUM_UI_ELEMENTS]; memset( ui_elements, 0, sizeof(UI_Element *) * NUM_UI_ELEMENTS ); // allocate (not in loop if some are UI_Exps) for( i = 0; i < NUM_UI_ELEMENTS; i++ ) ui_elements[i] = new UI_Element; // get id for each element for( i = 0; i < NUM_UI_ELEMENTS; i++ ) { ui_elements[i]->id = IDManager::instance()->getPickID(); ui_elements[i]->name = ui_str[i]; } // font size for( i = SL_VAL_A; i <= SL_WEI_E; i++ ) ui_elements[i]->font_size = 1.3f; for( i = BT_LISTEN; i <= BT_ADD_DB; i++ ) ui_elements[i]->font_size = 0.8f; ui_elements[BT_TOGGLE_VIEW]->font_size = 0.7f; ui_elements[BT_CENTER]->font_size = 0.7f; // slider values for( i = SL_VAL_A; i <= SL_VAL_E; i++ ) { ui_elements[i]->set_bounds( 0, 1 ); ui_elements[i]->set_slide( 0 ); } for( i = SL_WEI_A; i <= SL_WEI_E; i++ ) { ui_elements[i]->set_bounds( 0, 1 ); ui_elements[i]->set_slide( 1 ); } for( i = SL_ROTATE_H; i <= SL_NUM_MATCHES; i++ ) { ui_elements[i]->set_bounds( -180, 180, true ); ui_elements[i]->set_slide( 0 ); } // overwrite some bounds ui_elements[SL_VAL_E]->set_bounds( 0, 2 ); ui_elements[SL_VAL_E]->set_slide( 0 ); ui_elements[SL_ZOOM]->set_bounds(0, 5, false); ui_elements[SL_ZOOM]->set_slide( 1 ); ui_elements[SL_NUM_MATCHES]->set_bounds(0, 1, true); ui_elements[SL_NUM_MATCHES]->set_slide( 1 ); // initialize down = NULL; selected = NULL; selected_from_matches = false; load_sliders = false; m_list_view = true; m_center = true; xyz_center_init = false; // set background color m_bg[0] = 0.7; m_bg[1] = 0.8; m_bg[2] = 0.8; m_bg[3] = 1.0; // -... -... --- -..- (fix bounds later) m_nbboxs = 4; m_cur_bbox = -1; m_bboxs = new BBox[m_nbboxs]; // lower sliders m_bboxs[0].add2d( Point2D( 0.0f, -1.2f ) ); m_bboxs[0].add2d( Point2D( 10.0f, 0.0f ) ); // library m_bboxs[1].add2d( Point2D( -10.0f, -1.2f ) ); m_bboxs[1].add2d( Point2D( 0.0f, 0.0f ) ); // matches m_bboxs[3].add2d( Point2D( -10.0f, 0.0f ) ); m_bboxs[3].add2d( Point2D( 0.0f, 1.2f ) ); // higher sliders m_bboxs[2].add2d( Point2D( 0.0, 0.0f ) ); m_bboxs[2].add2d( Point2D( 10.0f, 1.2f ) ); // highlight ON/OFF m_highlight = false; // everything (default) m_vrs.push_back( new ViewRegionManual( 0, 0, -1.0f, 1.0f, FALSE, FALSE ) ); // library m_vrs.push_back( new ViewRegionManual( -1.2, 0.0, -1.0, 0.0, TRUE, TRUE ) ); // lower sliders m_vrs.push_back( new ViewRegionManual( 0.0, 1.2, -1.0, 0.0, TRUE, TRUE ) ); // higher sliders m_vrs.push_back( new ViewRegionManual( 0.0, 1.2, 0.0, 1.0, TRUE, TRUE ) ); // matches m_vrs.push_back( new ViewRegionManual( -1.2, 0.0, 0.0, 1.0, TRUE, TRUE ) ); // set ids according to pushback order and desired location m_vr_library_id = 1; m_vr_values_id = 2; m_vr_weights_id = 3; m_vr_matches_id = 4; // feature database db = NULL; db_indices = NULL; db_distances = NULL; db_path = ""; db_filename = ""; // fog fog_mode[0] = 0; /*fog_mode[1] = GL_EXP; fog_mode[2] = GL_EXP2;*/ fog_mode[1] = GL_LINEAR; fog_filter = 0; fog_density = .035f; // log BB_log( BB_LOG_INFO, "num ui elements: %d", NUM_UI_ELEMENTS ); // pop log BB_poplog(); // set //if( !g_search_face ) // g_search_face = this; return TRUE; } //----------------------------------------------------------------------------- // name: destroy() // desc: ... //----------------------------------------------------------------------------- t_CKBOOL UISearch::destroy( ) { this->on_deactivate( 0.0 ); m_id = Audicle::NO_FACE; m_state = INACTIVE; SAFE_DELETE( db ); SAFE_DELETE_ARRAY( db_indices ); SAFE_DELETE_ARRAY( db_distances ); return TRUE; } //----------------------------------------------------------------------------- // name: render() // desc: ... //----------------------------------------------------------------------------- t_CKUINT UISearch::render( void * data ) { // render each pane render_library_pane(); render_matches_pane(); render_weights_pane(); render_values_pane(); // buttons (currently homeless) draw_button( *ui_elements[BT_LOAD_DB], 0.2, -0.05, 0.0, .5, .5, 1.0, IMG_LOAD ); draw_button( *ui_elements[BT_FIND], 0.35, -0.05, 0.0, .8, .8, .8, IMG_FIND ); draw_button( *ui_elements[BT_ADD_DB], 0.5, -0.05, 0.0, .7, .7, .5, IMG_UPARROW ); draw_button( *ui_elements[BT_ADD], 0.65, -0.05, 0.0, .7, .6, .5, IMG_LOAD ); draw_button( *ui_elements[BT_LISTEN], 0.8, -0.05, 0.0, 0.5, 1.0, 0.5, IMG_PLAY ); draw_button( *ui_elements[BT_STOP], 0.95, -0.05, 0.0, 1.0, 0.5, 0.5, IMG_STOP ); // bouncing play button if( selected != NULL && selected->core != NULL ) ui_elements[BT_LISTEN]->on = selected->core->playing(); else ui_elements[BT_LISTEN]->on = false; // rotate g_r += 1.0; // highlighting glDisable( GL_LIGHTING ); if( m_highlight && m_cur_bbox >= 0 && m_cur_bbox < m_nbboxs ) { Point3D p1 = m_bboxs[m_cur_bbox].pmin(); Point3D p2 = m_bboxs[m_cur_bbox].pmax(); glPushMatrix(); glTranslatef( 0.0f, 0.0f, -0.5f ); glColor3f( 0.7f, 0.9f, 1.0f ); glBegin( GL_QUADS ); glVertex2f( p1[0], p1[1] ); glVertex2f( p2[0], p1[1] ); glVertex2f( p2[0], p2[1] ); glVertex2f( p1[0], p2[1] ); glEnd(); glPopMatrix(); } glEnable( GL_LIGHTING ); return 0; } //----------------------------------------------------------------------------- // name: render_library_pane() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_library_pane() { assert( m_vr_library_id >= 0 && m_vr_library_id < m_vrs.size() ); ViewRegion * lib = m_vrs[m_vr_library_id]; Spectre color; color.r = color.g = color.b = 0.0f; float x_offset = 0.15f, y_offset = 0.2f; draw_library( selected, NULL, lib->left() + x_offset, lib->down() + y_offset, lib->right() - x_offset, lib->up() - y_offset, &color ); } //----------------------------------------------------------------------------- // name: render_weights_pane() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_weights_pane() { assert( m_vr_weights_id >= 0 && m_vr_weights_id < m_vrs.size() ); ViewRegion * wei = m_vrs[m_vr_weights_id]; glPushMatrix(); glTranslatef( wei->left(), wei->down(), 0.0f ); // sliders ui_elements[SL_WEI_A]->offset = draw_slider_mini( *ui_elements[SL_WEI_A], 0.2f, .25f, 0.0f ); ui_elements[SL_WEI_B]->offset = draw_slider_mini( *ui_elements[SL_WEI_B], 0.4f, .25f, 0.0f ); ui_elements[SL_WEI_C]->offset = draw_slider_mini( *ui_elements[SL_WEI_C], 0.6f, .25f, 0.0f ); ui_elements[SL_WEI_D]->offset = draw_slider_mini( *ui_elements[SL_WEI_D], 0.8f, .25f, 0.0f ); ui_elements[SL_WEI_E]->offset = draw_slider_mini( *ui_elements[SL_WEI_E], 1.0f, .25f, 0.0f ); // pane name glPushMatrix(); glTranslatef( (wei->right() - wei->left()) / 2, wei->up() - wei->down() - 0.25f, 0.0f ); glColor3f( g_text_color[0], g_text_color[1], g_text_color[2] ); scaleFont( .035 ); glLineWidth( 2.0f ); drawString_centered( "feature weights" ); glLineWidth( 1.0f ); glPopMatrix(); glPopMatrix(); } //----------------------------------------------------------------------------- // name: render_matches_pane() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_matches_pane() { assert( m_vr_matches_id >= 0 && m_vr_matches_id < m_vrs.size() ); ViewRegion * mat = m_vrs[m_vr_matches_id]; float x_offset = 0.15f, y_offset = -0.2f, y_inc = -0.07; float x_button = mat->right() - 0.7*x_offset - mat->left(), y_button = mat->down() - 0.5*y_offset - mat->up(); Spectre color; color.r = 0.5; color.g = 0.3; color.b = 0.1; char char_buffer[128]; glPushMatrix(); glTranslatef( mat->left(), mat->up(), 0.0f ); // button draw_button( *ui_elements[BT_TOGGLE_VIEW], x_button, y_button, 0.0f, .5f, .5f, 1.0f, IMG_TOG ); // list view if( m_list_view ) { for( int m = 0; mat->up() + y_offset + y_inc * m > mat->down() - y_offset; m++ ) { // load match template if necessary if( m >= Library::matches()->size() ) // if it needs loading if( !load_match( m ) || m >= Library::matches()->size() ) // if it couldn't load or is an invalid index break; // forget it // draw template draw_template( x_offset, y_offset+y_inc*m, Library::matches()->templates[m], true, 0.0f, &color ); // draw box if( selected == Library::matches()->templates[m] ) { glPushMatrix(); glTranslatef( x_offset, y_offset+y_inc*m, 0.0f ); float width = .085f, height = .085f; glLineWidth( 2.0 ); glColor3f( color.r, color.g, color.b ); glBegin( GL_LINE_LOOP ); glVertex2f( -width/2.0f, -height/2.0f ); glVertex2f( -width/2.0f, height/2.0f ); glVertex2f( width/2.0f, height/2.0f ); glVertex2f( width/2.0f, -height/2.0f ); glEnd(); glLineWidth( 1.0 ); glColor3f( g_text_color[0], g_text_color[1], g_text_color[2] ); glPopMatrix(); } // draw distance sprintf( char_buffer, "%.3f", db_distances[m] ); glPushMatrix(); glTranslatef( (mat->right() - mat->left())/2, y_offset+y_inc*m-0.01, 0.0f ); scaleFont( 0.025 ); drawString( char_buffer ); glPopMatrix(); } } // 3D? hmm. else { int my_name = -1, feature_x, feature_y, feature_z; float x, y, z, vr_mid_x, vr_mid_y, vr_mid_z; // midpoint of view region vr_mid_x = (mat->right() - mat->left()) / 2; vr_mid_y = (mat->up() - mat->down()) / 2 - (mat->up() - mat->down()); vr_mid_z = (10 - 2.3)/2; if( !xyz_center_init ) { x_center = vr_mid_x; y_center = vr_mid_y; z_center = vr_mid_z; xyz_center_init = true; } // select features/sliders feature_x = 0; feature_y = 1; feature_z = 2; // draw matches glPushMatrix(); // center around selected if available if( m_center && selected && selected->core->features ) { // find center x_center = g_num_features > 0 ? selected->core->features[0] : 0; y_center = g_num_features > 1 ? selected->core->features[1] : 0; z_center = g_num_features > 2 ? selected->core->features[2] : 0; // map to this view region x_center = offset_in_range( selected->core->features[feature_x], ui_elements[SL_VAL_A + feature_x]->slide_0, ui_elements[SL_VAL_A + feature_x]->slide_1, mat->left(), mat->right() ); y_center = offset_in_range( selected->core->features[feature_y], ui_elements[SL_VAL_A + feature_y]->slide_0, ui_elements[SL_VAL_A + feature_y]->slide_1, mat->down(), mat->up() ); y_center = y_center - (mat->up() - mat->down()); z_center = offset_in_range( selected->core->features[feature_z], ui_elements[SL_VAL_A + feature_z]->slide_0, ui_elements[SL_VAL_A + feature_z]->slide_1, 2.3, 10 ); m_center = false; } // each match glEnable( GL_NORMALIZE ); // global transformation (to run from clip plane) glTranslatef( -.6f, 0.45f, -2.0f ); glTranslatef( 0.25*vr_mid_x, 0.6*vr_mid_y, -0.25*vr_mid_z ); // multiplied to make up for perspective // rotate glRotatef( ui_elements[SL_ROTATE_H]->fvalue(), 0.0f, 1.0f, 0.0f ); glRotatef( ui_elements[SL_ROTATE_V]->fvalue(), -1.0f, 0.0f, 0.0f ); for( int m = 0; m < (int)ui_elements[SL_NUM_MATCHES]->fvalue(); m++ ) { // load match template if necessary if( m >= Library::matches()->size() ) // if it needs loading if( !load_match( m ) || m >= Library::matches()->size() ) // if it couldn't load or is an invalid index break; // forget it // draw template UI_Template * ui_temp = Library::matches()->templates[m]; // no, first load features into template if( !ui_temp->core->features ) { int filenum = db_indices[m]; load_features_from_db( ui_temp->core, filenum ); } // now draw? // scale features between left and right x = offset_in_range( ui_temp->core->features[feature_x], ui_elements[SL_VAL_A + feature_x]->slide_0, ui_elements[SL_VAL_A + feature_x]->slide_1, mat->left(), mat->right() ); // same for y between top and bottom y = offset_in_range( ui_temp->core->features[feature_y], ui_elements[SL_VAL_A + feature_y]->slide_0, ui_elements[SL_VAL_A + feature_y]->slide_1, mat->down(), mat->up() ); // also move y down to get final value y = y - (mat->up() - mat->down()); // same for z z = offset_in_range( ui_temp->core->features[feature_z], ui_elements[SL_VAL_A + feature_z]->slide_0, ui_elements[SL_VAL_A + feature_z]->slide_1, 2.3, 10 ); // getting there... glPushMatrix(); // weights float weight_x = ui_elements[SL_WEI_A + feature_x]->fvalue(); float weight_y = ui_elements[SL_WEI_A + feature_y]->fvalue(); float weight_z = ui_elements[SL_WEI_A + feature_z]->fvalue(); // zoom float zoom = ui_elements[SL_ZOOM]->fvalue(); glTranslatef( 0, 0, weight_z*zoom*(z_center-z) ); x = weight_x*(x - x_center); y = weight_y*(y - y_center); // scale const float constant = 2.0f; glScalef( constant, constant, constant ); // draw template! draw_template( zoom*x, zoom*y, ui_temp, false, 0.0f, &color ); // don't draw name // draw box if( selected == Library::matches()->templates[m] ) { glPushMatrix(); glTranslatef( zoom*x, zoom*y, 0.0f ); float width = .065f; glLineWidth( 2.0 ); glColor3f( color.r, color.g, color.b ); glutWireCube( width ); glLineWidth( 1.0 ); glColor3f( g_text_color[0], g_text_color[1], g_text_color[2] ); glPopMatrix(); my_name = m; } glPopMatrix(); } glDisable( GL_NORMALIZE ); glPopMatrix(); // end of draw matches // draw selected's name if( my_name != -1 ) { sprintf( char_buffer, "%s (%.3f)", selected->core->name.c_str(), db_distances[my_name] ); glPushMatrix(); glTranslatef( x_offset, y_offset, 0.0f ); glLineWidth( 2.0f ); scaleFont( 0.025 ); glDisable( GL_LIGHTING ); glColor3f( color.r, color.g, color.b ); drawString( char_buffer ); glColor3f( g_text_color[0], g_text_color[1], g_text_color[2] ); glEnable( GL_LIGHTING ); glLineWidth( 1.0f ); glPopMatrix(); } // draw additional controls draw_button( *ui_elements[BT_CENTER], x_button - .15, y_button, 0.0f, .7f, .5f, .5f, IMG_CENTER ); ui_elements[SL_ROTATE_H]->offset = draw_slider_h_mini( *ui_elements[SL_ROTATE_H], x_button - g_slider_height_mini - .3f, y_button -.01f, 0.0f ); ui_elements[SL_ROTATE_V]->offset = draw_slider_mini( *ui_elements[SL_ROTATE_V], x_button, y_button + .25f, 0.0f ); ui_elements[SL_ZOOM]->offset = draw_slider_h_mini( *ui_elements[SL_ZOOM], x_button - 2 * g_slider_height_mini - .35f, y_button -.01f, 0.0f ); ui_elements[SL_NUM_MATCHES]->offset = draw_slider_mini( *ui_elements[SL_NUM_MATCHES], x_button - .15f, y_button + .25f, 0.0f ); } glPopMatrix(); } //----------------------------------------------------------------------------- // name: render_values_pane() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_values_pane() { assert( m_vr_values_id >= 0 && m_vr_values_id < m_vrs.size() ); ViewRegion * val = m_vrs[m_vr_values_id]; glPushMatrix(); glTranslatef( val->left(), val->down(), 0.0f ); // sliders ui_elements[SL_VAL_A]->offset = draw_slider_mini( *ui_elements[SL_VAL_A], 0.2f, .25f, 0.0f ); ui_elements[SL_VAL_B]->offset = draw_slider_mini( *ui_elements[SL_VAL_B], 0.4f, .25f, 0.0f ); ui_elements[SL_VAL_C]->offset = draw_slider_mini( *ui_elements[SL_VAL_C], 0.6f, .25f, 0.0f ); ui_elements[SL_VAL_D]->offset = draw_slider_mini( *ui_elements[SL_VAL_D], 0.8f, .25f, 0.0f ); ui_elements[SL_VAL_E]->offset = draw_slider_mini( *ui_elements[SL_VAL_E], 1.0f, .25f, 0.0f ); // pane name glPushMatrix(); glTranslatef( (val->right() - val->left()) / 2, val->up() - val->down() - 0.28f, 0.0f ); glColor3f( g_text_color[0], g_text_color[1], g_text_color[2] ); scaleFont( .035 ); glLineWidth( 2.0f ); drawString_centered( "feature values" ); glLineWidth( 1.0f ); glPopMatrix(); glPopMatrix(); } //----------------------------------------------------------------------------- // name: render_pre() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_pre() { AudicleFace::render_pre(); glPushAttrib( GL_LIGHTING_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // enable depth glEnable( GL_DEPTH_TEST ); // enable lighting glEnable( GL_LIGHTING ); // enable light 0 glEnable( GL_LIGHT0 ); // material have diffuse and ambient lighting glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE ); // enable color glEnable( GL_COLOR_MATERIAL ); // setup and enable light 1 glLightfv( GL_LIGHT1, GL_AMBIENT, m_light1_ambient ); glLightfv( GL_LIGHT1, GL_DIFFUSE, m_light1_diffuse ); glLightfv( GL_LIGHT1, GL_SPECULAR, m_light1_specular ); glEnable( GL_LIGHT1 ); } //----------------------------------------------------------------------------- // name: render_post() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_post() { glPopAttrib(); AudicleFace::render_post(); } //----------------------------------------------------------------------------- // name: render_view() // desc: ... //----------------------------------------------------------------------------- void UISearch::render_view( ) { if( m_first ) { // set again m_vr.init( *m_vrs[0] ); m_first = false; } // set the matrix mode to project glMatrixMode( GL_PROJECTION ); // load the identity matrix // this is handled by AudicleWindow, in order to set up pick matrices... // you can assume that LoadIdentity has been called already // glLoadIdentity( ); // create the viewing frustum //gluPerspective( 45.0, (GLfloat) AudicleWindow::main()->m_w / // (GLfloat) AudicleWindow::main()->m_h, 1.0, 300.0 ); if( m_list_view ) glOrtho( m_vr.left(), m_vr.right(), m_vr.down(), m_vr.up(), -10, 10 ); else glFrustum( m_vr.left(), m_vr.right(), m_vr.down(), m_vr.up(), 2.44f, 10.0f ); m_vr.next(); // set the matrix mode to modelview glMatrixMode( GL_MODELVIEW ); // load the identity matrix glLoadIdentity( ); // position the view point gluLookAt( 0.0f, 0.0f, 2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f ); // set the position of the lights glLightfv( GL_LIGHT0, GL_POSITION, m_light0_pos ); glLightfv( GL_LIGHT1, GL_POSITION, m_light1_pos ); } //----------------------------------------------------------------------------- // name: on_activate() // desc: ... //----------------------------------------------------------------------------- t_CKUINT UISearch::on_activate() { // set text color g_text_color[0] = 0.0f; g_text_color[1] = 0.0f; g_text_color[2] = 0.0f; // check if selected has been deleted? int i; bool found = false; for( i = 0; !found && i < Library::instance()->size(); i++ ) if( Library::instance()->templates[i] == selected ) found = true; for( i = 0; !found && i < Library::matches()->size(); i++ ) if( Library::matches()->templates[i] == selected ) found = true; if( !found) selected = NULL; // fog GLfloat fogColor[4]= {0.5f, 0.5f, 0.5f, 1.0f}; // Fog Color if( fog_filter ) glFogi(GL_FOG_MODE, fog_mode[fog_filter]); // Fog Mode glFogfv(GL_FOG_COLOR, fogColor); // Set Fog Color glFogf(GL_FOG_DENSITY, fog_density); // How Dense Will The Fog Be glHint(GL_FOG_HINT, GL_DONT_CARE); // Fog Hint Value glFogf(GL_FOG_START, 5.0f); // Fog Start Depth glFogf(GL_FOG_END, 5.5f); // Fog End Depth if( fog_filter ) glEnable(GL_FOG); // audicle stuff return AudicleFace::on_activate(); } //----------------------------------------------------------------------------- // name: on_deactivate() // desc: ... //----------------------------------------------------------------------------- t_CKUINT UISearch::on_deactivate( t_CKDUR dur ) { glDisable(GL_FOG); return AudicleFace::on_deactivate( dur ); } //----------------------------------------------------------------------------- // name: on_event() // desc: ... //----------------------------------------------------------------------------- t_CKUINT UISearch::on_event( const AudicleEvent & event ) { static t_CKUINT m_mouse_down = FALSE; static t_CKUINT which = 0; static Point2D last; t_CKBOOL hit = FALSE; t_CKBOOL somewhere = FALSE; // danger Point2D diff; int i, j; if( event.type == ae_event_INPUT ) { InputEvent * ie = (InputEvent *)event.data; if( ie->type == ae_input_MOUSE ) { ie->popStack(); for( i = 0; i < NUM_UI_ELEMENTS; i++ ) { if( ie->checkID( ui_elements[i]->id ) ) { if( ie->state == ae_input_DOWN ) { hit = TRUE; last_hit_pos = ie->pos; ui_elements[i]->down = TRUE; // sliders if( i >= SL_VAL_A && i <= SL_VAL_E ) { float y_offset = m_vrs[m_vr_values_id]->down() + ui_elements[i]->offset; ui_elements[i]->slide_last = ( vr_to_world_y(m_vr,ie->pos[1]) - y_offset ) / g_slider_height_mini; } if( i >= SL_WEI_A && i <= SL_WEI_E ) { float y_offset = m_vrs[m_vr_weights_id]->down() + ui_elements[i]->offset; ui_elements[i]->slide_last = ( vr_to_world_y(m_vr,ie->pos[1]) - y_offset ) / g_slider_height_mini; } if( i >= SL_ROTATE_H && i <= SL_ZOOM ) { float x_offset = m_vrs[m_vr_matches_id]->left() + ui_elements[i]->offset; ui_elements[i]->slide_last = ( vr_to_world_x(m_vr,ie->pos[0]) - x_offset ) / g_slider_height_mini; } if( i >= SL_ROTATE_V && i <= SL_NUM_MATCHES ) { float y_offset = m_vrs[m_vr_matches_id]->up() + ui_elements[i]->offset; ui_elements[i]->slide_last = ( vr_to_world_y(m_vr,ie->pos[1]) - y_offset ) / g_slider_height_mini; } } if( ie->state == ae_input_UP && ui_elements[i]->down == TRUE ) { // flippers, buttons switch( i ) { case BT_FIND: // search based on selected library template { // this was a templategrabber test, but seems useful TemplateGrabber tg( 3 * BirdBrain::srate() ); if( selected ) { Frame * f = new Frame; tg.grab( selected->core, f ); AudioSrcFrame * matlab = new AudioSrcFrame( f ); AudioCentral::instance()->bus(2)->play( matlab ); } // clear things to prevent nasty happenings if( selected_from_matches ) selected = NULL; if( !Library::matches()->clear() ) msg_box( "no", "could not clear" ); // do actual finding and draw somewhere if( db ) { // load weights from sliders float weights[5]; // hard-coded. boo. for( j = 0; j < 5; j++ ) weights[j] = ui_elements[SL_WEI_A + j]->fvalue(); db->setWeights( weights ); // get target values float targets[5]; // hard-coded. boo. for( j = 0; j < 5; j++ ) targets[j] = ui_elements[SL_VAL_A + j]->fvalue(); // match db->rankClosestFiles( targets, db_indices, db_distances ); BB_log( BB_LOG_INFO, "Closest index: %i", db_indices[0] ); // enter into matches library? :| for( j = 0; j < 1; j++ ) { load_match( j ); } // select top match if( Library::matches()->size() > 0 ) { selected = Library::matches()->templates[0]->orig; selected_from_matches = true; load_features_from_db( selected->core, db_indices[0] ); load_sliders = true; m_center = true; } } else msg_box( "wait", "first pick a features database"); break; } case BT_ADD: // add selected matched sound effect to library if( selected && selected_from_matches && !Library::instance()->has( selected->core ) ) Library::instance()->add( selected->core->copy() ); else if( !selected ) msg_box( "Stop confusing me", "Nothing is selected!!" ); else if( !selected_from_matches ) msg_box( "No no no", "Load from matches (above) to library (below)" ); else BB_log( BB_LOG_INFO, "Template already in library; not adding" ); break; case BT_ADD_DB: // add selected template to database if( db ) { if( selected && !selected_from_matches ) { // log BB_log( BB_LOG_INFO, "add-db: '%s'...", selected->core->name.c_str() ); string path = db_path + "/tapsfiles/" + selected->core->name + ".tap"; BB_log( BB_LOG_INFO, "add-db path: '%s'...", path.c_str() ); // write Writer w; if( w.open( (char *)path.c_str() ) ) { w.write_template( selected->core ); w.close(); } else { msg_box( "ding!", "cannot open file for writing!" ); } if( selected->core->features ) { // adding to database db->addFile( selected->core->name.c_str(), selected->core->features, true ); } else { msg_box( "But", "Selected template has no features!!" ); } // path path = db_path + "/" + db_filename + ".fli"; BB_log( BB_LOG_INFO, "add-db updating FLI file: '%s'...", path.c_str() ); // write the faile db->writeFLIFile( path.c_str() ); } else if( !selected ) msg_box( "Stop confusing me", "Nothing is selected!!" ); else if( selected_from_matches ) msg_box( "No no no", "Add-db from library (below) to database (above)" ); } else { msg_box( "Okay", "Load a database first" ); } break; case BT_LOAD_DB: // load "feature library" / database { DirScanner dScan; dScan.setFileTypes( "Database files (*.fli)\0*.fli\0" ); fileData * fD = dScan.openFileDialog(); if( fD ) { SAFE_DELETE( db ); db = new FeatureLibrary( (char *)(fD->fileName.c_str()) ); if( db ) { g_num_features = db->getNumFeats(); BB_log( BB_LOG_INFO, "loaded feature database, apparently; %i features", g_num_features ); // assign space for matching SAFE_DELETE_ARRAY( db_indices ); db_indices = new int[db->size()]; SAFE_DELETE_ARRAY( db_distances ); db_distances = new float[db->size()]; // set path db_path = BirdBrain::getpath( fD->fileName.c_str() ); // set filename db_filename = BirdBrain::getname( fD->fileName.c_str() ); // clear earlier matches for( j = 0; selected && j < Library::matches()->size(); j++ ) if( selected == Library::matches()->templates[j] ) selected = NULL; Library::matches()->clear(); // update slider names for( j = 0; j < g_num_features && j < 5; j++ ) { ui_elements[SL_VAL_A + j]->name = db->getFeatureName( j ); ui_elements[SL_WEI_A + j]->name = db->getFeatureName( j ); } for( j = g_num_features; j < 5; j++ ) { ui_elements[SL_VAL_A + j]->name = "null"; ui_elements[SL_WEI_A + j]->name = "null"; ui_elements[SL_VAL_A + j]->set_slide( 0 ); } // update slider values load_sliders = true; // update max number of matches displayed in 3D view ui_elements[SL_NUM_MATCHES]->set_bounds(1, db->size(), true ); ui_elements[SL_NUM_MATCHES]->set_slide( db->size() / 2 ); // clear library template features? // makes limited sense since template features depend on RegionComparer // rather than database // but g_num_features depends on database, so safer this way (in case it increases) for( j = 0; j < Library::instance()->size(); j++ ) { Library::instance()->templates[j]->core->clear_features(); } } else { BB_log( BB_LOG_INFO, "could not open feature database %s", fD->fileName.c_str() ); } } break; } case BT_TOGGLE_VIEW: m_list_view = !m_list_view; break; case BT_CENTER: m_center = true; break; case BT_LISTEN: if( selected != NULL ) play_template( selected ); else msg_box( "aren't you paying attention?", "select something first!" ); break; case BT_STOP: if( selected != NULL ) selected->core->stop(); break; default: break; } } if( ie->state == ae_input_UP ) { // place events on timeline } } // if checkid // button up if( ie->state == ae_input_UP && ui_elements[i]->down ) ui_elements[i]->down = FALSE; } // check templates t_CKBOOL nulldown = FALSE; hit = check_library_event( ie, Library::instance(), nulldown ) || hit; hit = check_library_event( ie, Library::matches(), nulldown ) || hit; // background if( hit == FALSE ) { if( ie->state == ae_input_DOWN ) { which = !!(ie->mods & ae_input_CTRL); m_mouse_down = TRUE; last = ie->pos; } else { m_mouse_down = FALSE; } } // mouse up in background (hopefully) if( somewhere == FALSE && ie->state != ae_input_DOWN ) { } // END of mouse up in background // danger if( nulldown ) down = NULL; } // END OF ae_input_MOUSE else if( ie->type == ae_input_MOTION ) { handle_motion_event( ie ); } // end of ae_input_MOTION else if( ie->type == ae_input_KEY ) { handle_keyboard_event( ie->key ); } // end of ae_input_KEY // load sliders? if( load_sliders && selected ) { // get features /*if( db && !selected->core->features ) { int filenum = db->getFileNum( selected->core->name.c_str() ); BB_log( BB_LOG_INFO, "File num %i for %s", filenum, selected->core->name.c_str() ); load_features_from_db( selected->core, filenum ); }*/ if( !selected->core->features ) { extract_features( selected->core ); } // load sliders if( selected->core->features ) for( j = 0; j < g_num_features; j++ ) ui_elements[SL_VAL_A + j]->set_slide( selected->core->features[j] ); load_sliders = false; } } return AudicleFace::on_event( event ); } // what to do if something a ui_temp from a library is hit t_CKBOOL UISearch::check_library_event( InputEvent *ie, Library *lib, t_CKBOOL &released ) { t_CKBOOL hit = FALSE; for( int j = 0; j < lib->size(); j++ ) { // if a template is selected if( ie->checkID( lib->templates[j]->id ) ) { UI_Template * ui_temp_j = lib->templates[j]; if( ie->state == ae_input_DOWN ) { hit = TRUE; last_hit_pos = ie->pos; down = ui_temp_j; orig_pt = curr_pt = vr_to_world(m_vr,ie->pos); ui_temp_j->down = TRUE; } if( ie->state == ae_input_UP && ui_temp_j->down == TRUE ) { // right button: just play if( ie->button == ae_input_RIGHT_BUTTON ) { UI_Template * me = ui_temp_j->orig; if( me->core->playing() ) { me->core->stop(); BB_log( BB_LOG_INFO, "Stopping template" ); } else { play_template( me ); BB_log( BB_LOG_INFO, "Playing template" ); } } // other button: select else { selected = ui_temp_j->orig; selected_from_matches = (lib == Library::matches()); load_sliders = true; } } } // button up if( ie->state == ae_input_UP && lib->templates[j]->down ) { lib->templates[j]->down = FALSE; released = TRUE; } } return hit; } // handle keyboard events t_CKBOOL UISearch::handle_keyboard_event( char key ) { t_CKBOOL valid = TRUE; switch( key ) { case 8: // backspace if( selected != NULL ) { if( selected->core->playing() ) { BB_log( BB_LOG_INFO, "Stopping template in preparation for deletion" ); selected->core->stop(); while( selected->core->playing() ) usleep( 5000 ); } BB_log( BB_LOG_INFO, "Deleting template %s (0x%x)...", selected->core->name.c_str(), selected ); } break; case ' ': if( selected != NULL ) play_template( selected ); break; case 'h': case 'H': m_highlight = !m_highlight; BB_log( BB_LOG_INFO, "Highlighting %s", m_highlight ? "ON" : "OFF" ); break; //case 'r': //case 'R': // g_show_slider_range = !g_show_slider_range; // BB_log( BB_LOG_INFO, "%showing ranges of sliders", g_show_slider_range ? "S" : "Not s" ); // :) // break; case 'q': case 'z': g_show_qz = !g_show_qz; BB_log( BB_LOG_INFO, "%showing quantization markers", g_show_qz ? "S" : "Not s" ); break; case '0': case 27: // escape m_vr.setDest( *m_vrs[0] ); break; case '1': case '2': case '3': case '4': { long index = key - '0'; m_vr.setDest( m_vr.m_dest == m_vrs[index] ? *m_vrs[0] : *m_vrs[index] ); } break; // temp case 'r': m_bg[0] -= 0.1; if( m_bg[0] < 0 ) m_bg[0] = 0; BB_log( BB_LOG_INFO, "rgb: %f %f %f", m_bg[0], m_bg[1], m_bg[2] ); break; case 'R': m_bg[0] += 0.1; if( m_bg[0] > 1 ) m_bg[0] = 1; BB_log( BB_LOG_INFO, "rgb: %f %f %f", m_bg[0], m_bg[1], m_bg[2] ); break; case 'g': m_bg[1] -= 0.1; if( m_bg[1] < 0 ) m_bg[1] = 0; BB_log( BB_LOG_INFO, "rgb: %f %f %f", m_bg[0], m_bg[1], m_bg[2] ); break; case 'G': m_bg[1] += 0.1; if( m_bg[1] > 1 ) m_bg[1] = 1; BB_log( BB_LOG_INFO, "rgb: %f %f %f", m_bg[0], m_bg[1], m_bg[2] ); break; case 'b': m_bg[2] -= 0.1; if( m_bg[2] < 0 ) m_bg[2] = 0; BB_log( BB_LOG_INFO, "rgb: %f %f %f", m_bg[0], m_bg[1], m_bg[2] ); break; case 'B': m_bg[2] += 0.1; if( m_bg[2] > 1 ) m_bg[2] = 1; BB_log( BB_LOG_INFO, "rgb: %f %f %f", m_bg[0], m_bg[1], m_bg[2] ); break; // fog case 'F': fog_filter++; if( fog_filter > 1 ) fog_filter = 0; if( fog_filter ) { // log BB_log( BB_LOG_INFO, "fog: ON" ); glFogi(GL_FOG_MODE, fog_mode[fog_filter]); // Fog Mode glEnable(GL_FOG); } else { // log BB_log( BB_LOG_INFO, "fog: OFF" ); glDisable(GL_FOG); } break; // density case '<': fog_density *= .95f; BB_log( BB_LOG_INFO, "fog density: %f", fog_density ); glFogf(GL_FOG_DENSITY, fog_density); break; case '>': fog_density *= 1.05f; BB_log( BB_LOG_INFO, "fog density: %f", fog_density ); glFogf(GL_FOG_DENSITY, fog_density); break; default: valid = FALSE; break; } return valid; } // handle motion events t_CKBOOL UISearch::handle_motion_event( InputEvent * ie ) { t_CKBOOL nothing = TRUE; int i; // fix sliders for( i = SL_VAL_A; i <= SL_VAL_E; i++ ) { if( ui_elements[i]->down ) { float y_offset = m_vrs[m_vr_values_id]->down() + ui_elements[i]->offset; fix_slider_motion( *ui_elements[i], m_vr, ie->pos, y_offset, g_slider_height_mini, true ); nothing = FALSE; } } // fix more sliders for( i = SL_WEI_A; i <= SL_WEI_E; i++ ) { if( ui_elements[i]->down ) { float y_offset = m_vrs[m_vr_weights_id]->down() + ui_elements[i]->offset; fix_slider_motion( *ui_elements[i], m_vr, ie->pos, y_offset, g_slider_height_mini, true ); nothing = FALSE; } } // and more for( i = SL_ROTATE_H; i <= SL_ZOOM; i++ ) { if( ui_elements[i]->down ) { float x_offset = m_vrs[m_vr_matches_id]->left() + ui_elements[i]->offset; fix_slider_motion( *ui_elements[i], m_vr, ie->pos, x_offset, g_slider_height_mini, false ); nothing = FALSE; } } for( i = SL_ROTATE_V; i <= SL_NUM_MATCHES; i++ ) { if( ui_elements[i]->down ) { float y_offset = m_vrs[m_vr_matches_id]->up() + ui_elements[i]->offset; fix_slider_motion( *ui_elements[i], m_vr, ie->pos, y_offset, g_slider_height_mini, true ); nothing = FALSE; } } // highlighting... if( nothing ) { m_cur_bbox = -1; for( int b = 0; b < m_nbboxs; b++ ) if( m_bboxs[b].in( vr_to_world(m_vr, ie->pos ) ) ) { m_cur_bbox = b; break; } } // ... if( down ) { prev_pt = curr_pt; curr_pt = vr_to_world(m_vr,ie->pos); } // why?!? return TRUE; } void UISearch::play_template( UI_Template * playme ) { assert( playme->core != NULL ); if( playme->core->playing() ) { playme->core->stop(); while( playme->core->playing() ) usleep( 5000 ); } // start over, taking parameters into account playme->core->recompute(); AudioCentral::instance()->bus(2)->play( playme->core ); } // load features from given database file index into given template t_CKBOOL UISearch::load_features_from_db( Template * temp, int index ) { if( temp && db && index >= 0 && index < db->size() ) { const float * tmpfeats = db->getFeatureVec( index ); temp->clear_features(); temp->features = new float[g_num_features]; for( int j = 0; j < g_num_features; j++ ) temp->features[j] = tmpfeats[j]; return TRUE; } else return FALSE; } // extract features for given template in real-time t_CKBOOL UISearch::extract_features( Template * temp ) { t_CKBOOL okay = FALSE; if( temp ) { TemplateGrabber tg( 3 * BirdBrain::srate() ); Frame grabbed; okay = tg.grab( selected->core, &grabbed ); if( okay ) { std::vector<float> featvec; RegionComparer::getFeatures( grabbed, featvec ); temp->clear_features(); temp->features = new float[g_num_features]; for( int j = 0; j < g_num_features; j++ ) if( j < featvec.size() ) temp->features[j] = featvec[j]; } } return okay; } // load match from given index t_CKBOOL UISearch::load_match( int index ) { // initial checks if( !db || index < 0 || index >= db->size() || db_indices[index] < 0 || db_indices[index] >= db->size() ) return FALSE; int oldsize = Library::matches()->size(); if( db->isTemplate( db_indices[index] ) ) { // read taps file std::string filename = BirdBrain::getname( db->getFileName( db_indices[index] ) ); filename = db_path + "/tapsfiles/" + filename + ".tap"; const char * c = filename.c_str(); Reader r; if( r.open( (char *)c ) ) { Template * tmp = r.read_template(); r.close(); if( tmp != NULL ) Library::matches()->add( tmp ); } else msg_box( "ding!", "cannot open file for reading!" ); } else { // read sound file std::string filename = db->getFileName( db_indices[index] ); //BB_log( BB_LOG_INFO, "Reading %s as sound file", filename.c_str() ); File * file = new File( db_path + "/rawfiles/" + filename ); file->name = BirdBrain::getname( filename.c_str() ); Library::matches()->add( file ); } return (Library::matches()->size() > oldsize); } // map given value in [val_low, val_high] to [low, high] // return offset from low in [low, high] instead of actual value in [low, high] float offset_in_range( float value, float val_low, float val_high, float low, float high ) { assert( low < high ); assert( val_low < val_high ); return (value - val_low) / (val_high - val_low) * (high - low); // + low for actual mapping }
[ [ [ 1, 1424 ] ] ]
f6e487c0e150ca014b4ae884b6652da48b4cd082
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCNetLib/SolidSBCPacketConfigResponse.cpp
3f8822b4ea8a0dfa116abd7f41e2fdffb9e77f5e
[]
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
390
cpp
#include "StdAfx.h" #include "SolidSBCPacketConfigResponse.h" CSolidSBCPacketConfigResponse::CSolidSBCPacketConfigResponse(const CString& sXml) : CSolidSBCPacket() { ParseXml(sXml); } CSolidSBCPacketConfigResponse::CSolidSBCPacketConfigResponse(const PBYTE pPacket) : CSolidSBCPacket(pPacket) { } CSolidSBCPacketConfigResponse::~CSolidSBCPacketConfigResponse(void) { }
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 18 ] ] ]
c6762badf612bc92e74f9cb2ac7cdb1cc3377542
7e6ec7aa30a113650f66e8f945d0b6a2ded825d5
/Source/ThetaG.h
f349a9b527053b3d4520195e66e89b032bc99531
[]
no_license
quanpla/xloops-ginac
d1db82c0de54a8894deecc99de936488248049d0
b8d2487ed07da49aa7b7b9e5a054040209734f34
refs/heads/master
2020-05-18T03:52:57.026251
2009-09-13T14:38:44
2009-09-13T14:38:44
32,206,011
1
0
null
null
null
null
UTF-8
C++
false
false
415
h
#ifndef __XLOOPS_ONELOOP_4PT_THETAGFUNCTION_H__ #define __XLOOPS_ONELOOP_4PT_THETAGFUNCTION_H__ #include <ginac/ginac.h> using namespace std; using namespace GiNaC; namespace xloops{ ex ThetaG(const ex &a, const ex &b, const ex &x, const ex &y); ex ThetaGC(const ex &a, const ex &b, const ex &c, const ex &x, const ex &y); } // Namespace xloops #endif // __XLOOPS_ONELOOP_4PT_THETAGFUNCTION_H__
[ "anhquan.phanle@d83109c4-a28d-11dd-9dc9-65bc890fb60a" ]
[ [ [ 1, 13 ] ] ]
dce00b80fa487809472dbf0ce38cd3e25c4959d9
b625515fcaaa5ff9ed05ff79970b85d4a4c82e74
/SkyBox.cpp
da12545f2a09b95fc5b0535f1f9a987079629e31
[]
no_license
aznjustinx/opengl3dmaze
8f409d17b33f675e8345aeba128b865d8839660a
f51aa18a2cfff411251b27e45c5474a75a946fd8
refs/heads/master
2016-09-06T16:03:17.827891
2009-12-03T21:38:55
2009-12-03T21:38:55
33,142,332
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
cpp
#include "SkyBox.h" SkyBox::SkyBox(void) { glGenTextures(SKY_MAX_TEXTURES, g_skyTextures); main::loadImage(g_skyTextures[TEX_SKY], ".\\stars.jpg"); } SkyBox::~SkyBox(void) { } void SkyBox::update() { } void SkyBox::display() { main::materialColor(1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.); glBindTexture( GL_TEXTURE_2D, g_skyTextures[TEX_SKY] ); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glPushMatrix(); glTranslatef(-5, 7, 5); main::makePlate(SKY_WIDTH, SKY_HEIGHT, SKY_NR_OF_VERTS, SKY_NR_OF_VERTS, SKY_WIDTH/2, SKY_HEIGHT/2); glPopMatrix(); glPushMatrix(); glTranslatef(30, 7, 5); glRotatef(90, 0., 1., 0.); main::makePlate(SKY_WIDTH, SKY_HEIGHT, SKY_NR_OF_VERTS, SKY_NR_OF_VERTS, SKY_WIDTH/2, SKY_HEIGHT/2); glPopMatrix(); glPushMatrix(); glTranslatef(-5, 7, -30); glRotatef(-90, 0., 1., 0.); main::makePlate(SKY_WIDTH, SKY_HEIGHT, SKY_NR_OF_VERTS, SKY_NR_OF_VERTS, SKY_WIDTH/2, SKY_HEIGHT/2); glPopMatrix(); glPushMatrix(); glTranslatef(-5, SKY_HEIGHT + 7, -30); glRotatef(180, 1., 0., 0.); main::makePlate(SKY_WIDTH, SKY_HEIGHT, SKY_NR_OF_VERTS, SKY_NR_OF_VERTS, SKY_WIDTH/2, SKY_HEIGHT/2); glPopMatrix(); }
[ "[email protected]@46c2c806-c88e-11de-9233-4169c94807ec" ]
[ [ [ 1, 42 ] ] ]
0d3014aede9fa27ef2df6bebe9ff160354ffc8ce
89b01aac84d7ace68526f3619b872e52bd9e8160
/BattleCube/src/Projectile.cpp
c232837df8ffe79f4a2ae98cdb8b2a7215170e0f
[]
no_license
shekibobo/BattleCube
f9692ce628c76fc78e8887c92630625ec3756547
97b71aa7663d4edd9805573363875a8e58674c23
refs/heads/master
2021-01-10T18:34:14.214360
2011-04-26T17:40:43
2011-04-26T17:40:43
1,485,440
0
0
null
null
null
null
UTF-8
C++
false
false
2,438
cpp
#include "../include/Projectile.h" #include "../include/Drone.h" #include "../include/World.h" #define GRAVITY 0.015 GLubyte projectileTexture[340][340][3]; Projectile::Projectile(World* world) { //ctor setTexture(); m_pWorld = world; Player* player = Env()->GetPlayer(); SetPos(player->GetPosX(), player->GetPosY(), player->GetPosZ()); SetDir(player->GetLookX() - Posx(), player->GetLookY() - Posy() + 0.2, player->GetLookZ() - Posz()); m_size = 2.0; Setcolor(1.0, 0.0, 0.0, 0.6); } Projectile::~Projectile() { //dtor } void Projectile::Move() { Setposx(Posx() + Dirx() * SPEED); Setposy(Posy() + Diry() * SPEED); Setposz(Posz() + Dirz() * SPEED); GLfloat xbound = Env()->GetWallLength() / 2.0; if (Posx() <= -xbound + Size() || Posx() >= xbound - Size()) { Setdirx(0); //Setdirx(-Dirx()); Setdirz(0); } if (Posz() <= -xbound + Size() || Posz() >= xbound - Size()) { Setdirx(0); //Setdirx(-Dirx()); Setdirz(0); } if (Posy() <= Env()->FloorPos()) Stop(); if (Dirx() == 0 && Dirz() == 0) { SetSize(Size() + 2); } Setdiry(Diry() - GRAVITY); } void Projectile::Draw() { const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0; const double a = t*90.0; glPushMatrix(); glColor4fv(m_color); glEnable(GL_TEXTURE_2D); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 340, 340, 0, GL_RGB, GL_UNSIGNED_BYTE, projectileTexture); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glTranslatef(Posx(), Posy(), Posz()); glRotatef(a, 1.0, 0.0, 0.0); glutSolidSphere(Size(), 12, 12); glutWireSphere(Size(), 12, 12); glDisable(GL_TEXTURE_2D); glDisable(GL_TEXTURE_GEN_S); glDisable(GL_TEXTURE_GEN_T); glPopMatrix(); } void Projectile::setTexture() { int i, j; unsigned char data[3]; FILE *fp; char file[256] = "plasma.dat"; if((fp = fopen(file, "rb")) == NULL) { printf("file not found"); exit(0); } for(i = 0; i < 340; i++){ for(j = 0; j < 340; j++){ fread(data, sizeof(unsigned char), 3, fp); projectileTexture[i][j][0] = (GLubyte) data[0]; projectileTexture[i][j][1] = (GLubyte) data[1]; projectileTexture[i][j][2] = (GLubyte) data[2]; } } }
[ [ [ 1, 1 ], [ 5, 11 ], [ 13, 57 ], [ 59, 59 ], [ 63, 66 ], [ 71, 72 ], [ 74, 74 ], [ 78, 79 ], [ 87, 89 ] ], [ [ 2, 4 ], [ 12, 12 ], [ 58, 58 ], [ 60, 62 ], [ 67, 70 ], [ 73, 73 ], [ 75, 77 ], [ 80, 86 ], [ 90, 92 ] ] ]
6790b1c9ebdcf32b6f733ad9a6e1f144b78674b6
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/mario.h
683e69e1aef9d8a3f632e54f7a5f6464afdfb54a
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,080
h
#ifndef MARIO_H_ #define MARIO_H_ /* * From the schematics: * * Video generation like dkong/dkongjr. However, clock is 24MHZ * 7C -> 100 => 256 - 124 = 132 ==> 264 Scanlines */ #define MASTER_CLOCK XTAL_24MHz #define PIXEL_CLOCK (MASTER_CLOCK / 4) #define CLOCK_1H (MASTER_CLOCK / 8) #define CLOCK_16H (CLOCK_1H / 16) #define CLOCK_1VF ((CLOCK_16H) / 12 / 2) #define CLOCK_2VF ((CLOCK_1VF) / 2) #define HTOTAL (384) #define HBSTART (256) #define HBEND (0) #define VTOTAL (264) #define VBSTART (240) #define VBEND (16) #define Z80_MASTER_CLOCK XTAL_8MHz #define Z80_CLOCK (Z80_MASTER_CLOCK / 2) /* verified on pcb */ #define I8035_MASTER_CLOCK XTAL_11MHz /* verified on pcb: 730Khz */ #define I8035_CLOCK (I8035_MASTER_CLOCK) #define MARIO_PALETTE_LENGTH (256) class mario_state : public driver_device { public: mario_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ /* machine states */ /* sound state */ UINT8 m_last; UINT8 m_portT; const char *m_eabank; /* video state */ UINT8 m_gfx_bank; UINT8 m_palette_bank; UINT16 m_gfx_scroll; UINT8 m_flip; /* driver general */ UINT8 *m_spriteram; UINT8 *m_videoram; size_t m_spriteram_size; tilemap_t *m_bg_tilemap; int m_monitor; }; /*----------- defined in video/mario.c -----------*/ WRITE8_HANDLER( mario_videoram_w ); WRITE8_HANDLER( mario_gfxbank_w ); WRITE8_HANDLER( mario_palettebank_w ); WRITE8_HANDLER( mario_scroll_w ); WRITE8_HANDLER( mario_flip_w ); PALETTE_INIT( mario ); VIDEO_START( mario ); SCREEN_UPDATE( mario ); /*----------- defined in audio/mario.c -----------*/ WRITE8_DEVICE_HANDLER( mario_sh1_w ); WRITE8_DEVICE_HANDLER( mario_sh2_w ); WRITE8_HANDLER( mario_sh3_w ); WRITE8_HANDLER( mario_sh_tuneselect_w ); WRITE8_HANDLER( masao_sh_irqtrigger_w ); MACHINE_CONFIG_EXTERN( mario_audio ); MACHINE_CONFIG_EXTERN( masao_audio ); #endif /*MARIO_H_*/
[ "Mike@localhost" ]
[ [ [ 1, 88 ] ] ]
5a4bcfce0e3219c60a064fd9307ece079c4016b9
3276915b349aec4d26b466d48d9c8022a909ec16
/数据结构/串/模式匹配/顺序串的kmp算法--上机习题2.cpp
a55b233a4742c2ffd3f79549754b55dd92f46c0f
[]
no_license
flyskyosg/3dvc
c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82
0279b1a7ae097b9028cc7e4aa2dcb67025f096b9
refs/heads/master
2021-01-10T11:39:45.352471
2009-07-31T13:13:50
2009-07-31T13:13:50
48,670,844
0
0
null
null
null
null
GB18030
C++
false
false
2,064
cpp
#include<iostream> #include<string.h> using namespace std; #define maxlen 255 typedef char SString[maxlen+1]; int index_kmp(SString S,SString T,int pos,int next[]) //1<=pos<=strlen(s); { int i=pos,j=1,n=0; while(i<=S[0]-0x30 && j<=T[0]-0x30) { cout<<S[i]<<T[j]<<++n<<endl; if(j==0||S[i]==T[j]) { i++;j++; } else { j=next[j]; } } if(j>T[0]-0x30) { return i-T[0]+0x30; } else return 0; } void getnext(char T[],int next[]) { int i=1,j=0, n=0;next[1]=0; while(i<T[0]-0x30) { if(j==0 ||T[i]==T[j]) { i++;j++;next[i]=j; } else { j=next[j]; } } } void getnextval(char T[],int nextval[]) { int i=1;nextval[1]=0;int j=0,n=0; while(i<T[0]-0x30) { if(j==0||T[i]==T[j]) { i++;j++; if(T[i]!=T[j]) nextval[i]=j; else nextval[i]=nextval[j]; } else { j=nextval[j]; } } } void main() { SString S,T;int pos,next[maxlen];char a; do { cout<<"input master str:输入格式:长度,相应数量的字符:"; cin>>S; cout<<"input master str:输入格式:长度,相应数量的字符:"; cin>>T; cout<<S<<" "<<T<<endl; for(int i=0;i<=T[0]-0x30;i++) { cout<<"next["<<i<<"]="<<next[i]<<" "; } cout<<endl; getnext(T,next); for( i=1;i<=T[0]-0x30;i++) { cout<<"\nnext["<<i<<"]="<<next[i]; } cout<<"\ninput pos="; cin>>pos;cout<<endl; cout<<index_kmp(S,T,pos,next)<<endl; cout<<"继续进行修正匹配的吗?是,请按回车"<<endl; fflush(stdin); cin>>a; if(a=='\xA') { getnextval(T,next); for(i=1;i<=T[0]-0x30;i++) cout<<"\nnextval["<<i<<"]"<<"="<<next[i]; cout<<"\ninput pos="; cin>>pos;cout<<endl; cout<<index_kmp(S,T,pos,next)<<endl; } cout<<"继续吗?是,按回车!"<<endl; fflush(stdin); cin>>a; }while(a=='\xA'); }
[ [ [ 1, 185 ] ] ]
afd3a44fbf22182d02b320182c8571b48837a2ff
3e69b159d352a57a48bc483cb8ca802b49679d65
/branches/bokeoa-scons/include/drawpanel_wxstruct.h
6c83997d2845ee100ebaca003f2374bc4394028e
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,058
h
/****************************************************/ /* drawpanel_wxstruct.h: */ /* descriptions des principales classes utilisees: */ /* ici classe: "WinEDA_DrawPanel", "BASE_SCREEN" */ /*****************************************************/ /* Doit etre inclus dans "wxstruch.h" */ #ifndef PANEL_WXSTRUCT_H #define PANEL_WXSTRUCT_H #ifndef eda_global #define eda_global extern #endif /****************************************************/ /* classe representant un ecran graphique de dessin */ /****************************************************/ class WinEDA_DrawPanel: public EDA_DRAW_PANEL { public: int m_Ident; WinEDA_DrawFrame * m_Parent; EDA_Rect m_ClipBox; /* position et taille de la fenetre de trace pour les "RePaint" d'ecran */ wxPoint m_CursorStartPos; // utile dans controles du mouvement curseur int m_Scroll_unit; // Valeur de l'unite de scroll en pixels pour les barres de scroll int m_ScrollButt_unit; // Valeur de l'unite de scroll en pixels pour les boutons de scroll bool m_AbortRequest; // Flag d'arret de commandes longues bool m_AbortEnable; // TRUE si menu ou bouton Abort doit etre affiche bool m_AutoPAN_Enable; // TRUE pour autoriser auto pan (autorisation générale) bool m_AutoPAN_Request; // TRUE pour auto pan (lorsque auto pan nécessaire) bool m_IgnoreMouseEvents; // TRUE pour ne par traiter les evenements souris bool m_Block_Enable; // TRUE pour autoriser Bloc Commandes (autorisation générale) int m_CanStartBlock; // >= 0 (ou >= n) si un bloc peut demarrer // (filtrage des commandes de debut de bloc ) int m_PanelDefaultCursor; // Current mouse cursor default shape id for this window int m_PanelCursor; // Current mouse cursor shape id for this window public: // Constructor and destructor WinEDA_DrawPanel(WinEDA_DrawFrame *parent, int id, const wxPoint& pos, const wxSize& size); ~WinEDA_DrawPanel(void){} /****************************/ BASE_SCREEN * GetScreen(void) { return m_Parent->m_CurrentScreen; } void PrepareGraphicContext(wxDC * DC); wxPoint CalcAbsolutePosition(const wxPoint & rel_pos); bool IsPointOnDisplay(wxPoint ref_pos); void OnPaint(wxPaintEvent & event); void OnSize(wxSizeEvent & event); void SetBoundaryBox(void); void ReDraw(wxDC * DC, bool erasebg = TRUE); void PrintPage(wxDC * DC, bool Print_Sheet_Ref, int PrintMask); void DrawBackGround(wxDC * DC); void m_Draw_Auxiliary_Axe(wxDC * DC, int drawmode); void OnEraseBackground(wxEraseEvent& event); void OnActivate(wxActivateEvent& event); /* Mouse and keys events */ void OnMouseEvent(wxMouseEvent& event); void OnMouseLeaving(wxMouseEvent& event); void OnKeyEvent(wxKeyEvent& event); /*************************/ void EraseScreen(wxDC * DC); void OnScrollWin( wxCommandEvent &event ); void OnScroll( wxScrollWinEvent &event ); void SetZoom(int mode); int GetZoom(void); void SetGrid(const wxSize & size); wxSize GetGrid(void); void AddMenuZoom( wxMenu * MasterMenu ); void OnRightClick(wxMouseEvent& event); void Process_Popup_Zoom( wxCommandEvent &event ); void Process_Special_Functions(wxCommandEvent& event); wxPoint CursorRealPosition(const wxPoint & ScreenPos); wxPoint CursorScreenPosition(void); wxPoint GetScreenCenterRealPosition(void); void MouseToCursorSchema(void); void MouseTo(const wxPoint & Mouse); DECLARE_EVENT_TABLE() }; /**************************/ /* class DrawBlockStruct */ /**************************/ /* Definition d'un block pour les fonctions sur block (block move, ..) */ typedef enum { /* definition de l'etat du block */ STATE_NO_BLOCK, /* Block non initialise */ STATE_BLOCK_INIT, /* Block initialise: 1er point defini */ STATE_BLOCK_END, /* Block initialise: 2eme point defini */ STATE_BLOCK_MOVE, /* Block en deplacement */ STATE_BLOCK_STOP /* Block fixe (fin de deplacement) */ } BlockState; /* codes des differentes commandes sur block: */ typedef enum { BLOCK_IDLE, BLOCK_MOVE, BLOCK_COPY, BLOCK_SAVE, BLOCK_DELETE, BLOCK_PASTE, BLOCK_DRAG, BLOCK_ROTATE, BLOCK_INVERT, BLOCK_ZOOM, BLOCK_ABORT, BLOCK_PRESELECT_MOVE, BLOCK_SELECT_ITEMS_ONLY, BLOCK_MIRROR_X, BLOCK_MIRROR_Y } CmdBlockType; class DrawBlockStruct: public EDA_BaseStruct, public EDA_Rect { public: BlockState m_State; /* Etat (enum BlockState) du block */ CmdBlockType m_Command; /* Type (enum CmdBlockType) d'operation */ EDA_BaseStruct *m_BlockDrawStruct; /* pointeur sur la structure selectionnee dans le bloc */ int m_Color; /* Block Color */ wxPoint m_MoveVector; /* Move distance in move, drag, copy ... command */ wxPoint m_BlockLastCursorPosition; /* Last Mouse position in block command = last cursor position in move commands = 0,0 in block paste */ public: DrawBlockStruct(void); ~DrawBlockStruct(void); void SetMessageBlock(WinEDA_DrawFrame * frame); void Draw(WinEDA_DrawPanel * panel, wxDC * DC); }; /*******************************************************************/ /* Class to handle how to draw a screen (a board, a schematic ...) */ /*******************************************************************/ class BASE_SCREEN: public EDA_BaseStruct { public: int m_Type; /* indicateur: type d'ecran */ WinEDA_DrawFrame * m_FrameSource; // Used to get useful datas (internal units ...) wxPoint m_DrawOrg; /* offsets pour tracer le circuit sur l'ecran */ wxPoint m_Curseur; /* Screen cursor coordinate (on grid) in user units. */ wxPoint m_MousePosition; /* Mouse cursor coordinate (off grid) in user units. */ wxPoint m_O_Curseur; /* Relative Screen cursor coordinate (on grid) in user units. (coordinates from last reset position)*/ wxPoint m_ScrollbarPos; // Position effective des Curseurs de scroll wxSize m_ScrollbarNumber; /* Valeur effective des Nombres de Scrool c.a.d taille en unites de scroll de la surface totale affichable */ wxPoint m_StartVisu; // Coord absolues du 1er pixel visualisé a l'ecran (en nombre de pixels) wxSize m_SizeVisu; /* taille en pixels de l'ecran (fenetre de visu Utile pour recadrer les affichages lors de la navigation dans la hierarchie */ bool m_Center; // TRUE: coord algebriques, FALSE: coord >= 0 int m_GridColor; bool m_FirstRedraw; /* Cursor management (shape, editing functions) */ void (*ManageCurseur)(WinEDA_DrawPanel * panel, wxDC * DC, bool erase); /* Fonction d'affichage sur deplacement souris si erase : effacement ancien affichage */ void (*ForceCloseManageCurseur)(WinEDA_DrawFrame * frame,wxDC * DC); /* Fonction de fermeture forcée de la fonction ManageCurseur */ int m_CurseurShape; /* indique une option de forme */ /* Gestion des editions */ EDA_BaseStruct *EEDrawList; /* Object list (main data) for schematic */ EDA_BaseStruct * m_UndoList; /* Object list for the undo command (old data) */ EDA_BaseStruct * m_RedoList; /* Object list for the redo command (old data) */ int m_UndoRedoCountMax; /* undo/Redo command Max depth */ EDA_BaseStruct * m_CurrentItem; /* Current selected object */ /* block control */ DrawBlockStruct BlockLocate; /* Bock description for block commands */ /* Page description */ Ki_PageDescr * m_CurrentSheet; int m_SheetNumber, m_NumberOfSheet; /* gestion hierarchie: numero de sousfeuille et nombre de feuilles. Root: SheetNumber = 1 */ wxString m_FileName; wxString m_Title; /* titre de la feuille */ wxString m_Date; /* date de mise a jour */ wxString m_Revision; /* code de revision */ wxString m_Company; /* nom du proprietaire */ wxString m_Commentaire1; wxString m_Commentaire2; wxString m_Commentaire3; wxString m_Commentaire4; private: /* indicateurs divers */ char m_FlagRefreshReq; /* indique que l'ecran doit redessine */ char m_FlagModified; // indique modif du PCB,utilise pour eviter une sortie sans sauvegarde char m_FlagSave; // indique sauvegarde auto faite /* Valeurs du pas de grille et du zoom */ public: wxSize m_Grid ; /* pas de la grille (peut differer en X et Y) */ wxSize * m_GridList; /* Liste des valeurs standard de grille */ wxRealPoint m_UserGrid; /* pas de la grille utilisateur */ int m_UserGridUnit; /* unité grille utilisateur (0 = inch, 1 = mm */ int m_Diviseur_Grille ; bool m_UserGridIsON; int * m_ZoomList; /* Liste des coefficients standard de zoom */ int m_Zoom ; /* coeff de ZOOM */ public: BASE_SCREEN(EDA_BaseStruct * parent, WinEDA_DrawFrame * frame_source, int idscreen); ~BASE_SCREEN(void); BASE_SCREEN * Next(void) { return (BASE_SCREEN *) Pnext; } void InitDatas(void); /* Inits completes des variables */ void SetParentFrame(WinEDA_DrawFrame * frame_source); WinEDA_DrawFrame * GetParentFrame(void); wxSize ReturnPageSize(void); int GetInternalUnits(void); /* general Undo/Redo command control */ virtual void ClearUndoRedoList(void); virtual void AddItemToUndoList(EDA_BaseStruct * item); virtual void AddItemToRedoList(EDA_BaseStruct * item); virtual EDA_BaseStruct * GetItemFromUndoList(void); virtual EDA_BaseStruct * GetItemFromRedoList(void); /* Manipulation des flags */ void SetRefreshReq(void) { m_FlagRefreshReq = 1; } void ClrRefreshReq(void) { m_FlagRefreshReq = 0; } void SetModify(void) { m_FlagModified = 1; m_FlagSave = 0; } void ClrModify(void) { m_FlagModified = 0; m_FlagSave = 1; } void SetSave(void) { m_FlagSave = 1; } void ClrSave(void) { m_FlagSave = 0; } int IsModify(void) { return (m_FlagModified & 1); } int IsRefreshReq(void) { return (m_FlagRefreshReq & 1); } int IsSave(void) { return (m_FlagSave & 1); } /* fonctions relatives au zoom */ int GetZoom(void); /* retourne le coeff de zoom */ void SetZoom(int coeff) ; /* ajuste le coeff de zoom a coeff */ void SetZoomList(int * zoomlist); /* init liste des zoom (NULL terminated) */ void SetNextZoom(void); /* ajuste le prochain coeff de zoom */ void SetPreviousZoom(void); /* ajuste le precedent coeff de zoom */ void SetFirstZoom(void); /* ajuste le coeff de zoom a 1*/ void SetLastZoom(void); /* ajuste le coeff de zoom au max */ /* fonctions relatives a la grille */ wxSize GetGrid(void); /* retourne la grille */ void SetGrid(const wxSize & size); void SetGridList(wxSize * sizelist); /* init liste des grilles (NULL terminated) */ void SetNextGrid(void); /* ajuste le prochain coeff de grille */ void SetPreviousGrid(void); /* ajuste le precedent coeff de grille */ void SetFirstGrid(void); /* ajuste la grille au mini*/ void SetLastGrid(void); /* ajuste la grille au max */ /* fonctions relatives au curseur*/ void Trace_Curseur(WinEDA_DrawPanel * panel, wxDC * DC); // trace du curseur sur grille }; #endif /* PANEL_WXSTRUCT_H */
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 273 ] ] ]
9361abe56b39969ac201a868685f59e862098f3a
d504537dae74273428d3aacd03b89357215f3d11
/src/Renderer/Dx10/RendererDx10.cpp
6371307390b7fbbbf30cdc5c5bc35f3953c5a676
[]
no_license
h0MER247/e6
1026bf9aabd5c11b84e358222d103aee829f62d7
f92546fd1fc53ba783d84e9edf5660fe19b739cc
refs/heads/master
2020-12-23T05:42:42.373786
2011-02-18T16:16:24
2011-02-18T16:16:24
237,055,477
1
0
null
2020-01-29T18:39:15
2020-01-29T18:39:14
null
UTF-8
C++
false
false
15,547
cpp
#include "../../e6/e6_impl.h" #include "../../e6/e6_math.h" #include "../../Core/Core.h" #include "../BaseRenderer.h" #include <windows.h> #include <d3d10.h> #include <d3dx10.h> #include <dxerr.h> using e6::uint; using e6::float2; using e6::float3; using e6::float4; using e6::float4x4; using e6::ClassInfo; #define COM_ADDREF(x) if((x)) (x)->AddRef(); #define COM_RELEASE(x) if((x)) (x)->Release(); (x)=0; #define E_TRACE(hr) if(hr!=0) printf( __FUNCTION__ " : DXERR %s(%x)\n", DXGetErrorString((hr)), (hr) ); namespace Dx10 { struct Shader { ID3D10VertexShader *shader; Shader() : shader(0) { } ~Shader() { } uint setup( Core::Shader* cvb, ID3D10Device* device ) { static const char * def_vs = "float4 VS( in float3 Pos : SV_POSITION ) : SV_POSITION" "{" " return float4(Pos,1);" "}\r\n\r\n"; ID3D10Blob *err = 0; ID3D10Blob *blob = 0; HRESULT hr = D3D10CompileShader( def_vs, // LPCSTR pSrcData, strlen( def_vs ), // SIZE_T SrcDataLen, "default", // LPCSTR pFileName, 0, // CONST D3D10_SHADER_MACRO *pDefines, 0, // LPD3D10INCLUDE *pInclude, "VS", // LPCSTR pFunctionName, "vs_4_0", // LPCSTR pProfile, 0, // UINT Flags, &blob, // ID3D10Blob **ppShader, &err // ID3D10Blob **ppErrorMsgs ); E_TRACE(hr); if ( FAILED(hr) ) { printf( __FUNCTION__ " : %s\n", (const char *) err->GetBufferPointer() ); COM_RELEASE( err ); COM_RELEASE( blob ); return 0; } hr = device->CreateVertexShader( blob->GetBufferPointer(), blob->GetBufferSize(), &shader ); E_TRACE(hr); COM_RELEASE( blob ); return SUCCEEDED(hr); } static void clear( Shader * b ) { COM_RELEASE(b->shader); delete b; } }; struct ShaderCache : BaseRenderer::Cache< Core::Shader*, Shader*, 500, Shader > { ShaderCache() {} ~ShaderCache() {} Shader * addShader( Core::Shader* cvb, ID3D10Device* device ) { Shader * vb = new Shader; vb->setup( cvb, device ); insert( cvb, vb ); return vb; } Shader * get( Core::Shader* cvb, ID3D10Device* device ) { //printf( "%s %s\n", __FUNCTION__, (m?m->getName():"nil")); Item * it = find( cvb ); if ( ! it || ! it->val ) { return addShader(cvb, device); } it->ttl = 500; return it->val; } }; struct VBuffer { ID3D10Buffer * vb; uint stride; uint nLayouts; D3D10_INPUT_ELEMENT_DESC layout[8]; VBuffer() : vb(0), stride(0), nLayouts(0) {} void setSemantic( char * name, DXGI_FORMAT fmt, uint vSize, uint semanticIndex=0 ) { D3D10_INPUT_ELEMENT_DESC & lo = layout[nLayouts]; lo.SemanticName = name; lo.SemanticIndex = semanticIndex; lo.Format = fmt; lo.InputSlot = nLayouts; lo.AlignedByteOffset = D3D10_APPEND_ALIGNED_ELEMENT; // stride; lo.InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA; lo.InstanceDataStepRate = 0; nLayouts++; stride += vSize; } uint setup( Core::VertexBuffer * cvb, ID3D10Device* device ) { HRESULT hr = 0; Core::VertexFeature * pos = cvb->getFeature( e6::VF_POS ); Core::VertexFeature * nor = cvb->getFeature( e6::VF_NOR ); Core::VertexFeature * col = cvb->getFeature( e6::VF_COL ); Core::VertexFeature * uv0 = cvb->getFeature( e6::VF_UV0 ); Core::VertexFeature * uv1 = cvb->getFeature( e6::VF_UV1 ); Core::VertexFeature * tan = cvb->getFeature( e6::VF_TAN ); // set stride & collect layout if ( pos ) { setSemantic( "POSITION", DXGI_FORMAT_R32G32B32_FLOAT, 3 ); } if ( nor ) { setSemantic( "NORMAL", DXGI_FORMAT_R32G32B32_FLOAT, 3 ); } if ( col ) { setSemantic( "COLOR", DXGI_FORMAT_R32_UINT, 1 ); ///PPP??? } if ( uv0 ) { setSemantic( "TEXCOORD0", DXGI_FORMAT_R32G32_FLOAT, 2 ); } if ( uv1 ) { setSemantic( "TEXCOORD1", DXGI_FORMAT_R32G32_FLOAT, 2, 1 ); } if ( tan ) { setSemantic( "TANGENT", DXGI_FORMAT_R32G32B32_FLOAT, 3 ); } // copy vb to flat float arr: uint nVerts = 3 * cvb->numFaces(); uint numFloats = nVerts * stride; float *pVertData = new float[ numFloats ]; if(!pVertData) return E_OUTOFMEMORY; float *pV = pVertData; float *v = 0; for ( uint i=0; i<nVerts; i++ ) { { v = (float*)pos->getElement( i ); *pV++ = *v++; *pV++ = *v++; *pV++ = *v++; } if ( nor ) { v = (float*)nor->getElement( i ); *pV++ = *v++; *pV++ = *v++; *pV++ = *v++; } if ( col ) { *(uint*)pV = *(uint*)uv0->getElement( i ); pV ++; } if ( uv0 ) { v = (float*)uv0->getElement( i ); *pV++ = *v++; *pV++ = *v++; } if ( uv1 ) { v = (float*)uv1->getElement( i ); *pV++ = *v++; *pV++ = *v++; } if ( tan ) { v = (float*)tan->getElement( i ); *pV++ = *v++; *pV++ = *v++; *pV++ = *v++; } } // Create a Vertex Buffer D3D10_BUFFER_DESC vbDesc; vbDesc.ByteWidth = numFloats*sizeof(float); vbDesc.Usage = D3D10_USAGE_DEFAULT; vbDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; vbDesc.CPUAccessFlags = 0; vbDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA vbInitData; vbInitData.pSysMem = pVertData; vbInitData.SysMemPitch = 0; vbInitData.SysMemSlicePitch = 0; hr = device->CreateBuffer( &vbDesc, &vbInitData, &vb ); E_TRACE( hr ); E_RELEASE( pos ); E_RELEASE( nor ); E_RELEASE( col ); E_RELEASE( uv0 ); E_RELEASE( uv1 ); E_RELEASE( tan ); E_DELETEA( pVertData ); //// Create our vertex input layout //const D3D10_INPUT_ELEMENT_DESC layout[] = //{ // { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, //}; //device->CreateInputLayout( layout, 1, pVSBuf->GetBufferPointer(), pVSBuf->GetBufferSize(), &g_pVertexLayout ); return SUCCEEDED(hr); } static void clear( VBuffer * b ) { COM_RELEASE(b->vb); delete b; } }; struct VertexCache : BaseRenderer::Cache< Core::VertexBuffer*, VBuffer*, 500, VBuffer > { VertexCache() {} ~VertexCache() {} VBuffer * addBuffer( Core::VertexBuffer* cvb, ID3D10Device* device ) { VBuffer * vb = new VBuffer; vb->setup( cvb, device ); insert( cvb, vb ); return vb; } VBuffer * get( Core::VertexBuffer* cvb, ID3D10Device* device ) { //printf( "%s %s\n", __FUNCTION__, (m?m->getName():"nil")); Item * it = find( cvb ); if ( ! it || ! it->val ) { return addBuffer(cvb, device); } it->ttl = 500; return it->val; } }; struct CRenderer : public e6::CName< Core::Renderer, CRenderer > { ID3D10Device* device; IDXGISwapChain* swapChain; ID3D10RenderTargetView* renderTargetView; ID3D10DepthStencilView* depthStencilView; ID3D10Texture2D* backBuffer; VertexCache vertexCache; ShaderCache shaderCache; HRESULT hr; CRenderer() : device(0) , swapChain(0) , renderTargetView(0) , depthStencilView(0) , backBuffer(0) , hr(0) { setName( "RendererDx10" ); } virtual ~CRenderer() { COM_RELEASE( backBuffer ); COM_RELEASE( renderTargetView ); COM_RELEASE( depthStencilView ); COM_RELEASE( swapChain ); COM_RELEASE( device ); } virtual uint init( const void *win, uint w, uint h ) { if ( ! device ) { vertexCache.clear(); shaderCache.clear(); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory( &sd, sizeof(sd) ); sd.BufferCount = 1; sd.BufferDesc.Width = w; sd.BufferDesc.Height = h; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = (HWND)win; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG; #endif D3D10_DRIVER_TYPE driverTypes[] = { D3D10_DRIVER_TYPE_HARDWARE, D3D10_DRIVER_TYPE_REFERENCE, }; uint numDriverTypes = sizeof(driverTypes) / sizeof(driverTypes[0]); for( uint driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ ) { hr = D3D10CreateDeviceAndSwapChain( NULL, driverTypes[driverTypeIndex], NULL, createDeviceFlags, D3D10_SDK_VERSION, &sd, &swapChain, &device ); if( SUCCEEDED( hr ) ) { char *ds[] = { "Hardware", "Software" }; printf( __FUNCTION__ " : created %s device.\n", ds[driverTypeIndex] ); break; } } if ( ! device ) { printf( __FUNCTION__ " : no device created !\n" ); return 0; } // Create a render target view hr = swapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), (LPVOID*)&backBuffer ); E_TRACE(hr); if( FAILED(hr) || (!backBuffer) ) { printf( __FUNCTION__ " : no BackBuffer !\n" ); return 0; } //hr = device->CreateDepthStencilView( backBuffer, NULL, NULL ); //if( hr != S_FALSE ) //{ // printf( __FUNCTION__ " : wrong backbuffer params for DepthStencilView !\n" ); // return 0; //} //hr = device->CreateDepthStencilView( backBuffer, NULL, &depthStencilView ); //E_TRACE(hr); //if( FAILED(hr) ) //{ // printf( __FUNCTION__ " : no depth buffer created !\n" ); // return 0; //} //printf( __FUNCTION__ " : depth buffer %x.\n", depthStencilView); //D3D10_TEXTURE2D_DESC tdesc; //backBuffer->GetDesc( &tdesc ); //D3D10_RENDER_TARGET_VIEW_DESC rtvdesc; //ZeroMemory(&rtvdesc, sizeof(D3D10_RENDER_TARGET_VIEW_DESC)); //rtvdesc.Format = tdesc.Format; //rtvdesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D; //hr = device->CreateRenderTargetView( backBuffer, &rtvdesc, NULL ); //hr = device->CreateRenderTargetView( backBuffer, NULL, NULL ); //E_TRACE(hr); //if( hr != S_FALSE ) //{ // printf( __FUNCTION__ " : wrong backbuffer params for render target !\n" ); // return 0; //} hr = device->CreateRenderTargetView( backBuffer, NULL, &renderTargetView ); E_TRACE(hr); if( FAILED(hr) ) { printf( __FUNCTION__ " : DXERR(%x) %s[%s]\n", (hr) , DXGetErrorString((hr)), DXGetErrorDescription((hr)) ); printf( __FUNCTION__ " : no render target created !\n" ); return 0; } printf( __FUNCTION__ " : render target %x.\n", renderTargetView ); device->OMSetRenderTargets( 1, &renderTargetView, NULL ); //return 1; } return reset( win,w,h ); } uint reset( const void * win, uint w, uint h ) { // Setup the viewport D3D10_VIEWPORT vp; vp.Width = w; vp.Height = h; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; device->RSSetViewports( 1, &vp ); return 1; } virtual void clear() { float ClearColor[4] = { 0.3f, 0.125f, 0.1f, 1.0f }; // red, green, blue, alpha device->ClearRenderTargetView( renderTargetView, ClearColor ); //// //// Clear the depth stencil //// //ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView(); //device->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 ); } virtual void swapBuffers() { hr = swapChain->Present( 0, 0 ); E_TRACE(hr); } virtual uint begin3D() { return 1; //NOT_IMPL } virtual uint setCamera( Core::Camera * cam ) { return 0; //NOT_IMPL } virtual uint setLight( uint n, Core::Light * light ) { return 0; //NOT_IMPL } virtual uint setMesh( Core::Mesh * mesh ) { if ( ! mesh ) return 0; Core::VertexBuffer * cvb = mesh->getBuffer(); VBuffer * dxvb = vertexCache.get( cvb, device ); // Set IA parameters UINT strides[1] = { dxvb->stride * sizeof(float) }; UINT offsets[1] = {0}; ID3D10Buffer* pBuffers[1] = { dxvb->vb }; device->IASetVertexBuffers( 0, 1, pBuffers, strides, offsets ); //device->IASetInputLayout( g_pVertexLayout ); //device->IASetIndexBuffer( g_pIB10, DXGI_FORMAT_R16_UINT, 0 ); device->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); // Bind the constant buffer to the device // pBuffers[0] = g_pConstantBuffer10; // hr = device->VSSetConstantBuffers( 0, 1, pBuffers ); E_TRACE(hr); // hr = device->OMSetBlendState(g_pBlendStateNoBlend, 0, 0xffffffff); E_TRACE(hr); // hr = device->RSSetState(g_pRasterizerStateNoCull); E_TRACE(hr); Core::Shader * cvs = mesh->getVertexShader(); device->VSSetShader( shaderCache.get( cvs, device )->shader ); E_RELEASE( cvs ); // device->GSSetShader( NULL ); // device->PSSetShader( NULL ); // hr = device->DrawIndexed( g_dwNumIndices, 0, 0 ); E_TRACE(hr); uint nVerts = mesh->numFaces() * 3; device->Draw( nVerts, 0 ); E_RELEASE(cvb); return 1; } virtual uint setRenderTarget( Core::Texture * tex ) { return 0; //NOT_IMPL } virtual uint setRenderState( uint key, uint value ) { return 0; //NOT_IMPL } virtual uint setVertexShaderConstant( uint i, const float4 & v ) { return 0; //NOT_IMPL } virtual uint setPixelShaderConstant( uint i, const float4 & v ) { return 0; //NOT_IMPL } virtual uint end3D() { return 1; //NOT_IMPL } virtual uint get( uint what ) { switch( what ) { //case e6::RF_CULL: return doCull; //case e6::RF_CCW: return doCCW; //case e6::RF_SHADE: return shadeMode; //case e6::RF_WIRE: return doWire; //case e6::RF_TEXTURE: return doTexture; //case e6::RF_LIGHTING: return doLighting; //case e6::RF_ALPHA: return doAlpha; //case e6::RF_ALPHA_TEST: return doAlphaTest; //case e6::RF_ZWRITE: return doZWrite; //case e6::RF_ZTEST: return doZTest; //case e6::RF_ZDEPTH: return zBufferDepth; //case e6::RF_SRCBLEND: return stateBlendSrc; //case e6::RF_DSTBLEND: return stateBlendDst; //case e6::RF_CLEAR_COLOR: return bgColor; //case e6::RF_CLEAR_BUFFER: return doClearBackBuffer; //case e6::RF_NUM_HW_TEX: return textureCache.cache.size(); case e6::RF_NUM_HW_VB : return vertexCache.cache.size(); case e6::RF_NUM_HW_VSH: return shaderCache.cache.size(); //case e6::RF_NUM_HW_PSH: return pixelShaderCache.cache.size(); } return 0; } virtual uint captureFrontBuffer( const char * fileName ) { return 0; //NOT_IMPL } }; // CRenderer }; // namespace Dx10 extern "C" uint getClassInfo( ClassInfo ** ptr ) { const static ClassInfo _ci[] = { { "Core.Renderer", "RendererDx10", Dx10::CRenderer::createInterface, Dx10::CRenderer::classRef }, { 0, 0, 0 }//, //0 }; *ptr = (ClassInfo *)_ci; return 1; // classses } #include "../../e6/version.h" extern "C" uint getVersion( e6::ModVersion * mv ) { mv->modVersion = ("RendererDx10 00.000.0023 (" __DATE__ ")"); mv->e6Version = e6::e6_version; return 1; }
[ [ [ 1, 610 ] ] ]
0ee50167b0f1ee630bd2ab4e99110238d9c18db0
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleAffectors/ParticleUniverseVelocityMatchingAffectorFactory.h
d194def434995f52387cb1d8559f7940d7cce2b2
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
1,949
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __PU_VELOCITY_MATCHING_AFFECTOR_FACTORY_H__ #define __PU_VELOCITY_MATCHING_AFFECTOR_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseAffectorFactory.h" #include "ParticleUniverseVelocityMatchingAffector.h" #include "ParticleUniverseVelocityMatchingAffectorTokens.h" namespace ParticleUniverse { /** Factory class responsible for creating the VelocityMatchingAffector. */ class _ParticleUniverseExport VelocityMatchingAffectorFactory : public ParticleAffectorFactory { public: VelocityMatchingAffectorFactory(void) {}; virtual ~VelocityMatchingAffectorFactory(void) {}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType() const { return "VelocityMatching"; } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { return _createAffector<VelocityMatchingAffector>(); } /** See ParticleAffectorFactory */ virtual void setupTokenDefinitions(ITokenRegister* tokenRegister) { // Delegate to mVelocityMatchingAffectorTokens mVelocityMatchingAffectorTokens.setupTokenDefinitions(tokenRegister); }; protected: VelocityMatchingAffectorTokens mVelocityMatchingAffectorTokens; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 59 ] ] ]
f7aa49ab911a5991c6f584e26d83417c5d05d8df
7476d2c710c9a48373ce77f8e0113cb6fcc4c93b
/RakNet/ReliabilityLayer.h
b15d2d7a4e7059ff8d1d044aebcea920e0ee1e2b
[]
no_license
CmaThomas/Vault-Tec-Multiplayer-Mod
af23777ef39237df28545ee82aa852d687c75bc9
5c1294dad16edd00f796635edaf5348227c33933
refs/heads/master
2021-01-16T21:13:29.029937
2011-10-30T21:58:41
2011-10-30T22:00:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,727
h
/// \file /// \brief \b [Internal] Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence. /// /// This file is part of RakNet Copyright 2003 Jenkins Software LLC /// /// Usage of RakNet is subject to the appropriate license agreement. /// Creative Commons Licensees are subject to the /// license found at /// http://creativecommons.org/licenses/by-nc/2.5/ /// Single application licensees are subject to the license found at /// http://www.jenkinssoftware.com/SingleApplicationLicense.html /// Custom license users are subject to the terms therein. /// GPL license users are subject to 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. #ifndef __RELIABILITY_LAYER_H #define __RELIABILITY_LAYER_H #include "RakMemoryOverride.h" #include "MTUSize.h" #include "DS_LinkedList.h" #include "DS_List.h" #include "SocketLayer.h" #include "PacketPriority.h" #include "DS_Queue.h" #include "BitStream.h" #include "InternalPacket.h" #include "RakNetStatistics.h" #include "SHA1.h" #include "DS_OrderedList.h" #include "DS_RangeList.h" #include "DS_BPlusTree.h" #include "DS_MemoryPool.h" #include "DS_Multilist.h" #include "RakNetDefines.h" #include "DS_Heap.h" #include "BitStream.h" #include "NativeFeatureIncludes.h" #include "SecureHandshake.h" #include "PluginInterface2.h" #include "Rand.h" #if USE_SLIDING_WINDOW_CONGESTION_CONTROL!=1 #include "CCRakNetUDT.h" #define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 1 #else #include "CCRakNetSlidingWindow.h" #define INCLUDE_TIMESTAMP_WITH_DATAGRAMS 0 #endif /// Number of ordered streams available. You can use up to 32 ordered streams #define NUMBER_OF_ORDERED_STREAMS 32 // 2^5 #define RESEND_TREE_ORDER 32 namespace RakNet { /// Forward declarations class PluginInterface2; class RakNetRandom; typedef uint64_t reliabilityHeapWeightType; // int SplitPacketIndexComp( SplitPacketIndexType const &key, InternalPacket* const &data ); struct SplitPacketChannel//<SplitPacketChannel> { CCTimeType lastUpdateTime; DataStructures::List<InternalPacket*> splitPacketList; #if PREALLOCATE_LARGE_MESSAGES==1 InternalPacket *returnedPacket; bool gotFirstPacket; unsigned int stride; unsigned int splitPacketsArrived; #else // This is here for progress notifications, since progress notifications return the first packet data, if available InternalPacket *firstPacket; #endif }; int RAK_DLL_EXPORT SplitPacketChannelComp( SplitPacketIdType const &key, SplitPacketChannel* const &data ); // Helper class struct BPSTracker { BPSTracker(); ~BPSTracker(); void Reset(const char *file, unsigned int line); inline void Push1(CCTimeType time, uint64_t value1) {dataQueue.Push(TimeAndValue2(time,value1),_FILE_AND_LINE_); total1+=value1; lastSec1+=value1;} // void Push2(RakNet::TimeUS time, uint64_t value1, uint64_t value2); inline uint64_t GetBPS1(CCTimeType time) {(void) time; return lastSec1;} inline uint64_t GetBPS1Threadsafe(CCTimeType time) {(void) time; return lastSec1;} // uint64_t GetBPS2(RakNetTimeUS time); // void GetBPS1And2(RakNetTimeUS time, uint64_t &out1, uint64_t &out2); uint64_t GetTotal1(void) const; // uint64_t GetTotal2(void) const; struct TimeAndValue2 { TimeAndValue2(); ~TimeAndValue2(); TimeAndValue2(CCTimeType t, uint64_t v1); // TimeAndValue2(RakNet::TimeUS t, uint64_t v1, uint64_t v2); // uint64_t value1, value2; uint64_t value1; CCTimeType time; }; uint64_t total1, lastSec1; // uint64_t total2, lastSec2; DataStructures::Queue<TimeAndValue2> dataQueue; void ClearExpired1(CCTimeType time); // void ClearExpired2(RakNet::TimeUS time); }; /// Datagram reliable, ordered, unordered and sequenced sends. Flow control. Message splitting, reassembly, and coalescence. class ReliabilityLayer//<ReliabilityLayer> { public: // Constructor ReliabilityLayer(); // Destructor ~ReliabilityLayer(); /// Resets the layer for reuse void Reset( bool resetVariables, int MTUSize, bool _useSecurity ); /// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable packet /// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug. /// \param[in] time Time, in MS void SetTimeoutTime( RakNet::TimeMS time ); /// Returns the value passed to SetTimeoutTime. or the default if it was never called /// \param[out] the value passed to SetTimeoutTime RakNet::TimeMS GetTimeoutTime(void); /// Packets are read directly from the socket layer and skip the reliability layer because unconnected players do not use the reliability layer /// This function takes packet data after a player has been confirmed as connected. /// \param[in] buffer The socket data /// \param[in] length The length of the socket data /// \param[in] systemAddress The player that this data is from /// \param[in] messageHandlerList A list of registered plugins /// \param[in] MTUSize maximum datagram size /// \retval true Success /// \retval false Modified packet bool HandleSocketReceiveFromConnectedPlayer( const char *buffer, unsigned int length, SystemAddress &systemAddress, DataStructures::List<PluginInterface2*> &messageHandlerList, int MTUSize, SOCKET s, RakNetRandom *rnr, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions, CCTimeType timeRead); /// This allocates bytes and writes a user-level message to those bytes. /// \param[out] data The message /// \return Returns number of BITS put into the buffer BitSize_t Receive( unsigned char**data ); /// Puts data on the send queue /// \param[in] data The data to send /// \param[in] numberOfBitsToSend The length of \a data in bits /// \param[in] priority The priority level for the send /// \param[in] reliability The reliability type for the send /// \param[in] orderingChannel 0 to 31. Specifies what channel to use, for relational ordering and sequencing of packets. /// \param[in] makeDataCopy If true \a data will be copied. Otherwise, only a pointer will be stored. /// \param[in] MTUSize maximum datagram size /// \param[in] currentTime Current time, as per RakNet::GetTimeMS() /// \param[in] receipt This number will be returned back with ID_SND_RECEIPT_ACKED or ID_SND_RECEIPT_LOSS and is only returned with the reliability types that contain RECEIPT in the name /// \return True or false for success or failure. bool Send( char *data, BitSize_t numberOfBitsToSend, PacketPriority priority, PacketReliability reliability, unsigned char orderingChannel, bool makeDataCopy, int MTUSize, CCTimeType currentTime, uint32_t receipt ); /// Call once per game cycle. Handles internal lists and actually does the send. /// \param[in] s the communication end point /// \param[in] systemAddress The Unique Player Identifier who shouldhave sent some packets /// \param[in] MTUSize maximum datagram size /// \param[in] time current system time /// \param[in] maxBitsPerSecond if non-zero, enforces that outgoing bandwidth does not exceed this amount /// \param[in] messageHandlerList A list of registered plugins void Update( SOCKET s, SystemAddress &systemAddress, int MTUSize, CCTimeType time, unsigned bitsPerSecondLimit, DataStructures::List<PluginInterface2*> &messageHandlerList, RakNetRandom *rnr, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions); /// Were you ever unable to deliver a packet despite retries? /// \return true means the connection has been lost. Otherwise not. bool IsDeadConnection( void ) const; /// Causes IsDeadConnection to return true void KillConnection(void); /// Get Statistics /// \return A pointer to a static struct, filled out with current statistical information. RakNetStatistics * GetStatistics( RakNetStatistics *rns ); ///Are we waiting for any data to be sent out or be processed by the player? bool IsOutgoingDataWaiting(void); bool AreAcksWaiting(void); // Set outgoing lag and packet loss properties void ApplyNetworkSimulator( double _maxSendBPS, RakNet::TimeMS _minExtraPing, RakNet::TimeMS _extraPingVariance ); /// Returns if you previously called ApplyNetworkSimulator /// \return If you previously called ApplyNetworkSimulator bool IsNetworkSimulatorActive( void ); void SetSplitMessageProgressInterval(int interval); void SetUnreliableTimeout(RakNet::TimeMS timeoutMS); /// Has a lot of time passed since the last ack bool AckTimeout(RakNet::Time curTime); CCTimeType GetNextSendTime(void) const; CCTimeType GetTimeBetweenPackets(void) const; RakNet::TimeMS GetTimeLastDatagramArrived(void) const {return timeLastDatagramArrived;} // If true, will update time between packets quickly based on ping calculations //void SetDoFastThroughputReactions(bool fast); // Encoded as numMessages[unsigned int], message1BitLength[unsigned int], message1Data (aligned), ... //void GetUndeliveredMessages(RakNet::BitStream *messages, int MTUSize); // Told of the system ping externally void OnExternalPing(double pingMS); private: /// Send the contents of a bitstream to the socket /// \param[in] s The socket used for sending data /// \param[in] systemAddress The address and port to send to /// \param[in] bitStream The data to send. void SendBitStream( SOCKET s, SystemAddress &systemAddress, RakNet::BitStream *bitStream, RakNetRandom *rnr, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions, CCTimeType currentTime); ///Parse an internalPacket and create a bitstream to represent this data /// \return Returns number of bits used BitSize_t WriteToBitStreamFromInternalPacket( RakNet::BitStream *bitStream, const InternalPacket *const internalPacket, CCTimeType curTime ); /// Parse a bitstream and create an internal packet to represent this data InternalPacket* CreateInternalPacketFromBitStream( RakNet::BitStream *bitStream, CCTimeType time ); /// Does what the function name says unsigned RemovePacketFromResendListAndDeleteOlderReliableSequenced( const MessageNumberType messageNumber, CCTimeType time, DataStructures::List<PluginInterface2*> &messageHandlerList, const SystemAddress &systemAddress ); /// Acknowledge receipt of the packet with the specified messageNumber void SendAcknowledgementPacket( const DatagramSequenceNumberType messageNumber, CCTimeType time); /// This will return true if we should not send at this time bool IsSendThrottled( int MTUSize ); /// We lost a packet void UpdateWindowFromPacketloss( CCTimeType time ); /// Increase the window size void UpdateWindowFromAck( CCTimeType time ); /// Parse an internalPacket and figure out how many header bits would be written. Returns that number BitSize_t GetMaxMessageHeaderLengthBits( void ); BitSize_t GetMessageHeaderLengthBits( const InternalPacket *const internalPacket ); /// Get the SHA1 code void GetSHA1( unsigned char * const buffer, unsigned int nbytes, char code[ SHA1_LENGTH ] ); /// Check the SHA1 code bool CheckSHA1( char code[ SHA1_LENGTH ], unsigned char * const buffer, unsigned int nbytes ); /// Search the specified list for sequenced packets on the specified ordering channel, optionally skipping those with splitPacketId, and delete them void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::List<InternalPacket*>&theList, int splitPacketId = -1 ); /// Search the specified list for sequenced packets with a value less than orderingIndex and delete them void DeleteSequencedPacketsInList( unsigned char orderingChannel, DataStructures::Queue<InternalPacket*>&theList ); /// Returns true if newPacketOrderingIndex is older than the waitingForPacketOrderingIndex bool IsOlderOrderedPacket( OrderingIndexType newPacketOrderingIndex, OrderingIndexType waitingForPacketOrderingIndex ); /// Split the passed packet into chunks under MTU_SIZE bytes (including headers) and save those new chunks void SplitPacket( InternalPacket *internalPacket ); /// Insert a packet into the split packet list void InsertIntoSplitPacketList( InternalPacket * internalPacket, CCTimeType time ); /// Take all split chunks with the specified splitPacketId and try to reconstruct a packet. If we can, allocate and return it. Otherwise return 0 InternalPacket * BuildPacketFromSplitPacketList( SplitPacketIdType splitPacketId, CCTimeType time, SOCKET s, SystemAddress &systemAddress, RakNetRandom *rnr, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions); InternalPacket * BuildPacketFromSplitPacketList( SplitPacketChannel *splitPacketChannel, CCTimeType time ); /// Delete any unreliable split packets that have long since expired //void DeleteOldUnreliableSplitPackets( CCTimeType time ); /// Creates a copy of the specified internal packet with data copied from the original starting at dataByteOffset for dataByteLength bytes. /// Does not copy any split data parameters as that information is always generated does not have any reason to be copied InternalPacket * CreateInternalPacketCopy( InternalPacket *original, int dataByteOffset, int dataByteLength, CCTimeType time ); /// Get the specified ordering list DataStructures::LinkedList<InternalPacket*> *GetOrderingListAtOrderingStream( unsigned char orderingChannel ); /// Add the internal packet to the ordering list in order based on order index void AddToOrderingList( InternalPacket * internalPacket ); /// Inserts a packet into the resend list in order void InsertPacketIntoResendList( InternalPacket *internalPacket, CCTimeType time, bool firstResend, bool modifyUnacknowledgedBytes ); /// Memory handling void FreeMemory( bool freeAllImmediately ); /// Memory handling void FreeThreadSafeMemory( void ); // Initialize the variables void InitializeVariables( void ); /// Given the current time, is this time so old that we should consider it a timeout? bool IsExpiredTime(unsigned int input, CCTimeType currentTime) const; // Make it so we don't do resends within a minimum threshold of time void UpdateNextActionTime(void); /// Does this packet number represent a packet that was skipped (out of order?) //unsigned int IsReceivedPacketHole(unsigned int input, RakNet::TimeMS currentTime) const; /// Skip an element in the received packets list //unsigned int MakeReceivedPacketHole(unsigned int input) const; /// How many elements are waiting to be resent? unsigned int GetResendListDataSize(void) const; /// Update all memory which is not threadsafe void UpdateThreadedMemory(void); void CalculateHistogramAckSize(void); // Used ONLY for RELIABLE_ORDERED // RELIABLE_SEQUENCED just returns the newest one DataStructures::List<DataStructures::LinkedList<InternalPacket*>*> orderingList; DataStructures::Queue<InternalPacket*> outputQueue; int splitMessageProgressInterval; CCTimeType unreliableTimeout; struct MessageNumberNode { DatagramSequenceNumberType messageNumber; MessageNumberNode *next; }; struct DatagramHistoryNode { DatagramHistoryNode() {} DatagramHistoryNode(MessageNumberNode *_head //, bool r ) : head(_head) // , isReliable(r) {} MessageNumberNode *head; // bool isReliable; }; // Queue length is programmatically restricted to DATAGRAM_MESSAGE_ID_ARRAY_LENGTH // This is essentially an O(1) lookup to get a DatagramHistoryNode given an index // datagramHistory holds a linked list of MessageNumberNode. Each MessageNumberNode refers to one element in resendList which can be cleared on an ack. DataStructures::Queue<DatagramHistoryNode> datagramHistory; DataStructures::MemoryPool<MessageNumberNode> datagramHistoryMessagePool; void RemoveFromDatagramHistory(DatagramSequenceNumberType index); MessageNumberNode* GetMessageNumberNodeByDatagramIndex(DatagramSequenceNumberType index/*, bool *isReliable*/); void AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber); MessageNumberNode* AddFirstToDatagramHistory(DatagramSequenceNumberType datagramNumber, DatagramSequenceNumberType messageNumber); MessageNumberNode* AddSubsequentToDatagramHistory(MessageNumberNode *messageNumberNode, DatagramSequenceNumberType messageNumber); DatagramSequenceNumberType datagramHistoryPopCount; DataStructures::MemoryPool<InternalPacket> internalPacketPool; // DataStructures::BPlusTree<DatagramSequenceNumberType, InternalPacket*, RESEND_TREE_ORDER> resendTree; InternalPacket *resendBuffer[RESEND_BUFFER_ARRAY_LENGTH]; InternalPacket *resendLinkedListHead; InternalPacket *unreliableLinkedListHead; void RemoveFromUnreliableLinkedList(InternalPacket *internalPacket); void AddToUnreliableLinkedList(InternalPacket *internalPacket); // unsigned int numPacketsOnResendBuffer; //unsigned int blockWindowIncreaseUntilTime; // DataStructures::RangeList<DatagramSequenceNumberType> acknowlegements; // Resend list is a tree of packets we need to resend // Set to the current time when the resend queue is no longer empty // Set to zero when it becomes empty // Set to the current time if it is not zero, and we get incoming data // If the current time - timeResendQueueNonEmpty is greater than a threshold, we are disconnected // CCTimeType timeResendQueueNonEmpty; RakNet::TimeMS timeLastDatagramArrived; // If we backoff due to packetloss, don't remeasure until all waiting resends have gone out or else we overcount // bool packetlossThisSample; // int backoffThisSample; // unsigned packetlossThisSampleResendCount; // CCTimeType lastPacketlossTime; //DataStructures::Queue<InternalPacket*> sendPacketSet[ NUMBER_OF_PRIORITIES ]; DataStructures::Heap<reliabilityHeapWeightType, InternalPacket*, false> outgoingPacketBuffer; reliabilityHeapWeightType outgoingPacketBufferNextWeights[NUMBER_OF_PRIORITIES]; void InitHeapWeights(void); reliabilityHeapWeightType GetNextWeight(int priorityLevel); // unsigned int messageInSendBuffer[NUMBER_OF_PRIORITIES]; // double bytesInSendBuffer[NUMBER_OF_PRIORITIES]; DataStructures::OrderedList<SplitPacketIdType, SplitPacketChannel*, SplitPacketChannelComp> splitPacketChannelList; MessageNumberType sendReliableMessageNumberIndex; MessageNumberType internalOrderIndex; //unsigned int windowSize; RakNet::BitStream updateBitStream; OrderingIndexType waitingForOrderedPacketWriteIndex[ NUMBER_OF_ORDERED_STREAMS ], waitingForSequencedPacketWriteIndex[ NUMBER_OF_ORDERED_STREAMS ]; // STUFF TO NOT MUTEX HERE (called from non-conflicting threads, or value is not important) OrderingIndexType waitingForOrderedPacketReadIndex[ NUMBER_OF_ORDERED_STREAMS ], waitingForSequencedPacketReadIndex[ NUMBER_OF_ORDERED_STREAMS ]; bool deadConnection, cheater; // unsigned int lastPacketSendTime,retransmittedFrames, sentPackets, sentFrames, receivedPacketsCount, bytesSent, bytesReceived,lastPacketReceivedTime; SplitPacketIdType splitPacketId; RakNet::TimeMS timeoutTime; // How long to wait in MS before timing someone out //int MAX_AVERAGE_PACKETS_PER_SECOND; // Name says it all // int RECEIVED_PACKET_LOG_LENGTH, requestedReceivedPacketLogLength; // How big the receivedPackets array is // unsigned int *receivedPackets; RakNetStatistics statistics; // CCTimeType histogramStart; // unsigned histogramBitsSent; /// Memory-efficient receivedPackets algorithm: /// receivedPacketsBaseIndex is the packet number we are expecting /// Everything under receivedPacketsBaseIndex is a packet we already got /// Everything over receivedPacketsBaseIndex is stored in hasReceivedPacketQueue /// It stores the time to stop waiting for a particular packet number, where the packet number is receivedPacketsBaseIndex + the index into the queue /// If 0, we got got that packet. Otherwise, the time to give up waiting for that packet. /// If we get a packet number where (receivedPacketsBaseIndex-packetNumber) is less than half the range of receivedPacketsBaseIndex then it is a duplicate /// Otherwise, it is a duplicate packet (and ignore it). // DataStructures::Queue<CCTimeType> hasReceivedPacketQueue; DataStructures::Queue<bool> hasReceivedPacketQueue; DatagramSequenceNumberType receivedPacketsBaseIndex; bool resetReceivedPackets; CCTimeType lastUpdateTime; CCTimeType timeBetweenPackets, nextSendTime; // CCTimeType ackPingSamples[ACK_PING_SAMPLES_SIZE]; // Must be range of unsigned char to wrap ackPingIndex properly CCTimeType ackPingSum; unsigned char ackPingIndex; //CCTimeType nextLowestPingReset; RemoteSystemTimeType remoteSystemTime; // bool continuousSend; // CCTimeType lastTimeBetweenPacketsIncrease,lastTimeBetweenPacketsDecrease; // Limit changes in throughput to once per ping - otherwise even if lag starts we don't know about it // In the meantime the connection is flooded and overrun. CCTimeType nextAllowedThroughputSample; bool bandwidthExceededStatistic; // If Update::maxBitsPerSecond > 0, then throughputCapCountdown is used as a timer to prevent sends for some amount of time after each send, depending on // the amount of data sent long long throughputCapCountdown; unsigned receivePacketCount; #ifdef _DEBUG struct DataAndTime//<InternalPacket> { SOCKET s; char data[ MAXIMUM_MTU_SIZE ]; unsigned int length; RakNet::TimeMS sendTime; // SystemAddress systemAddress; unsigned short remotePortRakNetWasStartedOn_PS3; unsigned int extraSocketOptions; }; DataStructures::Queue<DataAndTime*> delayList; // Internet simulator double packetloss; RakNet::TimeMS minExtraPing, extraPingVariance; #endif CCTimeType elapsedTimeSinceLastUpdate; CCTimeType nextAckTimeToSend; #if USE_SLIDING_WINDOW_CONGESTION_CONTROL==1 RakNet::CCRakNetSlidingWindow congestionManager; #else RakNet::CCRakNetUDT congestionManager; #endif uint32_t unacknowledgedBytes; bool ResendBufferOverflow(void) const; void ValidateResendList(void) const; void ResetPacketsAndDatagrams(void); void PushPacket(CCTimeType time, InternalPacket *internalPacket, bool isReliable); void PushDatagram(void); bool TagMostRecentPushAsSecondOfPacketPair(void); void ClearPacketsAndDatagrams(bool releaseToInternalPacketPoolIfNeedsAck); void MoveToListHead(InternalPacket *internalPacket); void RemoveFromList(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes); void AddToListTail(InternalPacket *internalPacket, bool modifyUnacknowledgedBytes); void PopListHead(bool modifyUnacknowledgedBytes); bool IsResendQueueEmpty(void) const; void SortSplitPacketList(DataStructures::List<InternalPacket*> &data, unsigned int leftEdge, unsigned int rightEdge) const; void SendACKs(SOCKET s, SystemAddress &systemAddress, CCTimeType time, RakNetRandom *rnr, unsigned short remotePortRakNetWasStartedOn_PS3, unsigned int extraSocketOptions); DataStructures::List<InternalPacket*> packetsToSendThisUpdate; DataStructures::List<bool> packetsToDeallocThisUpdate; // boundary is in packetsToSendThisUpdate, inclusive DataStructures::List<unsigned int> packetsToSendThisUpdateDatagramBoundaries; DataStructures::List<bool> datagramsToSendThisUpdateIsPair; DataStructures::List<unsigned int> datagramSizesInBytes; BitSize_t datagramSizeSoFar; BitSize_t allDatagramSizesSoFar; double totalUserDataBytesAcked; CCTimeType timeOfLastContinualSend; CCTimeType timeToNextUnreliableCull; // This doesn't need to be a member, but I do it to avoid reallocations DataStructures::RangeList<DatagramSequenceNumberType> incomingAcks; // Every 16 datagrams, we make sure the 17th datagram goes out the same update tick, and is the same size as the 16th int countdownToNextPacketPair; InternalPacket* AllocateFromInternalPacketPool(void); void ReleaseToInternalPacketPool(InternalPacket *ip); DataStructures::RangeList<DatagramSequenceNumberType> acknowlegements; DataStructures::RangeList<DatagramSequenceNumberType> NAKs; bool remoteSystemNeedsBAndAS; unsigned int GetMaxDatagramSizeExcludingMessageHeaderBytes(void); BitSize_t GetMaxDatagramSizeExcludingMessageHeaderBits(void); // ourOffset refers to a section within externallyAllocatedPtr. Do not deallocate externallyAllocatedPtr until all references are lost void AllocInternalPacketData(InternalPacket *internalPacket, InternalPacketRefCountedData **refCounter, unsigned char *externallyAllocatedPtr, unsigned char *ourOffset); // Set the data pointer to externallyAllocatedPtr, do not allocate void AllocInternalPacketData(InternalPacket *internalPacket, unsigned char *externallyAllocatedPtr); // Allocate new void AllocInternalPacketData(InternalPacket *internalPacket, unsigned int numBytes, bool allowStack, const char *file, unsigned int line); void FreeInternalPacketData(InternalPacket *internalPacket, const char *file, unsigned int line); DataStructures::MemoryPool<InternalPacketRefCountedData> refCountedDataPool; BPSTracker bpsMetrics[RNS_PER_SECOND_METRICS_COUNT]; CCTimeType lastBpsClear; #if LIBCAT_SECURITY==1 public: cat::AuthenticatedEncryption* GetAuthenticatedEncryption(void) { return &auth_enc; } protected: cat::AuthenticatedEncryption auth_enc; bool useSecurity; #endif // LIBCAT_SECURITY }; } // namespace RakNet #endif
[ [ [ 1, 562 ] ] ]
7940d6c1c0bdaadd40cff58eb60411baa43d4dcf
2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83
/BasicOgreFramework/PhysxSDK/Samples/SampleMeshMaterials/src/NxSampleMeshMaterials.cpp
682637469be188eb04c7a3d37f8c7e87f3e8d068
[]
no_license
mgq812/simengines-g2-code
5908d397ef2186e1988b1d14fa8b73f4674f96ea
699cb29145742c1768857945dc59ef283810d511
refs/heads/master
2016-09-01T22:57:54.845817
2010-01-11T19:26:51
2010-01-11T19:26:51
32,267,377
0
0
null
null
null
null
UTF-8
C++
false
false
22,283
cpp
// =============================================================================== // // AGEIA PhysX SDK Sample Program // // Title: Mesh Materials Sample // Description: This sample builds on the SampleTerrain program and demonstrates how // the user can assign a different material to various triangles in a // triangle mesh (this is the same technique as for heightfields and // other meshes) // // We make a terrain, and then based on the slope, of each triangle, // we assign one of four different materials: ice, rock, mud, and grass. // These materials are rendered with appropriate colors to better // visualize the effect. // // Boxes thrown onto the terrain by pressing 'w' will react accordingly. // This means that the different materials result in different sliding // and bouncing behavior. // // Additionally, you can query the material type at a certain point // and use this information as a special effect. This is demonstrated // by creating small boxes that represent ice particles when a box // collides with an ice surface. // // =============================================================================== #ifdef WIN32 #define NOMINMAX #include <windows.h> #endif #include <stdio.h> #include <GL/glut.h> // Physics code #undef random #include "NxPhysics.h" #include "cooking.h" #include "Stream.h" #include "Utilities.h" #include "SamplesVRDSettings.h" #include "CustomRandom.h" static bool gPause = false; static NxPhysicsSDK* gPhysicsSDK = NULL; static NxScene* gScene = NULL; static NxVec3 gDefaultGravity(0.0f, -98.1f, 0.0f); #define TERRAIN_SIZE 33 #define TERRAIN_NB_VERTS TERRAIN_SIZE*TERRAIN_SIZE #define TERRAIN_NB_FACES (TERRAIN_SIZE-1)*(TERRAIN_SIZE-1)*2 #define TERRAIN_OFFSET -20.0f #define TERRAIN_WIDTH 20.0f #define TERRAIN_CHAOS 150.0f static NxVec3* gTerrainVerts = NULL; static NxVec3* gTerrainNormals = NULL; static NxU32* gTerrainFaces = NULL; static NxMaterialIndex * gTerrainMaterials = NULL; static NxMaterialIndex materialIce, materialRock, materialMud, materialGrass, materialDefault = 0; static NxActor * gTerrain = NULL; static NxArray<NxVec3> contactBuffer; static NxTriangleMeshShape* gMeshShape = NULL; float trand() { static Random random(4095); return ((float)random.rand()/((float)random.rand_max+1))*(2.0f) -1.0f; } void smoothTriangle(NxU32 a, NxU32 b, NxU32 c) { NxVec3 & v0 = gTerrainVerts[a]; NxVec3 & v1 = gTerrainVerts[b]; NxVec3 & v2 = gTerrainVerts[c]; NxReal avg = (v0.y + v1.y + v2.y) * 0.333f; avg *= 0.5f; v0.y = v0.y * 0.5f + avg; v1.y = v1.y * 0.5f + avg; v2.y = v2.y * 0.5f + avg; } void chooseTrigMaterial(NxU32 faceIndex) { NxVec3 & v0 = gTerrainVerts[gTerrainFaces[faceIndex * 3]]; NxVec3 & v1 = gTerrainVerts[gTerrainFaces[faceIndex * 3 + 1]]; NxVec3 & v2 = gTerrainVerts[gTerrainFaces[faceIndex * 3 + 2]]; NxVec3 edge0 = v1 - v0; NxVec3 edge1 = v2 - v0; NxVec3 normal = edge0.cross(edge1); normal.normalize(); NxReal steepness = 1.0f - normal.y; if (steepness > 0.25f) { gTerrainMaterials[faceIndex] = materialIce; } else if (steepness > 0.2f) { gTerrainMaterials[faceIndex] = materialRock; } else if (steepness > 0.1f) { gTerrainMaterials[faceIndex] = materialMud; } else gTerrainMaterials[faceIndex] = materialGrass; } static void InitTerrain() { // Initialize terrain vertices gTerrainVerts = new NxVec3[TERRAIN_NB_VERTS]; for(NxU32 y=0;y<TERRAIN_SIZE;y++) { for(NxU32 x=0;x<TERRAIN_SIZE;x++) { NxVec3 v; v.set(NxF32(x)-(NxF32(TERRAIN_SIZE-1)*0.5f), 0.0f, NxF32(y)-(NxF32(TERRAIN_SIZE-1)*0.5f)); v *= TERRAIN_WIDTH; gTerrainVerts[x+y*TERRAIN_SIZE] = v; } } struct Local { static void _Compute(bool* done, NxVec3* field, NxU32 x0, NxU32 y0, NxU32 size, NxF32 value) { // Compute new size size>>=1; if(!size) return; // Compute new heights NxF32 v0 = value * trand(); NxF32 v1 = value * trand(); NxF32 v2 = value * trand(); NxF32 v3 = value * trand(); NxF32 v4 = value * trand(); NxU32 x1 = (x0+size) % TERRAIN_SIZE; NxU32 x2 = (x0+size+size) % TERRAIN_SIZE; NxU32 y1 = (y0+size) % TERRAIN_SIZE; NxU32 y2 = (y0+size+size) % TERRAIN_SIZE; if(!done[x1 + y0*TERRAIN_SIZE]) field[x1 + y0*TERRAIN_SIZE].y = v0 + 0.5f * (field[x0 + y0*TERRAIN_SIZE].y + field[x2 + y0*TERRAIN_SIZE].y); if(!done[x0 + y1*TERRAIN_SIZE]) field[x0 + y1*TERRAIN_SIZE].y = v1 + 0.5f * (field[x0 + y0*TERRAIN_SIZE].y + field[x0 + y2*TERRAIN_SIZE].y); if(!done[x2 + y1*TERRAIN_SIZE]) field[x2 + y1*TERRAIN_SIZE].y = v2 + 0.5f * (field[x2 + y0*TERRAIN_SIZE].y + field[x2 + y2*TERRAIN_SIZE].y); if(!done[x1 + y2*TERRAIN_SIZE]) field[x1 + y2*TERRAIN_SIZE].y = v3 + 0.5f * (field[x0 + y2*TERRAIN_SIZE].y + field[x2 + y2*TERRAIN_SIZE].y); if(!done[x1 + y1*TERRAIN_SIZE]) field[x1 + y1*TERRAIN_SIZE].y = v4 + 0.5f * (field[x0 + y1*TERRAIN_SIZE].y + field[x2 + y1*TERRAIN_SIZE].y); done[x1 + y0*TERRAIN_SIZE] = true; done[x0 + y1*TERRAIN_SIZE] = true; done[x2 + y1*TERRAIN_SIZE] = true; done[x1 + y2*TERRAIN_SIZE] = true; done[x1 + y1*TERRAIN_SIZE] = true; // Recurse through 4 corners value *= 0.5f; _Compute(done, field, x0, y0, size, value); _Compute(done, field, x0, y1, size, value); _Compute(done, field, x1, y0, size, value); _Compute(done, field, x1, y1, size, value); } }; // Fractalize bool* done = new bool[TERRAIN_NB_VERTS]; memset(done,0,TERRAIN_NB_VERTS); gTerrainVerts[0].y = 10.0f; gTerrainVerts[TERRAIN_SIZE-1].y = 10.0f; gTerrainVerts[TERRAIN_SIZE*(TERRAIN_SIZE-1)].y = 10.0f; gTerrainVerts[TERRAIN_NB_VERTS-1].y = 10.0f; Local::_Compute(done, gTerrainVerts, 0, 0, TERRAIN_SIZE, TERRAIN_CHAOS); for(NxU32 i=0;i<TERRAIN_NB_VERTS;i++) gTerrainVerts[i].y += TERRAIN_OFFSET; delete[] done; // Initialize terrain faces gTerrainFaces = new NxU32[TERRAIN_NB_FACES*3]; NxU32 k = 0; for(NxU32 j=0;j<TERRAIN_SIZE-1;j++) { for(NxU32 i=0;i<TERRAIN_SIZE-1;i++) { // Create first triangle gTerrainFaces[k] = i + j*TERRAIN_SIZE; gTerrainFaces[k+1] = i + (j+1)*TERRAIN_SIZE; gTerrainFaces[k+2] = i+1 + (j+1)*TERRAIN_SIZE; //while we're at it do some smoothing of the random terrain because its too rough to do a good demo of this effect. smoothTriangle(gTerrainFaces[k],gTerrainFaces[k+1],gTerrainFaces[k+2]); k+=3; // Create second triangle gTerrainFaces[k] = i + j*TERRAIN_SIZE; gTerrainFaces[k+1] = i+1 + (j+1)*TERRAIN_SIZE; gTerrainFaces[k+2] = i+1 + j*TERRAIN_SIZE; smoothTriangle(gTerrainFaces[k],gTerrainFaces[k+1],gTerrainFaces[k+2]); k+=3; } } //allocate terrain materials -- one for each face. gTerrainMaterials = new NxMaterialIndex[TERRAIN_NB_FACES]; for(NxU32 f=0;f<TERRAIN_NB_FACES;f++) { //new: generate material indices for all the faces chooseTrigMaterial(f); } // Build vertex normals gTerrainNormals = new NxVec3[TERRAIN_NB_VERTS]; NxBuildSmoothNormals(TERRAIN_NB_FACES, TERRAIN_NB_VERTS, gTerrainVerts, gTerrainFaces, NULL, gTerrainNormals, true); // Build physical model NxTriangleMeshDesc terrainDesc; terrainDesc.numVertices = TERRAIN_NB_VERTS; terrainDesc.numTriangles = TERRAIN_NB_FACES; terrainDesc.pointStrideBytes = sizeof(NxVec3); terrainDesc.triangleStrideBytes = 3*sizeof(NxU32); terrainDesc.points = gTerrainVerts; terrainDesc.triangles = gTerrainFaces; terrainDesc.flags = 0; //add the mesh material data: terrainDesc.materialIndexStride = sizeof(NxMaterialIndex); terrainDesc.materialIndices = gTerrainMaterials; terrainDesc.heightFieldVerticalAxis = NX_Y; terrainDesc.heightFieldVerticalExtent = -1000.0f; NxTriangleMeshShapeDesc terrainShapeDesc; terrainShapeDesc.shapeFlags |= NX_SF_FEATURE_INDICES; bool status = InitCooking(); if (!status) { printf("Unable to initialize the cooking library. Please make sure that you have correctly installed the latest version of the AGEIA PhysX SDK."); exit(1); } MemoryWriteBuffer buf; status = CookTriangleMesh(terrainDesc, buf); if (!status) { printf("Unable to cook a triangle mesh."); exit(1); } MemoryReadBuffer readBuffer(buf.data); terrainShapeDesc.meshData = gPhysicsSDK->createTriangleMesh(readBuffer); // // Please note about the created Triangle Mesh, user needs to release it when no one uses it to save memory. It can be detected // by API "meshData->getReferenceCount() == 0". And, the release API is "gPhysicsSDK->releaseTriangleMesh(*meshData);" // NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&terrainShapeDesc); gTerrain = gScene->createActor(ActorDesc); gMeshShape = (NxTriangleMeshShape*)gTerrain->getShapes()[0]; gTerrain->userData = (void*)0; CloseCooking(); } static void RenderTerrain() { static float* pVertList = NULL; static float* pNormList = NULL; static float* pColorList = NULL; if(pVertList == NULL && pNormList == NULL) { pVertList = new float[TERRAIN_NB_FACES*3*3]; pNormList = new float[TERRAIN_NB_FACES*3*3]; pColorList = new float[TERRAIN_NB_FACES*3*4]; int vertIndex = 0; int normIndex = 0; int colorIndex = 0; for(int i=0;i<TERRAIN_NB_FACES;i++) { NxMaterialIndex mat = gTerrainMaterials[i]; float r,g,b; if(mat == materialIce) { r=1; g=1; b=1; } else { if(mat == materialRock) { r=0.3f; g=0.3f; b=0.3f; } else { if (mat == materialMud) { r=0.6f; g=0.3f; b=0.2f; } else { r=0.2f; g=0.8f; b=0.2f; } } } for(int j=0;j<3;j++) { pVertList[vertIndex++] = gTerrainVerts[gTerrainFaces[i*3+j]].x; pVertList[vertIndex++] = gTerrainVerts[gTerrainFaces[i*3+j]].y; pVertList[vertIndex++] = gTerrainVerts[gTerrainFaces[i*3+j]].z; pNormList[normIndex++] = gTerrainNormals[gTerrainFaces[i*3+j]].x; pNormList[normIndex++] = gTerrainNormals[gTerrainFaces[i*3+j]].y; pNormList[normIndex++] = gTerrainNormals[gTerrainFaces[i*3+j]].z; pColorList[colorIndex++] = r; pColorList[colorIndex++] = g; pColorList[colorIndex++] = b; pColorList[colorIndex++] = 1.0f; } } } if(pVertList != NULL && pNormList != NULL) { glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3,GL_FLOAT, 0, pVertList); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, pNormList); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, 0, pColorList); glDrawArrays(GL_TRIANGLES, 0, TERRAIN_NB_FACES*3); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); } } static void CreateCube(const NxVec3& pos, int size=2, const NxVec3* initial_velocity=NULL) { // Create body NxBodyDesc BodyDesc; BodyDesc.angularDamping = 0.5f; // BodyDesc.maxAngularVelocity = 10.0f; if(initial_velocity) BodyDesc.linearVelocity = *initial_velocity; NxBoxShapeDesc BoxDesc; BoxDesc.dimensions = NxVec3(float(size), float(size), float(size)); NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&BoxDesc); ActorDesc.body = &BodyDesc; ActorDesc.density = 10.0f; ActorDesc.globalPose.t = pos; NxActor * cube = gScene->createActor(ActorDesc); cube->userData = (void*)size; gScene->setActorPairFlags(*cube, *gTerrain, NX_NOTIFY_ON_START_TOUCH|NX_NOTIFY_ON_TOUCH|NX_NOTIFY_ON_END_TOUCH); } static void CreateStack(int size) { float CubeSize = 2.0f; // float Spacing = 0.01f; float Spacing = 0.0001f; NxVec3 Pos(0.0f, CubeSize, 0.0f); float Offset = -size * (CubeSize * 2.0f + Spacing) * 0.5f; while(size) { for(int i=0;i<size;i++) { Pos.x = Offset + float(i) * (CubeSize * 2.0f + Spacing); CreateCube(Pos, (int)CubeSize); } Offset += CubeSize; Pos.y += (CubeSize * 2.0f + Spacing); size--; } } static void CreateTower(int size) { float CubeSize = 2.0f; float Spacing = 0.01f; NxVec3 Pos(0.0f, CubeSize, 0.0f); while(size) { CreateCube(Pos, (int)CubeSize); Pos.y += (CubeSize * 2.0f + Spacing); size--; } } class MyContactReport : public NxUserContactReport { public: virtual NxU32 onPairCreated(NxActor& s1, NxActor& s2) { return NX_NOTIFY_ON_START_TOUCH; } virtual void onContactNotify(NxContactPair& pair, NxU32 events) { // Iterate through contact points NxContactStreamIterator i(pair.stream); //user can call getNumPairs() here while(i.goNextPair()) { //user can also call getShape() and getNumPatches() here NxU32 meshId = 2; if (i.getShape(0) == (NxShape*)gMeshShape) meshId = 0; else if (i.getShape(1) == (NxShape*)gMeshShape) meshId = 1; while(i.goNextPatch()) { //user can also call getPatchNormal() and getNumPoints() here const NxVec3& contactNormal = i.getPatchNormal(); while(i.goNextPoint()) { //user can also call getPoint() and getSeparation() here const NxVec3& contactPoint = i.getPoint(); if (meshId != 2) { NxU32 featureIndex = (meshId == 0) ? i.getFeatureIndex0() : i.getFeatureIndex1(); NxMaterialIndex meshMaterial = materialDefault; if (featureIndex != 0xffffffff) meshMaterial = gTerrainMaterials[featureIndex]; if (meshMaterial == materialIce) contactBuffer.pushBack(contactPoint); } } } } } }gMyContactReport; class MyErrorStream : public NxUserOutputStream { public: void reportError(NxErrorCode e, const char * message, const char *file, int line) { printf("%s (%d) :", file, line); switch (e) { case NXE_INVALID_PARAMETER: printf( "invalid parameter"); break; case NXE_INVALID_OPERATION: printf( "invalid operation"); break; case NXE_OUT_OF_MEMORY: printf( "out of memory"); break; case NXE_DB_INFO: printf( "info"); break; case NXE_DB_WARNING: printf( "warning"); break; default: printf("unknown error"); } printf(" : %s\n", message); } NxAssertResponse reportAssertViolation(const char * message, const char *file, int line) { printf("access violation : %s (%s line %d)\n", message, file, line); #ifdef WIN32 switch (MessageBox(0, message, "AssertViolation, see console for details.", MB_ABORTRETRYIGNORE)) { case IDRETRY: return NX_AR_CONTINUE; case IDIGNORE: return NX_AR_IGNORE; case IDABORT: default: return NX_AR_BREAKPOINT; } #else return NX_AR_BREAKPOINT; #endif } void print(const char * message) { printf(message); } } myErrorStream; static bool InitNx() { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &myErrorStream, desc, &errorCode); if(gPhysicsSDK == NULL) { printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode)); return false; } #if SAMPLES_USE_VRD // The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger()) gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK); #endif gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.025f); // Create a scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.userContactReport = &gMyContactReport; gScene = gPhysicsSDK->createScene(sceneDesc); if(gScene == NULL) { printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n"); return false; } NxMaterial * defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); NxMaterialDesc m; //terrain materials: m.restitution = 1.0f; m.staticFriction = 0.0f; m.dynamicFriction = 0.0f; materialIce = gScene->createMaterial(m)->getMaterialIndex(); m.restitution = 0.3f; m.staticFriction = 1.2f; m.dynamicFriction = 1.0f; materialRock = gScene->createMaterial(m)->getMaterialIndex(); m.restitution = 0.0f; m.staticFriction = 3.0f; m.dynamicFriction = 1.0f; materialMud = gScene->createMaterial(m)->getMaterialIndex(); m.restitution = 0.0f; m.staticFriction = 0.0f; m.dynamicFriction = 0.0f; materialGrass = gScene->createMaterial(m)->getMaterialIndex(); InitTerrain(); return true; } static void createParticles() { for(NxArray<NxVec3>::Iterator i = contactBuffer.begin(); i != contactBuffer.end(); i++) { NxBodyDesc BodyDesc; BodyDesc.linearVelocity.set(0,10.0f, 0); NxBoxShapeDesc BoxDesc; BoxDesc.dimensions = NxVec3(1,1,1); BoxDesc.materialIndex = materialMud; NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&BoxDesc); ActorDesc.body = &BodyDesc; ActorDesc.density = 1.0f; ActorDesc.globalPose.t = *i; gScene->createActor(ActorDesc)->userData = (void*)1; } contactBuffer.clear(); } // Render code static int gMainHandle; static NxVec3 Eye(0.0f, 50.0f, -300.0f); static NxVec3 Dir(0,0,1); static NxVec3 N; static int mx = 0; static int my = 0; static void KeyboardCallback(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; case ' ': CreateCube(NxVec3(0.0f, 20.0f, 0.0f), 1+(rand()&3)); break; case 's': CreateStack(10); break; case 'b': CreateStack(30); break; case 't': CreateTower(30); break; case 'p': gPause = !gPause; break; case 101: case '8': Eye += Dir * 2.0f; break; case 103: case '2': Eye -= Dir * 2.0f; break; case 100: case '4': Eye -= N * 2.0f; break; case 102: case '6': Eye += N * 2.0f; break; case 'w': { NxVec3 t = Eye; NxVec3 Vel = Dir; Vel.normalize(); Vel*=180.0f; CreateCube(t, 3, &Vel); } break; } } static void ArrowKeyCallback(int key, int x, int y) { KeyboardCallback(key,x,y); } static void MouseCallback(int button, int state, int x, int y) { mx = x; my = y; } static void MotionCallback(int x, int y) { int dx = mx - x; int dy = my - y; Dir.normalize(); N.cross(Dir,NxVec3(0,1,0)); NxQuat qx(NxPiF32 * dx * 20/ 180.0f, NxVec3(0,1,0)); qx.rotate(Dir); NxQuat qy(NxPiF32 * dy * 20/ 180.0f, N); qy.rotate(Dir); mx = x; my = y; } static void setupGLMatrix(const NxMat34& pose) { float glmat[16]; pose.M.getColumnMajorStride4(&(glmat[0])); pose.t.get(&(glmat[12])); glmat[3] = glmat[7] = glmat[11] = 0.0f; glmat[15] = 1.0f; glMultMatrixf(&(glmat[0])); } static void RenderCallback() { float glmat[16]; // Physics code if(gScene && !gPause) { gScene->simulate(1.0f/60.0f); //Note: a real application would compute and pass the elapsed time here. gScene->flushStream(); gScene->fetchResults(NX_RIGID_BODY_FINISHED, true); createParticles(); } // ~Physics code // Clear buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup camera glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT), 1.0f, 10000.0f); gluLookAt(Eye.x, Eye.y, Eye.z, Eye.x + Dir.x, Eye.y + Dir.y, Eye.z + Dir.z, 0.0f, 1.0f, 0.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Keep physics & graphics in sync glColor4f(1.0f, 1.0f, 1.0f, 1.0f); int nbActors = gScene->getNbActors(); NxActor** actors = gScene->getActors(); while(nbActors--) { NxActor* actor = *actors++; if(!int(actor->userData)) continue; glPushMatrix(); actor->getGlobalPose().getColumnMajor44(glmat); glMultMatrixf(glmat); glutSolidCube(float(int(actor->userData))*2.0f); glPopMatrix(); } RenderTerrain(); glutSwapBuffers(); } static void ReshapeCallback(int width, int height) { glViewport(0, 0, width, height); } static void IdleCallback() { glutPostRedisplay(); } static void ExitCallback() { if (gPhysicsSDK) { if (gScene) gPhysicsSDK->releaseScene(*gScene); gPhysicsSDK->release(); } } int main(int argc, char** argv) { printf("Press the keys w,space,s,b, and t to create various things.\n"); printf("Use the arrow keys or 2, 4, 6 and 8 to move the camera, mouse to look around.\n"); printf("Press p to pause the simulation.\n"); // Initialize Glut glutInit(&argc, argv); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); gMainHandle = glutCreateWindow("SampleMeshMaterials"); glutSetWindow(gMainHandle); glutDisplayFunc(RenderCallback); glutReshapeFunc(ReshapeCallback); glutIdleFunc(IdleCallback); glutKeyboardFunc(KeyboardCallback); glutSpecialFunc(ArrowKeyCallback); glutMouseFunc(MouseCallback); glutMotionFunc(MotionCallback); MotionCallback(0,0); atexit(ExitCallback); // Setup default render states glClearColor(0.3f, 0.4f, 0.5f, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_CULL_FACE); // Setup lighting glEnable(GL_LIGHTING); float AmbientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientColor); float DiffuseColor[] = { 1.0f, 1.0f, 1.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseColor); float SpecularColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularColor); float Position[] = { -10.0f, 100.0f, 4.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, Position); glEnable(GL_LIGHT0); // Initialize physics scene and start the application main loop if scene was created if (InitNx()) glutMainLoop(); return 0; }
[ "erucarno@789472dc-e1c3-11de-81d3-db62269da9c1" ]
[ [ [ 1, 768 ] ] ]
58deb76cf69ca9e2c42e2e04f97921029709afb6
b5ad65ebe6a1148716115e1faab31b5f0de1b493
/src/Aran/BwWin32Timer.cpp
ae817db0ee158715f641a1904e906d78cc634cb1
[]
no_license
gasbank/aran
4360e3536185dcc0b364d8de84b34ae3a5f0855c
01908cd36612379ade220cc09783bc7366c80961
refs/heads/master
2021-05-01T01:16:19.815088
2011-03-01T05:21:38
2011-03-01T05:21:38
1,051,010
1
0
null
null
null
null
UTF-8
C++
false
false
2,391
cpp
#include "AranPCH.h" #include "BwWin32Timer.h" #ifdef WIN32 #include <mmsystem.h> #endif BwWin32Timer::BwWin32Timer(void) : m_bInited(false) { } BwWin32Timer::~BwWin32Timer(void) { } void BwWin32Timer::start() { #ifdef WIN32 memset(&timer, 0, sizeof(timer)); // Clear Our Timer Structure // Check To See If A Performance Counter Is Available // If One Is Available The Timer Frequency Will Be Updated if (!QueryPerformanceFrequency((LARGE_INTEGER *) &timer.frequency)) { // No Performace Counter Available timer.performance_timer = FALSE; // Set Performance Timer To FALSE timer.mm_timer_start = timeGetTime(); // Use timeGetTime() To Get Current Time timer.resolution = 1.0f/1000.0f; // Set Our Timer Resolution To .001f timer.frequency = 1000; // Set Our Timer Frequency To 1000 timer.mm_timer_elapsed = timer.mm_timer_start; // Set The Elapsed Time To The Current Time } else { // Performance Counter Is Available, Use It Instead Of The Multimedia Timer // Get The Current Time And Store It In performance_timer_start QueryPerformanceCounter((LARGE_INTEGER *) &timer.performance_timer_start); timer.performance_timer = TRUE; // Set Performance Timer To TRUE // Calculate The Timer Resolution Using The Timer Frequency timer.resolution = (float) (((double)1.0f)/((double)timer.frequency)); // Set The Elapsed Time To The Current Time timer.performance_timer_elapsed = timer.performance_timer_start; } #else // LINUX code goes here ... clock_gettime(CLOCK_REALTIME, &m_startTime); #endif m_bInited = true; } double BwWin32Timer::getTicks() { assert(m_bInited); #ifdef WIN32 __int64 time; // time Will Hold A 64 Bit Integer if (timer.performance_timer) // Are We Using The Performance Timer? { QueryPerformanceCounter((LARGE_INTEGER *) &time); // Grab The Current Performance Time // Return The Current Time Minus The Start Time Multiplied By The Resolution And 1000 (To Get MS) return ( (double) ( time - timer.performance_timer_start) * timer.resolution) * 1000.0; } else { // Return The Current Time Minus The Start Time Multiplied By The Resolution And 1000 (To Get MS) return( (double) ( timeGetTime() - timer.mm_timer_start) * timer.resolution) * 1000.0; } #else // LINUX code goes here ... return 0; #endif }
[ [ [ 1, 71 ] ] ]
21737777edca36a6fdd2288826e6f403ed53d6d4
b40f0ed5f556ffa46b3480a0889466e9c50356b6
/AdvButton/ButtonManager.h
e634c0783ffa41e2f66b9a0396826a8de5ec272d
[]
no_license
StarvingMarvin/sketchbook
62788ba705729f29649bad3dbe98556606022454
1388ca07c80b6f42a648a8466c08bcf26c35cbe3
refs/heads/master
2016-09-06T11:27:26.429908
2010-06-21T09:23:25
2010-06-21T09:23:25
731,660
1
0
null
null
null
null
UTF-8
C++
false
false
1,053
h
/* * * Thanks for using this library! If you like it, please drop me a comment at [email protected]. * * File : ButtonManager.h * Version : 1.0 * Released : 24/01/2010 * Author : Bart Meijer ([email protected]) * * This is the Advanced Button library for the Arduino platform. It will enable you to easily * react to user input using simple press-to-make buttons. Features include: * - Event based implementation * - Recording the time a button is pressed * - Adjustable repeat delay, start delay for the keypressed event * - requires only a single call in the main loop * * This file defines the ButtonManager class. * */ #include "AdvButton.h" // define the number of buttons #define MAXBUTTONS 10 #ifndef BUTTONMANAGER_H #define BUTTONMANAGER_H class ButtonManager { int numButtons; AdvButton* buttons[MAXBUTTONS]; static ButtonManager *s_instance; ButtonManager(); public: static ButtonManager *instance(); void checkButtons(); void addButton(AdvButton* but); }; //extern #endif;
[ "luka@hewlett.(none)" ]
[ [ [ 1, 50 ] ] ]
377563146e02ad59446415415188b2903d61821b
faaac39c2cc373003406ab2ac4f5363de07a6aae
/ zenithprime/inc/view/SpaceCombatViewport.h
185ad0ca2775e3252d756fa83d4936019c4dcbfc
[]
no_license
mgq812/zenithprime
595625f2ec86879eb5d0df4613ba41a10e3158c0
3c8ff4a46fb8837e13773e45f23974943a467a6f
refs/heads/master
2021-01-20T06:57:05.754430
2011-02-05T17:20:19
2011-02-05T17:20:19
32,297,284
0
0
null
null
null
null
UTF-8
C++
false
false
555
h
#pragma once #include "OpenGLViewport.h" #include "BattleBoardGUI.h" class SpaceCombatViewport : OpenGLViewport { public: SpaceCombatViewport(BattleBoardView* bbView, int offsetX, int offsetY, int width, int height); SpaceCombatViewport(BattleBoardView* bbView); ~SpaceCombatViewport(); virtual int Draw(); virtual int Update(); virtual int Resize(int width, int height); virtual int MoveTo(int offsetX, int offsetY); BattleBoardView* battleBoardView; private: int Width; int Height; int offsetX; int offsetY; };
[ "mhsmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394", "ElderGrimes@2c223db4-e1a0-a0c7-f360-d8b483a75394" ]
[ [ [ 1, 19 ], [ 25, 25 ] ], [ [ 20, 24 ] ] ]
9f62cd25357b4c7ca31577e1fc45ba5986a5eb3e
ad33a51b7d45d8bf1aa900022564495bc08e0096
/DES/DES_GOBSTG/Core/Export_Lua_HGEHelper.cpp
48e09d1662b3e9f4c3c92cf3b640f87b610a0e0b
[]
no_license
CBE7F1F65/e20671a6add96e9aa3551d07edee6bd4
31aff43df2571d334672929c88dfd41315a4098a
f33d52bbb59dfb758b24c0651449322ecd1b56b7
refs/heads/master
2016-09-11T02:42:42.116248
2011-09-26T04:30:32
2011-09-26T04:30:32
32,192,691
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
#ifndef __NOTUSELUA #include "../Header/Export_Lua_HGEHelp.h" #include "../Header/LuaConstDefine.h" #include "../Header/Export.h" #include "../../../src/hge/HGEExport.h" bool Export_Lua_HGEHelp::_LuaRegistFunction(LuaObject * obj) { return true; } bool Export_Lua_HGEHelp::_LuaRegistConst(LuaObject * obj) { // hgeFont obj->SetInteger("HGETEXT_LEFT", HGETEXT_LEFT); obj->SetInteger("HGETEXT_RIGHT", HGETEXT_RIGHT); obj->SetInteger("HGETEXT_CENTER", HGETEXT_CENTER); obj->SetInteger("HGETEXT_HORZMASK", HGETEXT_HORZMASK); obj->SetInteger("HGETEXT_TOP", HGETEXT_TOP); obj->SetInteger("HGETEXT_BOTTOM", HGETEXT_BOTTOM); obj->SetInteger("HGETEXT_MIDDLE", HGETEXT_MIDDLE); obj->SetInteger("HGETEXT_VERTMASK", HGETEXT_VERTMASK); return true; } #endif
[ "CBE7F1F65@b503aa94-de59-8b24-8582-4b2cb17628fa" ]
[ [ [ 1, 30 ] ] ]
6d1bbf3e44894c15d78a4bed459f80d9c4d7b152
724cded0e31f5fd52296d516b4c3d496f930fd19
/source/P2PCommon/P2SCommand.cpp
3c96066e812cc1c6a3c6598674efccf32e4741cc
[]
no_license
yubik9/p2pcenter
0c85a38f2b3052adf90b113b2b8b5b312fefcb0a
fc4119f29625b1b1f4559ffbe81563e6fcd2b4ea
refs/heads/master
2021-08-27T15:40:05.663872
2009-02-19T00:13:33
2009-02-19T00:13:33
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
50,923
cpp
#include ".\p2scommand.h" #include <assert.h> namespace P2S_COMMAND { //------------------------------------------------------------------------------------ string CP2SCommandQuery::CommandString( unsigned int unCommand ) { string sRet = "-- no name command --"; switch( unCommand ) { case P2S_CMD_SHOOTHOLE: sRet = "UDP_P2S_CMD_SHOOTHOLE"; break; case P2S_CMD_SHOOTHOLE_RET: sRet = "UDP_P2S_CMD_SHOOTHOLE_RET"; break; case P2S_CMD_UDP_HEARTBEAT: sRet = "UDP_P2S_CMD_UDP_HEARTBEAT"; break; case P2S_CMD_UDP_HEARTBEAT_RET: sRet = "UDP_P2S_CMD_UDP_HEARTBEAT_RET"; break; case P2S_CMD_CONNECT: sRet = "P2S_CMD_CONNECT"; break; case P2S_CMD_CONNECT_RET: sRet = "P2S_CMD_CONNECT_RET"; break; case P2S_CMD_GETGROUPS: sRet = "P2S_CMD_GETGROUPS"; break; case P2S_CMD_GETGROUPS_RET: sRet = "P2S_CMD_GETGROUPS_RET"; break; case P2S_CMD_GETNODES: sRet = "P2S_CMD_GETNODES"; break; case P2S_CMD_GETNODES_RET: sRet = "P2S_CMD_GETNODES_RET"; break; case P2S_CMD_LOGIN_CHANNEL: sRet = "P2S_CMD_LOGIN_CHANNEL"; break; case P2S_CMD_LOGIN_CHANNEL_RET: sRet = "P2S_CMD_LOGIN_CHANNEL_RET"; break; case P2S_CMD_LOGOUT_CHANNEL: sRet = "P2S_CMD_LOGOUT_CHANNEL"; break; case P2S_CMD_LOGOUT_CHANNEL_RET: sRet = "P2S_CMD_LOGOUT_CHANNEL_RET"; break; case P2S_CMD_GETPEERS: sRet = "P2S_CMD_GETPEERS"; break; case P2S_CMD_GETPEERS_RET: sRet = "P2S_CMD_GETPEERS_RET"; break; case P2S_CMD_PEERLOGIN: sRet = "P2S_CMD_PEERLOGIN"; break; case P2S_CMD_PEERLOGOUT: sRet = "P2S_CMD_PEERLOGOUT"; break; case P2S_CMD_REQSHOOTTO: sRet = "P2S_CMD_REQSHOOTTO"; break; case P2S_CMD_REQSHOOTTO_RET: sRet = "P2S_CMD_REQSHOOTTO_RET"; break; case P2S_CMD_SHOOTARRIVED: sRet = "P2S_CMD_SHOOTARRIVED"; break; case P2S_CMD_TCP_HEARTBEAT: sRet = "P2S_CMD_TCP_HEARTBEAT"; break; case P2S_CMD_CLOSE: sRet = "P2S_CMD_CLOSE"; break; case P2S_CMD_CLOSE_RET: sRet = "P2S_CMD_CLOSE_RET"; break; default: break; } return sRet; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateConnectCmd( string sUsername, string sPassword, int nLocalIP, short sLocalUdpPort, short sLocalTcpPort) { CCmdConnect* pCmd = new CCmdConnect(); if ( pCmd ) { pCmd->m_sUsername = sUsername; pCmd->m_sPassword = sPassword; pCmd->m_nLocalIP = nLocalIP; pCmd->m_sLocalUdpPort = sLocalUdpPort; pCmd->m_sLocalTcpPort = sLocalTcpPort; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateGetPeersCmd( int nUserID, int nSessionID, string sChannelID, bool bSource ) { CCmdGetPeers* pCmd = new CCmdGetPeers(); if ( pCmd ) { pCmd->m_sChannelID = sChannelID; pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; bSource ? pCmd->m_cSource = '1' : pCmd->m_cSource = '0'; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateLoginChannelCmd( int nUserID, int nSessionID, string sNodeName, string sChannelID, bool bSource, string sFilePath, string sFileName, string sFileSize ) { CCmdLoginChannel* pCmd = new CCmdLoginChannel(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; pCmd->m_sNodeName = sNodeName; pCmd->m_sChannelID = sChannelID; bSource ? pCmd->m_cSource = '1' : pCmd->m_cSource = '0'; pCmd->m_sFilePath = sFilePath; pCmd->m_sFileName = sFileName; pCmd->m_sFileSize = sFileSize; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateLoginChannelRetCmd( int nUserID, int nSessionID, string sNodeName, string sChannelID, bool bSource, string sFilePath, string sFileName, string sFileSize ) { CCmdLoginChannelRet* pCmd = new CCmdLoginChannelRet(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; pCmd->m_sNodeName = sNodeName; pCmd->m_sChannelID = sChannelID; bSource ? pCmd->m_cSource = '1' : pCmd->m_cSource = '0'; pCmd->m_sFilePath = sFilePath; pCmd->m_sFileName = sFileName; pCmd->m_sFileSize = sFileSize; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateLogoutChannelCmd( int nUserID, int nSessionID, string sChannelID ) { CCmdLogoutChannel* pCmd = new CCmdLogoutChannel(); if ( pCmd ) { pCmd->m_sChannelID = sChannelID; pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateLogoutChannelRetCmd( int nUserID, int nSessionID, string sChannelID ) { CCmdLogoutChannelRet* pCmd = new CCmdLogoutChannelRet(); if ( pCmd ) { pCmd->m_sChannelID = sChannelID; pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateUdpHeartbeatCmd( int nUserID, int nSessionID, string sAuthStr ) { CCmdUdpHeartbeat* pCmd = new CCmdUdpHeartbeat(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; } return pCmd; } CBaseCommand* CCommandFactory::CreateUdpHeartbeatRetCmd( int nUserID, int nSessionID, unsigned long ulExternalIP, unsigned short usExternalUDPPort, string sAuthStr ) { CCmdUdpHeartbeatRet* pCmd = new CCmdUdpHeartbeatRet(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; pCmd->m_ulExternalIP = ulExternalIP; pCmd->m_usExternalUDPPort = usExternalUDPPort; } return pCmd; } CBaseCommand* CCommandFactory::CreateTcpHeartbeatCmd( int nUserID, int nSessionID, string sAuthStr ) { CCmdTcpHeartbeat* pCmd = new CCmdTcpHeartbeat(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateReqShootToCmd( int nUserID, int nSessionID, int nTargetUserID ) { CCmdReqShootTo* pCmd = new CCmdReqShootTo(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; pCmd->m_nTargetUserID = nTargetUserID; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateReqShootToRetCmd( int nUserID, int nSessionID, int nTargetUserID ) { CCmdReqShootToRet* pCmd = new CCmdReqShootToRet(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; pCmd->m_nTargetUserID = nTargetUserID; } return pCmd; } //------------------------------------------------------------------------------------ CBaseCommand* CCommandFactory::CreateReqShootArritedCmd( int nUserID, int nSessionID, const PEERINFO& targetPeerinfo) { CCmdShootArrived* pCmd = new CCmdShootArrived(); if ( pCmd ) { pCmd->m_nUserID = nUserID; pCmd->m_nSessionID = nSessionID; pCmd->m_peerinfoSource = targetPeerinfo; } return pCmd; } //------------------------------------------------------------------------------------ CCmdShootHole::CCmdShootHole() : CBaseCommand(P2S_CMD_SHOOTHOLE) { } CCmdShootHole::~CCmdShootHole(void) { } int CCmdShootHole::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdShootHole::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdShootHoleRet::CCmdShootHoleRet() : CBaseCommand(P2S_CMD_SHOOTHOLE_RET) { } CCmdShootHoleRet::~CCmdShootHoleRet(void) { } int CCmdShootHoleRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdShootHoleRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdConnect::CCmdConnect() : CBaseCommand(P2S_CMD_CONNECT) { } CCmdConnect::~CCmdConnect(void) { } int CCmdConnect::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_str_2( p, m_sUsername, nLen ); p = push_str_2( p, m_sPassword, nLen ); p = push_int32_2( p, m_nLocalIP, nLen); p = push_int16_2( p, m_sLocalUdpPort, nLen); p = push_int16_2( p, m_sLocalTcpPort, nLen); return (int)(p - pBuffer); } int CCmdConnect::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_str( p, m_sUsername ); p = pop_str( p, m_sPassword ); p = pop_int32( p, m_nLocalIP ); p = pop_int16( p, m_sLocalUdpPort ); p = pop_int16( p, m_sLocalTcpPort ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdConnectRet::CCmdConnectRet() : CBaseCommand(P2S_CMD_CONNECT_RET), m_nResult(0) { } CCmdConnectRet::~CCmdConnectRet(void) { } int CCmdConnectRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nResult, nLen); return (int)(p - pBuffer); } int CCmdConnectRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nResult ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdGetGroups::CCmdGetGroups() : CBaseCommand(P2S_CMD_GETGROUPS) { } CCmdGetGroups::~CCmdGetGroups(void) { } int CCmdGetGroups::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdGetGroups::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdGetGroupsRet::CCmdGetGroupsRet() : CBaseCommand(P2S_CMD_GETGROUPS_RET) { } CCmdGetGroupsRet::~CCmdGetGroupsRet(void) { } int CCmdGetGroupsRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdGetGroupsRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdGetNodes::CCmdGetNodes() : CBaseCommand(P2S_CMD_GETNODES) { } CCmdGetNodes::~CCmdGetNodes(void) { } int CCmdGetNodes::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdGetNodes::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdGetNodesRet::CCmdGetNodesRet() : CBaseCommand(P2S_CMD_GETGROUPS_RET) { } CCmdGetNodesRet::~CCmdGetNodesRet(void) { } int CCmdGetNodesRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdGetNodesRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdLoginChannel::CCmdLoginChannel() : CBaseCommand(P2S_CMD_LOGIN_CHANNEL) { } CCmdLoginChannel::~CCmdLoginChannel(void) { } int CCmdLoginChannel::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sNodeName, nLen ); p = push_str_2( p, m_sChannelID, nLen ); p = push_int8_2( p, m_cSource, nLen ); p = push_str_2( p, m_sFilePath, nLen ); p = push_str_2( p, m_sFileName, nLen ); p = push_str_2( p, m_sFileSize, nLen ); return (int)(p - pBuffer); } int CCmdLoginChannel::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sNodeName ); p = pop_str( p, m_sChannelID ); p = pop_int8( p, m_cSource ); p = pop_str( p, m_sFilePath ); p = pop_str( p, m_sFileName ); p = pop_str( p, m_sFileSize ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdLoginChannelRet::CCmdLoginChannelRet() : CBaseCommand(P2S_CMD_LOGIN_CHANNEL_RET) { } CCmdLoginChannelRet::~CCmdLoginChannelRet(void) { } int CCmdLoginChannelRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen ); return (int)(p - pBuffer); } int CCmdLoginChannelRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdLogoutChannel::CCmdLogoutChannel() : CBaseCommand(P2S_CMD_LOGOUT_CHANNEL) { } CCmdLogoutChannel::~CCmdLogoutChannel(void) { } int CCmdLogoutChannel::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen ); return (int)(p - pBuffer); } int CCmdLogoutChannel::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdLogoutChannelRet::CCmdLogoutChannelRet() : CBaseCommand(P2S_CMD_LOGOUT_CHANNEL_RET) { } CCmdLogoutChannelRet::~CCmdLogoutChannelRet(void) { } int CCmdLogoutChannelRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen ); return (int)(p - pBuffer); } int CCmdLogoutChannelRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdGetPeers::CCmdGetPeers() : CBaseCommand(P2S_CMD_GETPEERS) { } CCmdGetPeers::~CCmdGetPeers(void) { } int CCmdGetPeers::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen ); p = push_int8_2( p, m_cSource, nLen ); return (int)(p - pBuffer); } int CCmdGetPeers::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); p = pop_int8( p, m_cSource); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdGetPeersRet::CCmdGetPeersRet() : CBaseCommand(P2S_CMD_GETPEERS_RET) { } CCmdGetPeersRet::~CCmdGetPeersRet(void) { } int CCmdGetPeersRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen); m_nPeerCount = (int)m_listPeers.size(); p = push_int32_2( p, m_nPeerCount, nLen ); list<PEERINFO>::iterator it = m_listPeers.begin(); while ( it != m_listPeers.end() ) { PEERINFO& peerinfo = *it; int len = sizeof(peerinfo); p = push_buf_2( p, (const char *)&peerinfo, len, nLen ); it++; } return (int)(p - pBuffer); } int CCmdGetPeersRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); p = pop_int32( p, m_nPeerCount ); PEERINFO peerinfo; short slen = sizeof(peerinfo); for ( int i = 0; i < m_nPeerCount; i++ ) { p = pop_buf( p, (char *)&peerinfo, slen ); m_listPeers.push_back(peerinfo); } return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdPeerLogin::CCmdPeerLogin() : CBaseCommand(P2S_CMD_PEERLOGIN) { } CCmdPeerLogin::~CCmdPeerLogin(void) { } int CCmdPeerLogin::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen); m_nPeerCount = (int)m_listPeers.size(); p = push_int32_2( p, m_nPeerCount, nLen ); list<PEERINFO>::iterator it = m_listPeers.begin(); while ( it != m_listPeers.end() ) { PEERINFO& peerinfo = *it; int len = sizeof(peerinfo); p = push_buf_2( p, (const char *)&peerinfo, len, nLen ); it++; } return (int)(p - pBuffer); } int CCmdPeerLogin::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); p = pop_int32( p, m_nPeerCount ); PEERINFO peerinfo; short slen = sizeof(peerinfo); for ( int i = 0; i < m_nPeerCount; i++ ) { p = pop_buf( p, (char *)&peerinfo, slen ); m_listPeers.push_back(peerinfo); } return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdPeerLogout::CCmdPeerLogout() : CBaseCommand(P2S_CMD_PEERLOGOUT) { } CCmdPeerLogout::~CCmdPeerLogout(void) { } int CCmdPeerLogout::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_str_2( p, m_sChannelID, nLen); m_nPeerCount = (int)m_listPeers.size(); p = push_int32_2( p, m_nPeerCount, nLen ); list<PEERINFO>::iterator it = m_listPeers.begin(); while ( it != m_listPeers.end() ) { PEERINFO& peerinfo = *it; int len = sizeof(peerinfo); p = push_buf_2( p, (const char *)&peerinfo, len, nLen ); it++; } return (int)(p - pBuffer); } int CCmdPeerLogout::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_str( p, m_sChannelID ); p = pop_int32( p, m_nPeerCount ); PEERINFO peerinfo; short slen = sizeof(peerinfo); for ( int i = 0; i < m_nPeerCount; i++ ) { p = pop_buf( p, (char *)&peerinfo, slen ); m_listPeers.push_back(peerinfo); } return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdReqShootTo::CCmdReqShootTo() : CBaseCommand(P2S_CMD_REQSHOOTTO) { } CCmdReqShootTo::~CCmdReqShootTo(void) { } int CCmdReqShootTo::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nTargetUserID, nLen); return (int)(p - pBuffer); } int CCmdReqShootTo::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nTargetUserID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdReqShootToRet::CCmdReqShootToRet() : CBaseCommand(P2S_CMD_REQSHOOTTO_RET) { } CCmdReqShootToRet::~CCmdReqShootToRet(void) { } int CCmdReqShootToRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nTargetUserID, nLen); return (int)(p - pBuffer); } int CCmdReqShootToRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nTargetUserID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdShootArrived::CCmdShootArrived() : CBaseCommand(P2S_CMD_SHOOTARRIVED) { } CCmdShootArrived::~CCmdShootArrived(void) { } int CCmdShootArrived::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_buf_2( p, (const char *)&m_peerinfoSource, sizeof(PEERINFO), nLen ); return (int)(p - pBuffer); } int CCmdShootArrived::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); short len = 0; p = pop_buf( p, (char *)&m_peerinfoSource, len ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdTcpHeartbeat::CCmdTcpHeartbeat() : CBaseCommand(P2S_CMD_TCP_HEARTBEAT) { } CCmdTcpHeartbeat::~CCmdTcpHeartbeat(void) { } int CCmdTcpHeartbeat::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdTcpHeartbeat::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdClose::CCmdClose() : CBaseCommand(P2S_CMD_CLOSE) { } CCmdClose::~CCmdClose(void) { } int CCmdClose::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdClose::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdCloseRet::CCmdCloseRet() : CBaseCommand(P2S_CMD_CLOSE_RET) { } CCmdCloseRet::~CCmdCloseRet(void) { } int CCmdCloseRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdCloseRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdUdpHeartbeat::CCmdUdpHeartbeat() : CBaseCommand(P2S_CMD_UDP_HEARTBEAT) { } CCmdUdpHeartbeat::~CCmdUdpHeartbeat(void) { } int CCmdUdpHeartbeat::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); return (int)(p - pBuffer); } int CCmdUdpHeartbeat::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdUdpHeartbeatRet::CCmdUdpHeartbeatRet() : CBaseCommand(P2S_CMD_UDP_HEARTBEAT_RET) { } CCmdUdpHeartbeatRet::~CCmdUdpHeartbeatRet(void) { } int CCmdUdpHeartbeatRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_timestamp_2( p, m_ulExternalIP, nLen); p = push_uint16_2( p, m_usExternalUDPPort, nLen); return (int)(p - pBuffer); } int CCmdUdpHeartbeatRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_timestamp( p, m_ulExternalIP); p = pop_uint16( p, m_usExternalUDPPort); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ CCmdRoomCreate::CCmdRoomCreate() : CBaseCommand(P2S_CMD_ROOM_CREATE) { } CCmdRoomCreate::~CCmdRoomCreate(void) { } int CCmdRoomCreate::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int8_2( p, m_ucMaxPersons, nLen); p = push_int32_2( p, m_nKind, nLen); p = push_str_2( p, m_sName, nLen ); p = push_str_2( p, m_sPassword, nLen ); return (int)(p - pBuffer); } int CCmdRoomCreate::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int8( p, (char &)m_ucMaxPersons); p = pop_int32( p, m_nKind ); p = pop_str( p, m_sName ); p = pop_str( p, m_sPassword ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomCreateRet::CCmdRoomCreateRet() : CBaseCommand(P2S_CMD_ROOM_CREATE_RET) { } CCmdRoomCreateRet::~CCmdRoomCreateRet(void) { } int CCmdRoomCreateRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int8_2( p, m_ucMaxPersons, nLen); p = push_int32_2( p, m_nKind, nLen); p = push_str_2( p, m_sName, nLen ); p = push_int32_2( p, m_nID, nLen); return (int)(p - pBuffer); } int CCmdRoomCreateRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int8( p, (char &)m_ucMaxPersons); p = pop_int32( p, m_nKind ); p = pop_str( p, m_sName ); p = pop_int32( p, m_nID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomLogin::CCmdRoomLogin() : CBaseCommand(P2S_CMD_ROOM_LOGIN) { } CCmdRoomLogin::~CCmdRoomLogin(void) { } int CCmdRoomLogin::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); return (int)(p - pBuffer); } int CCmdRoomLogin::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomLoginRet::CCmdRoomLoginRet() : CBaseCommand(P2S_CMD_ROOM_LOGIN_RET) { } CCmdRoomLoginRet::~CCmdRoomLoginRet(void) { } int CCmdRoomLoginRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nMasterID, nLen); p = push_int32_2( p, m_nRet, nLen); p = push_int8_2( p, m_ucIndex, nLen); p = push_int8_2( p, m_ucMaxPersons, nLen); p = push_int8_2( p, m_ucCurPersons, nLen); return (int)(p - pBuffer); } int CCmdRoomLoginRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID); p = pop_int32( p, m_nSessionID); p = pop_int32( p, m_nID); p = pop_int32( p, m_nMasterID); p = pop_int32( p, m_nRet); p = pop_int8( p, (char &)m_ucIndex); p = pop_int8( p, (char &)m_ucMaxPersons); p = pop_int8( p, (char &)m_ucCurPersons); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomLoginNtf::CCmdRoomLoginNtf() : CBaseCommand(P2S_CMD_ROOM_LOGIN_NTF) { } CCmdRoomLoginNtf::~CCmdRoomLoginNtf(void) { } int CCmdRoomLoginNtf::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nMasterID, nLen); p = push_int8_2( p, m_ucMaxPersons, nLen); m_ucCurPersons = (unsigned char)m_mapPersons.size(); p = push_int8_2( p, m_ucCurPersons, nLen); map<unsigned char, PEERINFO>::iterator it = m_mapPersons.begin(); while ( it != m_mapPersons.end() ) { p = push_int8_2( p, it->first, nLen); p = push_buf_2( p, (char *)(&it->second), sizeof(PEERINFO), nLen); it ++; } return (int)(p - pBuffer); } int CCmdRoomLoginNtf::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID); p = pop_int32( p, m_nSessionID); p = pop_int32( p, m_nID); p = pop_int32( p, m_nMasterID); p = pop_int8( p, (char &)m_ucMaxPersons); p = pop_int8( p, (char &)m_ucCurPersons); unsigned char ucIndex; PEERINFO peerInfo; for ( unsigned char uc = 0; uc < m_ucCurPersons; uc ++) { short len = 0; p = pop_int8( p, (char &)ucIndex); p = pop_buf( p, (char *)(&peerInfo), len); m_mapPersons[ucIndex] = peerInfo; } return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomLogout::CCmdRoomLogout() : CBaseCommand(P2S_CMD_ROOM_LOGOUT) { } CCmdRoomLogout::~CCmdRoomLogout(void) { } int CCmdRoomLogout::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); return (int)(p - pBuffer); } int CCmdRoomLogout::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomLogoutRet::CCmdRoomLogoutRet() : CBaseCommand(P2S_CMD_ROOM_LOGOUT_RET) { } CCmdRoomLogoutRet::~CCmdRoomLogoutRet(void) { } int CCmdRoomLogoutRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nRet, nLen); p = push_int8_2( p, m_ucIndex, nLen); return (int)(p - pBuffer); } int CCmdRoomLogoutRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID); p = pop_int32( p, m_nSessionID); p = pop_int32( p, m_nID); p = pop_int32( p, m_nRet); p = pop_int8( p, (char &)m_ucIndex); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomLogoutNtf::CCmdRoomLogoutNtf() : CBaseCommand(P2S_CMD_ROOM_LOGOUT_NTF) { } CCmdRoomLogoutNtf::~CCmdRoomLogoutNtf(void) { } int CCmdRoomLogoutNtf::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nPeerID, nLen); p = push_int8_2( p, m_ucIndex, nLen); return (int)(p - pBuffer); } int CCmdRoomLogoutNtf::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID); p = pop_int32( p, m_nSessionID); p = pop_int32( p, m_nID); p = pop_int32( p, m_nPeerID); p = pop_int8( p, (char &)m_ucIndex); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomDelete::CCmdRoomDelete() : CBaseCommand(P2S_CMD_ROOM_DELETE) { } CCmdRoomDelete::~CCmdRoomDelete(void) { } int CCmdRoomDelete::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); return (int)(p - pBuffer); } int CCmdRoomDelete::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomDeleteRet::CCmdRoomDeleteRet() : CBaseCommand(P2S_CMD_ROOM_DELETE_RET) { } CCmdRoomDeleteRet::~CCmdRoomDeleteRet(void) { } int CCmdRoomDeleteRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nRet, nLen); return (int)(p - pBuffer); } int CCmdRoomDeleteRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID); p = pop_int32( p, m_nSessionID); p = pop_int32( p, m_nID); p = pop_int32( p, m_nRet); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomModify::CCmdRoomModify() : CBaseCommand(P2S_CMD_ROOM_MODIFY) { } CCmdRoomModify::~CCmdRoomModify(void) { } int CCmdRoomModify::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nOldKind, nLen); p = push_int32_2( p, m_nNewKind, nLen); p = push_str_2( p, m_sName, nLen); return (int)(p - pBuffer); } int CCmdRoomModify::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nOldKind ); p = pop_int32( p, m_nNewKind ); p = pop_str( p, m_sName ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomModifyRet::CCmdRoomModifyRet() : CBaseCommand(P2S_CMD_ROOM_MODIFY_RET) { } CCmdRoomModifyRet::~CCmdRoomModifyRet(void) { } int CCmdRoomModifyRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nOldKind, nLen); p = push_int32_2( p, m_nNewKind, nLen); p = push_str_2( p, m_sName, nLen); p = push_int32_2( p, m_nRet, nLen); return (int)(p - pBuffer); } int CCmdRoomModifyRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nOldKind ); p = pop_int32( p, m_nNewKind ); p = pop_str( p, m_sName ); p = pop_int32( p, m_nRet ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomPostData::CCmdRoomPostData() : CBaseCommand(P2S_CMD_ROOM_POST_DATA) { } CCmdRoomPostData::~CCmdRoomPostData(void) { } int m_nUserID; int m_nSessionID; int m_nID; int m_nDataNum; // ÐòºÅ unsigned short m_usDataLen; char m_szData[ROOM_PACKET_MAX_LEN]; int CCmdRoomPostData::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nDataNum, nLen); p = push_int16_2( p, m_usDataLen, nLen); p = push_buf_2( p, m_szData, m_usDataLen, nLen); return (int)(p - pBuffer); } int CCmdRoomPostData::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nDataNum ); p = pop_int16( p, (short &)m_usDataLen ); short len = 0; p = pop_buf( p, m_szData, len); assert( m_usDataLen == len ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomPostDataRet::CCmdRoomPostDataRet() : CBaseCommand(P2S_CMD_ROOM_POST_DATA_RET) { } CCmdRoomPostDataRet::~CCmdRoomPostDataRet(void) { } int CCmdRoomPostDataRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nDataNum, nLen); p = push_int16_2( p, m_usDataLen, nLen); return (int)(p - pBuffer); } int CCmdRoomPostDataRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nDataNum ); p = pop_int16( p, (short &)m_usDataLen ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomPostDataBrd::CCmdRoomPostDataBrd() : CBaseCommand(P2S_CMD_ROOM_POST_DATA_BRD) { } CCmdRoomPostDataBrd::~CCmdRoomPostDataBrd(void) { } int CCmdRoomPostDataBrd::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nDataNum, nLen); m_ucBroadcastNum = m_listBroadcastIndex.size(); p = push_int8_2( p, m_ucBroadcastNum, nLen); list<unsigned char>::iterator it = m_listBroadcastIndex.begin(); while ( it != m_listBroadcastIndex.end() ) { p = push_int8_2( p, *it, nLen); it ++; } p = push_int16_2( p, m_usDataLen, nLen); p = push_buf_2( p, m_szData, m_usDataLen, nLen); return (int)(p - pBuffer); } int CCmdRoomPostDataBrd::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nDataNum ); p = pop_int8( p, (char &)m_ucBroadcastNum ); for( unsigned char uc = 0; uc < m_ucBroadcastNum; uc ++) { unsigned char ucIndex; p = pop_int8( p, (char &)ucIndex); m_listBroadcastIndex.push_back( ucIndex); } p = pop_int16( p, (short &)m_usDataLen ); short len = 0; p = pop_buf( p, m_szData, len); assert( len == m_usDataLen); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomGetData::CCmdRoomGetData() : CBaseCommand(P2S_CMD_ROOM_GET_DATA) { } CCmdRoomGetData::~CCmdRoomGetData(void) { } int CCmdRoomGetData::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nDataNum, nLen); p = push_int32_2( p, m_nPriority, nLen); return (int)(p - pBuffer); } int CCmdRoomGetData::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nDataNum ); p = pop_int32( p, m_nPriority ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomGetDataRet::CCmdRoomGetDataRet() : CBaseCommand(P2S_CMD_ROOM_GET_DATA_RET) { } CCmdRoomGetDataRet::~CCmdRoomGetDataRet(void) { } int CCmdRoomGetDataRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nDataNum, nLen); p = push_int16_2( p, m_usDataLen, nLen); p = push_buf_2( p, m_szData, m_usDataLen, nLen); return (int)(p - pBuffer); } int CCmdRoomGetDataRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nDataNum ); p = pop_int16( p, (short &)m_usDataLen ); short len = 0; p = pop_buf( p, m_szData, len); assert( m_usDataLen == len ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomClose::CCmdRoomClose() : CBaseCommand(P2S_CMD_ROOM_CLOSE) { } CCmdRoomClose::~CCmdRoomClose(void) { } int CCmdRoomClose::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); return (int)(p - pBuffer); } int CCmdRoomClose::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdRoomCloseRet::CCmdRoomCloseRet() : CBaseCommand(P2S_CMD_ROOM_CLOSE_RET) { } CCmdRoomCloseRet::~CCmdRoomCloseRet(void) { } int CCmdRoomCloseRet::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int32_2( p, m_nRet, nLen); return (int)(p - pBuffer); } int CCmdRoomCloseRet::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int32( p, m_nRet); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ CCmdMonitorTransdata::CCmdMonitorTransdata() : CBaseCommand(P2S_CMD_MONITOR_TRANSDATA) { } CCmdMonitorTransdata::~CCmdMonitorTransdata(void) { } int CCmdMonitorTransdata::Create( char* pBuffer, int& nLen ) { int nRet = CBaseCommand::Create( pBuffer, nLen ); char* p = pBuffer + nRet; p = push_int32_2( p, m_nUserID, nLen); p = push_int32_2( p, m_nSessionID, nLen); p = push_int32_2( p, m_nID, nLen); p = push_int8_2( p, m_cRemoveAllFlag, nLen); p = push_int8_2( p, m_cTransType, nLen); p = push_int8_2( p, m_cMonitorType, nLen); p = push_int8_2( p, m_cTransWeight, nLen); p = push_int8_2( p, m_cSendInterval, nLen); p = push_int32_2( p, m_nDstIP, nLen); p = push_int16_2( p, m_usDstPort, nLen); return (int)(p - pBuffer); } int CCmdMonitorTransdata::Parse( char* pBuffer, int nLen ) { int nRet = CBaseCommand::Parse( pBuffer, nLen ); char* p = pBuffer + nRet; p = pop_int32( p, m_nUserID ); p = pop_int32( p, m_nSessionID ); p = pop_int32( p, m_nID ); p = pop_int8( p, m_cRemoveAllFlag ); p = pop_int8( p, m_cTransType ); p = pop_int8( p, m_cMonitorType ); p = pop_int8( p, m_cTransWeight ); p = pop_int8( p, m_cSendInterval ); p = pop_int32( p, m_nDstIP ); p = pop_int16( p, (short &)m_usDstPort ); return (int)(p - pBuffer); } //------------------------------------------------------------------------------------ }
[ "fuwenke@b5bb1052-fe17-11dd-bc25-5f29055a2a2d" ]
[ [ [ 1, 1845 ] ] ]
dba76c912627d7857e7dc79dec86cd5d6be64a35
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/FugueDLL/Virtual Machine/Operations/Concurrency/Tasks.cpp
1e5a767f8846ccc69a95896ce69e4d5364a9f052
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
5,262
cpp
// // The Epoch Language Project // FUGUE Virtual Machine // // Operations and auxiliary functions for asynchronous task support // #include "pch.h" #include "Virtual Machine/Core Entities/Block.h" #include "Virtual Machine/Core Entities/Scopes/ActivatedScope.h" #include "Virtual Machine/Core Entities/Concurrency/ResponseMap.h" #include "Virtual Machine/Core Entities/Program.h" #include "Virtual Machine/Operations/Concurrency/Tasks.h" #include "Virtual Machine/Thread Pooling/WorkItems.h" #include "Virtual Machine/Types Management/TypeInfo.h" #include "Virtual Machine/Routines.inl" #include "Virtual Machine/VMExceptions.h" #include "Virtual Machine/SelfAware.inl" #include "Parser/Parser State Machine/ParserState.h" #include "Utility/Threading/Threads.h" #include "Utility/Memory/Heap.h" #include "Utility/Memory/Stack.h" #include "Utility/Strings.h" #include "Validator/Validator.h" #include "Serialization/SerializationTraverser.h" using namespace VM; using namespace VM::Operations; // Prototypes DWORD __stdcall ExecuteEpochTask(void* info); // // Destruct and clean up a task forking operation // ForkTask::~ForkTask() { delete CodeBlock; } // // Fork a task and start execution in the new context // void ForkTask::ExecuteFast(ExecutionContext& context) { StringVariable temp(context.Stack.GetCurrentTopOfStack()); std::wstring taskname = temp.GetValue(); context.Stack.Pop(temp.GetStorageSize()); Threads::Create(taskname, ExecuteEpochTask, CodeBlock, &context.RunningProgram); } RValuePtr ForkTask::ExecuteAndStoreRValue(ExecutionContext& context) { ExecuteFast(context); return RValuePtr(new NullRValue); } template <typename TraverserT> void ForkTask::TraverseHelper(TraverserT& traverser) { traverser.TraverseNode(*this); traverser.EnterTask(); if(CodeBlock) CodeBlock->Traverse(traverser); traverser.ExitTask(); } void ForkTask::Traverse(Validator::ValidationTraverser& traverser) { TraverseHelper(traverser); } void ForkTask::Traverse(Serialization::SerializationTraverser& traverser) { TraverseHelper(traverser); } // // Destruct and clean up a thread forking operation // ForkThread::~ForkThread() { delete CodeBlock; } // // Fork a thread and start execution in the new context // void ForkThread::ExecuteFast(ExecutionContext& context) { std::wstring threadname, poolname; { StringVariable temp(context.Stack.GetCurrentTopOfStack()); poolname = temp.GetValue(); context.Stack.Pop(temp.GetStorageSize()); } { StringVariable temp(context.Stack.GetCurrentTopOfStack()); threadname = temp.GetValue(); context.Stack.Pop(temp.GetStorageSize()); } std::auto_ptr<Threads::PoolWorkItem> workitem(new ForkThreadWorkItem(*CodeBlock, context)); context.RunningProgram.AddPoolWorkItem(poolname, threadname, workitem); } RValuePtr ForkThread::ExecuteAndStoreRValue(ExecutionContext& context) { ExecuteFast(context); return RValuePtr(new NullRValue); } template <typename TraverserT> void ForkThread::TraverseHelper(TraverserT& traverser) { traverser.TraverseNode(*this); traverser.EnterThread(); if(CodeBlock) CodeBlock->Traverse(traverser); traverser.ExitThread(); } void ForkThread::Traverse(Validator::ValidationTraverser& traverser) { TraverseHelper(traverser); } void ForkThread::Traverse(Serialization::SerializationTraverser& traverser) { TraverseHelper(traverser); } void CreateThreadPool::ExecuteFast(ExecutionContext& context) { std::wstring poolname; Integer32 numthreads; { IntegerVariable temp(context.Stack.GetCurrentTopOfStack()); numthreads = temp.GetValue(); context.Stack.Pop(temp.GetStorageSize()); } { StringVariable temp(context.Stack.GetCurrentTopOfStack()); poolname = temp.GetValue(); context.Stack.Pop(temp.GetStorageSize()); } context.RunningProgram.CreateThreadPool(poolname, numthreads); } RValuePtr CreateThreadPool::ExecuteAndStoreRValue(ExecutionContext& context) { ExecuteFast(context); return RValuePtr(new NullRValue); } // // Entry point stub for forked Epoch task threads // DWORD __stdcall ExecuteEpochTask(void* info) { try { Threads::Enter(info); Threads::ThreadInfo* threadinfo = reinterpret_cast<Threads::ThreadInfo*>(info); Block* codeblock = threadinfo->CodeBlock; StackSpace stack; FlowControlResult flowresult = FLOWCONTROL_NORMAL; std::auto_ptr<ActivatedScope> newscope(new ActivatedScope(*codeblock->GetBoundScope(), threadinfo->RunningProgram->GetActivatedGlobalScope())); newscope->TaskOrigin = threadinfo->TaskOrigin; codeblock->ExecuteBlock(ExecutionContext(*threadinfo->RunningProgram, *newscope, stack, flowresult), NULL); newscope->Exit(stack); if(stack.GetAllocatedStack() != 0) throw InternalFailureException("A stack space leak was detected when exiting an Epoch task."); } catch(std::exception& ex) { ::MessageBoxA(0, ex.what(), Strings::WindowTitle, MB_ICONERROR); } catch(...) { ::MessageBoxA(0, "An unexpected error has occurred while executing an Epoch task.", Strings::WindowTitle, MB_ICONERROR); } Threads::Exit(); return 0; }
[ "[email protected]", "don.apoch@localhost", "Mike Lewis@localhost" ]
[ [ [ 1, 15 ], [ 17, 20 ], [ 23, 53 ], [ 55, 55 ], [ 57, 57 ], [ 60, 61 ], [ 63, 63 ], [ 65, 88 ], [ 174, 187 ], [ 190, 190 ], [ 192, 211 ] ], [ [ 16, 16 ], [ 54, 54 ], [ 56, 56 ], [ 58, 59 ], [ 62, 62 ], [ 64, 64 ], [ 100, 100 ], [ 105, 105 ], [ 107, 107 ], [ 111, 111 ], [ 113, 113 ], [ 116, 117 ], [ 120, 120 ], [ 122, 122 ], [ 147, 147 ], [ 149, 149 ], [ 153, 153 ], [ 155, 155 ], [ 159, 161 ], [ 164, 164 ], [ 167, 167 ], [ 169, 169 ], [ 188, 189 ], [ 191, 191 ] ], [ [ 21, 22 ], [ 89, 99 ], [ 101, 104 ], [ 106, 106 ], [ 108, 110 ], [ 112, 112 ], [ 114, 115 ], [ 118, 119 ], [ 121, 121 ], [ 123, 146 ], [ 148, 148 ], [ 150, 152 ], [ 154, 154 ], [ 156, 158 ], [ 162, 163 ], [ 165, 166 ], [ 168, 168 ], [ 170, 173 ] ] ]
66add10b3f6612fe07594bb7286b6a9822926b97
62874cd4e97b2cfa74f4e507b798f6d5c7022d81
/src/libMidi-Me/Timer.h
c76c2453024cb67de725ad0d6b933f7bc2ef404a
[]
no_license
rjaramih/midi-me
6a4047e5f390a5ec851cbdc1b7495b7fe80a4158
6dd6a1a0111645199871f9951f841e74de0fe438
refs/heads/master
2021-03-12T21:31:17.689628
2011-07-31T22:42:05
2011-07-31T22:42:05
36,944,802
0
0
null
null
null
null
UTF-8
C++
false
false
784
h
#ifndef MIDIME_TIMER_H #define MIDIME_TIMER_H // Includes #include "global.h" namespace MidiMe { /** This class is a cross-platform timer. You can get the current tick (in miliseconds) and sleep. */ class LIBMIDIME_API Timer { public: struct LIBMIDIME_API TimeValue { int year; int month; //! 1-12 int day; //! 1-31 int hour; //! 0-59 int minute; //! 0-59 int second; //! 0-59 int millisecond; //! 0-99 TimeValue operator-(const TimeValue &time) const; string dateString() const; string timeString() const; }; public: // Static functions static unsigned int getTickCount(); static TimeValue getLocalTime(); static void wait(unsigned int milliSeconds); }; } #endif // MIDIME_TIMER_H
[ "Jeroen.Dierckx@d8a2fbcc-2753-0410-82a0-8bc2cd85795f" ]
[ [ [ 1, 38 ] ] ]
1ab3b3d65acda1bf466d65fa14e02349d5d2d372
115c6a1371464f59f4e29fdc9202e082d4e9f18a
/3ba3/OS/Assignments/Deadlock/MessageQueue.h
df66761d27239d6a304cfa27b9cc520efc0921f4
[]
no_license
conallob/college-notes
a371152fade819801e9d1454287ea0e06526d27a
57d29cc8e4100eba9c07c12b3c48c741799d1d27
refs/heads/master
2021-02-25T06:19:29.955774
2011-01-15T16:56:02
2011-01-15T16:56:02
245,449,579
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
// $Id$ #ifndef MESSAGEQ_H #define MESSAGEQ_H #define MAX_MESSAGE_LENGTH 100 typedef struct MessageFormat { long message_type; char mess[MAX_MESSAGE_LENGTH]; } tMessageFormat; class CMessageQueue { public: CMessageQueue(); ~CMessageQueue(); void Send(tMessageFormat* message, int message_size); bool Receive(long message_type, tMessageFormat* message, int& message_size); private: int mID; }; #endif
[ [ [ 1, 22 ] ] ]
40898519048da6ca0d13cc203f511062aef174e9
d8ee6216089aa884589ca9175d3bc191dcc1ea12
/PostEffectProgram/Src/DeferredLighting.cpp
4c8e0ab69191a651c0ed215904a178fed6689031
[]
no_license
OtterOrder/posteffectprogram
a15035eb96a107ec220f834baeb4c4db2573fd56
ff713b71ba72984e74fc62e9a1f7b1fb8fb43198
refs/heads/master
2016-09-05T09:06:20.138050
2009-06-30T07:21:43
2009-06-30T07:21:43
32,115,407
0
0
null
null
null
null
UTF-8
C++
false
false
3,474
cpp
#include "DeferredLighting.h" #include "PostRenderer.h" #include "Scene.h" #include "Light.h" //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ DeferredLighting::DeferredLighting() { } //------------------------------------------------------------------------------------------------------------------------------ DeferredLighting::~DeferredLighting() { } //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ void DeferredLighting::Create (Vector2i _size) { SetShader(NULL, NULL, "..\\Datas\\Shaders\\PSDeferredLighting.psh", "PSMain"); } //------------------------------------------------------------------------------------------------------------------------------ void DeferredLighting::Release () { } //------------------------------------------------------------------------------------------------------------------------------ void DeferredLighting::Destroy () { } //------------------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------------------ void DeferredLighting::Apply() { m_pShader->Activate(); GBufferRenderer* pGBRenderer = GBufferRenderer::GetSingleton(); PostRenderer* pPostRenderer = PostRenderer::GetSingleton(); Vector3f cameraPosition = *(pGBRenderer->GetCamera().GetEyePt()); m_pShader->SetPSVector3f("gCamPosition", cameraPosition); m_pShader->SetPSFloat("gZNear", pGBRenderer->GetCamera().GetNearClip()); m_pShader->SetPSFloat("gZFar", pGBRenderer->GetCamera().GetFarClip()); Matrix ViewProjInv; MatrixMultiply (&ViewProjInv, pGBRenderer->GetCamera().GetViewMatrix(), pGBRenderer->GetCamera().GetProjMatrix()); MatrixInverse(&ViewProjInv, NULL, &ViewProjInv); m_pShader->SetPSMatrix("gViewProjInv", ViewProjInv); m_pShader->SetPSSampler("DiffuseSampler", pPostRenderer->GetGBuffer()->m_pDiffuseMap.GetTexture()); m_pShader->SetPSSampler("NormalSampler", pPostRenderer->GetGBuffer()->m_pNormalMap.GetTexture()); m_pShader->SetPSSampler("DepthSampler", pPostRenderer->GetGBuffer()->m_pDepthMap.GetTexture()); getDevice->ColorFill(pPostRenderer->GetBackRenderSurface(), NULL, Vector3fToColor(Vector3f(0.f, 0.f, 0.f)) ); vector<Light*>* pLightList = Scene::GetSingleton()->GetLightList(); Light::Iterator LightIt; for (LightIt = pLightList->begin(); LightIt < pLightList->end(); LightIt++) { pPostRenderer->SetRenderTarget(pPostRenderer->GetFrontRenderSurface()); m_pShader->SetPSSampler("RenderSampler", pPostRenderer->GetBackRenderTexture()); m_pShader->SetPSVector3f("gLightPosition", (*LightIt)->GetPosition()); //m_pShader->SetPSVector3f("gLightDirection", lightDirection); m_pShader->SetPSVector3f("gLightDiffuse", (*LightIt)->GetDiffuse()); m_pShader->SetPSVector3f("gLightSpecular", (*LightIt)->GetSpecular()); pPostRenderer->DrawScreenQuad(); pPostRenderer->SwapSceneRender(); } pPostRenderer->SwapSceneRender(); }
[ "alban.chagnoleau@7ea0d518-2368-11de-96a1-5542d1fc8aa6" ]
[ [ [ 1, 80 ] ] ]
3b2b0519596fb04fb9de1f1733a161793f205eff
fd3f2268460656e395652b11ae1a5b358bfe0a59
/cryptopp/adler32.h
18413884f54a0e185be1501e231cd11760144d86
[ "LicenseRef-scancode-cryptopp", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
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
656
h
#ifndef CRYPTOPP_ADLER32_H #define CRYPTOPP_ADLER32_H #include "cryptlib.h" NAMESPACE_BEGIN(CryptoPP) //! ADLER-32 checksum calculations class Adler32 : public HashTransformation { public: CRYPTOPP_CONSTANT(DIGESTSIZE = 4) Adler32() {Reset();} void Update(const byte *input, size_t length); void TruncatedFinal(byte *hash, size_t size); unsigned int DigestSize() const {return DIGESTSIZE;} static const char * StaticAlgorithmName() {return "Adler32";} std::string AlgorithmName() const {return StaticAlgorithmName();} private: void Reset() {m_s1 = 1; m_s2 = 0;} word16 m_s1, m_s2; }; NAMESPACE_END #endif
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b", "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 16 ], [ 19, 28 ] ], [ [ 17, 18 ] ] ]
7140af50d627eeb045c857b484d6e352727b0ac4
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/spirit/example/lex/example.hpp
0582afa00b18cf20cdc2c2825f24ef969f737f70
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
962
hpp
// Copyright (c) 2001-2009 Hartmut Kaiser // Copyright (c) 2001-2007 Joel de Guzman // // 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) #include <iostream> #include <fstream> #include <string> /////////////////////////////////////////////////////////////////////////////// // Helper function reading a file into a string /////////////////////////////////////////////////////////////////////////////// inline std::string read_from_file(char const* infile) { std::ifstream instream(infile); if (!instream.is_open()) { std::cerr << "Couldn't open file: " << infile << std::endl; exit(-1); } instream.unsetf(std::ios::skipws); // No white space skipping! return std::string(std::istreambuf_iterator<char>(instream.rdbuf()), std::istreambuf_iterator<char>()); }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 26 ] ] ]
5ae0ccd35b08eb239d13a23ead44d3159fd04c6c
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/CheckConflict.cpp
2f37037ee87eacfd6277809ad9da516eb966ec47
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
14,731
cpp
#include "StdAfx.h" #include <strsafe.h> #include ".\checkconflict.h" #include "ini2.h" #include "emule.h" const CCheckConflict::CONFILCT_MOD_ENTRY CCheckConflict::s_conflictModuleList[] = { _T("Fortress.dll"), _T("山丽网络堡垒"), 1, CCheckConflict::ThirdPartyError, _T("KB8964115.log"), _T("未知"), 1, CCheckConflict::ThirdPartyError, _T("ESPI11.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, _T("asycfilt.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, // _T("jscript.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, _T("imon.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, // _T("uxtheme.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, _T("nvappfilter.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, _T("dictnt.dll"), _T("未知"), 1, CCheckConflict::ThirdPartyError, _T("iKeeper.dll"), _T("网吧管理系统"), 1, CCheckConflict::ThirdPartyError, _T("unispim.ime"), _T("紫光输入法"), 1, CCheckConflict::ThirdPartyError, _T("jpwb.IME"), _T("极品五笔输入法"), 1, CCheckConflict::ThirdPartyError, _T("PINTLGNT.IME"), _T("输入法"), 1, CCheckConflict::ThirdPartyError, _T("winwb86.IME"), _T("Windows五笔输入法86"), 1, CCheckConflict::ThirdPartyError, _T("WINABC.IME"), _T("ABC输入法"), 1, CCheckConflict::ThirdPartyError, _T("mshtml.dll"), _T("WebBrowser"), 0, CCheckConflict::WebBrowserProblem, _T("urlmon.dll"), _T("WebBrowser"), 0, CCheckConflict::WebBrowserProblem, // VC-Huby[2007-02-10]: build 070206 的2007-02-08中发现350/680的比例是由flash*.ocx 引起Crash _T("flash.ocx"), _T("WebBrowser"), 0, CCheckConflict::FlashProblem, _T("flash9.ocx"), _T("WebBrowser"), 0, CCheckConflict::FlashProblem, _T("flash9b.ocx"), _T("WebBrowser"), 0, CCheckConflict::FlashProblem, _T("flash8.ocx"), _T("WebBrowser"), 0, CCheckConflict::FlashProblem, _T("flash8b.ocx"), _T("WebBrowser"), 0, CCheckConflict::FlashProblem, _T("flash8a.ocx"), _T("WebBrowser"), 0, CCheckConflict::FlashProblem, _T("sockspy.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("K7PSWSEn.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("Iefilter.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("tcpipdog.dll"), _T("未知"), 0, CCheckConflict::SimplyPrompt, _T("tcpipdog0.dll"), _T("未知"), 0, CCheckConflict::SimplyPrompt, _T("HintSock.dll"), _T("Hintsoft Pubwin 网吧管理系统"), 0, CCheckConflict::SimplyPrompt, _T("EagleFlt.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("BtFilter.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("MiFilter2.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("WinFilter.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt, _T("iaudit.dll"), _T("未知"), 1, CCheckConflict::SimplyPrompt }; #define MODULE_LIST_COUNT ( sizeof(s_conflictModuleList) / (sizeof (CONFILCT_MOD_ENTRY)) ) BOOL CCheckConflict::SimplyPrompt(int iModuleIndex, HMODULE hMod) { TCHAR szModuleFileName[MAX_PATH]; szModuleFileName[0] = _T('\0'); GetModuleFileName(hMod, szModuleFileName, MAX_PATH); szModuleFileName[MAX_PATH - 1] = _T('\0'); //*Warning* 修改显示方式时,注重下面szOutput申请的内存是否足够容纳要写入的字符。 LPCTSTR lpcszOutputFormat = _T("eMule 与其他软件发生冲突,即将关闭。\r\n") _T("\r\n") _T("发生冲突的软件名称: [%s]\r\n") _T("发生冲突的模块: [%s]"); size_t nOutputMax = _tcslen(lpcszOutputFormat) + MAX_PATH + DESC_MAX + 1; TCHAR *szOutput = new TCHAR[nOutputMax]; StringCchPrintf(szOutput, nOutputMax, lpcszOutputFormat, s_conflictModuleList[iModuleIndex].szModuleDescription, szModuleFileName); MessageBox(NULL, szOutput, GetResString(IDS_CONFLICT), MB_OK); delete[] szOutput; szOutput = NULL; return TRUE; } BOOL CCheckConflict::ThirdPartyError(int iModuleIndex, HMODULE hMod) { TCHAR szModuleFileName[MAX_PATH]; szModuleFileName[0] = _T('\0'); GetModuleFileName(hMod, szModuleFileName, MAX_PATH); szModuleFileName[MAX_PATH - 1] = _T('\0'); //*Warning* 修改显示方式时,注重下面szOutput申请的内存是否足够容纳要写入的字符。 LPCTSTR lpcszOutputFormat = _T("第三方软件处理出错,导致eMule退出。\r\n") _T("\r\n") _T("出错的软件名称: [%s]\r\n") _T("出错的模块: [%s]"); size_t nOutputMax = _tcslen(lpcszOutputFormat) + MAX_PATH + DESC_MAX + 1; TCHAR *szOutput = new TCHAR[nOutputMax]; StringCchPrintf(szOutput, nOutputMax, lpcszOutputFormat, s_conflictModuleList[iModuleIndex].szModuleDescription, szModuleFileName); MessageBox(NULL, szOutput, _T("第三方软件出错导致eMule退出"), MB_OK); delete[] szOutput; szOutput = NULL; return TRUE; } BOOL CCheckConflict::WebBrowserProblem(int /*iModuleIndex*/, HMODULE /*hMod*/) { BOOL bShowBrowser; if (! GetIniBool(_T("eMule"), _T("Showbrowser"), &bShowBrowser) || !bShowBrowser) //WebBrowser has already been disabled. return FALSE; if (! WriteIniBool(_T("eMule"), _T("Showbrowser"), FALSE)) return FALSE; LPCTSTR lpcszOutput = _T("eMule使用网页浏览器时发生错误。\r\n") _T("\r\n") _T("我们已为您禁用了内置的网页浏览器,以尝试解决这个问题。\r\n") _T("您可以重启eMule,看是否已经可以正常使用。\r\n"); MessageBox(NULL, lpcszOutput, _T("eMule发生错误"), MB_OK); return TRUE; } BOOL CCheckConflict::FlashProblem(int /*iModuleIndex*/, HMODULE hMod) { BOOL bShowBrowser; if (! GetIniBool(_T("eMule"), _T("Showbrowser"), &bShowBrowser) || !bShowBrowser) //WebBrowser has already been disabled. return FALSE; if (! WriteIniBool(_T("eMule"), _T("Showbrowser"), FALSE)) return FALSE; TCHAR szModuleFileName[MAX_PATH]; szModuleFileName[0] = _T('\0'); GetModuleFileName(hMod, szModuleFileName, MAX_PATH); szModuleFileName[MAX_PATH - 1] = _T('\0'); //*Warning* 修改显示方式时,注重下面szOutput申请的内存是否足够容纳要写入的字符。 LPCTSTR lpcszOutputFormat = _T("您目前使用的Flash模块为[%s].\r\n") _T("它可能存在一些问题导致eMule退出。\r\n") _T("我们已经帮你禁用了浏览器功能,您可以尝试再次打开eMule看是否正常。\r\n") _T("\r\n") _T("另外,在您把Flash更新到最新版本之后,\r\n") _T("可以尝试在eMule的“选项”里,打开浏览器功能,以继续正常使用eMule。\r\n"); size_t nOutputMax = _tcslen(lpcszOutputFormat) + MAX_PATH + 1; TCHAR *szOutput = new TCHAR[nOutputMax]; StringCchPrintf(szOutput, nOutputMax, lpcszOutputFormat, szModuleFileName); MessageBox(NULL, szOutput, _T("Flash出现问题"), MB_OK); delete[] szOutput; szOutput = NULL; return TRUE; } CCheckConflict::CCheckConflict(void) { m_hPsapiDll = NULL; m_pfnGetModuleInformation = NULL; m_hDbgHelpDll = NULL; m_pfnStackWalk64 = NULL; m_pfnSymFunctionTableAccess64 = NULL; m_pfnSymGetModuleBase64 = NULL; m_pfnEnumProcessModules = NULL; m_hPsapiDll = LoadLibrary(_T("psapi.dll")); if (NULL != m_hPsapiDll) { m_pfnGetModuleInformation = (PFN_GetModuleInformation) GetProcAddress(m_hPsapiDll, "GetModuleInformation"); m_pfnEnumProcessModules = (PFN_EnumProcessModules) GetProcAddress(m_hPsapiDll, "EnumProcessModules"); } m_hDbgHelpDll = LoadLibrary(_T("dbghelp.dll")); if (NULL != m_hDbgHelpDll) { m_pfnStackWalk64 = (PFN_StackWalk64) GetProcAddress(m_hDbgHelpDll, "StackWalk64"); m_pfnSymFunctionTableAccess64 = (PFUNCTION_TABLE_ACCESS_ROUTINE64) GetProcAddress(m_hDbgHelpDll, "SymFunctionTableAccess64"); m_pfnSymGetModuleBase64 = (PGET_MODULE_BASE_ROUTINE64) GetProcAddress(m_hDbgHelpDll, "SymGetModuleBase64"); } } CCheckConflict::~CCheckConflict(void) { if (NULL != m_hPsapiDll) { FreeLibrary(m_hPsapiDll); m_hPsapiDll = NULL; } if (NULL != m_hDbgHelpDll) { FreeLibrary(m_hDbgHelpDll); m_hDbgHelpDll = NULL; } } BOOL CCheckConflict::CheckConflict(struct _EXCEPTION_POINTERS* pExceptionInfo) { if (!IsFuncitonsReady()) return FALSE; if (IsCrashInEmuleExe(pExceptionInfo)) return FALSE; if (PreCheck(pExceptionInfo)) return TRUE; if (CheckModules(pExceptionInfo)) return TRUE; if (PostCheck(pExceptionInfo)) return TRUE; //if (UserAnalyseDiy(pExceptionInfo)) //如果用户自己已经知道崩溃是怎么回事了,就不弹出“发送错误报告”窗口了。 // return TRUE; return FALSE; } BOOL CCheckConflict::IsFuncitonsReady() { if (NULL == m_pfnGetModuleInformation) return FALSE; if (NULL == m_pfnStackWalk64) return FALSE; if (NULL == m_pfnSymFunctionTableAccess64) return FALSE; if (NULL == m_pfnSymGetModuleBase64) return FALSE; if (NULL == m_pfnEnumProcessModules) return FALSE; return TRUE; } BOOL CCheckConflict::IsAddressInModule(PVOID pvAddress, HMODULE hModule) { if (NULL == m_pfnGetModuleInformation) return FALSE; MODULEINFO mi; if ( m_pfnGetModuleInformation(GetCurrentProcess(), hModule, &mi, sizeof(mi)) ) { if (pvAddress >= mi.lpBaseOfDll && (size_t)pvAddress < (size_t)mi.lpBaseOfDll + (size_t)mi.SizeOfImage) { return TRUE; } } return FALSE; } BOOL CCheckConflict::IsCrashInEmuleExe(struct _EXCEPTION_POINTERS* pExceptionInfo) { HMODULE hEmuleMod = GetModuleHandle(NULL); return IsAddressInModule((PVOID)pExceptionInfo->ExceptionRecord->ExceptionAddress, hEmuleMod); } BOOL CCheckConflict::PreCheck(struct _EXCEPTION_POINTERS* /*pExceptionInfo*/) { return FALSE; } BOOL CCheckConflict::CheckModules(struct _EXCEPTION_POINTERS* pExceptionInfo) { int i, j, jCount; HMODULE hMod; CONTEXT context; STACKFRAME64 sf; for (i = 0; i < MODULE_LIST_COUNT; i++) { hMod = GetModuleHandle(s_conflictModuleList[i].szModuleName); if (NULL == hMod) continue; memcpy(&context, pExceptionInfo->ContextRecord, sizeof(context)); ZeroMemory(&sf, sizeof(sf)); sf.AddrPC.Offset = context.Eip; sf.AddrPC.Mode = AddrModeFlat; sf.AddrFrame.Offset = context.Ebp; sf.AddrFrame.Mode = AddrModeFlat; jCount = (s_conflictModuleList[i].iStackSearchLevel == 0) ? 100/*最多查找100层*/ : s_conflictModuleList[i].iStackSearchLevel; for (j = 0; j < jCount; j++) { if (! m_pfnStackWalk64(IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), GetCurrentThread(), &sf, NULL, NULL, m_pfnSymFunctionTableAccess64, m_pfnSymGetModuleBase64, NULL)) { break; } if (IsAddressInModule((PVOID)sf.AddrPC.Offset, hMod)) { return s_conflictModuleList[i].conflictProc(i, hMod); } } } return FALSE; } BOOL CCheckConflict::PostCheck(struct _EXCEPTION_POINTERS* /*pExceptionInfo*/) { HMODULE hMod = LoadLibrary(_T("SysWin64.Sys")); if (NULL != hMod) { TCHAR szModuleFileName[MAX_PATH]; szModuleFileName[0] = _T('\0'); GetModuleFileName(hMod, szModuleFileName, MAX_PATH); szModuleFileName[MAX_PATH - 1] = _T('\0'); LPCTSTR lpcszOutputFormat = _T("eMule 与 %s 发生冲突,即将关闭。\r\n"); size_t nOutputMax = _tcslen(lpcszOutputFormat) + MAX_PATH + 1; TCHAR *szOutput = new TCHAR[nOutputMax]; StringCchPrintf(szOutput, nOutputMax, lpcszOutputFormat, szModuleFileName); MessageBox(NULL, szOutput, GetResString(IDS_CONFLICT), MB_OK); return TRUE; } return FALSE; } BOOL CCheckConflict::UserAnalyseDiy(struct _EXCEPTION_POINTERS* pExceptionInfo) { //让用户先自己分析一下。 int i; int iModCount; DWORD dwNeedBytes; TCHAR szModName[MAX_PATH]; HMODULE *arrMods = NULL; int iChoice = IDNO; m_pfnEnumProcessModules(GetCurrentProcess(), NULL, 0, &dwNeedBytes); iModCount = dwNeedBytes/sizeof(HMODULE); arrMods = new HMODULE[iModCount]; m_pfnEnumProcessModules(GetCurrentProcess(), arrMods, dwNeedBytes, &dwNeedBytes); for (i = 0; i < iModCount; i++) { if (IsAddressInModule(pExceptionInfo->ExceptionRecord->ExceptionAddress, arrMods[i])) { GetModuleFileName(arrMods[i], szModName, MAX_PATH); // 询问用户 <begin> LPCTSTR lpcszOutputFormat = _T("程序在[%s]模块里出现异常情况。\r\n") _T("\r\n") _T("如果您已经知道这个模块本身存在问题,您可以选“是”来结束程序;\r\n") _T("或者,您可以选“否”,然后发送错误报告,让我们来为您作进一步分析。"); size_t nOutputMax = _tcslen(lpcszOutputFormat) + MAX_PATH + 1; TCHAR *szOutput = new TCHAR[nOutputMax]; StringCchPrintf(szOutput, nOutputMax, lpcszOutputFormat, szModName); iChoice = MessageBox(NULL, szOutput, _T("程序出错"), MB_YESNO | MB_DEFBUTTON2); delete[] szOutput; szOutput = NULL; // 询问用户 <end> break; } } delete[] arrMods; arrMods = NULL; return (iChoice == IDYES); } BOOL CCheckConflict::GetAppPath(LPTSTR lpszBuffer, DWORD dwBufferCch) { TCHAR szModuleFileName[MAX_PATH]; TCHAR drive[_MAX_DRIVE]; TCHAR dir[_MAX_DIR]; TCHAR fname[_MAX_FNAME]; TCHAR ext[_MAX_EXT]; if (NULL == GetModuleFileName(NULL, szModuleFileName, MAX_PATH)) return FALSE; _tsplitpath( szModuleFileName, drive, dir, fname, ext ); if ( FAILED(StringCchCopy(lpszBuffer, dwBufferCch, drive))) return FALSE; if ( FAILED(StringCchCat(lpszBuffer, dwBufferCch, dir)) ) return FALSE; return TRUE; } BOOL CCheckConflict::GetIniPathName(LPTSTR lpszBuffer, DWORD dwBufferCch) { if (!GetAppPath(lpszBuffer, dwBufferCch)) return FALSE; if ( FAILED(StringCchCat(lpszBuffer, dwBufferCch, _T("config\\preferences.ini"))) ) return FALSE; return TRUE; } BOOL CCheckConflict::GetIniBool(LPCTSTR lpszSection, LPCTSTR lpszEntry, BOOL *pbValue) { if (NULL == pbValue) return FALSE; TCHAR szIniFile[MAX_PATH]; if (! GetIniPathName(szIniFile, MAX_PATH)) return FALSE; TCHAR szValue[MAX_INI_BUFFER]; if (0 == GetPrivateProfileString(lpszSection, lpszEntry, _T("0"), szValue, MAX_INI_BUFFER, szIniFile) ) return FALSE; *pbValue = _tstoi(szValue); return TRUE; } BOOL CCheckConflict::WriteIniBool(LPCTSTR lpszSection, LPCTSTR lpszEntry, BOOL bValue) { TCHAR szIniFile[MAX_PATH]; if (! GetIniPathName(szIniFile, MAX_PATH)) return FALSE; TCHAR szBuffer[2]; szBuffer[0] = bValue ? _T('1') : _T('0'); szBuffer[1] = _T('\0'); return WritePrivateProfileString(lpszSection, lpszEntry, szBuffer, szIniFile); }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 452 ] ] ]
aa019fd48469e77dc4a92980d5e0b654900fbf47
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DXGI/DXGIException.h
62c490f2f3a959dde2e619a08f3b3da410520b2d
[]
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
828
h
// Copyright (c) Microsoft Corporation. All rights reserved. #pragma once #include "DirectXException.h" using namespace System; using namespace Microsoft::WindowsAPICodePack::DirectX; namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace DXGI { /// <summary> /// An exception thrown by DXGI. /// </summary> public ref class DXGIException : public DirectXException { public: DXGIException(void) : DirectXException() {} DXGIException(int hr) : DirectXException("DXGI Error was returned. Check ErrorCode.", hr) { } DXGIException(String^ message, int hr) : DirectXException(message, hr) { } DXGIException(String^ message, Exception^ innerException, int hr) : DirectXException(message, innerException, hr) { } }; } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 30 ] ] ]
0de1d55522f6d3f1948f2ea1eb42cf52dd55bde7
c31bd425f234be558d9535bf140696dbc798aafb
/src/server.cpp
1a03014252091425e91fa770e874c8f23b183cda
[]
no_license
dfyx/SibNet
43efb47f02022d468c969bdd9937b28bc602e16c
14090f599d97249ad82a1ff4dd67a620be01afeb
refs/heads/master
2018-12-28T19:56:09.982294
2011-04-15T14:34:55
2011-04-15T14:34:55
1,291,784
1
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
#include <server.h> #include <listenersocket.h> #include <blocksocket.h> using namespace std; Server::Server() { m_pinSocket = new ListenerSocket(); m_pinSocket->SetAddClientSocketCB(this); } Server::~Server() { delete m_pinSocket; } bool Server::Listen(unsigned short p_sPort) { return m_pinSocket->Listen(p_sPort); } void Server::Stop() { m_pinSocket->StopListening(); } vector<BlockSocket*> Server::GetBlockSockets() { return m_pinSocket->GetBlockSockets(); }
[ [ [ 1, 9 ], [ 11, 27 ], [ 29, 29 ], [ 31, 31 ] ], [ [ 10, 10 ], [ 28, 28 ], [ 30, 30 ] ] ]
dfa53a62bbbd4d482505ec56130ff03128ebcac3
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ai/src/WayPointGraph.cpp
22b4bfe235cb9b7a38e39f04b57e13efa7d62915
[ "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
8,015
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 "WayPointGraph.h" #include <algorithm> #include <xercesc/dom/DOM.hpp> #include "ConfigurationManager.h" #include "ContentModule.h" #include "CoreSubsystem.h" #include "Exception.h" #include "LineSetPrimitive.h" #include "WayPointNode.h" #include "World.h" using namespace std; using namespace Ogre; namespace rl { WayPointGraph::WayPointGraph() : mRoot(NULL), mChanged(false) { } WayPointGraph::~WayPointGraph() { WayPointNodeList::iterator it; for (it = mNodeList.begin(); it != mNodeList.end(); it++) { delete *it; } // the scenenode seems // already deleted when this destructor gets called. // Remove debug scene node from root scene note, if debugview was used. if (mSceneNode != NULL && mSceneNode->getParent() != NULL) { CoreSubsystem::getSingletonPtr()->getWorld()->getSceneManager()-> getRootSceneNode()->removeChild(mSceneNode); } } WayPointNode* WayPointGraph::addWayPoint(const Vector3& position, const WayPointNode::WayPointNodeType type) { WayPointNodeList::iterator it; for (it = mNodeList.begin(); it != mNodeList.end(); it++) { // equal to some waypoint already added ... if ( (*it)->getPosition() == position ) return NULL; } return rawAddWayPoint(position, type); } WayPointNode* WayPointGraph::rawAddWayPoint(const Vector3& position, const WayPointNode::WayPointNodeType type) { WayPointNode* newWayPoint = new WayPointNode(position, type); mNodeList.push_back(newWayPoint); mChanged = true; return newWayPoint; } void WayPointGraph::addConnection(WayPointNode* wp1, WayPointNode* wp2) { wp1->addNeighbour(wp2); wp2->addNeighbour(wp1); mChanged = true; } void WayPointGraph::addDirectedConnection(WayPointNode* wp1, const WayPointNode* wp2) { wp1->addNeighbour(wp2); mChanged = true; } void WayPointGraph::load(const Ogre::String& filename, const Ogre::String& resourceGroup) { using namespace XERCES_CPP_NAMESPACE; Ogre::String group = resourceGroup; if (group.empty()) { group = CoreSubsystem::getSingleton().getActiveAdventureModule()->getId(); } initializeXml(); DOMDocument* doc = loadDocument(filename, group); if (doc) { DOMElement* rootElem = doc->getDocumentElement(); DOMElement* nodesElem = getChildNamed(rootElem, "waypointnodes"); std::map<int, WayPointNode*> lookupTable; for (DOMNode* curNode = nodesElem->getFirstChild(); curNode; curNode = curNode->getNextSibling()) { if (curNode->getNodeType() == DOMNode::ELEMENT_NODE || hasNodeName(curNode, "node")) { DOMElement* curElem = static_cast<DOMElement*>(curNode); Vector3 pos = getValueAsVector3(curElem); CeGuiString typeS = getAttributeValueAsString(curElem, "type"); int id = getAttributeValueAsInteger(curElem, "id"); WayPointNode::WayPointNodeType type = WayPointNode::WP_UNKNOWN; if (typeS == "int") { type = WayPointNode::WP_INTERIOR; } else if (typeS == "ext") { type = WayPointNode::WP_EXTERIOR; } WayPointNode* node = addWayPoint(pos, type); lookupTable[id] = node; } } DOMElement* edgesElem = getChildNamed(rootElem, "waypointedges"); for (DOMNode* curNode = edgesElem->getFirstChild(); curNode; curNode = curNode->getNextSibling()) { if (curNode->getNodeType() == DOMNode::ELEMENT_NODE || hasNodeName(curNode, "edge")) { DOMElement* curElem = static_cast<DOMElement*>(curNode); int source = getAttributeValueAsInteger(curElem, "source"); int destination = getAttributeValueAsInteger(curElem, "destination"); addDirectedConnection(lookupTable[source], lookupTable[destination]); } } } shutdownXml(); } const WayPointNode* WayPointGraph::getNearestWayPoint(const Vector3& position) const { WayPointNodeList::const_iterator it; WayPointNode* nearestWayPoint = NULL; Vector3 nearestVec; Ogre::Real nearestDistance; // if list is empty simply return no waypoint if (mNodeList.begin() == mNodeList.end()) return NULL; // first waypoint is the nearest at the beginning it = mNodeList.begin(); nearestVec = position - (*it)->getPosition(); nearestDistance = nearestVec.length(); nearestWayPoint = (*it); // search the full list for points that are nearer for (it = mNodeList.begin(); it != mNodeList.end(); it++) { // calculate distance nearestVec = position - (*it)->getPosition(); // test if distance is smaller than the smallest seen until now if ( nearestDistance > nearestVec.length() ) { nearestDistance = nearestVec.length(); nearestWayPoint = (*it); } } return nearestWayPoint; } const WayPointGraph::WayPointNodeList& WayPointGraph::getWayPointList() const { return mNodeList; } const WayPointNode* WayPointGraph::getWayPointAt(unsigned int index) const { if (index >= mNodeList.size()) Throw(OutOfRangeException,"no data at specified index"); return mNodeList[index]; } DebugVisualisableFlag WayPointGraph::getFlag() const { return DVF_WAYPOINT; } void WayPointGraph::updatePrimitive() { if (mSceneNode->getParent() == NULL) { CoreSubsystem::getSingletonPtr()->getWorld()->getSceneManager()-> getRootSceneNode()->addChild(mSceneNode); //mCharacterActor->_getSceneNode()->addChild(mSceneNode); } // avoid building graph again and again if (! mChanged) return; LineSetPrimitive* lineSet = static_cast<LineSetPrimitive*>(mPrimitive); lineSet->clear(); // list storing added lines (for avoiding drawing bidirectional lines twice) std::multimap<const WayPointNode*,const WayPointNode*> edgeList; std::multimap<const WayPointNode*,const WayPointNode*>::iterator edgeListIt; WayPointNodeList::const_iterator it; Vector3 wp1Vec; Vector3 wp2Vec; for (it = mNodeList.begin(); it != mNodeList.end(); it++) { wp1Vec = (*it)->getPosition(); // draw the waypoint itself lineSet->addLine(wp1Vec, wp1Vec + Vector3(0,1,0), Ogre::ColourValue::Red); const WayPointNode::WayPointWeightNodeList subnodes = (*it)->getNeighbours(); WayPointNode::WayPointWeightNodeList::const_iterator nit; for (nit = subnodes.begin(); nit != subnodes.end(); nit++) { /*bool found = false; while ( (edgeListIt = edgeList.find( (*nit).second )) != edgeList.end() ) { if ( (*edgeListIt).second == (*it) ) found = true; } if (found) // already 'drawn' continue; */ lineSet->addLine(wp1Vec, (*nit).second->getPosition(), Ogre::ColourValue::Blue); edgeList.insert(pair<const WayPointNode*,const WayPointNode*>((*nit).second, (*it)) ); } } edgeList.clear(); mChanged = false; } void WayPointGraph::doCreatePrimitive() { mPrimitive = new LineSetPrimitive(); } };
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 273 ] ] ]
2bcf0bbd1e3ac517f3dae891009bd630d475adbf
16d6176d43bf822ad8d86d4363c3fee863ac26f9
/Submission/Submission/Source code/rayTracer/Camera.h
69ffe4274cdb717c3ecde7cdadc47c5f3e4eb74e
[]
no_license
preethinarayan/cgraytracer
7a0a16e30ef53075644700494b2f8cf2a0693fbd
46a4a22771bd3f71785713c31730fdd8f3aebfc7
refs/heads/master
2016-09-06T19:28:04.282199
2008-12-10T00:02:32
2008-12-10T00:02:32
32,247,889
0
0
null
null
null
null
UTF-8
C++
false
false
406
h
#pragma once class Camera { vec3 eye; vec3 center; vec3 up; float fov; int width; int height; vec3 u, v, w; void initCoordinates(); public: Camera(); vec3 calcRays(int i,int j); void setImageParameters(int width,int height); bool setArgs(char **args); vec3 executeCommand(int i, int j){return (calcRays(i,j));}; vec3 getEye(){return eye;}; public: ~Camera(void); };
[ "[email protected]@074c0a88-b503-11dd-858c-a3a1ac847323" ]
[ [ [ 1, 23 ] ] ]
af70796c1f6ab1e9c7b40daa8d4d6e4684b9f0fc
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/snes.h
c71dda161b6a78bef2f6d4b6737395c4fe0cd653
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,060
h
#ifndef _SNES_H_ #define _SNES_H_ #include "devlegcy.h" #include "devcb.h" #include "cpu/spc700/spc700.h" #include "cpu/g65816/g65816.h" #include "cpu/upd7725/upd7725.h" #include "audio/snes_snd.h" /* SNES timing theory: the master clock drives the CPU and PPU 4 MC ticks = 1 PPU dot 6 MC ticks = 1 65816 cycle for 3.58 MHz (3.579545) 8 MC ticks = 1 65816 cycle for 2.68 MHz (2.684659) 12 MC ticks = 1 65816 cycle for 1.78 MHz (1.789772) Each scanline has 341 readable positions and 342 actual dots. This is because 2 dots are "long" dots that last 6 MC ticks, resulting in 1 extra dot per line. */ #define MCLK_NTSC (21477272) /* verified */ #define MCLK_PAL (21218370) /* verified */ #define DOTCLK_NTSC (MCLK_NTSC/4) #define DOTCLK_PAL (MCLK_PAL/4) #define SNES_LAYER_DEBUG 0 #define SNES_DSP1B_OFFSET (0x0000) #define SNES_DSP1_OFFSET (0x3000) #define SNES_DSP2_OFFSET (0x6000) #define SNES_DSP3_OFFSET (0x9000) #define SNES_DSP4_OFFSET (0xc000) /* Debug definitions */ #ifdef MAME_DEBUG /* #define SNES_DBG_GENERAL*/ /* Display general debug info */ /* #define SNES_DBG_VIDEO */ /* Display video debug info */ /* #define SNES_DBG_DMA*/ /* Display DMA debug info */ /* #define SNES_DBG_HDMA*/ /* Display HDMA debug info */ /* #define SNES_DBG_REG_R*/ /* Display register read info */ /* #define SNES_DBG_REG_W*/ /* Display register write info */ #endif /* MAME_DEBUG */ /* Useful definitions */ #define SNES_SCR_WIDTH 256 /* 32 characters 8 pixels wide */ #define SNES_SCR_HEIGHT_NTSC 224 /* Can be 224 or 240 height */ #define SNES_SCR_HEIGHT_PAL 274 /* ??? */ #define SNES_VTOTAL_NTSC 262 /* Maximum number of lines for NTSC systems */ #define SNES_VTOTAL_PAL 312 /* Maximum number of lines for PAL systems */ #define SNES_HTOTAL 341 /* Maximum number pixels per line (incl. hblank) */ #define SNES_DMA_BASE 0x4300 /* Base DMA register address */ #define SNES_MODE_20 0x01 /* Lo-ROM cart */ #define SNES_MODE_21 0x02 /* Hi-ROM cart */ #define SNES_MODE_22 0x04 /* Extended Lo-ROM cart - SDD-1 */ #define SNES_MODE_25 0x08 /* Extended Hi-ROM cart */ #define SNES_MODE_BSX 0x10 #define SNES_MODE_BSLO 0x20 #define SNES_MODE_BSHI 0x40 #define SNES_MODE_ST 0x80 #define SNES_NTSC 0x00 #define SNES_PAL 0x10 #define SNES_VRAM_SIZE 0x20000 /* 128kb of video ram */ #define SNES_CGRAM_SIZE 0x202 /* 256 16-bit colours + 1 tacked on 16-bit colour for fixed colour */ #define SNES_OAM_SIZE 0x440 /* 1088 bytes of Object Attribute Memory */ #define SNES_EXROM_START 0x1000000 #define FIXED_COLOUR 256 /* Position in cgram for fixed colour */ /* Definitions for PPU Memory-Mapped registers */ #define INIDISP 0x2100 #define OBSEL 0x2101 #define OAMADDL 0x2102 #define OAMADDH 0x2103 #define OAMDATA 0x2104 #define BGMODE 0x2105 /* abcdefff = abcd: bg4-1 tile size | e: BG3 high priority | f: mode */ #define MOSAIC 0x2106 /* xxxxabcd = x: pixel size | abcd: affects bg 1-4 */ #define BG1SC 0x2107 #define BG2SC 0x2108 #define BG3SC 0x2109 #define BG4SC 0x210A #define BG12NBA 0x210B #define BG34NBA 0x210C #define BG1HOFS 0x210D #define BG1VOFS 0x210E #define BG2HOFS 0x210F #define BG2VOFS 0x2110 #define BG3HOFS 0x2111 #define BG3VOFS 0x2112 #define BG4HOFS 0x2113 #define BG4VOFS 0x2114 #define VMAIN 0x2115 /* i---ffrr = i: Increment timing | f: Full graphic | r: increment rate */ #define VMADDL 0x2116 /* aaaaaaaa = a: LSB of vram address */ #define VMADDH 0x2117 /* aaaaaaaa = a: MSB of vram address */ #define VMDATAL 0x2118 /* dddddddd = d: data to be written */ #define VMDATAH 0x2119 /* dddddddd = d: data to be written */ #define M7SEL 0x211A /* ab----yx = a: screen over | y: vertical flip | x: horizontal flip */ #define M7A 0x211B /* aaaaaaaa = a: COSINE rotate angle / X expansion */ #define M7B 0x211C /* aaaaaaaa = a: SINE rotate angle / X expansion */ #define M7C 0x211D /* aaaaaaaa = a: SINE rotate angle / Y expansion */ #define M7D 0x211E /* aaaaaaaa = a: COSINE rotate angle / Y expansion */ #define M7X 0x211F #define M7Y 0x2120 #define CGADD 0x2121 #define CGDATA 0x2122 #define W12SEL 0x2123 #define W34SEL 0x2124 #define WOBJSEL 0x2125 #define WH0 0x2126 /* pppppppp = p: Left position of window 1 */ #define WH1 0x2127 /* pppppppp = p: Right position of window 1 */ #define WH2 0x2128 /* pppppppp = p: Left position of window 2 */ #define WH3 0x2129 /* pppppppp = p: Right position of window 2 */ #define WBGLOG 0x212A /* aabbccdd = a: BG4 params | b: BG3 params | c: BG2 params | d: BG1 params */ #define WOBJLOG 0x212B /* ----ccoo = c: Colour window params | o: Object window params */ #define TM 0x212C #define TS 0x212D #define TMW 0x212E #define TSW 0x212F #define CGWSEL 0x2130 #define CGADSUB 0x2131 #define COLDATA 0x2132 #define SETINI 0x2133 #define MPYL 0x2134 #define MPYM 0x2135 #define MPYH 0x2136 #define SLHV 0x2137 #define ROAMDATA 0x2138 #define RVMDATAL 0x2139 #define RVMDATAH 0x213A #define RCGDATA 0x213B #define OPHCT 0x213C #define OPVCT 0x213D #define STAT77 0x213E #define STAT78 0x213F #define APU00 0x2140 #define APU01 0x2141 #define APU02 0x2142 #define APU03 0x2143 #define WMDATA 0x2180 #define WMADDL 0x2181 #define WMADDM 0x2182 #define WMADDH 0x2183 /* Definitions for CPU Memory-Mapped registers */ #define OLDJOY1 0x4016 #define OLDJOY2 0x4017 #define NMITIMEN 0x4200 #define WRIO 0x4201 #define WRMPYA 0x4202 #define WRMPYB 0x4203 #define WRDIVL 0x4204 #define WRDIVH 0x4205 #define WRDVDD 0x4206 #define HTIMEL 0x4207 #define HTIMEH 0x4208 #define VTIMEL 0x4209 #define VTIMEH 0x420A #define MDMAEN 0x420B #define HDMAEN 0x420C #define MEMSEL 0x420D #define RDNMI 0x4210 #define TIMEUP 0x4211 #define HVBJOY 0x4212 #define RDIO 0x4213 #define RDDIVL 0x4214 #define RDDIVH 0x4215 #define RDMPYL 0x4216 #define RDMPYH 0x4217 #define JOY1L 0x4218 #define JOY1H 0x4219 #define JOY2L 0x421A #define JOY2H 0x421B #define JOY3L 0x421C #define JOY3H 0x421D #define JOY4L 0x421E #define JOY4H 0x421F /* DMA */ #define DMAP0 0x4300 #define BBAD0 0x4301 #define A1T0L 0x4302 #define A1T0H 0x4303 #define A1B0 0x4304 #define DAS0L 0x4305 #define DAS0H 0x4306 #define DSAB0 0x4307 #define A2A0L 0x4308 #define A2A0H 0x4309 #define NTRL0 0x430A #define DMAP1 0x4310 #define BBAD1 0x4311 #define A1T1L 0x4312 #define A1T1H 0x4313 #define A1B1 0x4314 #define DAS1L 0x4315 #define DAS1H 0x4316 #define DSAB1 0x4317 #define A2A1L 0x4318 #define A2A1H 0x4319 #define NTRL1 0x431A #define DMAP2 0x4320 #define BBAD2 0x4321 #define A1T2L 0x4322 #define A1T2H 0x4323 #define A1B2 0x4324 #define DAS2L 0x4325 #define DAS2H 0x4326 #define DSAB2 0x4327 #define A2A2L 0x4328 #define A2A2H 0x4329 #define NTRL2 0x432A #define DMAP3 0x4330 #define BBAD3 0x4331 #define A1T3L 0x4332 #define A1T3H 0x4333 #define A1B3 0x4334 #define DAS3L 0x4335 #define DAS3H 0x4336 #define DSAB3 0x4337 #define A2A3L 0x4338 #define A2A3H 0x4339 #define NTRL3 0x433A #define DMAP4 0x4340 #define BBAD4 0x4341 #define A1T4L 0x4342 #define A1T4H 0x4343 #define A1B4 0x4344 #define DAS4L 0x4345 #define DAS4H 0x4346 #define DSAB4 0x4347 #define A2A4L 0x4348 #define A2A4H 0x4349 #define NTRL4 0x434A #define DMAP5 0x4350 #define BBAD5 0x4351 #define A1T5L 0x4352 #define A1T5H 0x4353 #define A1B5 0x4354 #define DAS5L 0x4355 #define DAS5H 0x4356 #define DSAB5 0x4357 #define A2A5L 0x4358 #define A2A5H 0x4359 #define NTRL5 0x435A #define DMAP6 0x4360 #define BBAD6 0x4361 #define A1T6L 0x4362 #define A1T6H 0x4363 #define A1B6 0x4364 #define DAS6L 0x4365 #define DAS6H 0x4366 #define DSAB6 0x4367 #define A2A6L 0x4368 #define A2A6H 0x4369 #define NTRL6 0x436A #define DMAP7 0x4370 #define BBAD7 0x4371 #define A1T7L 0x4372 #define A1T7H 0x4373 #define A1B7 0x4374 #define DAS7L 0x4375 #define DAS7H 0x4376 #define DSAB7 0x4377 #define A2A7L 0x4378 #define A2A7H 0x4379 #define NTRL7 0x437A /* Definitions for sound DSP */ #define DSP_V0_VOLL 0x00 #define DSP_V0_VOLR 0x01 #define DSP_V0_PITCHL 0x02 #define DSP_V0_PITCHH 0x03 #define DSP_V0_SRCN 0x04 #define DSP_V0_ADSR1 0x05 /* gdddaaaa = g:gain enable | d:decay | a:attack */ #define DSP_V0_ADSR2 0x06 /* llllrrrr = l:sustain left | r:sustain right */ #define DSP_V0_GAIN 0x07 #define DSP_V0_ENVX 0x08 #define DSP_V0_OUTX 0x09 #define DSP_V1_VOLL 0x10 #define DSP_V1_VOLR 0x11 #define DSP_V1_PITCHL 0x12 #define DSP_V1_PITCHH 0x13 #define DSP_V1_SRCN 0x14 #define DSP_V1_ADSR1 0x15 #define DSP_V1_ADSR2 0x16 #define DSP_V1_GAIN 0x17 #define DSP_V1_ENVX 0x18 #define DSP_V1_OUTX 0x19 #define DSP_V2_VOLL 0x20 #define DSP_V2_VOLR 0x21 #define DSP_V2_PITCHL 0x22 #define DSP_V2_PITCHH 0x23 #define DSP_V2_SRCN 0x24 #define DSP_V2_ADSR1 0x25 #define DSP_V2_ADSR2 0x26 #define DSP_V2_GAIN 0x27 #define DSP_V2_ENVX 0x28 #define DSP_V2_OUTX 0x29 #define DSP_V3_VOLL 0x30 #define DSP_V3_VOLR 0x31 #define DSP_V3_PITCHL 0x32 #define DSP_V3_PITCHH 0x33 #define DSP_V3_SRCN 0x34 #define DSP_V3_ADSR1 0x35 #define DSP_V3_ADSR2 0x36 #define DSP_V3_GAIN 0x37 #define DSP_V3_ENVX 0x38 #define DSP_V3_OUTX 0x39 #define DSP_V4_VOLL 0x40 #define DSP_V4_VOLR 0x41 #define DSP_V4_PITCHL 0x42 #define DSP_V4_PITCHH 0x43 #define DSP_V4_SRCN 0x44 #define DSP_V4_ADSR1 0x45 #define DSP_V4_ADSR2 0x46 #define DSP_V4_GAIN 0x47 #define DSP_V4_ENVX 0x48 #define DSP_V4_OUTX 0x49 #define DSP_V5_VOLL 0x50 #define DSP_V5_VOLR 0x51 #define DSP_V5_PITCHL 0x52 #define DSP_V5_PITCHH 0x53 #define DSP_V5_SRCN 0x54 #define DSP_V5_ADSR1 0x55 #define DSP_V5_ADSR2 0x56 #define DSP_V5_GAIN 0x57 #define DSP_V5_ENVX 0x58 #define DSP_V5_OUTX 0x59 #define DSP_V6_VOLL 0x60 #define DSP_V6_VOLR 0x61 #define DSP_V6_PITCHL 0x62 #define DSP_V6_PITCHH 0x63 #define DSP_V6_SRCN 0x64 #define DSP_V6_ADSR1 0x65 #define DSP_V6_ADSR2 0x66 #define DSP_V6_GAIN 0x67 #define DSP_V6_ENVX 0x68 #define DSP_V6_OUTX 0x69 #define DSP_V7_VOLL 0x70 #define DSP_V7_VOLR 0x71 #define DSP_V7_PITCHL 0x72 #define DSP_V7_PITCHH 0x73 #define DSP_V7_SRCN 0x74 #define DSP_V7_ADSR1 0x75 #define DSP_V7_ADSR2 0x76 #define DSP_V7_GAIN 0x77 #define DSP_V7_ENVX 0x78 #define DSP_V7_OUTX 0x79 #define DSP_MVOLL 0x0C #define DSP_MVOLR 0x1C #define DSP_EVOLL 0x2C #define DSP_EVOLR 0x3C #define DSP_KON 0x4C /* 01234567 = Key on for voices 0-7 */ #define DSP_KOF 0x5C /* 01234567 = Key off for voices 0-7 */ #define DSP_FLG 0x6C /* rme--n-- = r:Soft reset | m:Mute | e:External memory through echo | n:Clock of noise generator */ #define DSP_ENDX 0x7C #define DSP_EFB 0x0D /* sfffffff = s: sign bit | f: feedback */ #define DSP_PMOD 0x2D #define DSP_NON 0x3D #define DSP_EON 0x4D #define DSP_DIR 0x5D #define DSP_ESA 0x6D #define DSP_EDL 0x7D /* ----dddd = d: echo delay */ #define DSP_FIR_C0 0x0F #define DSP_FIR_C1 0x1F #define DSP_FIR_C2 0x2F #define DSP_FIR_C3 0x3F #define DSP_FIR_C4 0x4F #define DSP_FIR_C5 0x5F #define DSP_FIR_C6 0x6F #define DSP_FIR_C7 0x7F struct snes_cart_info { UINT8 mode; /* ROM memory mode */ UINT32 sram; /* Amount of sram in cart */ UINT32 sram_max; /* Maximum amount sram in cart (based on ROM mode) */ int small_sram; int slot_in_use; /* this is needed by Sufami Turbo slots (to check if SRAM has to be saved) */ }; struct snes_joypad { UINT16 buttons; }; struct snes_mouse { INT16 x, y, oldx, oldy; UINT8 buttons; UINT8 deltax, deltay; int speed; }; struct snes_superscope { INT16 x, y; UINT8 buttons; int turbo_lock, pause_lock, fire_lock; int offscreen; }; typedef void (*snes_io_read)(running_machine &machine); typedef UINT8 (*snes_oldjoy_read)(running_machine &machine); class snes_state : public driver_device { public: snes_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* misc */ UINT16 m_htmult; /* in 512 wide, we run HTOTAL double and halve it on latching */ UINT16 m_cgram_address; /* CGRAM address */ UINT8 m_vram_read_offset; /* VRAM read offset */ UINT8 m_read_ophct; UINT8 m_read_opvct; UINT16 m_hblank_offset; UINT16 m_vram_fgr_high; UINT16 m_vram_fgr_increment; UINT16 m_vram_fgr_count; UINT16 m_vram_fgr_mask; UINT16 m_vram_fgr_shift; UINT16 m_vram_read_buffer; UINT32 m_wram_address; UINT16 m_htime; UINT16 m_vtime; UINT16 m_vmadd; /* timers */ emu_timer *m_scanline_timer; emu_timer *m_hblank_timer; emu_timer *m_nmi_timer; emu_timer *m_hirq_timer; emu_timer *m_div_timer; emu_timer *m_mult_timer; emu_timer *m_io_timer; /* DMA/HDMA-related */ struct { UINT8 dmap; UINT8 dest_addr; UINT16 src_addr; UINT16 trans_size; UINT8 bank; UINT8 ibank; UINT16 hdma_addr; UINT16 hdma_iaddr; UINT8 hdma_line_counter; UINT8 unk; int do_transfer; int dma_disabled; // used to stop DMA if HDMA is enabled (currently not implemented, see machine/snes.c) }m_dma_channel[8]; UINT8 m_hdmaen; /* channels enabled for HDMA */ /* input-related */ UINT8 m_joy1l; UINT8 m_joy1h; UINT8 m_joy2l; UINT8 m_joy2h; UINT8 m_joy3l; UINT8 m_joy3h; UINT8 m_joy4l; UINT8 m_joy4h; UINT16 m_data1[2]; UINT16 m_data2[2]; UINT8 m_read_idx[2]; snes_joypad m_joypad[2]; snes_mouse m_mouse[2]; snes_superscope m_scope[2]; /* input callbacks (to allow MESS to have its own input handlers) */ snes_io_read m_io_read; snes_oldjoy_read m_oldjoy1_read; snes_oldjoy_read m_oldjoy2_read; /* cart related */ UINT8 m_has_addon_chip; UINT32 m_cart_size; snes_cart_info m_cart[2]; // the second one is used by MESS for Sufami Turbo and, eventually, BS-X /* devices */ _5a22_device *m_maincpu; spc700_device *m_soundcpu; snes_sound_device *m_spc700; cpu_device *m_superfx; upd7725_device *m_upd7725; upd96050_device *m_upd96050; }; /* Special chips, checked at init and used in memory handlers */ enum { HAS_NONE = 0, HAS_DSP1, HAS_DSP2, HAS_DSP3, HAS_DSP4, HAS_SUPERFX, HAS_SA1, HAS_SDD1, HAS_OBC1, HAS_RTC, HAS_Z80GB, HAS_CX4, HAS_ST010, HAS_ST011, HAS_ST018, HAS_SPC7110, HAS_SPC7110_RTC, HAS_UNK }; /* offset-per-tile modes */ enum { SNES_OPT_NONE = 0, SNES_OPT_MODE2, SNES_OPT_MODE4, SNES_OPT_MODE6 }; /* layers */ enum { SNES_BG1 = 0, SNES_BG2, SNES_BG3, SNES_BG4, SNES_OAM, SNES_COLOR }; /*----------- defined in machine/snes.c -----------*/ extern DRIVER_INIT( snes ); extern DRIVER_INIT( snes_hirom ); extern MACHINE_START( snes ); extern MACHINE_RESET( snes ); READ8_HANDLER( snes_open_bus_r ); extern READ8_HANDLER( snes_r_io ); extern WRITE8_HANDLER( snes_w_io ); extern READ8_HANDLER( snes_r_bank1 ); extern READ8_HANDLER( snes_r_bank2 ); extern READ8_HANDLER( snes_r_bank3 ); extern READ8_HANDLER( snes_r_bank4 ); extern READ8_HANDLER( snes_r_bank5 ); extern READ8_HANDLER( snes_r_bank6 ); extern READ8_HANDLER( snes_r_bank7 ); extern WRITE8_HANDLER( snes_w_bank1 ); extern WRITE8_HANDLER( snes_w_bank2 ); extern WRITE8_HANDLER( snes_w_bank4 ); extern WRITE8_HANDLER( snes_w_bank5 ); extern WRITE8_HANDLER( snes_w_bank6 ); extern WRITE8_HANDLER( snes_w_bank7 ); extern READ8_HANDLER( superfx_r_bank1 ); extern READ8_HANDLER( superfx_r_bank2 ); extern READ8_HANDLER( superfx_r_bank3 ); extern WRITE8_HANDLER( superfx_w_bank1 ); extern WRITE8_HANDLER( superfx_w_bank2 ); extern WRITE8_HANDLER( superfx_w_bank3 ); WRITE_LINE_DEVICE_HANDLER( snes_extern_irq_w ); extern UINT8 *snes_ram; /* Main memory */ /* (PPU) Video related */ struct SNES_PPU_STRUCT /* once all the regs are saved in this structure, it would be better to reorganize it a bit... */ { struct { /* clipmasks */ UINT8 window1_enabled, window1_invert; UINT8 window2_enabled, window2_invert; UINT8 wlog_mask; /* color math enabled */ UINT8 color_math; UINT8 charmap; UINT8 tilemap; UINT8 tilemap_size; UINT8 tile_size; UINT8 mosaic_enabled; // actually used only for layers 0->3! UINT8 main_window_enabled; UINT8 sub_window_enabled; UINT8 main_bg_enabled; UINT8 sub_bg_enabled; UINT16 hoffs; UINT16 voffs; } layer[6]; // this is for the BG1 - BG2 - BG3 - BG4 - OBJ - color layers struct { UINT8 address_low; UINT8 address_high; UINT8 saved_address_low; UINT8 saved_address_high; UINT16 address; UINT16 priority_rotation; UINT8 next_charmap; UINT8 next_size; UINT8 size; UINT32 next_name_select; UINT32 name_select; UINT8 first_sprite; UINT8 flip; UINT16 write_latch; } oam; struct { UINT16 horizontal[4]; UINT16 vertical[4]; } bgd_offset; struct { UINT16 latch_horz; UINT16 latch_vert; UINT16 current_horz; UINT16 current_vert; UINT8 last_visible_line; UINT8 interlace_count; } beam; struct { UINT8 repeat; UINT8 hflip; UINT8 vflip; INT16 matrix_a; INT16 matrix_b; INT16 matrix_c; INT16 matrix_d; INT16 origin_x; INT16 origin_y; UINT16 hor_offset; UINT16 ver_offset; UINT8 extbg; } mode7; UINT8 mosaic_size; UINT8 clip_to_black; UINT8 prevent_color_math; UINT8 sub_add_mode; UINT8 bg3_priority_bit; UINT8 direct_color; UINT8 ppu_last_scroll; /* as per Anomie's doc and Theme Park, all scroll regs shares (but mode 7 ones) the same 'previous' scroll value */ UINT8 mode7_last_scroll; /* as per Anomie's doc mode 7 scroll regs use a different value, shared with mode 7 matrix! */ UINT8 ppu1_open_bus, ppu2_open_bus; UINT8 ppu1_version, ppu2_version; UINT8 window1_left, window1_right, window2_left, window2_right; UINT16 mosaic_table[16][4096]; UINT8 clipmasks[6][SNES_SCR_WIDTH]; UINT8 update_windows; UINT8 update_offsets; UINT8 update_oam_list; UINT8 mode; UINT8 interlace; //doubles the visible resolution UINT8 obj_interlace; UINT8 screen_brightness; UINT8 screen_disabled; UINT8 pseudo_hires; UINT8 color_modes; UINT8 stat77_flags; }; extern struct snes_cart_info snes_cart; /*----------- defined in video/snes.c -----------*/ extern struct SNES_PPU_STRUCT snes_ppu; extern void snes_latch_counters(running_machine &machine); extern VIDEO_START( snes ); extern SCREEN_UPDATE( snes ); extern READ8_HANDLER( snes_ppu_read ); extern WRITE8_HANDLER( snes_ppu_write ); #endif /* _SNES_H_ */
[ "Mike@localhost" ]
[ [ [ 1, 696 ] ] ]
5e91ee584af0bc05f240450f6458a9d53da1c5f2
9b6eced5d80668bd4328a8f3d1f75c97f04f5e08
/bthci/hci2implementations/hctls/usb_original/fdc/src/fdchctloriginal.cpp
ec2cb0d445e57449fbd42c77af57f4e369116ae8
[]
no_license
SymbianSource/oss.FCL.sf.os.bt
3ca94a01740ac84a6a35718ad3063884ea885738
ba9e7d24a7fa29d6dd93808867c28bffa2206bae
refs/heads/master
2021-01-18T23:42:06.315016
2010-10-14T10:30:12
2010-10-14T10:30:12
72,765,157
1
0
null
null
null
null
UTF-8
C++
false
false
7,125
cpp
// Copyright (c) 2007-2010 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: // /** @file @internalComponent */ #include "fdchctloriginal.h" #include <d32usbdescriptors.h> #include <usbhost/internal/fdcpluginobserver.h> #include <usbhosterrors.h> #include <bluetooth/logger.h> #include "fdchctloriginalserver.h" #include <bluetooth/logger.h> #ifdef __FLOG_ACTIVE _LIT8(KLogComponent, "fdchctloriginal"); #endif CFdcHctlOriginal* CFdcHctlOriginal::NewL(MFdcPluginObserver& aObserver) { LOG_STATIC_FUNC CFdcHctlOriginal* self = new(ELeave) CFdcHctlOriginal(aObserver); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(); return self; } CFdcHctlOriginal::CFdcHctlOriginal(MFdcPluginObserver& aObserver) : CFdcPlugin(aObserver) { LOG_FUNC } CFdcHctlOriginal::~CFdcHctlOriginal() { LOG_FUNC iHctlSession.Close(); delete iServer; } void CFdcHctlOriginal::ConstructL() { LOG_FUNC iServer = CFdcHctlOriginalServer::NewL(*this); } TAny* CFdcHctlOriginal::GetInterface(TUid aUid) { LOG_FUNC LOG1(_L8("\taUid = 0x%08x"), aUid); TAny* ret = NULL; if(aUid == TUid::Uid(KFdcInterfaceV1)) { ret = reinterpret_cast<TAny*>(static_cast<MFdcInterfaceV1*>(this)); } LOG1(_L8("\tret = [0x%08x]"), ret); return ret; } TInt CFdcHctlOriginal::Mfi1NewFunction(TUint aDeviceId, const TArray<TUint>& aInterfaces, const TUsbDeviceDescriptor& aDeviceDescriptor, const TUsbConfigurationDescriptor& aConfigurationDescriptor) { LOG_FUNC // Normally an FDC is required to claim it's interfaces first. In this // case we need to parse the descriptor tree to determine if the device // firmware update interface is present. (We don't do firmware updates but // we claim it until to provide successful device attachments. If a // firmware update FDC is provided this should be removed.) #ifdef SYMBIAN_FDC_HCTL_ORIGINAL_ACCEPT_FIRMWARE_UPDATE TBool firmwareIntFound = EFalse; TUint8 firmwareIntNum = 0xff; TUint8 KDfuInterfaceClass = 0xfe; TUint8 KDfuInterfaceSubClass = 0x01; // Drop down a level from the configuration descriptor. TUsbGenericDescriptor* descriptor = aConfigurationDescriptor.iFirstChild; // Search across the interface tier (note doesn't handle DFU in IAD). while(descriptor) { TUsbInterfaceDescriptor* interface; if (interface = TUsbInterfaceDescriptor::Cast(descriptor), interface) { if( interface->InterfaceClass() == KDfuInterfaceClass && interface->InterfaceSubClass() == KDfuInterfaceSubClass) { firmwareIntNum = interface->InterfaceNumber(); firmwareIntFound = ETrue; break; } } descriptor = descriptor->iNextPeer; } #endif // SYMBIAN_FDC_HCTL_ORIGINAL_ACCEPT_FIRMWARE_UPDATE // We claim the interfaces we are to represent, we must claim the // first interface given to us as FDF has already determined that // we are to use it. const TUint KNumOfHctlInterfaces = 2; const TUint8 KAclInterfaceNum = 0x00, KScoInterfaceNum = 0x01; TBool gotAcl = EFalse, gotSco = EFalse, fatalError = EFalse; for(TInt i=0; i<aInterfaces.Count(); ++i) { TUint intNum = aInterfaces[i]; if(intNum == KAclInterfaceNum) { fatalError = (fatalError || gotAcl); // The USB device should only report one ACL interface iAclToken = Observer().TokenForInterface(intNum); gotAcl = ETrue; } else if(intNum == KScoInterfaceNum) { fatalError = (fatalError || gotSco); // The USB device should only report one ACL interface iScoToken = Observer().TokenForInterface(intNum); gotSco = ETrue; } else if(i == 0) { // We always need to claim the first interface, this should have // been claimed already, but if we have a funny device then this // might not be the case. We will need to error. TUint32 unknownToken = Observer().TokenForInterface(intNum); return KErrCorrupt; } #ifdef SYMBIAN_FDC_HCTL_ORIGINAL_ACCEPT_FIRMWARE_UPDATE else if(firmwareIntFound && intNum == firmwareIntNum) { TUint32 dfuToken = Observer().TokenForInterface(intNum); } #endif // SYMBIAN_FDC_HCTL_ORIGINAL_ACCEPT_FIRMWARE_UPDATE } // At this point we will have claimed to the interface mandated by FDF and // so we are at liberty to return an error. // firstly, check to see if a fatal error occured. if(fatalError) { LOG(_L8("\tFatal error when retrieving interfaces for driver instance...")); return KErrGeneral; } // Now we perform some validation that the function is what we expect. // There should be two interfaces as part of the function. One is // the standard data and control planes. The other for the sync- // chronous connections. if(aConfigurationDescriptor.NumInterfaces() < KNumOfHctlInterfaces) { LOG(_L8("\tInsufficent interfaces in USB config. descriptor...")); return KErrUsbBadDescriptor; } if(aInterfaces.Count() < KNumOfHctlInterfaces) { LOG(_L8("\tInsufficient interfaces provided to FDC...")); return KErrUnderflow; } // Ensure that we got both interfaces, otherwise the device is malformed. if(!gotAcl || !gotSco) { LOG2(_L8("\tMissing Token [ACL=%d] [SCO=%d]"), gotAcl, gotSco); return KErrNotFound; } // At this point we are set-up to use the device. iReady = ETrue; // We try our best; the Bluetooth stack may not be running, it may not be even using // the USB HCTL. So we accept the tokens and try the best to set-up the HCTL. // If we fail now the HCTL should later inform us to try again. RequestConnection(); return KErrNone; } void CFdcHctlOriginal::Mfi1DeviceDetached(TUint aDeviceId) { LOG_FUNC iReady = EFalse; if(iHctlSession.Handle()) { // Inform of disconnection. iHctlSession.DeviceDetached(); } // Close Hctl Handle iHctlSession.Close(); } void CFdcHctlOriginal::RequestConnection() { LOG_FUNC // Trigger the attempt to connect to the USB HCTL Server. if(!iReady) { // For whatever reason, we have not got the tokens for the USB interfaces. LOG(_L8("\tFDC is not ready")); return; } // Note that this will error if, the bt thread or usb hctl is not running; // or if there is another FDC already connected to it. TInt err = iHctlSession.Connect(); if(err != KErrNone) { LOG1(_L8("\tRHCTLUsbOriginal::Connect error = %d"), err); return; } // Now inform the stack that we have a connected device. err = iHctlSession.DeviceAttached(iAclToken, iScoToken); if(err != KErrNone) { LOG1(_L8("\tRHCTLUsbOriginal::DeviceAttached error = %d"), err); iHctlSession.Close(); return; } }
[ "none@none" ]
[ [ [ 1, 248 ] ] ]
86169fdfa8d4bc7200313ae5db7e58fca6eb0a1f
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/TransCritical/TTechQAL/QALHeater.h
c01d01dd1b556a48c2e76d308f3695203fd4ffb5
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,984
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // Time-stamp: <2006-11-01 11:54:00 Rod Stephenson Transcritical Pty Ltd> // $Nokeywords: $ //=========================================================================== #pragma once #ifndef __MD_HEADERS_H #include "md_headers.h" #endif #include "..\TTCommon\STHX.h" //--------------------------------------------------------------------------- class CQALHeater : public MBaseMethod, CSTHx { friend class CCondensateFinder; public: CQALHeater(MUnitDefBase *pUnitDef, TaggedObject * pNd); virtual ~CQALHeater(void); virtual void Init(); virtual void BuildDataFields(); virtual bool ExchangeDataFields(); virtual bool ConfigureJoins(); virtual bool EvalJoinPressures(); virtual void EvalProducts(); virtual void ClosureInfo(MClosureInfo & CI); // Macro Model (Flash Train)... virtual void MacroMdlEvaluate(eScdMacroMdlEvals Eval) {}; virtual bool MacroMdlValidNd(int iIONo) { return true; }; virtual void MacroMdlAddNd(int iIONo) {}; virtual void MacroMdlRemoveNd(int iIONo) {}; virtual CMacroMdlBase* MacroMdlActivate() { return m_FTC; }; virtual void MacroMdlDeactivate() {}; protected: void DoCondensingHeater(MStream & ShellI, MStream & TubeI, MStream & ShellO, MStream & TubeO); // Heat Transfer Area is referred to INSIDE of tubes, based on distance between tubeplates // Pressure drop requires additional length of tubes across tubeplates. void flowRE(MStream &, MStream &); bool m_bSSScaling; bool m_bTSScaling; bool m_bOnline; // If not online, only dP, no calculation of heat transfer long m_lOpMode; long m_lHxMode; long m_lTSHxMode; long m_lSSHxMode; long m_lTSdPMode; long m_lSSdPMode; double m_dHTC; double m_dHTEffArea; // Effective Area double m_dTSHTC; // Tubeside heat transfer coefficient double m_dSSHTC; // Shellside heat transfer coefficient double m_dSSKdFactor; // Kd factor for shellside double m_dTSKdFactor; // Kd factor for tubeside double m_dG; //Mass flow kg/s/m^2 double m_dTSVel; // Tubeside velocity double m_dReIn, m_dReOut; //Reynolds no double m_dftIn, m_dftOut; //Friction Factor double m_dNuGIn, m_dNuGout; //Nussalt Number double m_dPdLIn, m_dPdLOut; //Pressure Gradient double m_dP; //Pressure Drop double m_dUA; double m_dLMTD; double m_dDuty; double m_dLMTDFactor; double m_dSScaleConductivity; // Shell Scale Conductivity double m_dQmVent, m_dSecQm; MVLEBlk m_VLE; MFT_Condenser m_FTC; #ifdef TTDEBUG double m_tmp1,m_tmp2, m_tmp3, m_tmp4, m_tmp5 ; #endif };
[ [ [ 1, 24 ], [ 26, 92 ] ], [ [ 25, 25 ] ] ]
cbb4ef8d95408a3c4ff0a4775196c88bb2d0916e
7f6fe18cf018aafec8fa737dfe363d5d5a283805
/ntk/interface/bitmap.h
7f1fdc6818861b45b7842102ea6bd9b8667b01c4
[]
no_license
snori/ntk
4db91d8a8fc836ca9a0dc2bc41b1ce767010d5ba
86d1a32c4ad831e791ca29f5e7f9e055334e8fe7
refs/heads/master
2020-05-18T05:28:49.149912
2009-08-04T16:47:12
2009-08-04T16:47:12
268,861
2
0
null
null
null
null
UTF-8
C++
false
false
4,360
h
/****************************************************************************** The NTK Library Copyright (C) 1998-2003 Noritaka Suzuki $Id: bitmap.h,v 1.9 2003/11/11 12:07:06 nsuzuki Exp $ ******************************************************************************/ #pragma once #ifndef __NTK_INTERFACE_BITMAP_H__ #define __NTK_INTERFACE_BITMAP_H__ #ifndef __NTK_WINDOWS_WINDOWS_H__ #include <ntk/windows/windows.h> #endif #ifndef __NTK_DEFS_H__ #include <ntk/defs.h> #endif #ifndef __NTK_INTERFACE_POINT_H__ #include <ntk/interface/point.h> #endif #ifndef __NTK_INTERFACE_DC_H__ #include <ntk/interface/dc.h> #endif namespace ntk { class Bitmap { public: // // types // typedef uint8* iterator; typedef const uint8* const_iterator; typedef size_t size_type; #pragma pack(push, 1) struct BitmapInfoHeader { dword size; long width; long height; word planes; word bit_count; dword compression; dword size_image; long h_pixels_per_meter; long v_pixels_per_meter; dword color_used; dword color_important; }; struct BitmapInfo { BitmapInfoHeader info_header; RGBQUAD palette[1]; }; #pragma pack(pop) typedef BitmapInfoHeader DIBInfoHeader; typedef BitmapInfo DIBInfo; #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef size_type size_t; typedef BitmapInfoHeader bitmap_info_header_t; typedef BitmapInfo bitmap_info_t; typedef DIBInfoHeader dib_info_header_t; typedef DIBInfo dib_info_t; #endif // // constants // enum ColorSpace { NO_COLOR_SPACE = 0, INDEX_8 = 8, RGB_16 = 16, RGB_24 = 24, RGBA_32 = 32, }; #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef ColorSpace color_space_t; #endif // // methods // NtkExport Bitmap(coord width, coord height, ColorSpace color_space); Bitmap(const Bitmap& bitmap) {operator=(bitmap);} NtkExport Bitmap& operator=(const Bitmap& rhs); NtkExport ~Bitmap(); // // accessors // iterator begin() {return reinterpret_cast<iterator>(m_bits);} const_iterator begin() const {return reinterpret_cast<const_iterator>(m_bits);} iterator end() {return begin() + length();} const_iterator end() const {return begin() + length();} size_type size() const {return pitch()*height();} size_type length() const {return size();} void* bits() {return m_bits;} const void* bits() const {return m_bits;} void* at(coord x, coord y) {return begin() + pitch()*y + x*(bpp() >> 3);} const void* at(coord x, coord y) const {return begin() + pitch()*y + x*(bpp() >> 3);} void* at(const Point& point) {return at(point.x, point.y);} const void* at(const Point& point) const {return at(point.x, point.y);} ColorSpace color_space() const {return (ColorSpace)m_color_space;} coord width() const {return m_width;} coord height() const {return m_height;} uint bpp() const {return m_color_space;}// bits per pixel uint Bpp() const {return m_color_space/8;}// bytes per pixel uint bits_per_pixel() const {return bpp();} uint bytes_per_pixel() const {return Bpp();} coord pitch() const {return m_pitch;} Rect bounds() const {return Rect(0, 0, width(), height());} HBITMAP handle() const {return m_hbitmap;} HDC hdc() const {return m_hdc;} DC dc() const {return DC(m_hdc);} // // operators // operator HBITMAP() {return handle();} operator const HBITMAP() const {return handle();} private: // // methods // void initialize_(coord width, coord height, ColorSpace color_space); void finalize_(); // // data // void* m_bits; coord m_width, m_height, m_pitch; uint m_color_space; BitmapInfo m_bitmap_info; HDC m_hdc; HBITMAP m_hbitmap, m_old_hbitmap; // // friends // friend class TranslationUtils; };// class Bitmap typedef Bitmap DIB; #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef Bitmap bitmap_t; typedef DIB dib_t; #endif } namespace Ntk = ntk; #ifdef NTK_TYPEDEF_TYPES_AS_GLOBAL_TYPE #ifdef NTK_TYPEDEF_GLOBAL_NCLASS typedef ntk::Bitmap NBitmap; typedef ntk::DIB NDIB; #endif #ifdef NTK_TYPEDEF_LOWERCASE_ONLY_TYPE_NAME typedef ntk::Bitmap ntk_bitmap; typedef ntk::DIB ntk_dib; #endif #endif #endif//EOH
[ [ [ 1, 190 ] ] ]
4a8e641bda3a0689e8bd681e1ccf841a9a190361
f5b309f76238ca822b03ccfeebc16d7bce2229a8
/ pppoe-killer/src/MainFrame.cpp
21dac6e56eb20570e57d989721a915b170efde3a
[]
no_license
mluis/pppoe-killer
41e043dfeaf65bab70ca9abb2693f8c78ce2f99d
015efa47e10127336860712a5fcd6c664c43c56a
refs/heads/master
2021-06-04T11:06:26.219992
2008-09-09T06:44:14
2008-09-09T06:44:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,992
cpp
#include <hippolib/net/nettool.hpp> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <boost/bind.hpp> #include <boost/thread/thread.hpp> #include <wx/tglbtn.h> #include <wx/grid.h> #include <wx/aboutdlg.h> #include <hippolib/system/thread.hpp> #include "pppoe.xpm" #include "Resource.h" #include <hippolib/util/properties.hpp> #include "MainFrame.h" #include "MainFunction.h" #include "PreferenceDialog.h" using namespace hippolib; using namespace std; IMPLEMENT_APP(MainApp) bool MainApp::OnInit() { #ifdef WIN32 HANDLE hMutexOneInstance = CreateMutex( NULL, FALSE, _T("PKILLER_GUID")); bool AlreadyRunning = ( GetLastError() == ERROR_ALREADY_EXISTS || GetLastError() == ERROR_ACCESS_DENIED); if(AlreadyRunning == true) { ::wxMessageBox(wxT("PPPoE Killer is running"), wxT("Error"), wxOK | wxICON_ERROR); return false; } #endif wxIcon icon(pppoe_xpm); // Create the main frame window MainFrame *frame = new MainFrame; frame->SetIcon(icon); frame->SetSize(450, 300); frame->Centre(); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MainFrame, wxFrame) EVT_MENU(PKID_ENTERMAC, MainFrame::forward) EVT_MENU(PKID_ENTERISPMAC, MainFrame::forward) EVT_MENU(PKID_SAVE, MainFrame::forward) EVT_MENU(PKID_LOAD, MainFrame::forward) EVT_MENU(PKID_EXIT, MainFrame::exit) EVT_MENU(PKID_RESTORE, MainFrame::menu_restore) EVT_MENU(PKID_SETTING, MainFrame::preference) EVT_MENU(wxID_ABOUT, MainFrame::about) EVT_TASKBAR_LEFT_DCLICK(MainFrame::tray_restore) EVT_CLOSE(MainFrame::close) END_EVENT_TABLE() MainFrame::MainFrame() : wxFrame(NULL, PKID_MAINFRAME, _T("PPPoE Killer v1.2"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE & ~ (wxRESIZE_BORDER | wxRESIZE_BORDER | wxMAXIMIZE_BOX)) { m_panel = new MainPanel(this); m_tray = new MainTrayIcon(this); wxMenu *func_menu = new wxMenu; wxMenu *entermac_menu = new wxMenu; wxMenu *help_menu = new wxMenu; wxMenuBar *menu_bar = new wxMenuBar; //m_tray->SetEvtHandlerEnabled(false); m_tray->SetNextHandler(this); entermac_menu->Append(PKID_ENTERMAC, _T("Target(&T)")); entermac_menu->Append(PKID_ENTERISPMAC, _T("ISP(&I)")); func_menu->AppendSubMenu(entermac_menu, _T("Input MAC(&M)")); func_menu->Append(PKID_LOAD, _T("Load(&L)")); func_menu->Append(PKID_SAVE, _T("Save(&S)")); func_menu->Append(PKID_SETTING, _T("Preferences(&P)")); func_menu->AppendSeparator(); func_menu->Append(PKID_EXIT, _T("Exit(&X)")); help_menu->Append(wxID_ABOUT, _T("About(&A)")); menu_bar->Append(func_menu, _T("Options(&O)")); menu_bar->Append(help_menu, _T("Help(&H)")); SetMenuBar(menu_bar); boost::thread *helper = new boost::thread(boost::bind(&MainFrame::helperthread, this)); } MainFrame::~MainFrame() { delete m_tray; } void MainFrame::restore() { m_tray->RemoveIcon(); Show(true); } void MainFrame::helperthread() { while(true) { m_panel->GetMainFunction()->refreshButton(); thread::sleep(500); } } void MainFrame::menu_restore(wxCommandEvent & event) { restore(); } void MainFrame::tray_restore(wxTaskBarIconEvent & event) { restore(); } wxMenu* MainFrame::GetTrayMenu() { wxMenu *traymenu = new wxMenu; traymenu->Append(PKID_RESTORE, _T("Restore PPPoE Killer(&O)")); traymenu->Append(PKID_EXIT, _T("Exit(&X)")); traymenu->SetNextHandler(this); return traymenu; } void MainFrame::forward(wxCommandEvent & event) { m_panel->GetMainFunction()->ProcessEvent(event); } void MainFrame::about(wxCommandEvent & event) { wxAboutDialogInfo info; info.SetName(wxT("PPPoE Killer")); info.SetVersion(wxT("v1.1")); info.SetWebSite(wxT("http://www.google.com/group/pppoe-killer")); info.SetCopyright(wxT("(C) 2007 [email protected] <[email protected]>")); wxAboutBox(info); } void MainFrame::exit(wxCommandEvent& event) { Close(true); } void MainFrame::preference(wxCommandEvent & event) { PreferenceDialog dialog(this, m_panel->GetMainFunction()); dialog.SetSize(400, 300); dialog.ShowModal(); } void MainFrame::close(wxCloseEvent& event) { if(event.CanVeto()) { m_tray->SetIcon(this->GetIcon(), "PPPoE Killer v1.2"); this->Show(false); } else { this->Destroy(); } } MainPanel::MainPanel(wxFrame *frame) : wxPanel(frame, wxID_ANY) { vector<netadapter> adapters; adapters = nettool::getLocalAdapters(); m_cards = new wxComboBox(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); for(vector<netadapter>::size_type i = 0; i < adapters.size(); i++) { string *clientData = new string; *clientData = adapters[i].getName(); #ifdef WIN32 m_cards->Append(adapters[i].getDescription(), (void*)clientData); #else m_cards->Append(adapters[i].getName(), (void*)clientData); #endif } if(adapters.size() > 0) m_cards->SetSelection(0); m_detect = new wxToggleButton(this, PKID_DETECT, "Detect"); wxBoxSizer *cards_sizer = new wxBoxSizer(wxHORIZONTAL); cards_sizer->Add(m_cards, 1, wxEXPAND | wxALL, 10); cards_sizer->Add(m_detect, 0, wxEXPAND | wxALL, 10); m_maclist = new wxListBox(this, PKID_MACLIST, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_SINGLE | wxLB_HSCROLL |wxLB_NEEDED_SB); m_kill = new wxButton(this, PKID_KILL, "Kill"); m_autokill = new wxToggleButton(this, PKID_AUTOKILL, "AutoKill"); m_mark = new wxButton(this, PKID_MARK, "Mark"); wxBoxSizer *toolbar_sizer = new wxBoxSizer(wxVERTICAL); toolbar_sizer->Add(m_kill, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); toolbar_sizer->AddSpacer(5); toolbar_sizer->Add(m_autokill, 0, wxEXPAND | wxLEFT | wxRIGHT, 10); toolbar_sizer->AddSpacer(5); toolbar_sizer->Add(m_mark, 0, wxEXPAND | wxLEFT | wxRIGHT, 10); wxBoxSizer *list_sizer = new wxBoxSizer(wxHORIZONTAL); list_sizer->Add(m_maclist, 1, wxEXPAND | wxALL, 10); list_sizer->Add(toolbar_sizer, 0, wxEXPAND | wxALL); wxStaticText *tlabel = new wxStaticText(this, wxID_ANY, "ISP MAC - "); m_dstmac = new wxStaticText(this, wxID_ANY, ""); wxBoxSizer *lbl_sizer = new wxBoxSizer(wxHORIZONTAL); lbl_sizer->Add(tlabel, 0, wxEXPAND | wxALL); lbl_sizer->Add(m_dstmac, 0, wxEXPAND | wxALL); wxBoxSizer *root_sizer = new wxBoxSizer(wxVERTICAL); root_sizer->Add(cards_sizer, 0, wxEXPAND | wxALL); root_sizer->Add(list_sizer, 1, wxEXPAND | wxALL); root_sizer->Add(lbl_sizer, 0, wxEXPAND | wxALL, 10); SetSizer(root_sizer); m_mainfunc = new MainFunction(m_cards, m_maclist, m_dstmac, m_autokill, m_kill); m_detect->PushEventHandler(m_mainfunc); m_kill->PushEventHandler(m_mainfunc); m_autokill->PushEventHandler(m_mainfunc); m_mark->PushEventHandler(m_mainfunc); m_maclist->PushEventHandler(m_mainfunc); m_mainfunc->loadConfig(); } MainFunction* MainPanel::GetMainFunction() { return m_mainfunc; }
[ "ptthippo@b4fe46aa-e838-0410-827a-8b5f5aca3737" ]
[ [ [ 1, 247 ] ] ]
75955eac1d8326347bac25aac5aaf72c8b3a4620
cb2a96dafbeb929ecfe13efc241f4d6952f13f0f
/PulseDisplay/PulseDisplay/PulseDisplay.h
9e1dfe5a266ef3928927c7282a0b3ffc11cc4de4
[]
no_license
enildne/agilpulse
2c237db0bf2db912ea533a6a5d3a000855b81ba7
7c72429fbd5928b1ae17c5f994904cea940bff18
refs/heads/master
2020-04-06T07:08:16.018801
2010-07-03T12:14:19
2010-07-03T12:14:19
41,840,049
0
0
null
null
null
null
UHC
C++
false
false
597
h
// PulseDisplay.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다. // #pragma once #ifndef __AFXWIN_H__ #error PCH에서 이 파일을 포함하기 전에 'stdafx.h'를 포함하십시오. #endif #include "resource.h" // 주 기호 // CPulseDisplayApp: // 이 클래스의 구현에 대해서는 PulseDisplay.cpp을 참조하십시오. // class CPulseDisplayApp : public CWinApp { public: CPulseDisplayApp(); // 재정의 public: virtual BOOL InitInstance(); // 구현 DECLARE_MESSAGE_MAP() }; extern CPulseDisplayApp theApp;
[ "zest.kor@b5a67afa-1c85-cad2-13df-3063a5d37f7f" ]
[ [ [ 1, 31 ] ] ]
cd0d5681b41c29feacff6a4aaac566915996129b
960a896c95a759a41a957d0e7dbd809b5929c999
/Game/GameManager.cpp
90fb654b432041f4eca8091e287ec4593b6f3a0e
[]
no_license
WSPSNIPER/dangerwave
8cbd67a02eb45563414eaf9ecec779cc1a7f09d5
51af1171880104aa823f6ef8795a2f0b85b460d8
refs/heads/master
2016-08-12T09:50:00.996204
2010-08-24T22:55:52
2010-08-24T22:55:52
48,472,531
0
0
null
null
null
null
UTF-8
C++
false
false
817
cpp
#include "GameManager.h" int score = 0; GameManager::GameManager(int width, int height, int bpp, std::string title) : sf::RenderWindow(sf::VideoMode(width, height, bpp), title) { _states.clear(); } GameManager::~GameManager() { _states.clear(); } void GameManager::HandleEvents() { _states.back()->HandleEvents(this); } void GameManager::Init() { } void GameManager::Cleanup() { } void GameManager::Update() { _states.back()->Update(this); } void GameManager::Render() { Clear(); _states.back()->Render(this); Display(); } void GameManager::PushState(State* state) { _states.push_back(state); _states.back()->Init(); } void GameManager::PopState() { _states.back()->Cleanup(); _states.pop_back(); }
[ "michaelbond2008@e78017d1-81bd-e181-eab4-ba4b7880cff6", "lukefangel@e78017d1-81bd-e181-eab4-ba4b7880cff6" ]
[ [ [ 1, 2 ], [ 4, 58 ] ], [ [ 3, 3 ] ] ]
3fa801318539a720a126ae9d7d88876769b46290
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/NxOgre/build/source/NxOgrePhysXPointer.cpp
6ae23f603ca7f64ebeb4284aff5234ccc994b529
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,456
cpp
/** File: NxOgrePhysXPointer.cpp Created on: 19-Apr-09 Author: Robin Southern "betajaen" © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre 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 3 of the License, or (at your option) any later version. NxOgre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #include "NxOgreStable.h" #include "NxOgrePhysXPointer.h" namespace NxOgre { } // namespace NxOgre
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 42 ] ] ]
b18f327a3d0f5297a655e73742d490a3fbd70825
07905495eca613d042d2c53744132b06761ddb40
/Matrix4.cpp
2fabc19684e02994609baf6175b7c1d5b7992d7e
[]
no_license
Sudoka/cse167
c35ae04ee08a6681ec7a6d6980c43dd798200c2b
414a523197f24038aef523268e2cd5f3a30a0c7d
refs/heads/master
2020-12-29T00:26:12.433188
2011-12-02T18:05:16
2011-12-02T18:05:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,365
cpp
#include <ostream> #include <stdio.h> #include "BasicMath.h" #include "Matrix4.h" using namespace std; Matrix4::Matrix4() { zero(); } Matrix4::Matrix4( double m00, double m01, double m02, double m03, double m10, double m11, double m12, double m13, double m20, double m21, double m22, double m23, double m30, double m31, double m32, double m33 ) { set(0, 0, m00); set(0, 1, m01); set(0, 2, m02); set(0, 3, m03); set(1, 0, m10); set(1, 1, m11); set(1, 2, m12); set(1, 3, m13); set(2, 0, m20); set(2, 1, m21); set(2, 2, m22); set(2, 3, m23); set(3, 0, m30); set(3, 1, m31); set(3, 2, m32); set(3, 3, m33); } double* Matrix4::getPointer(void) { return &m[0][0]; } void Matrix4::toIdentity(void) { double ident[4][4]={{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; for (int i=0; i<4; ++i) { for (int j=0; j<4; ++j) { set(i, j, ident[i][j]); } } } void Matrix4::set(int row, int col, double n) { // Matrix is stored as a column major array so reverse order of indexers m[col][row] = n; } double Matrix4::get(int row, int col) const { // Matrix is stored as a column major array so reverse order of indexers return m[col][row]; } void Matrix4::multiply(Matrix4 &mat) { Matrix4 temp; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { double total = 0.0; for (int k = 0; k < 4; k++) { total += get(i, k) * mat.get(k, j); } temp.set(i, j, total); } } (*this) = temp; } Vector4 Matrix4::multiply(Vector4 &vec) { Vector4 v; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { v[i] += get(i, j) * vec[j]; } } return v; } Vector3 Matrix4::multiply(Vector3& vec) { Vector4 v(vec.x, vec.y, vec.z, 1.0); Vector4 multipliedRes(multiply(v)); multipliedRes.dehomogenize(); return Vector3(multipliedRes.x, multipliedRes.y, multipliedRes.z); } // angle in degrees void Matrix4::toRotationMatrixX(double angle) { double th = BasicMath::radian(angle); zero(); set(0, 0, 1.0); set(1, 1, cos(th)); set(1, 2, -sin(th)); set(2, 1, sin(th)); set(2, 2, cos(th)); set(3, 3, 1.0); } // angle in degrees void Matrix4::toRotationMatrixY(double angle) { double th = BasicMath::radian(angle); set(0, 0, cos(th)); set(0, 1, 0.0); set(0, 2, sin(th)); set(0, 3, 0.0); set(1, 0, 0.0); set(1, 1, 1.0); set(1, 2, 0.0); set(1, 3, 0.0); set(2, 0, -sin(th)); set(2, 1, 0.0); set(2, 2, cos(th)); set(2, 3, 0.0); set(3, 0, 0.0); set(3, 1, 0.0); set(3, 2, 0.0); set(3, 3, 1.0); } // angle in degrees void Matrix4::toRotationMatrixZ(double angle) { double th = BasicMath::radian(angle); zero(); set(0, 0, cos(th)); set(0, 1, -sin(th)); set(1, 0, sin(th)); set(1, 1, cos(th)); set(2, 2, 1.0); set(3, 3, 1.0); } // angle in degrees void Matrix4::toRotationMatrix(double angle, const Vector4 &axis) { Vector4 a(axis); toRotationMatrix(angle, a.toVector3()); } // angle in degrees void Matrix4::toRotationMatrix(double angle, const Vector3 &axis) { // Make the x,y,z component specification of the axis a unit vector Vector3 a(axis); a.normalize(); double th = BasicMath::radian(angle); set(0, 0, 1.0 + (1.0 - cos(th)) * (a.x * a.x - 1.0)); set(0, 1, -a.z * sin(th) + (1.0 - cos(th)) * a.x * a.y); set(0, 2, a.y * sin(th) + (1.0 - cos(th)) * a.x * a.z); set(0, 3, 0.0); set(1, 0, a.z * sin(th) + (1.0 - cos(th)) * a.y * a.x); set(1, 1, 1.0 + (1.0 - cos(th)) * (a.y * a.y - 1.0)); set(1, 2, -a.x * sin(th) + (1.0 - cos(th)) * a.y * a.z); set(1, 3, 0.0); set(2, 0, -a.y * sin(th) + (1.0 - cos(th)) * a.z * a.x); set(2, 1, a.x * sin(th) + (1.0 - cos(th)) * a.z * a.y); set(2, 2, 1.0 + (1.0 - cos(th)) * (a.z * a.z - 1)); set(2, 3, 0.0); set(3, 0, 0.0); set(3, 1, 0.0); set(3, 2, 0.0); set(3, 3, 1.0); } void Matrix4::toScalingMatrix(double xFactor, double yFactor, double zFactor) { zero(); set(0, 0, xFactor); set(1, 1, yFactor); set(2, 2, zFactor); set(3, 3, 1.0); } void Matrix4::toTranslationMatrix(double dx, double dy, double dz) { toIdentity(); set(0, 3, dx); set(1, 3, dy); set(2, 3, dz); set(3, 3, 1.0); } void Matrix4::zero(void) { for (int i=0; i<4; ++i) { for (int j=0; j<4; ++j) { set(i, j, 0.0); } } } void Matrix4::transpose(void) { Matrix4 temp; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { temp.set(j, i, get(i, j)); } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { set(i, j, temp.get(i, j)); } } } ostream &operator<<(ostream &out, const Matrix4 &a) { out << "(" << endl; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { printf("%4.2f ", a.get(i, j)); } out << endl; } return out; }
[ [ [ 1, 228 ] ] ]
61411ab2ec5d58736c830438340c33dea36253b3
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/teststdio/src/tstdio_thread.cpp
e2b41d08ff85b3c6ae9dd6ee95cf8bcd025d1e22
[]
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
9,780
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /* * ============================================================================== * Name : tstdio_thread.cpp * Part of : teststdio * * Description : ?Description * Version: 0.5 * */ #include "tstdio.h" typedef struct node { int iCnt; sem_t * iSemaphore; char msg[100]; FILE *fp; } Node; /***************** these functions are for fseek,ftell test **********************/ void * tell_thread(void * param) { int res=1; int retval; FILE * fp; Node * nd=(Node *) param; int chk=nd->iCnt; int ret; fp=fopen("c:\\input.txt","r"); if(fp!=NULL) { retval=sem_wait(nd->iSemaphore); if(retval!=0) { res=1; } else { ret=ftell(fp); if(ret==chk) { res=0; } else { res=1; } } fclose(fp); } return (void *)res; } void * seek_thread(void * param) { int res=0; int retval; FILE * fp; Node * nd=(Node *) param; int chk=nd->iCnt; int ret; fp=fopen("c:\\input.txt","r"); if(fp==NULL) { res=1; } else { ret=fseek(fp,chk,SEEK_SET); if(ret!=0) { res=1; } fclose(fp); } retval=sem_post(nd->iSemaphore); if(retval!=0) { res=1; } return (void *)res; } /*****************parent thread function for fseek, ftell test ******************/ TInt CTestStdio::fseek_multithreaded() { TInt result=KErrGeneral; pthread_t thrid1=0,thrid2=0; pthread_attr_t threadAttr; int retval,exitReason1=0,exitReason2=0,res=0; sem_t semaphore; Node element; if(sem_init(&semaphore,0,0)!=0) { INFO_PRINTF1(_L("sem_init failed in main function\n")); return KErrGeneral; } pthread_attr_init( &threadAttr ); pthread_attr_setdetachstate( &threadAttr, PTHREAD_CREATE_JOINABLE ); element.iCnt=3; element.iSemaphore=&semaphore; if(pthread_create(&thrid1,&threadAttr,seek_thread,(void *)&element)!=0) { INFO_PRINTF1(_L("seek thread not created properly\n")); return KErrGeneral; } else { element.iCnt=0; if(pthread_create(&thrid2,&threadAttr,tell_thread,(void *)&element)!=0) { INFO_PRINTF1(_L("tell thread not created properly\n")); return KErrGeneral; } else { retval= pthread_join(thrid1, (void**)&exitReason1 ); if(retval) { INFO_PRINTF1(_L("Case failed because of seek thread\n")); res=1; } retval= pthread_join(thrid2, (void**)&exitReason2 ); if(retval) { INFO_PRINTF1(_L("Case failed because of tell thread\n")); res=1; } } } if(!(exitReason1||exitReason2)) { INFO_PRINTF1(_L("case passed successfully\n")); result=KErrNone; } else { result=KErrGeneral; } if(sem_destroy(&semaphore)==-1) { result=KErrGeneral; } INFO_PRINTF2(_L("fseek multithreaded case returned with code %d\n"),res); return result; } /***************** these functions are for printf test **********************/ void * print_thr2(void * param) { int res=KErrNone; int retval; Node * nd=(Node *) param; int ret; retval=sem_wait(nd->iSemaphore); if(retval!=0) { res=1; } else { ret=printf("hi again\n"); if(ret==9) { res=0; } } return (void *)res; } void * print_thr1(void * param) { int res=KErrNone; int retval; Node * nd=(Node *) param; int ret; ret=printf("hi\n"); if(ret==3) { res=0; } retval=sem_post(nd->iSemaphore); if(retval!=0) { res=1; } return (void *)res; } /*****************parent thread function for printf test ******************/ TInt CTestStdio::printf_multithreaded() { TInt result=KErrGeneral; pthread_t thrid1=0,thrid2=0; pthread_attr_t threadAttr; int retval,exitReason1=0,exitReason2=0,res=0; sem_t semaphore; Node element; if(sem_init(&semaphore,0,0)!=0) { INFO_PRINTF1(_L("sem_init failed in main function\n")); return KErrGeneral; } pthread_attr_init( &threadAttr ); pthread_attr_setdetachstate( &threadAttr, PTHREAD_CREATE_JOINABLE ); element.iSemaphore=&semaphore; if(pthread_create(&thrid1,&threadAttr,print_thr1,(void *)&element)!=0) { INFO_PRINTF1(_L("thread1 thread not created properly\n")); return KErrGeneral; } else { if(pthread_create(&thrid2,&threadAttr,print_thr2,(void *)&element)!=0) { INFO_PRINTF1(_L("thread2 thread not created properly\n")); return KErrGeneral; } else { retval= pthread_join(thrid1, (void**)&exitReason1 ); if(retval) { INFO_PRINTF1(_L("Case failed because of thread1 thread\n")); res=1; } retval= pthread_join(thrid2, (void**)&exitReason2 ); if(retval) { INFO_PRINTF1(_L("Case failed because of thread2 thread\n")); res=1; } } } if(!(exitReason1||exitReason2)) { INFO_PRINTF1(_L("case passed successfully\n")); result=KErrNone; } else { result=KErrGeneral; } if(sem_destroy(&semaphore)==-1) { result=KErrGeneral; } INFO_PRINTF2(_L("printf multithreaded case returned with code %d\n"),res); return result; } /*************************** freopen tests ************************************************/ void * map_thread(void * param) { int res=0; int retval; FILE * fp; Node * nd=(Node *) param; char msg[100]; // dup2(2,1); fp=freopen("c:\\cons.txt","w",stdout); // fp = fopen("c:\\cons3.txt", "w"); // dup2(fileno(fp), 1); /* int fperm = O_RDWR | O_CREAT; int fildes = open("c:\\cons2.txt", fperm); dup2(fildes, 1); if(fildes!=0)*/ if(fp!=NULL) { retval=sem_wait(nd->iSemaphore); if(retval!=0) { res=1; } else { //lseek(fildes,0,SEEK_CUR); fseek(fp, 0, SEEK_CUR); fgets(msg,sizeof(msg),fp); } fclose(fp); } return (void *)res; } void * cons_thread(void * param) { int res=0; int retval; Node * nd=(Node *) param; int ret=KErrNone; if(ret==strlen(nd->msg)) { res=0; } retval=sem_post(nd->iSemaphore); if(retval!=0) { res=1; } return (void *)res; } /*****************parent thread function for freopen test ******************/ TInt CTestStdio::freopen_multithreaded() { TInt result=KErrGeneral; pthread_t thrid1=0,thrid2=0; pthread_attr_t threadAttr; int retval,exitReason1=0,exitReason2=0,res=0; sem_t semaphore; Node element; if(sem_init(&semaphore,0,0)!=0) { INFO_PRINTF1(_L("sem_init failed in main function\n")); return KErrGeneral; } pthread_attr_init( &threadAttr ); pthread_attr_setdetachstate( &threadAttr, PTHREAD_CREATE_JOINABLE ); element.iSemaphore=&semaphore; strcpy(element.msg,"hi there\n"); if(pthread_create(&thrid1,&threadAttr,cons_thread,(void *)&element)!=0) { INFO_PRINTF1(_L("cons_thread not created properly\n")); return KErrGeneral; } else { if(pthread_create(&thrid2,&threadAttr,map_thread,(void *)&element)!=0) { INFO_PRINTF1(_L("map_thread not created properly\n")); return KErrGeneral; } else { retval= pthread_join(thrid1, (void**)&exitReason1 ); if(retval) { INFO_PRINTF1(_L("Case failed because of cons_thread\n")); res=1; } retval= pthread_join(thrid2, (void**)&exitReason2 ); if(retval) { INFO_PRINTF1(_L("Case failed because of map_thread\n")); res=1; } } } if(!(exitReason1||exitReason2)) { INFO_PRINTF1(_L("case passed successfully\n")); result=KErrNone; } else { result=KErrGeneral; } if(sem_destroy(&semaphore)==-1) { result=KErrGeneral; } INFO_PRINTF2(_L("freopen multithreaded case returned with code %d\n"),res); return result; } /***************************** putc_unlocked tests *******************************/ void * getc_thread(void * param) { int res=KErrNone; int retval; Node * nd=(Node *) param; flockfile(nd->fp); retval=getc_unlocked(nd->fp); if(retval==nd->msg[0]) { res=0; } fclose(nd->fp); funlockfile(nd->fp); return (void *)res; } /****************************** main thread for putc_unlocked tests *******************/ TInt CTestStdio::putc_multithreaded() { TInt result; pthread_t thrid1=0; pthread_attr_t threadAttr; int retval,exitReason1=0,res=0; sem_t semaphore; Node element; FILE * fp; element.iCnt=3; element.iSemaphore=&semaphore; element.msg[0]='a'; fp=fopen("C:\\cons.txt","w"); element.fp = fp; flockfile(fp); pthread_attr_init( &threadAttr ); pthread_attr_setdetachstate( &threadAttr, PTHREAD_CREATE_JOINABLE ); if(pthread_create(&thrid1,&threadAttr,getc_thread,(void *)&element)!=0) { funlockfile(fp); fclose(fp); INFO_PRINTF1(_L("getc thread not created properly\n")); } else { putc_unlocked('a',fp); funlockfile(fp); fclose(fp); retval=pthread_join(thrid1,(void **)&exitReason1); if(retval) { INFO_PRINTF1(_L("pthread join failed\n")); } } if(exitReason1) { res=1; } if(!res) { result=KErrNone; } else { result=KErrGeneral; } INFO_PRINTF2(_L("putc multithreaded case returned with code %d\n"),res); return result; }
[ "none@none" ]
[ [ [ 1, 519 ] ] ]
672b495c0988c903002267e46fec572510a13d2d
3e1a7d458b265a2689e02c51847eeee2fe242b38
/podglad.cpp
040437f07ac5f79dedd440b45cc8f706d0ad5929
[]
no_license
przenz/ramek
93b656d94b061a62c2048c29aad86c584b771ff0
9dac2ec0b97f976d00dcc8c3615d12c5a196fc8b
refs/heads/master
2020-04-03T06:10:59.748202
2011-09-07T17:16:25
2011-09-07T17:16:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,669
cpp
#include "podglad.h" #include <QPainter> podglad::podglad(QWidget *parent) : QWidget(parent) { rozmiar=390-2;//390 obrazSzer=0,obrazWys=0,paspartu=0,ramka=0; skala=1; szklo=1; } void podglad::paintEvent(QPaintEvent *e){ QPainter painter(this); QPen pen(QColor(0,0,0,100),2); painter.setPen(pen); int srodek=390/2; if( ramka>0 ){ QRect myQRect(srodek-(obrazSzer/2+paspartu+ramka),srodek-(obrazWys/2+paspartu+ramka) ,obrazSzer+2*paspartu+2*ramka,obrazWys+2*paspartu+2*ramka); QLinearGradient gradient(myQRect.topLeft(), myQRect.bottomRight()); // diagonal gradient from top-left to bottom-right gradient.setColorAt(0, QColor(110,40,0)); gradient.setColorAt(1, QColor(190,81,1)); painter.fillRect(myQRect, gradient); //painter.fillRect(srodek-(obrazSzer/2+paspartu+ramka),srodek-(obrazWys/2+paspartu+ramka) // ,obrazSzer+2*paspartu+2*ramka,obrazWys+2*paspartu+2*ramka,QColor(130,51,0)); painter.drawRect(srodek-(obrazSzer/2+paspartu+ramka),srodek-(obrazWys/2+paspartu+ramka) ,obrazSzer+2*paspartu+2*ramka,obrazWys+2*paspartu+2*ramka); } if( paspartu>0 ){ painter.fillRect(srodek-(obrazSzer/2+paspartu),srodek-(obrazWys/2+paspartu) ,obrazSzer+2*paspartu,obrazWys+2*paspartu,QColor(255,205,170)); painter.drawRect(srodek-(obrazSzer/2+paspartu),srodek-(obrazWys/2+paspartu) ,obrazSzer+2*paspartu,obrazWys+2*paspartu); } if( obrazSzer>0 && obrazWys>0 ){ //painter.fillRect(srodek-obrazSzer/2,srodek-obrazWys/2,obrazSzer,obrazWys,QColor(120,255,120)); painter.fillRect(srodek-obrazSzer/2,srodek-obrazWys/2,obrazSzer,obrazWys,QColor(255,255,255)); painter.drawRect(srodek-obrazSzer/2,srodek-obrazWys/2,obrazSzer,obrazWys); } if( szklo>0 ){ if( paspartu>0 ){ QRect myQRect(srodek-(obrazSzer/2+paspartu),srodek-(obrazWys/2+paspartu) ,obrazSzer+2*paspartu,obrazWys+2*paspartu); QLinearGradient gradient(myQRect.topLeft(), myQRect.bottomRight()); // diagonal gradient from top-left to bottom-right if(szklo==3){ gradient.setColorAt(0, QColor(100,100,255,100)); gradient.setColorAt(0.3, QColor(255,255,255,150)); gradient.setColorAt(0.4, QColor(255,255,255,250)); gradient.setColorAt(0.5, QColor(255,255,255,150)); gradient.setColorAt(1, QColor(100,100,255,100)); } else { gradient.setColorAt(0, QColor(255,255,255,150)); gradient.setColorAt(1, QColor(100,100,255,150)); } painter.fillRect(myQRect, gradient); //jesli antyrefleks if( szklo==2 ){ QBrush brusz(QColor(0,0,0,40),Qt::Dense5Pattern); painter.setBrush(brusz); painter.setPen(Qt::NoPen); painter.drawRect(myQRect); } } else if( obrazSzer>0 && obrazWys>0 ){ QRect myQRect(srodek-obrazSzer/2,srodek-obrazWys/2,obrazSzer,obrazWys); QLinearGradient gradient(myQRect.topLeft(), myQRect.bottomRight()); // diagonal gradient from top-left to bottom-right if(szklo==3){ gradient.setColorAt(0, QColor(100,100,255,100)); gradient.setColorAt(0.3, QColor(255,255,255,150)); gradient.setColorAt(0.4, QColor(255,255,255,250)); gradient.setColorAt(0.5, QColor(255,255,255,150)); gradient.setColorAt(1, QColor(100,100,255,100)); } else { gradient.setColorAt(0, QColor(255,255,255,150)); gradient.setColorAt(1, QColor(100,100,255,150)); } painter.fillRect(myQRect, gradient); //jesli antyrefleks if( szklo==2 ){ QBrush brusz(QColor(0,0,0,60),Qt::Dense5Pattern); painter.setBrush(brusz); painter.setPen(Qt::NoPen); painter.drawRect(myQRect); } } } } void podglad::ustawWymiary(float oWys, float oSzer, float pas, float ramk, int szk){ if(oWys>oSzer){ skala = (rozmiar)/(oWys*100+2*pas*100+2*ramk); } else { skala = (rozmiar)/(oSzer*100+2*pas*100+2*ramk); } obrazWys=oWys*100*skala; obrazSzer=oSzer*100*skala; paspartu=pas*100*skala; ramka=ramk*skala; szklo=szk; repaint(); }
[ [ [ 1, 105 ] ] ]
262da1e8debeb8e93fafce9377968887aebd7d80
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/numeric/ublas/bench1/bench1.hpp
dfd4e2a27957d5863191b24383e49fef409e4321
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
4,061
hpp
// // Copyright (c) 2000-2002 // Joerg Walter, Mathias Koch // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. The authors make no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. // // The authors gratefully acknowledge the support of // GeNeSys mbH & Co. KG in producing this work. // #ifndef BENCH1_H #define BENCH1_H #include <iostream> #include <string> #include <valarray> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/timer.hpp> namespace ublas = boost::numeric::ublas; void header (std::string text); template<class T> struct footer { void operator () (int multiplies, int plus, int runs, double elapsed) { std::cout << "elapsed: " << elapsed << " s, " << (multiplies * ublas::type_traits<T>::multiplies_complexity + plus * ublas::type_traits<T>::plus_complexity) * runs / (1024 * 1024 * elapsed) << " Mflops" << std::endl; } }; template<class T, int N> struct c_vector_traits { typedef T type [N]; }; template<class T, int N, int M> struct c_matrix_traits { typedef T type [N] [M]; }; template<class T, int N> struct initialize_c_vector { void operator () (typename c_vector_traits<T, N>::type &v) { for (int i = 0; i < N; ++ i) v [i] = std::rand () * 1.f; // v [i] = 0.f; } }; template<class V> BOOST_UBLAS_INLINE void initialize_vector (V &v) { int size = v.size (); for (int i = 0; i < size; ++ i) v [i] = std::rand () * 1.f; // v [i] = 0.f; } template<class T, int N, int M> struct initialize_c_matrix { void operator () (typename c_matrix_traits<T, N, M>::type &m) { for (int i = 0; i < N; ++ i) for (int j = 0; j < M; ++ j) m [i] [j] = std::rand () * 1.f; // m [i] [j] = 0.f; } }; template<class M> BOOST_UBLAS_INLINE void initialize_matrix (M &m) { int size1 = m.size1 (); int size2 = m.size2 (); for (int i = 0; i < size1; ++ i) for (int j = 0; j < size2; ++ j) m (i, j) = std::rand () * 1.f; // m (i, j) = 0.f; } template<class T> BOOST_UBLAS_INLINE void sink_scalar (const T &s) { static T g_s = s; } template<class T, int N> struct sink_c_vector { void operator () (const typename c_vector_traits<T, N>::type &v) { static typename c_vector_traits<T, N>::type g_v; for (int i = 0; i < N; ++ i) g_v [i] = v [i]; } }; template<class V> BOOST_UBLAS_INLINE void sink_vector (const V &v) { static V g_v (v); } template<class T, int N, int M> struct sink_c_matrix { void operator () (const typename c_matrix_traits<T, N, M>::type &m) { static typename c_matrix_traits<T, N, M>::type g_m; for (int i = 0; i < N; ++ i) for (int j = 0; j < M; ++ j) g_m [i] [j] = m [i] [j]; } }; template<class M> BOOST_UBLAS_INLINE void sink_matrix (const M &m) { static M g_m (m); } template<class T> struct peak { void operator () (int runs); }; template<class T, int N> struct bench_1 { void operator () (int runs); }; template<class T, int N> struct bench_2 { void operator () (int runs); }; template<class T, int N> struct bench_3 { void operator () (int runs); }; struct safe_tag {}; struct fast_tag {}; //#define USE_FLOAT #define USE_DOUBLE // #define USE_STD_COMPLEX #define USE_C_ARRAY // #define USE_BOUNDED_ARRAY #define USE_UNBOUNDED_ARRAY // #define USE_STD_VALARRAY //#define USE_STD_VECTOR #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 160 ] ] ]
6fa43e48c3d40f534813621a80e5b31c06a50b50
f6529b63d418f7d0563d33e817c4c3f6ec6c618d
/source/wstringEx.cpp
b63bf639055e598ae07b2847bad3a479102a66d6
[]
no_license
Captnoord/Wodeflow
b087659303bc4e6d7360714357167701a2f1e8da
5c8d6cf837aee74dc4265e3ea971a335ba41a47c
refs/heads/master
2020-12-24T14:45:43.854896
2011-07-25T14:15:53
2011-07-25T14:15:53
2,096,630
1
3
null
null
null
null
UTF-8
C++
false
false
3,145
cpp
#include "wstringEx.hpp" using namespace std; wstringEx::wstringEx(const wchar_t *s) : std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >(s) { } wstringEx::wstringEx(const basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> > &ws) : basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >(ws) { } wstringEx::wstringEx(const string &s) { std::string::size_type size; size = s.size(); resize(size); for (std::string::size_type i = 0; i < size; ++i) (*this)[i] = (unsigned char)s[i]; } wstringEx &wstringEx::operator=(const string &s) { std::string::size_type size; size = s.size(); this->resize(size); for (std::string::size_type i = 0; i < size; ++i) (*this)[i] = (unsigned char)s[i]; return *this; } static size_t utf8Len(const char *s) { size_t len = 0; for (int i = 0; s[i] != 0; ) { if ((s[i] & 0xF8) == 0xF0) { if (((s[i + 1] & 0xC0) != 0x80) || ((s[i + 2] & 0xC0) != 0x80) || ((s[i + 3] & 0xC0) != 0x80)) return 0; ++len; i += 4; } else if ((s[i] & 0xF0) == 0xE0) { if (((s[i + 1] & 0xC0) != 0x80) || ((s[i + 2] & 0xC0) != 0x80)) return 0; ++len; i += 3; } else if ((s[i] & 0xE0) == 0xC0) { if (((s[i + 1] & 0xC0) != 0x80)) return 0; ++len; i += 2; } else if ((s[i] & 0x80) == 0x00) { ++len; ++i; } else return 0; } return len; } void wstringEx::fromUTF8(const char *s) { size_t len = utf8Len(s); clear(); if (len == 0) return; reserve(len); for (int i = 0; s[i] != 0; ) { if ((s[i] & 0xF8) == 0xF0) { push_back(((wchar_t)(s[i] & 0x07) << 18) | ((wchar_t)(s[i + 1] & 0x3F) << 12) | ((wchar_t)(s[i + 2] & 0x3F) << 6) | (wchar_t)(s[i + 3] & 0x3F)); i += 4; } else if ((s[i] & 0xF0) == 0xE0) { push_back(((wchar_t)(s[i] & 0x0F) << 12) | ((wchar_t)(s[i + 1] & 0x3F) << 6) | (wchar_t)(s[i + 2] & 0x3F)); i += 3; } else if ((s[i] & 0xE0) == 0xC0) { push_back(((wchar_t)(s[i] & 0x1F) << 6) | (wchar_t)(s[i + 1] & 0x3F)); i += 2; } else { push_back((wchar_t)s[i]); ++i; } } } string wstringEx::toUTF8(void) const { string s; size_t len = 0; wchar_t wc; for (size_t i = 0; i < size(); ++i) { wc = operator[](i); if (wc < 0x80) ++len; else if (wc < 0x800) len += 2; else if (wc < 0x10000) len += 3; else len += 4; } s.reserve(len); for (size_t i = 0; i < size(); ++i) { wc = operator[](i); if (wc < 0x80) s.push_back((char)wc); else if (wc < 0x800) { s.push_back((char)((wc >> 6) | 0xC0)); s.push_back((char)((wc & 0x3F) | 0x80)); } else if (wc < 0x10000) { s.push_back((char)((wc >> 12) | 0xE0)); s.push_back((char)(((wc >> 6) & 0x3F) | 0x80)); s.push_back((char)((wc & 0x3F) | 0x80)); } else { s.push_back((char)(((wc >> 18) & 0x07) | 0xF0)); s.push_back((char)(((wc >> 12) & 0x3F) | 0x80)); s.push_back((char)(((wc >> 6) & 0x3F) | 0x80)); s.push_back((char)((wc & 0x3F) | 0x80)); } } return s; }
[ "[email protected]@a6d911d2-2a6f-2b2f-592f-0469abc2858f" ]
[ [ [ 1, 152 ] ] ]
17cc6be564a5b3a2e4534e2c43475800830effb8
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/Game/BattleView.h
4936d3161e0988957da24aeeaded59dade8352f7
[ "Apache-2.0" ]
permissive
notpushkin/palm-heroes
d4523798c813b6d1f872be2c88282161cb9bee0b
9313ea9a2948526eaed7a4d0c8ed2292a90a4966
refs/heads/master
2021-05-31T19:10:39.270939
2010-07-25T12:25:00
2010-07-25T12:25:00
62,046,865
2
1
null
null
null
null
UTF-8
C++
false
false
4,935
h
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ #ifndef _HMM_GAME_BATTLE_VIEW_H_ #define _HMM_GAME_BATTLE_VIEW_H_ ////////////////////////////////////////////////////////////////////////// class iCreatInfoPopup : public iFramePopupView { public: iCreatInfoPopup(iViewMgr* pViewMgr, PLAYER_ID pid, const iBattleGroup* pGroup); void DoCompose(const iRect& clRect); iSize ClientSize(); private: const iBattleGroup* m_pGroup; }; ////////////////////////////////////////////////////////////////////////// enum BattleNavMode { BNM_MELEE = 0, BNM_SHOOT, BNM_INFO, BNM_COUNT }; ////////////////////////////////////////////////////////////////////////// struct iBatObstEntry { iBatObstEntry(uint16 _obstId, const iPoint& _cell) : obstId(_obstId), cell(_cell) {} uint16 obstId; iPoint cell; }; typedef iSimpleArray<iBatObstEntry> iBatObstList; ////////////////////////////////////////////////////////////////////////// class iBattleToolBar; class iCastSpellToolBar; class iAutoBattleToolBar; class iBattleView : public iChildGameView { public: iBattleView(); ~iBattleView(); void BeginBattle(iBattleWrapper* pBattle, SURF_TYPE st); void Start(); void EndBattle(iBattleResult br); bool OnKeyDown(sint32 key); bool OnKeyUp(sint32 key); void OnMouseDown(const iPoint& pos); void OnMouseUp(const iPoint& pos); void OnMouseTrack(const iPoint& pos); bool Process(fix32 t); void PrepareSurface(); void OnCompose(); void AddLogEvent(const iStringT& msg); void AddCellEvent(const iStringT& msg, const iPoint& pos); private: void BeginAutobattle(); void EndAutobattle(); inline bool IsAutobattle() const { return m_pAutoBattleToolBar != NULL; } bool BeginSpellTrack(iCombatSpell* pSpell); void EndSpellTrack(const iPoint& cell); inline bool SpellTracking() const { return m_pCastSpellToolBar != NULL; } private: bool OnGroupChanged(); void BeginAni(); void EndAni(); void iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param); private: iCastSpellToolBar* m_pCastSpellToolBar; iBattleToolBar* m_pToolBar; iAutoBattleToolBar* m_pAutoBattleToolBar; BattleNavMode m_battleMode; iBattleWrapper* m_pBattle; SURF_TYPE m_surfType; iPoint m_trackPos; iPoint m_trackCell; iDib m_dibSurf; iDib m_dibTurnGlyph; bool m_bForceInfo; bool m_bHumanTurn; iStringT m_toolTip; // Obstacles iBatObstList m_obstacles; // Events iEventList m_cellEvents; iSimpleArray<iStringT> m_log; // Creature Info popup view iCreatInfoPopup* m_pCreatInfoPopup; // Animation fix32 m_actTimer; bool m_bAni; // Melee typedef const iBattleGroup::iMeleeEntry* iMeleeEntryPtr; iMeleeEntryPtr m_pMeleeTrack; sint32 m_meleeDir; // Shoot typedef const iBattleGroup::iShootEntry* iShootEntryPtr; iShootEntryPtr m_pShootTrack; // Spells iSimpleArray<iPoint> m_spellTargets; }; /* * Battle Toolbars */ class iBattleToolBar : public iView { public: enum StateFlags { EnemyTurn = 0x01, Acting = 0x02, CanMelee = 0x04, CanShoot = 0x08, CanInfo = 0x10, CanCast = 0x20, CanWait = 0x40 }; public: iBattleToolBar(iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iRect& rect); void OnCompose(); void EnableControls(uint32 flags); iIconButton* m_pBtnWait; iIconButton* m_pBtnDefend; iIconButton* m_pBtnCastSpell; iIconButton* m_pBtnAutoBattle; iIconButton* m_pBtnMsgLog; iIconButton* m_pBtnSettings; iHeroPortBtn* m_pBtnAssaulter; iHeroPortBtn* m_pBtnDefender; iBarTabSwitch* m_pModeSwitch; }; /* * Spell toolbar */ class iCastSpellToolBar : public iView { public: iCastSpellToolBar(iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iRect& rect, iCombatSpell* pSpell); void OnCompose(); // inline iCombatSpell* Spell() { return m_pSpell; } private: iCombatSpell* m_pSpell; }; /* * Autobattle toolbar */ class iAutoBattleToolBar : public iView { public: iAutoBattleToolBar(iViewMgr* pViewMgr, IViewCmdHandler* pCmdHandler, const iRect& rect); void OnCompose(); }; #endif //_HMM_GAME_BATTLE_VIEW_H_
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 195 ] ] ]
27c526290a6d03f87f54df100980658167961831
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/qrabout.hpp
2f2763ab14718a634affec1fe27f1466afc2fce4
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
2,619
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'QRAbout.pas' rev: 6.00 #ifndef QRAboutHPP #define QRAboutHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <ShellAPI.hpp> // Pascal unit #include <OleCtrls.hpp> // Pascal unit #include <StdCtrls.hpp> // Pascal unit #include <ExtCtrls.hpp> // Pascal unit #include <Dialogs.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Qrabout { //-- type declarations ------------------------------------------------------- class DELPHICLASS TQRAboutBox; class PASCALIMPLEMENTATION TQRAboutBox : public Forms::TForm { typedef Forms::TForm inherited; __published: Extctrls::TImage* Image1; Stdctrls::TButton* Button1; Stdctrls::TLabel* Label1; Stdctrls::TLabel* Label2; Stdctrls::TLabel* VisitLabel; Stdctrls::TLabel* Label3; Extctrls::TBevel* Bevel1; Stdctrls::TLabel* Label5; Extctrls::TImage* Image2; void __fastcall Button3Click(System::TObject* Sender); void __fastcall FormCreate(System::TObject* Sender); void __fastcall Label3Click(System::TObject* Sender); public: #pragma option push -w-inl /* TCustomForm.Create */ inline __fastcall virtual TQRAboutBox(Classes::TComponent* AOwner) : Forms::TForm(AOwner) { } #pragma option pop #pragma option push -w-inl /* TCustomForm.CreateNew */ inline __fastcall virtual TQRAboutBox(Classes::TComponent* AOwner, int Dummy) : Forms::TForm(AOwner, Dummy) { } #pragma option pop #pragma option push -w-inl /* TCustomForm.Destroy */ inline __fastcall virtual ~TQRAboutBox(void) { } #pragma option pop public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TQRAboutBox(HWND ParentWindow) : Forms::TForm(ParentWindow) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Qrabout */ using namespace Qrabout; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // QRAbout
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 79 ] ] ]
d02cfd9c14a6b5369583b2ea860ddcf6cc91deff
024dd2ce08c491bfe8441b0633ccd5f09a787a73
/fire.h
de84b6eee04a0914de22e484b4d1d3b729edbfd0
[]
no_license
Alyanorno/particle_system
838ac983d89853337d37b7d2509913731d2e952e
9135297e00abea29b6c063d097362838c1ac75ba
refs/heads/master
2016-09-05T18:09:38.014344
2011-02-02T20:03:04
2011-02-02T20:03:04
1,257,590
0
0
null
null
null
null
UTF-8
C++
false
false
2,826
h
#pragma once #include <windows.h> #include <gl/GL.h> #include <gl/GLU.h> #include <math.h> #include "vector.h" #define MAX_TIME 200 class Fire { typedef linear_math::Vector<3> Vector; public: Fire() {} void Initialize() { startPosition.Zero(); glGenTextures( 1, &texture ); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); glBindTexture(GL_TEXTURE_2D, texture); for( int i(0); i < 256*256*4; i += 4) { int x = (i/4) % (256); int y = (i/4) / (256); if( x > 256 / 2 ) x = 256 - x; if( y > 256 / 2 ) y = 256 - y; int c = (x+y)/2; particleTexture[i] = c; // Red particleTexture[i+1] = c/3; // Green particleTexture[i+2] = c/20; // Blue particleTexture[i+3] = c; //Alpha } // Linear Filtering glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, 4, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, &particleTexture); particleDisplayList = glGenLists(1); glNewList( particleDisplayList, GL_COMPILE ); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(-0.1f, -0.1f, 0.1f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 0.1f, -0.1f, 0.1f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 0.1f, 0.1f, 0.1f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-0.1f, 0.1f, 0.1f); glEnd(); glEndList(); } struct Particle { Vector position; Vector direction; int time; }; inline Particle Create( Vector& direction ) { Particle particle; particle.position = startPosition; particle.direction = Vector( direction[0] * 3200 + Random() - 16000, direction[1] * 3200 + Random() - 16000, direction[2] * 3200 + Random() - 16000 ); particle.direction.Normalize(); particle.direction /= 100; particle.time = Random() / MAX_TIME; return particle; } static inline bool Remove( Particle& particle ) { return particle.time <= 0 ? true : false; } inline void Prepare() { glBindTexture(GL_TEXTURE_2D, texture); glBlendFunc(GL_SRC_ALPHA, GL_ONE); } static inline void Update( Particle& particle ) { particle.position += particle.direction; --particle.time;} inline void Draw( Particle& particle ) { glPushMatrix(); glColor4f( 1, 1, 1, (float)particle.time/MAX_TIME ); glTranslatef( particle.position[0], particle.position[1], particle.position[2] ); glCallList( particleDisplayList ); glPopMatrix(); } protected: Vector startPosition; private: int Random() { static unsigned int seed = 0; seed = seed * 0x343FD + 0x269EC3; return seed >> 16 & 0x7FFF; } GLuint texture; GLuint particleDisplayList; BYTE particleTexture[256 * 256 * 4]; }; #undef MAX_TIME
[ [ [ 1, 111 ] ] ]
62ee04ff4dc35b6b826165d7208c555e06373853
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/projects/MainUI/GuiLib1.5/GuiVisioFolder.h
d683ace4d79b79a13bb7dc48cea4c74b026fbf43
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
UTF-8
C++
false
false
1,597
h
/**************************************************************************** * * * GuiToolKit * * (MFC extension) * * Created by Francisco Campos G. www.beyondata.com [email protected] * *--------------------------------------------------------------------------* * * * This program is free software;so you are free to use it any of your * * applications (Freeware, Shareware, Commercial),but leave this header * * intact. * * * * These files are provided "as is" without warranty of any kind. * * * * GuiToolKit is forever FREE CODE !!!!! * * * *--------------------------------------------------------------------------* * Created by: Francisco Campos G. * * Bug Fixes and improvements : (Add your name) * * -Francisco Campos * * * ****************************************************************************/ #pragma once #include "guifolder.h" class CGuiVisioFolder : public CGuiFolder { DECLARE_DYNAMIC(CGuiVisioFolder) protected: CImageList m_Img; public: void SetImageList(UINT nBitmapID, INT_PTR cx, INT_PTR nGrow, COLORREF crMask); virtual void DrawFolder(CFolderBar* cfb,Style m_Style); public: CGuiVisioFolder(void); virtual ~CGuiVisioFolder(void); DECLARE_MESSAGE_MAP() afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nHitTest, CPoint point); };
[ [ [ 1, 42 ] ] ]
659bd912bc036da87d5d31ce5d1ad75dc0d2c68e
2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc
/engine/component/componenttypes.h
35120ff645c033f62f5fc490cc6b59e54da6ae99
[]
no_license
tstivers/eXistenZ
eb2da9d6d58926b99495319080e13f780862fca0
2f5df51fb71d44c3e2689929c9249d10223f8d56
refs/heads/master
2021-09-02T22:50:36.733142
2010-11-16T06:47:24
2018-01-04T00:51:21
116,196,014
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
#pragma once #undef CONCAT #define CONCAT(a,b) a##b #define REGISTER_COMPONENT_TYPE(name, id) static component::ComponentRegistration CONCAT(name, _registration)(#name, id) #define ACTORCOMPONENT 3 #define MESHCOMPONENT 2 #define POSCOMPONENT 1 #define JSRENDERCOMPONENT 4 #define STATICACTORCOMPONENT 5 #define CAMERACOMPONENT 6 #define DYNAMICACTORCOMPONENT 7 #define TIMERCOMPONENT 8 #define CONTACTCALLBACKCOMPONENT 9 namespace component { void registerComponentType(const string& name, int id); int getComponentTypeId(const string& name); const string& getComponentTypeName(int id); struct ComponentRegistration { ComponentRegistration(const string& name, int id) { registerComponentType(name, id); } }; }
[ [ [ 1, 30 ] ] ]
cb5d00221a9628acb563dfe8b0c6f5722f4ff55d
d329abe3841020d9ab9b0030169aea5587c0537c
/libraries/Fat16/SdCard.cpp
1181c0c53aba1e9962b7a2ec9d2e13894b328d01
[]
no_license
enderdsus7/arduino-fermentation-controller
680632b644b3d522f2d7253e8b9a867be620550b
13a7a030b1db9ad5bc901d5cc88110d8b7881cc4
refs/heads/master
2020-05-17T02:57:51.641062
2010-04-17T22:33:36
2010-04-17T22:33:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,057
cpp
/* Arduino FAT16 Library * Copyright (C) 2008 by William Greiman * * This file is part of the Arduino FAT16 Library * * This Library 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 Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with the Arduino Fat16 Library. If not, see * <http://www.gnu.org/licenses/>. */ #include <wiring.h> #include "Fat16Config.h" #include "SdCard.h" //------------------------------------------------------------------------------ //r1 status values #define R1_READY_STATE 0 #define R1_IDLE_STATE 1 //start data token for read or write #define DATA_START_BLOCK 0XFE //data response tokens for write block #define DATA_RES_MASK 0X1F #define DATA_RES_ACCEPTED 0X05 #define DATA_RES_CRC_ERROR 0X0B #define DATA_RES_WRITE_ERROR 0X0D // // stop compiler from inlining where speed optimization is not required #define STATIC_NOINLINE static __attribute__((noinline)) //------------------------------------------------------------------------------ // SPI static functions // // clock byte in STATIC_NOINLINE uint8_t spiRec(void) { SPDR = 0xff; while(!(SPSR & (1 << SPIF))); return SPDR; } // clock byte out STATIC_NOINLINE void spiSend(uint8_t b) { SPDR = b; while(!(SPSR & (1 << SPIF))); } // set Slave Select HIGH STATIC_NOINLINE void spiSSHigh(void) { digitalWrite(SS, HIGH); } // set Slave Select LOW STATIC_NOINLINE void spiSSLow(void) { digitalWrite(SS, LOW); } //------------------------------------------------------------------------------ static uint8_t cardCommand(uint8_t cmd, uint32_t arg) { uint8_t r1; // some cards need extra clocks after transaction to go to ready state // easiest to put extra clocks before next transaction spiSSLow(); spiRec(); spiSend(cmd | 0x40); for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); spiSend(cmd == CMD0 ? 0x95 : 0XFF);//must send valid CRC for CMD0 //wait for not busy for (uint8_t retry = 0; (r1 = spiRec()) == 0xFF && retry != 0XFF; retry++); return r1; } //============================================================================== // SdCard member functions //------------------------------------------------------------------------------ #if SD_CARD_INFO_SUPPORT /** * Determine the size of a standard SD flash memory card * \return The number of 512 byte data blocks in the card */ uint32_t SdCard::cardSize(void) { uint16_t c_size; csd_t csd; if (!readReg(CMD9, (uint8_t *)&csd)) return 0; uint8_t read_bl_len = csd.read_bl_len; c_size = (csd.c_size_high << 10) | (csd.c_size_mid << 2) | csd.c_size_low; uint8_t c_size_mult = (csd.c_size_mult_high << 1) | csd.c_size_mult_low; return (uint32_t)(c_size+1) << (c_size_mult + read_bl_len - 7); } #endif //SD_CARD_INFO_SUPPORT //------------------------------------------------------------------------------ void SdCard::error(uint8_t code, uint8_t data) { errorData = data; error(code); } //------------------------------------------------------------------------------ void SdCard::error(uint8_t code) { errorCode = code; spiSSHigh(); } //------------------------------------------------------------------------------ /** * Initialize a SD flash memory card. * * \param[in] slow Set SPI Frequency F_CPU/4 if true else F_CPU/2. * * \return The value one, true, is returned for success and * the value zero, false, is returned for failure. * */ uint8_t SdCard::init(uint8_t slow) { pinMode(SS, OUTPUT); spiSSHigh(); pinMode(MOSI, OUTPUT); pinMode(SCK, OUTPUT); //Enable SPI, Master, clock rate F_CPU/128 SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR1) | (1 << SPR0); //must supply min of 74 clock cycles with CS high. for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); spiSSLow(); // next line prevent re-init hang by some cards (not sure why this works) for (uint16_t i = 0; i <= 512; i++) spiRec(); uint8_t r = cardCommand(CMD0, 0); for (uint16_t retry = 0; r != R1_IDLE_STATE; retry++){ if (retry == 10000) { error(SD_ERROR_CMD0, r); return false; } r = spiRec(); } for (uint16_t retry = 0; ; retry++) { cardCommand(CMD55, 0); if ((r = cardCommand(ACMD41, 0)) == R1_READY_STATE)break; if (retry == 1000) { error(SD_ERROR_ACMD41, r); return false; } } // set SPI frequency SPCR &= ~((1 << SPR1) | (1 << SPR0)); // F_CPU/4 if (!slow) SPSR |= (1 << SPI2X); // Doubled Clock Frequency to F_CPU/2 spiSSHigh(); return true; } //------------------------------------------------------------------------------ /** * Reads a 512 byte block from a storage device. * * \param[in] blockNumber Logical block to be read. * \param[out] dst Pointer to the location that will receive the data. * \return The value one, true, is returned for success and * the value zero, false, is returned for failure. */ uint8_t SdCard::readBlock(uint32_t blockNumber, uint8_t *dst) { if (cardCommand(CMD17, blockNumber << 9)) { error(SD_ERROR_CMD17); return false; } return readTransfer(dst, 512); } //------------------------------------------------------------------------------ #if SD_CARD_INFO_SUPPORT uint8_t SdCard::readReg(uint8_t cmd, uint8_t *dst) { if (cardCommand(cmd, 0)) { spiSSHigh(); return false; } return readTransfer(dst, 16); } #endif //SD_CARD_INFO_SUPPORT //------------------------------------------------------------------------------ uint8_t SdCard::readTransfer(uint8_t *dst, uint16_t count) { //wait for start of data for (uint16_t retry = 0; spiRec() != DATA_START_BLOCK; retry++) { if (retry == 0XFFFF) { error(SD_ERROR_READ_TIMEOUT); return false; } } //start first spi transfer SPDR = 0XFF; for (uint16_t i = 0; i < count; i++) { while(!(SPSR & (1 << SPIF))); dst[i] = SPDR; SPDR = 0XFF; } // wait for first CRC byte while(!(SPSR & (1 << SPIF))); spiRec();//second CRC byte spiSSHigh(); return true; } //------------------------------------------------------------------------------ /** * Writes a 512 byte block to a storage device. * * \param[in] blockNumber Logical block to be written. * \param[in] src Pointer to the location of the data to be written. * \return The value one, true, is returned for success and * the value zero, false, is returned for failure. */ uint8_t SdCard::writeBlock(uint32_t blockNumber, uint8_t *src) { uint32_t address = blockNumber << 9; #if SD_PROTECT_BLOCK_ZERO //don't allow write to first block if (address == 0) { error(SD_ERROR_BLOCK_ZERO_WRITE); return false; } #endif //SD_PROTECT_BLOCK_ZERO if (cardCommand(CMD24, address)) { error(SD_ERROR_CMD24); return false; } // optimize write loop SPDR = DATA_START_BLOCK; for (uint16_t i = 0; i < 512; i++) { while(!(SPSR & (1 << SPIF))); SPDR = src[i]; } while(!(SPSR & (1 << SPIF)));// wait for last data byte spiSend(0xFF);// dummy crc spiSend(0xFF);// dummy crc uint8_t r1 = spiRec(); if ((r1 & DATA_RES_MASK) != DATA_RES_ACCEPTED) { error(SD_ERROR_WRITE_RESPONSE, r1); return false; } // wait for card to complete write programming for (uint16_t retry = 0; spiRec() != 0XFF ; retry++) { if (retry == 0XFFFF) { error(SD_ERROR_WRITE_TIMEOUT); return false; } } spiSSHigh(); return true; }
[ [ [ 1, 252 ] ] ]
84027d45f83ade32e73357656b0b34831e3e76e7
38d9a3374e52b67ca01ed8bbf11cd0b878cce2a5
/branches/tbeta/CCV-fid/addons/ofx3DModelLoader/src/3DS/Vector3DS.h
3d09e7eb6701a9a56204f632be4b5fec4e117d2a
[]
no_license
hugodu/ccv-tbeta
8869736cbdf29685a62d046f4820e7a26dcd05a7
246c84989eea0b5c759944466db7c591beb3c2e4
refs/heads/master
2021-04-01T10:39:18.368714
2011-03-09T23:05:24
2011-03-09T23:05:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,355
h
/* Vector3DS class © Keith O'Conor 2004 keith.oconor @ {cs.tcd.ie, gmail.com} */ #ifndef VECTOR_H #define VECTOR_H #include <math.h> #include <iostream> class Vector3DS{ public: float x; float y; float z; /* Vector3DS(); Vector3DS(float a, float b, float c); Vector3DS(Vector3DS& copy); Vector3DS& operator=(const Vector3DS &other); int operator== (const Vector3DS &other); int operator!= (const Vector3DS &other); Vector3DS operator+(const Vector3DS &other); Vector3DS operator-(const Vector3DS &other); Vector3DS operator*(const float &value); Vector3DS operator/(const float &value); Vector3DS& operator+=(const Vector3DS &other); Vector3DS& operator-=(const Vector3DS &other); Vector3DS& operator*=(const float& other); Vector3DS& operator/=(const float& other); float operator[](unsigned i); float length(); float lengthSq(); float dotProduct(const Vector3DS &other); Vector3DS crossProduct(const Vector3DS &other); void normalize(); float distance(const Vector3DS &other); float distanceSq(const Vector3DS &other); void set(float newX, float newY, float newZ); void zero(); */ ///////////////// // Constructors ///////////////// inline Vector3DS():x(0),y(0),z(0){} inline Vector3DS(const float a, const float b, const float c):x(a),y(b),z(c){} inline Vector3DS(const Vector3DS& copy):x(copy.x),y(copy.y),z(copy.z){} ////////////// // Operators ////////////// inline Vector3DS& operator= (const Vector3DS &other){ x=other.x;y=other.y;z=other.z; return *this; } inline int operator== (const Vector3DS &other) const{ return (x==other.x && y==other.y && z==other.z); } inline int operator!= (const Vector3DS &other) const{ return (x!=other.x || y!=other.y || z!=other.z); } inline Vector3DS operator+ (const Vector3DS &other) const{ return Vector3DS(x+other.x, y+other.y, z+other.z); } inline Vector3DS operator- (const Vector3DS &other) const{ return Vector3DS(x-other.x, y-other.y, z-other.z); } inline Vector3DS operator* (const float &value) const{ return Vector3DS(x*value, y*value, z*value); } inline Vector3DS operator/ (const float &value) const{ return Vector3DS(x/value, y/value, z/value); } inline Vector3DS& operator+= (const Vector3DS &other){ x+=other.x; y+=other.y; z+=other.z; return *this; } inline Vector3DS& operator-= (const Vector3DS &other){ x-=other.x; y-=other.y; z-=other.z; return *this; } inline Vector3DS& operator*= (const float &value){ x*=value; y*=value; z*=value; return *this; } inline Vector3DS& operator/= (const float &value){ x/=value; y/=value; z/=value; return *this; } inline float operator[] (unsigned i) const{ switch(i){ case 0:return x; case 1:return y; case 2:return z; } } ///////////////////// // Other operations ///////////////////// inline float length() const{ float len=(x*x)+(y*y)+(z*z); return (float)sqrt(len); } inline float lengthSq() const{ return (x*x)+(y*y)+(z*z); } inline float dotProduct(const Vector3DS &other) const{ //this[dot]other return (x*other.x) + (y*other.y) + (z*other.z); } inline Vector3DS crossProduct(const Vector3DS &other) const{ //(x1,y1,z1)◊(x2,y2,z2) = (y1z2-y2z1, x2z1-x1z2, x1y2-x2y1). return Vector3DS( (y*other.z) - (z*other.y), (z*other.x) - (x*other.z), (x*other.y) - (y*other.x) ); } inline void normalize(){ float len=length(); if(len==0)return; len=1.0f/len; x*=len; y*=len; z*=len; } inline float distance(const Vector3DS &other) const{ return (Vector3DS(other.x-x,other.y-y,other.z-z)).length(); } inline float distanceSq(const Vector3DS &other) const{ return (Vector3DS(other.x-x,other.y-y,other.z-z)).lengthSq(); } inline void set(float newX, float newY, float newZ){ x=newX;y=newY;z=newZ; } inline void zero(){ x=y=z=0; } }; typedef Vector3DS Vertex; const Vector3DS vZero=Vector3DS(0,0,0); ///////////////////////////// // Global stream operators ////////////////////////////// inline std::ostream& operator<<(std::ostream &str, const Vector3DS &v){ str<<v.x<<", "<<v.y<<", "<<v.z; return str; } #endif //VECTOR_H
[ "schlupek@463ed9da-a5aa-4e33-a7e2-2d3b412cff85" ]
[ [ [ 1, 189 ] ] ]
78ffa42177f2d7e65f7df20e746c7339bcc3329e
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/ipappprotocols/sip/sipcodec/inc/t_sipstrings.h
a8e7c47487127e730f8bc8b3d2f2ccffebc2cd57
[]
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,256
h
/* * Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * This contains CT_DataSIPStrings */ #ifndef __T_DATASIPSTRINGS_H__ #define __T_DATASIPSTRINGS_H__ #include "DataWrapperBase.h" class CT_DataSIPStrings : public CDataWrapperBase { public: virtual TBool DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex); ~CT_DataSIPStrings(); static CT_DataSIPStrings* NewL(); virtual TAny* GetObject(); protected: void ConstructL(); CT_DataSIPStrings(); void DoCmdOpenL(const TTEFSectionName& aSection); void DoCmdClose(const TTEFSectionName& aSection); void DoCmdPool(const TTEFSectionName& aSection); void DoCmdStringF(const TTEFSectionName& aSection); void DoCmdTable(const TTEFSectionName& aSection); }; #endif /*__T_DATASIPSTRINGS_H__*/
[ "none@none" ]
[ [ [ 1, 43 ] ] ]
f99cfb934ef2e12d69368b6ed2bfd18027e7fa57
3d9e738c19a8796aad3195fd229cdacf00c80f90
/src/gui/app/Main_window.h
b17f422448d36632023d711cd21f9b66af992e69
[]
no_license
mrG7/mesecina
0cd16eb5340c72b3e8db5feda362b6353b5cefda
d34135836d686a60b6f59fa0849015fb99164ab4
refs/heads/master
2021-01-17T10:02:04.124541
2011-03-05T17:29:40
2011-03-05T17:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,402
h
/* This source file is part of Mesecina, a software for visualization and studying of * the medial axis and related computational geometry structures. * More info: http://www.agg.ethz.ch/~miklosb/mesecina * Copyright Balint Miklos, Applied Geometry Group, ETH Zurich * * $Id: Main_window.h 737 2009-05-16 15:40:46Z miklosb $ */ #ifndef MESECINA_MAIN_WINDOW_H #define MESECINA_MAIN_WINDOW_H #ifdef MESECINA_3D #include <gui/gl_widget_3/GL_cutting_plane_layer_3.h> #include <gui/gl_widget_3/GL_selection_layer_3.h> #include <gui/gl_widget_3/GL_widget_3.h> #else #include <gui/gl_widget_2/GL_selection_layer_2.h> #include <gui/gl_widget_2/GL_insert_point_layer_2.h> #include <gui/gl_widget_2/GL_insert_ball_layer_2.h> #include <gui/gl_widget_2/GL_image_layer_2.h> #endif #include <gui/gl_widget/Visualization_widget.h> #include <gui/app/Logger.h> #include <gui/layer_management/Layer_list_model.h> #include <gui/layer_management/Layer_list_widget.h> #include <gui/layer_management/Bundle_list_model.h> #include <gui/app/Record_toolbar.h> #include <gui/app/Input_mode_toolbar.h> #include <gui/app/Statistics_dialog.h> #include <gui/app/Settings_dialog.h> #include <gui/app/Help_browser_dialog.h> #include <gui/app/Evolution_slider_toolbar.h> #include <QtCore/QSettings> #include <QtGui/QMainWindow> #include <QtGui/QCloseEvent> #include <QtGui/QMenu> #include <QtGui/QLabel> #include <QtGui/QProgressBar> #include <string> #include <queue> class Geometry; //class Computation_thread; class Main_window : public QMainWindow { Q_OBJECT public: Main_window(int x, int y, QString app_name); ~Main_window(); Logger* logger; QMenu *createPopupMenu () { return 0; } //to hide all context menus std::list<Geometry*>* clone_geometries(); std::list<Geometry*>* clone_and_bind_geometries(); void set_geometries(std::list<Geometry*> *new_geometries = 0); public slots: void debug(QString msg); void msg(QString msg); void msg(QString msg, int level); void error(QString msg); void layers_changed(const QModelIndex &, const QModelIndex &); void update_stats_if_needed(); void update_stats(); void* get_shared_structure(const std::string& name); void shared_structure_changed(const std::string& name); void do_widget_repaint(); private slots: //void print(); void openRecentFile(); QString generic_file_filter_string(); QString generic_one_file_filter_string(const QString &extension); QString generic_current_file_filter_string(); void load_generic_file(); void load_generic_file(const QString &file_name); void save_generic_file(); void save_as_generic_file(); void save_generic_file(const QString &file_name); void load_file(QString file_name); void save_file(QString file_name); void save_balls(QString file_name); void load_balls(QString file_name); void print(); void closeEvent( QCloseEvent* ); void restart_geometry(); void export_image(); void export_next_image(); void record_status_change(bool checked); void ask_recording_directory(); #ifndef MESECINA_3D void input_mode_selected(Input_mode im); #endif void set_png_recording(); void set_pdf_recording(); void set_ps_recording(); //void set_double_kernel(); //void set_coreexpr_kernel(); void change_geometry_activation(); void show_statistics(bool); void show_help(bool); void show_settings(bool checked); void update_settings(); void application_settings_changed(const QString& settings_name); void about(); void bundle_text_changed ( const QString & text); void save_bundle(); void save_bundle(bool); void export_bundles(); void import_bundles(); void clear_bundles(); void remove_bundle(int); void export_bundle(int); void reorder_layers_on_widget(); void activate_selected_bundle(const QItemSelection & selected, const QItemSelection & deselected); void save_bundle_list(); void gl_widget_resized(const QRect& size); void mouse_moved(const QPointF& pos); #ifndef MESECINA_3D void point_created(double x, double y); void points_created(std::list<QPointF>* points); void ball_created(Point3D); void balls_created(std::list<Point3D>* points); #endif void points_modified(); private: void insure_geometry_dependencies(const QAction* action); void export_image(QString image_filepath); void print(QString file_name); virtual void keyPressEvent(QKeyEvent *e); virtual void keyReleaseEvent(QKeyEvent *e); void add_widgets(); void add_layers(); // void reset_evolutions(); void reset_evolutions_to_current_geometries(); void add_menu(); void add_toolbars(); void create_actions(); QString get_next_image_filname(); void update_record_format_menus(); void update_selected_geometries(); // void update_kernel_menus(); void set_current_file(const QString &fileName); void update_recent_file_actions(); QString strippedName(const QString &fullFileName); QLabel* coord_label; QPushButton* load_view; QPushButton* save_view; QProgressBar* progress_bar; QSettings* settings; QString last_edited_bundle_name; QStringList generic_file_types; QStringList generic_file_description; #ifdef MESECINA_3D GL_widget_3* widget; #else GL_widget_2* widget; Input_mode_toolbar* input_toolbar; #endif // Computation_thread* computation_thread; QString current_file_name; enum { MaxRecentFiles = 9 }; QMenu* file_menu; QAction *new_action; QAction *save_action; QAction *save_as_action; QAction *load_action; QAction *print_action; QAction *separator_action; QAction *recent_file_actions[MaxRecentFiles]; QAction *exit_action; QMenu* bundles_menu; QAction *export_bundles_action; QAction *import_bundles_action; QAction *clear_all_bundles_action; QMenu* options_menu; QMenu* record_menu; QAction *export_image_action; QAction *snapshot_action; QAction *record_action; QAction *record_directory_action; QMenu *record_format_menu; QAction *record_png_action; QAction *record_pdf_action; QAction *record_ps_action; QMenu* geometries_menu; std::list<QAction*> geometry_actions; QMenu* windows_menu; QAction* statistics_action; QAction* settings_action; QAction* help_action; QMenu* help_menu; QAction *about_action; Record_toolbar* record_toolbar; QString record_directory; QString record_format; QString kernel; Evolution_slider_toolbar* evolutions_toolbar; QSplitter* v_log_splitter; QSplitter* h_splitter; QSplitter* v_layer_splitter; Statistics_dialog* statistics_dialog; Settings_dialog* settings_dialog; Help_browser_dialog* help_dialog; Layer_list_model *layer_list_model; Layer_list_widget *layer_list_widget; Bundle_list_model *bundle_list_model; #ifdef MESECINA_3D GL_cutting_plane_layer_3* cutting_plane_layer; GL_selection_layer_3* selection_layer; #else GL_insert_point_layer_2* insert_point_layer; GL_insert_ball_layer_2* insert_ball_layer; GL_selection_layer_2* selection_layer; GL_image_layer_2* image_layer; #endif std::list<Geometry*> geometries; std::list<std::string> offered_structures; std::list<Geometry*> offering_geometries; void create_new_geometries(); std::queue<QImage*> frames; bool needs_stats_update; }; #endif //MESECINA_MAIN_WINDOW_H
[ "balint.miklos@localhost" ]
[ [ [ 1, 277 ] ] ]
e598508466735b71a8369ae96780c8f0f1f12047
150926210848ebc2773f4683180b2e53e67232f1
/UFOHunt/OpenMovie/stdafx.cpp
e012d7e9c3b5b86915768a760e15d13023a3eac1
[]
no_license
wkx11/kuradevsandbox
429dccabf6b07847ed33ea07bb77a93d7c8004f0
21f09987fd7e22ba6bf2c4929ca4cbf872827b36
refs/heads/master
2021-01-02T09:33:52.967804
2010-12-12T04:06:19
2010-12-12T04:06:19
37,631,953
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
268
cpp
// stdafx.cpp : 標準インクルード OpenMovie.pch のみを // 含むソース ファイルは、プリコンパイル済みヘッダーになります。 // stdafx.obj にはプリコンパイル済み型情報が含まれます。 #include "stdafx.h"
[ "taku.h72@cdde4f24-bdbc-632a-de5c-276029d4cb88" ]
[ [ [ 1, 7 ] ] ]
587e10a61856b9c22948ce84a5cae92ba423738f
b2685b1c15a93e266581bd4d96e738d01e7228bb
/src/TUIO/TuioServer.h
dca85aea3706f3cbd37179e9b6c39f971dc607b3
[]
no_license
Coffelius/KinectTouch
07d5874b7e3477ba85519ba527f887d4305fe758
0512cd6400210d1b4d14ab2525801fd3a11f76bd
refs/heads/master
2020-12-24T18:23:38.416164
2011-06-21T18:10:33
2011-06-21T18:10:33
1,802,342
3
0
null
null
null
null
UTF-8
C++
false
false
14,184
h
/* TUIO Server Component - part of the reacTIVision project http://reactivision.sourceforge.net/ Copyright (c) 2005-2009 Martin Kaltenbrunner <[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 */ #ifndef INCLUDED_TuioServer_H #define INCLUDED_TuioServer_H #ifndef WIN32 #include <pthread.h> #include <sys/time.h> #define DllImport #define DllExport #else #define DllImport __declspec( dllimport ) #define DllExport __declspec( dllexport ) #include <windows.h> #endif #include <iostream> #include <list> #include <algorithm> #include "osc/OscOutboundPacketStream.h" #include "ip/NetworkingUtils.h" #include "ip/UdpSocket.h" #include "TuioObject.h" #include "TuioCursor.h" #define IP_MTU_SIZE 1500 #define MAX_UDP_SIZE 65536 #define MIN_UDP_SIZE 576 #define OBJ_MESSAGE_SIZE 108 // setMessage + seqMessage size #define CUR_MESSAGE_SIZE 88 // TODO think about it!! namespace TUIO { /** * <p>The TuioServer class is the central TUIO protocol encoder component. * In order to encode and send TUIO messages an instance of TuioServer needs to be created. The TuioServer instance then generates TUIO messaged * which are sent via OSC over UDP to the configured IP address and port.</p> * <p>During runtime the each frame is marked with the initFrame and commitFrame methods, * while the currently present TuioObjects are managed by the server with ADD, UPDATE and REMOVE methods in analogy to the TuioClient's TuioListener interface.</p> * <p><code> * TuioClient *server = new TuioServer();<br/> * ...<br/> * server->initFrame(TuioTime::getSessionTime());<br/> * TuioObject *tobj = server->addTuioObject(xpos,ypos, angle);<br/> * TuioCursor *tcur = server->addTuioObject(xpos,ypos);<br/> * server->commitFrame();<br/> * ...<br/> * server->initFrame(TuioTime::getSessionTime());<br/> * server->updateTuioObject(tobj, xpos,ypos, angle);<br/> * server->updateTuioCursor(tcur, xpos,ypos);<br/> * server->commitFrame();<br/> * ...<br/> * server->initFrame(TuioTime::getSessionTime());<br/> * server->removeTuioObject(tobj);<br/> * server->removeTuioCursor(tcur);<br/> * server->commitFrame();<br/> * </code></p> * * @author Martin Kaltenbrunner * @version 1.4 */ class TuioServer { public: /** * The default constructor creates a TuioServer that sends to the default TUIO port 3333 on localhost * using the maximum packet size of 65536 bytes to use single packets on the loopback device */ DllExport TuioServer(bool mode3d = false); /** * This constructor creates a TuioServer that sends to the provided port on the the given host * using a default packet size of 1492 bytes to deliver unfragmented UDP packets on a LAN * * @param host the receiving host name * @param port the outgoing TUIO UDP port number */ DllExport TuioServer(const char *host, int port, bool mode3d = false); /** * This constructor creates a TuioServer that sends to the provided port on the the given host * the packet UDP size can be set to a value between 576 and 65536 bytes * * @param host the receiving host name * @param port the outgoing TUIO UDP port number * @param size the maximum UDP packet size */ DllExport TuioServer(const char *host, int port, int size, bool mode3d = false); /** * The destructor is doing nothing in particular. */ DllExport ~TuioServer(); /** * Creates a new TuioObject based on the given arguments. * The new TuioObject is added to the TuioServer's internal list of active TuioObjects * and a reference is returned to the caller. * * @param sym the Symbol ID to assign * @param xp the X coordinate to assign * @param yp the Y coordinate to assign * @param a the angle to assign * @return reference to the created TuioObject */ DllExport TuioObject* addTuioObject(int sym, float xp, float yp, float a); /** * Updates the referenced TuioObject based on the given arguments. * * @param tobj the TuioObject to update * @param xp the X coordinate to assign * @param yp the Y coordinate to assign * @param a the angle to assign */ DllExport void updateTuioObject(TuioObject *tobj, float xp, float yp, float a); /** * Removes the referenced TuioObject from the TuioServer's internal list of TuioObjects * and deletes the referenced TuioObject afterwards * * @param tobj the TuioObject to remove */ DllExport void removeTuioObject(TuioObject *tobj); /** * Adds an externally managed TuioObject to the TuioServer's internal list of active TuioObjects * * @param tobj the TuioObject to add */ DllExport void addExternalTuioObject(TuioObject *tobj); /** * Updates an externally managed TuioObject * * @param tobj the TuioObject to update */ DllExport void updateExternalTuioObject(TuioObject *tobj); /** * Removes an externally managed TuioObject from the TuioServer's internal list of TuioObjects * The referenced TuioObject is not deleted * * @param tobj the TuioObject to remove */ DllExport void removeExternalTuioObject(TuioObject *tobj); /** * Creates a new TuioCursor based on the given arguments. * The new TuioCursor is added to the TuioServer's internal list of active TuioCursors * and a reference is returned to the caller. * * @param xp the X coordinate to assign * @param yp the Y coordinate to assign * @return reference to the created TuioCursor */ DllExport TuioCursor* addTuioCursor(float xp, float yp, float zp=0); /** * Updates the referenced TuioCursor based on the given arguments. * * @param tcur the TuioObject to update * @param xp the X coordinate to assign * @param yp the Y coordinate to assign */ DllExport void updateTuioCursor(TuioCursor *tcur, float xp, float yp, float zp=0); /** * Removes the referenced TuioCursor from the TuioServer's internal list of TuioCursors * and deletes the referenced TuioCursor afterwards * * @param tcur the TuioCursor to remove */ DllExport void removeTuioCursor(TuioCursor *tcur); /** * Updates an externally managed TuioCursor * * @param tcur the TuioCursor to update */ DllExport void addExternalTuioCursor(TuioCursor *tcur); /** * Updates an externally managed TuioCursor * * @param tcur the TuioCursor to update */ DllExport void updateExternalTuioCursor(TuioCursor *tcur); /** * Removes an externally managed TuioCursor from the TuioServer's internal list of TuioCursor * The referenced TuioCursor is not deleted * * @param tcur the TuioCursor to remove */ DllExport void removeExternalTuioCursor(TuioCursor *tcur); /** * Initializes a new frame with the given TuioTime * * @param ttime the frame time */ DllExport void initFrame(TuioTime ttime); /** * Commits the current frame. * Generates and sends TUIO messages of all currently active and updated TuioObjects and TuioCursors. */ DllExport void commitFrame(); /** * Returns the next available Session ID for external use. * @return the next available Session ID for external use */ DllExport long getSessionID(); /** * Returns the current frame ID for external use. * @return the current frame ID for external use */ DllExport long getFrameID(); /** * Returns the current frame ID for external use. * @return the current frame ID for external use */ DllExport TuioTime getFrameTime(); /** * Generates and sends TUIO messages of all currently active TuioObjects and TuioCursors. */ DllExport void sendFullMessages(); /** * Disables the periodic full update of all currently active TuioObjects and TuioCursors * * @param interval update interval in seconds, defaults to one second */ DllExport void enablePeriodicMessages(int interval=1); /** * Disables the periodic full update of all currently active and inactive TuioObjects and TuioCursors */ DllExport void disablePeriodicMessages(); /** * Enables the full update of all currently active and inactive TuioObjects and TuioCursors * */ DllExport void enableFullUpdate() { full_update = true; } /** * Disables the full update of all currently active and inactive TuioObjects and TuioCursors */ DllExport void disableFullUpdate() { full_update = false; } /** * Returns true if the periodic full update of all currently active TuioObjects and TuioCursors is enabled. * @return true if the periodic full update of all currently active TuioObjects and TuioCursors is enabled */ DllExport bool periodicMessagesEnabled() { return periodic_update; } /** * Returns the periodic update interval in seconds. * @return the periodic update interval in seconds */ DllExport int getUpdateInterval() { return update_interval; } /** * Returns a List of all currently inactive TuioObjects * * @return a List of all currently inactive TuioObjects */ DllExport std::list<TuioObject*> getUntouchedObjects(); /** * Returns a List of all currently inactive TuioCursors * * @return a List of all currently inactive TuioCursors */ DllExport std::list<TuioCursor*> getUntouchedCursors(); /** * Calculates speed and acceleration values for all currently inactive TuioObjects */ DllExport void stopUntouchedMovingObjects(); /** * Calculates speed and acceleration values for all currently inactive TuioCursors */ DllExport void stopUntouchedMovingCursors(); /** * Removes all currently inactive TuioObjects from the TuioServer's internal list of TuioObjects */ DllExport void removeUntouchedStoppedObjects(); /** * Removes all currently inactive TuioCursors from the TuioServer's internal list of TuioCursors */ DllExport void removeUntouchedStoppedCursors(); /** * Returns a List of all currently active TuioObjects * * @return a List of all currently active TuioObjects */ DllExport std::list<TuioObject*> getTuioObjects(); /** * Returns a List of all currently active TuioCursors * * @return a List of all currently active TuioCursors */ DllExport std::list<TuioCursor*> getTuioCursors(); /** * Returns the TuioObject corresponding to the provided Session ID * or NULL if the Session ID does not refer to an active TuioObject * * @return an active TuioObject corresponding to the provided Session ID or NULL */ DllExport TuioObject* getTuioObject(long s_id); /** * Returns the TuioCursor corresponding to the provided Session ID * or NULL if the Session ID does not refer to an active TuioCursor * * @return an active TuioCursor corresponding to the provided Session ID or NULL */ DllExport TuioCursor* getTuioCursor(long s_id); /** * Returns the TuioObject closest to the provided coordinates * or NULL if there isn't any active TuioObject * * @return the closest TuioObject to the provided coordinates or NULL */ DllExport TuioObject* getClosestTuioObject(float xp, float yp); /** * Returns the TuioCursor closest to the provided coordinates * or NULL if there isn't any active TuioCursor * * @return the closest TuioCursor corresponding to the provided coordinates or NULL */ DllExport TuioCursor* getClosestTuioCursor(float xp, float yp, float zp=0); /** * Returns true if this TuioServer is currently connected. * @return true if this TuioServer is currently connected */ DllExport bool isConnected() { return connected; } /** * The TuioServer prints verbose TUIO event messages to the console if set to true. * @param verbose verbose message output if set to true */ DllExport void setVerbose(bool verbose) { this->verbose=verbose; } //void set3d(bool mode3d) { this->mode3d=mode3d; } DllExport bool isMode3d() { return mode3d; } private: std::list<TuioObject*> objectList; std::list<TuioCursor*> cursorList; int maxCursorID; std::list<TuioCursor*> freeCursorList; std::list<TuioCursor*> freeCursorBuffer; UdpTransmitSocket *socket; osc::OutboundPacketStream *oscPacket; char *oscBuffer; osc::OutboundPacketStream *fullPacket; char *fullBuffer; void initialize(const char *host, int port, int size, bool mode3d = false); void sendEmptyCursorBundle(); void startCursorBundle(); void addCursorMessage(TuioCursor *tcur); void sendCursorBundle(long fseq); void sendEmptyObjectBundle(); void startObjectBundle(); void addObjectMessage(TuioObject *tobj); void sendObjectBundle(long fseq); bool full_update; int update_interval; bool periodic_update; long currentFrame; TuioTime currentFrameTime; bool updateObject, updateCursor; long lastCursorUpdate, lastObjectUpdate; long sessionID; bool verbose; bool mode3d; char* cursorMessage; #ifndef WIN32 pthread_t thread; #else HANDLE thread; #endif bool connected; }; }; #endif /* INCLUDED_TuioServer_H */
[ [ [ 1, 443 ] ] ]
8496108a05d3dc17bb3dc24f27025c6a57d53ded
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/ShareModule/CommonModule/DataStorage.h
e8a3d4eee0bde70171844a5ac2f31a168a621a12
[]
no_license
m0o0m/01technology
1a3a5a48a88bec57f6a2d2b5a54a3ce2508de5ea
5e04cbfa79b7e3cf6d07121273b3272f441c2a99
refs/heads/master
2021-01-17T22:12:26.467196
2010-01-05T06:39:11
2010-01-05T06:39:11
null
0
0
null
null
null
null
GB18030
C++
false
false
1,671
h
#ifndef DATA_STORAGE_HEAD_FILE #define DATA_STORAGE_HEAD_FILE #include "CommonModule.h" #pragma once ////////////////////////////////////////////////////////////////////////// //结构体定义 //数据队列头 struct tagDataHead { WORD wDataSize; //数据大小 WORD wIdentifier; //类型标识 DWORD dwInsertTime; //插入时间 }; //负荷信息 struct tagBurthenInfo { DWORD dwDataSize; //数据大小 DWORD dwBufferSize; //缓冲区长度 DWORD dwDataPacketCount; //数据包数目 }; ////////////////////////////////////////////////////////////////////////// //数据存储类 class COM_SERVICE_CLASS CDataStorage { //数据变量 protected: DWORD m_dwDataSize; //数据大小 DWORD m_dwBufferSize; //缓冲区长度 DWORD m_dwInsertPos; //数据插入位 DWORD m_dwTerminalPos; //数据结束位 DWORD m_dwDataQueryPos; //数据查询位 DWORD m_dwDataPacketCount; //数据包数目 BYTE * m_pDataStorageBuffer; //数据指针 //函数定义 public: //构造函数 CDataStorage(void); //析构函数 virtual ~CDataStorage(void); //功能函数 public: //负荷信息 bool GetBurthenInfo(tagBurthenInfo & BurthenInfo); //插入数据 bool AddData(WORD wIdentifier, void * const pBuffer, WORD wDataSize); //获取数据 bool GetData(tagDataHead & DataHead, void * pBuffer, WORD wBufferSize); //删除数据 void RemoveData(bool bFreeMemroy); }; ////////////////////////////////////////////////////////////////////////// #endif
[ [ [ 1, 63 ] ] ]
c01b417ddede07b66996f13371fcadb2c0386a57
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/chrome/jobbie/src/cpp/InternetExplorerDriver/IEThread.h
f207d96a0f7df3add17af5fe1b7ada9007f22061
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
6,824
h
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. 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. */ #pragma once #include "IEThreadData.h" #include "scopeTracer.h" #define WM_KICKIDLE 0x036A // (params unused) causes idles to kick in // IeThread class ElementWrapper; class InternetExplorerDriver; class IeThread { public: IeThread(); // protected constructor used by dynamic creation virtual ~IeThread(); public: void PostThreadMessageW(UINT msg, WPARAM wp, LPARAM lp) {::PostThreadMessageW( threadID, msg, wp , lp);} MSG curMsg; virtual BOOL InitInstance(); virtual int ExitInstance(); IeThreadData* pBody; HANDLE hThread; DWORD threadID; static int runProcessStatic(void *); int runProcess(); void setVisible(bool isVisible); HWND bringToFront(); void waitForNavigateToFinish(); EventHandler sync_LaunchThread; EventHandler sync_LaunchIE; HANDLE m_EventToNotifyWhenNavigationCompleted; InternetExplorerDriver* pIED; BOOL CustomInternalPreTranslateMessage(MSG* pMsg); BOOL CustomInternalPumpMessage(); BOOL DispatchThreadMessageEx(MSG* pMsg); private: bool isOrUnder(const IHTMLDOMNode* root, IHTMLElement* child); void getDocument3(const IHTMLDOMNode* extractFrom, IHTMLDocument3** pdoc); void getDocument2(const IHTMLDOMNode* extractFrom, IHTMLDocument2** pdoc); void tryNotifyNavigCompleted(); void tryTransferEventReleaserToNotifyNavigCompleted(CScopeCaller *pSC, bool setETNWNC=true); IHTMLEventObj* newEventObject(IHTMLElement *pElement); void fireEvent(IHTMLElement *pElement, IHTMLEventObj*, const OLECHAR*); void fireEvent(IHTMLElement *pElement, IHTMLDOMNode* fireFrom, IHTMLEventObj*, const OLECHAR*); static void collapsingAppend(std::wstring& s, const std::wstring& s2); static std::wstring collapseWhitespace(CComBSTR &text); static bool isBlockLevel(IHTMLDOMNode *node); static void getText(std::wstring& toReturn, IHTMLDOMNode* node, bool isPreformatted); protected: void getTextAreaValue(IHTMLElement *pElement, std::wstring& res); HWND getHwnd(); void getDocument(IHTMLDocument2** pOutDoc); void getDocument3(IHTMLDocument3** pOutDoc); void executeScript(const wchar_t *script, SAFEARRAY* args, VARIANT *result, bool tryAgain = true); bool isCheckbox(IHTMLElement *pElement); bool isRadio(IHTMLElement *pElement); void getElementName(IHTMLElement *pElement, std::wstring& res); void getAttribute(IHTMLElement *pElement, LPCWSTR name, std::wstring& res); bool isSelected(IHTMLElement *pElement); int isDisplayed(IHTMLElement *element, bool* displayed); bool isEnabled(IHTMLElement *pElement); int getLocationWhenScrolledIntoView(IHTMLElement *pElement, HWND* hwnd, long *x, long *y); int click(IHTMLElement *pElement, CScopeCaller *pSC=NULL); void getValue(IHTMLElement *pElement, std::wstring& res); void getValueOfCssProperty(IHTMLElement *pElement, LPCWSTR propertyName, std::wstring& res); void getText(IHTMLElement *pElement, std::wstring& res); void getPageSource(std::wstring& res); void getTitle(std::wstring& res); void submit(IHTMLElement *pElement, CScopeCaller *pSC); // =NULL); void findParentForm(IHTMLElement *pElement, IHTMLFormElement **pform); std::vector<ElementWrapper*>* getChildrenWithTagName(IHTMLElement *pElement, LPCWSTR tagName) ; void waitForDocumentToComplete(IHTMLDocument2* doc); bool addEvaluateToDocument(const IHTMLDOMNode* node, int count); void findCurrentFrame(IHTMLWindow2 **result); void getDefaultContentFromDoc(IHTMLWindow2 **result, IHTMLDocument2* doc); bool getEval(IHTMLDocument2* doc, DISPID* evalId, bool* added); void removeScript(IHTMLDocument2* doc); bool createAnonymousFunction(IDispatch* scriptEngine, DISPID evalId, const wchar_t *script, VARIANT* result); void OnStartIE(WPARAM, LPARAM); void OnGetFramesCollection(WPARAM, LPARAM); void OnSwitchToFrame(WPARAM, LPARAM); void OnExecuteScript(WPARAM, LPARAM); void OnGetActiveElement(WPARAM, LPARAM); void OnElementIsDisplayed(WPARAM, LPARAM); void OnElementIsEnabled(WPARAM, LPARAM); void OnElementGetLocationOnceScrolledIntoView(WPARAM, LPARAM); void OnElementGetLocation(WPARAM, LPARAM); void OnElementGetHeight(WPARAM, LPARAM); void OnElementGetWidth(WPARAM, LPARAM); void OnElementGetElementName(WPARAM, LPARAM); void OnElementGetAttribute(WPARAM, LPARAM); void OnElementGetValue(WPARAM, LPARAM); void OnElementSendKeys(WPARAM, LPARAM); void OnElementClear(WPARAM, LPARAM); void OnElementIsSelected(WPARAM, LPARAM); void OnElementSetSelected(WPARAM, LPARAM); void OnElementGetValueOfCssProp(WPARAM, LPARAM); void OnElementGetText(WPARAM, LPARAM); void OnElementClick(WPARAM, LPARAM); void OnElementSubmit(WPARAM, LPARAM); void OnElementGetChildrenWithTagName(WPARAM, LPARAM); void OnGetVisible(WPARAM, LPARAM); void OnSetVisible(WPARAM, LPARAM); void OnGetCurrentUrl(WPARAM, LPARAM); void OnGetPageSource(WPARAM, LPARAM); void OnGetTitle(WPARAM, LPARAM); void OnGetUrl(WPARAM, LPARAM); void OnGoForward(WPARAM, LPARAM); void OnGoBack(WPARAM, LPARAM); void OnSelectElementByXPath(WPARAM, LPARAM); void OnSelectElementsByXPath(WPARAM, LPARAM); void OnSelectElementById(WPARAM, LPARAM); void OnSelectElementsById(WPARAM, LPARAM); void OnSelectElementByLink(WPARAM, LPARAM); void OnSelectElementsByLink(WPARAM, LPARAM); void OnSelectElementByPartialLink(WPARAM, LPARAM); void OnSelectElementsByPartialLink(WPARAM, LPARAM); void OnSelectElementByName(WPARAM, LPARAM); void OnSelectElementsByName(WPARAM, LPARAM); void OnSelectElementByTagName(WPARAM, LPARAM); void OnSelectElementsByTagName(WPARAM, LPARAM); void OnSelectElementByClassName(WPARAM, LPARAM); void OnSelectElementsByClassName(WPARAM, LPARAM); void OnGetCookies(WPARAM, LPARAM); void OnAddCookie(WPARAM, LPARAM); void OnWaitForNavigationToFinish(WPARAM, LPARAM); void OnElementRelease(WPARAM, LPARAM); void OnQuitIE(WPARAM, LPARAM); public: DataMarshaller& getCmdData() {return pBody->m_CmdData;} };
[ "simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 181 ] ] ]
c1f93333dcbeaef7097e43a83ce51983e9631955
c2ed485523750bc087a65e0e4dcd741377dcceba
/main.cpp
de97e694e31711a917d521c3c0b8263a5da31fe8
[]
no_license
harmattan/babyphone
afc673067b7637b398896041fc24fc5a9f179e71
05ca6a3a12382626a365d58673bf2fe0f3d474e7
refs/heads/master
2021-01-13T02:04:00.283927
2011-10-07T15:37:57
2015-03-07T11:27:34
31,809,669
0
1
null
null
null
null
UTF-8
C++
false
false
1,278
cpp
/* babyphone - A baby monitor application for Maemo / MeeGo (Nokia N900, N950, N9). Copyright (C) 2011 Roman Morawek <[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 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 <QtGui/QApplication> #ifdef Q_WS_MAEMO_5 #include "fremantle/mainwindow.h" #else #include "harmattan/mainwindow.h" #endif int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow mainWindow; #ifdef Q_WS_MAEMO_5 mainWindow.show(); #else mainWindow.showFullScreen(); QObject::connect(&mainWindow, SIGNAL(requestExit()), &app, SLOT(closeAllWindows())); #endif return app.exec(); }
[ [ [ 1, 41 ] ] ]
cb5d63307bfac857014110a21955e002241c8130
b4d726a0321649f907923cc57323942a1e45915b
/CODE/LIGHTING/LIGHTING.CPP
cf32481c4c45cbafd803df315422199effe69823
[]
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
37,210
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/Lighting/Lighting.cpp $ * $Revision: 1.1.1.1 $ * $Date: 2004/08/13 22:47:41 $ * $Author: Spearhawk $ * * Code to calculate dynamic lighting on a vertex. * * $Log: LIGHTING.CPP,v $ * Revision 1.1.1.1 2004/08/13 22:47:41 Spearhawk * no message * * Revision 1.1.1.1 2004/08/13 21:57:26 Darkhill * no message * * Revision 2.13 2004/03/05 09:02:04 Goober5000 * Uber pass at reducing #includes * --Goober5000 * * Revision 2.12 2003/10/16 00:17:17 randomtiger * Added incomplete code to allow selection of non-standard modes in D3D (requires new launcher). * As well as initialised in a different mode, bitmaps are stretched and for these modes * previously point filtered textures now use linear to keep them smooth. * I also had to shuffle some of the GR_1024 a bit. * Put my HT&L flags in ready for my work to sort out some of the render order issues. * Tided some other stuff up. * * Revision 2.11 2003/10/14 17:39:14 randomtiger * Implemented hardware fog for the HT&L code path. * It doesnt use the backgrounds anymore but its still an improvement. * Currently it fogs to a brighter colour than it should because of Bob specular code. * I will fix this after discussing it with Bob. * * Also tided up some D3D stuff, a cmdline variable name and changed a small bit of * the htl code to use the existing D3D engine instead of work around it. * And added extra information in version number on bottom left of frontend screen. * * Revision 2.10 2003/10/13 19:39:20 matt * prelim reworking of lighting code, dynamic lights work properly now * albeit at only 8 lights per object, although it looks just as good as * the old software version --Sticks * * Revision 2.9 2003/10/10 03:59:41 matt * Added -nohtl command line param to disable HT&L, nothing is IFDEFd * out now. -Sticks * * Revision 2.8 2003/09/26 14:37:14 bobboau * commiting Hardware T&L code, everything is ifdefed out with the compile flag HTL * still needs a lot of work, ubt the frame rates were getting with it are incredable * the biggest problem it still has is a bad lightmanegment system, and the zbuffer * doesn't work well with things still getting rendered useing the sofware pipeline, like thrusters, * and weapons, I think these should be modifyed to be sent through hardware, * it would be slightly faster and it would likely fix the problem * * also the thruster glow/particle stuff I did is now in. * * Revision 2.7 2003/09/14 19:00:36 wmcoolmon * Changed "nospec" to "Cmdline_nospec" -C * * Revision 2.6 2003/09/09 21:26:23 fryday * Fixed specular for dynamic lights, optimized it a bit * * Revision 2.5 2003/09/09 17:10:55 matt * Added -nospec cmd line param to disable specular -Sticks * * Revision 2.4 2003/08/22 07:35:09 bobboau * specular code should be bugless now, * cell shadeing has been added activated via the comand line '-cell', * 3D shockwave models, and a transparency method I'm calling edge and center alpha that could be usefull for other things, ask for details * * Revision 2.3 2003/08/16 03:52:23 bobboau * update for the specmapping code includeing * suport for seperate specular levels on lights and * optional strings for the stars table * code has been made more organised, * though there seems to be a bug in the state selecting code * resulting in the HUD being rendered incorectly * and specmapping failing ocasionaly * * Revision 2.2 2003/08/12 03:18:33 bobboau * Specular 'shine' mapping; * useing a phong lighting model I have made specular highlights * that are mapped to the model, * rendering them is still slow, but they look real purdy * * also 4 new (untested) comand lines, the XX is a floating point value * -spec_exp XX * the n value, you can set this from 0 to 200 (actualy more than that, but this is the recomended range), it will make the highlights bigger or smaller, defalt is 16.0 so start playing around there * -spec_point XX * -spec_static XX * -spec_tube XX * these are factors for the three diferent types of lights that FS uses, defalt is 1.0, * static is the local stars, * point is weapons/explosions/warp in/outs, * tube is beam weapons, * for thouse of you who think any of these lights are too bright you can configure them you're self for personal satisfaction * * Revision 2.1 2002/08/01 01:41:06 penguin * The big include file move * * Revision 2.0 2002/06/03 04:02:24 penguin * Warpcore CVS sync * * Revision 1.2 2002/05/04 04:52:22 mharris * 1st draft at porting * * Revision 1.1 2002/05/02 18:03:09 mharris * Initial checkin - converted filenames and includes to lower case * * * 5 6/22/99 2:22p Dave * Doh. Fixed a type bug. * * 4 6/18/99 5:16p Dave * Added real beam weapon lighting. Fixed beam weapon sounds. Added MOTD * dialog to PXO screen. * * 3 5/09/99 6:00p Dave * Lots of cool new effects. E3 build tweaks. * * 2 10/07/98 10:53a Dave * Initial checkin. * * 1 10/07/98 10:49a Dave * * 37 4/12/98 9:56a John * Made lighting detail flags work. Made explosions cast light on * highest. * * 36 4/10/98 5:20p John * Changed RGB in lighting structure to be ubytes. Removed old * not-necessary 24 bpp software stuff. * * 35 4/04/98 5:17p John * Added sun stuff. Made Glide optionally use 8-bpp textures. (looks * bad) * * 34 3/14/98 3:07p Adam * re-added some lighting changes * * 33 3/13/98 4:10p John * Put back in Adam's old lighting values. * * 32 3/12/98 8:42a John * Checked in Adam's new lighting values. * Checked in changes to timing models code * * 31 2/26/98 5:42p John * * 30 2/26/98 3:25p John * Added code to turn on/off lighting. Made lighting used dist*dist * instead of dist * * 29 2/19/98 10:51p John * Enabled colored lighting for hardware (Glide) * * 28 2/13/98 5:00p John * Made lighting push functions return number of releveent lights. * * 27 1/29/98 3:36p Johnson * JAS: Fixed some problems with pre_player_entry. * * 26 1/29/98 3:16p Allender * fix compiler warnings * * 25 1/29/98 8:14a John * Added support for RGB lighting * * 24 1/23/98 5:08p John * Took L out of vertex structure used B (blue) instead. Took all small * fireballs out of fireball types and used particles instead. Fixed some * debris explosion things. Restructured fireball code. Restructured * some lighting code. Made dynamic lighting on by default. Made groups * of lasers only cast one light. Made fireballs not cast light. * * 23 1/10/98 1:14p John * Added explanation to debug console commands * * 22 1/02/98 11:53a Adam * Changed lighting mode to darken. Changed ambient and reflect to .75 * and .50 to compensate. * * 21 1/02/98 11:28a Adam * Changed default ambient to 0.55f from 0.45f. * * 20 12/21/97 4:33p John * Made debug console functions a class that registers itself * automatically, so you don't need to add the function to * debugfunctions.cpp. * * 19 12/17/97 7:53p John * Fixed a bug where gunpoint for flashes were in world coordinates, * should have been object. * * 18 12/17/97 5:11p John * Added brightening back into fade table. Added code for doing the fast * dynamic gun flashes and thruster flashes. * * 17 12/12/97 3:02p John * First Rev of Ship Shadows * * 16 11/07/97 7:24p John * changed lighting to take two ranges. * In textest, added test code to draw nebulas * * 15 11/04/97 9:19p John * Optimized dynamic lighting more. * * 14 10/29/97 5:05p John * Changed dynamic lighting to only rotate and calculate lighting for * point lights that are close to an object. Changed lower framerate cap * from 4 to .5. * * 13 9/24/97 12:37p Mike * Crank ambient lighting from 0.2 to 0.6 * * 12 9/17/97 9:44a John * fixed bug with lighting set to default * * 11 9/11/97 5:36p Jasen * Changed ambient and reflective lighting values to give a bit more * realism to the game. Yeah, yeah, I know I am not a programmer. * * 10 4/24/97 2:58p John * * 9 4/24/97 11:49a John * added new lighting commands to console. * * 8 4/23/97 5:26p John * First rev of new debug console stuff. * * 7 4/22/97 3:14p John * upped the ambient light * * 6 4/17/97 6:06p John * New code/data for v19 of BSPGEN with smoothing and zbuffer * optimizations. * * 5 4/08/97 5:18p John * First rev of decent (dynamic, correct) lighting in FreeSpace. * * 4 2/17/97 5:18p John * Added a bunch of RCS headers to a bunch of old files that don't have * them. * * 3 1/30/97 9:35a Hoffoss * Added header for files. * * $NoKeywords: $ */ #include "math/vecmat.h" #include "render/3d.h" #include "lighting/lighting.h" #include "globalincs/systemvars.h" #include "graphics/2d.h" #include "cmdline/cmdline.h" #define MAX_LIGHTS 256 #define MAX_LIGHT_LEVELS 16 #define LT_DIRECTIONAL 0 // A light like a sun #define LT_POINT 1 // A point light, like an explosion #define LT_TUBE 2 // A tube light, like a fluorescent light int cell_shaded_lightmap = -1; typedef struct light { int type; // What type of light this is vector vec; // location in world space of a point light or the direction of a directional light or the first point on the tube for a tube light vector vec2; // second point on a tube light vector local_vec; // rotated light vector vector local_vec2; // rotated 2nd light vector for a tube light float intensity; // How bright the light is. float rad1, rad1_squared; // How big of an area a point light affect. Is equal to l->intensity / MIN_LIGHT; float rad2, rad2_squared; // How big of an area a point light affect. Is equal to l->intensity / MIN_LIGHT; float r,g,b; // The color components of the light float spec_r,spec_g,spec_b; // The specular color components of the light int ignore_objnum; // Don't light this object. Used to optimize weapons casting light on parents. int affected_objnum; // for "unique lights". ie, lights which only affect one object (trust me, its useful) int instance; } light; light Lights[MAX_LIGHTS]; int Num_lights=0; extern int Cmdline_nohtl; light *Relevent_lights[MAX_LIGHTS][MAX_LIGHT_LEVELS]; int Num_relevent_lights[MAX_LIGHT_LEVELS]; int Num_light_levels = 0; #define MAX_STATIC_LIGHTS 10 light * Static_light[MAX_STATIC_LIGHTS]; int Static_light_count = 0; static int Light_in_shadow = 0; // If true, this means we're in a shadow #define LM_BRIGHTEN 0 #define LM_DARKEN 1 #define MIN_LIGHT 0.03f // When light drops below this level, ignore it. Must be non-zero! (1/32) int Lighting_off = 0; // For lighting values, 0.75 is full intensity #if 1 // ADAM'S new stuff int Lighting_mode = LM_BRIGHTEN; #define AMBIENT_LIGHT_DEFAULT 0.15f //0.10f #define REFLECTIVE_LIGHT_DEFAULT 0.75f //0.90f #else int Lighting_mode = LM_DARKEN; #define AMBIENT_LIGHT_DEFAULT 0.75f //0.10f #define REFLECTIVE_LIGHT_DEFAULT 0.50f //0.90f #endif float Ambient_light = AMBIENT_LIGHT_DEFAULT; float Reflective_light = REFLECTIVE_LIGHT_DEFAULT; int Lighting_flag = 1; DCF(light,"Changes lighting parameters") { if ( Dc_command ) { dc_get_arg(ARG_STRING); if ( !strcmp( Dc_arg, "ambient" )) { dc_get_arg(ARG_FLOAT); if ( (Dc_arg_float < 0.0f) || (Dc_arg_float > 1.0f) ) { Dc_help = 1; } else { Ambient_light = Dc_arg_float; } } else if ( !strcmp( Dc_arg, "reflect" )) { dc_get_arg(ARG_FLOAT); if ( (Dc_arg_float < 0.0f) || (Dc_arg_float > 1.0f) ) { Dc_help = 1; } else { Reflective_light = Dc_arg_float; } } else if ( !strcmp( Dc_arg, "default" )) { Lighting_mode = LM_BRIGHTEN; Ambient_light = AMBIENT_LIGHT_DEFAULT; Reflective_light = REFLECTIVE_LIGHT_DEFAULT; Lighting_flag = 0; } else if ( !strcmp( Dc_arg, "mode" )) { dc_get_arg(ARG_STRING); if ( !strcmp(Dc_arg, "light") ) { Lighting_mode = LM_BRIGHTEN; } else if ( !strcmp(Dc_arg, "darken")) { Lighting_mode = LM_DARKEN; } else { Dc_help = 1; } } else if ( !strcmp( Dc_arg, "dynamic" )) { dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE); if ( Dc_arg_type & ARG_TRUE ) Lighting_flag = 1; else if ( Dc_arg_type & ARG_FALSE ) Lighting_flag = 0; else if ( Dc_arg_type & ARG_NONE ) Lighting_flag ^= 1; } else if ( !strcmp( Dc_arg, "on" ) ) { Lighting_off = 0; } else if ( !strcmp( Dc_arg, "off" ) ) { Lighting_off = 1; } else { // print usage, not stats Dc_help = 1; } } if ( Dc_help ) { dc_printf( "Usage: light keyword\nWhere keyword can be in the following forms:\n" ); dc_printf( "light on|off Turns all lighting on/off\n" ); dc_printf( "light default Resets lighting to all default values\n" ); dc_printf( "light ambient X Where X is the ambient light between 0 and 1.0\n" ); dc_printf( "light reflect X Where X is the material reflectiveness between 0 and 1.0\n" ); dc_printf( "light dynamic [bool] Toggles dynamic lighting on/off\n" ); dc_printf( "light mode [light|darken] Changes the lighting mode.\n" ); dc_printf( " Where 'light' means the global light adds light.\n"); dc_printf( " and 'darken' means the global light subtracts light.\n"); Dc_status = 0; // don't print status if help is printed. Too messy. } if ( Dc_status ) { dc_printf( "Ambient light is set to %.2f\n", Ambient_light ); dc_printf( "Reflective light is set to %.2f\n", Reflective_light ); dc_printf( "Dynamic lighting is: %s\n", (Lighting_flag?"on":"off") ); switch( Lighting_mode ) { case LM_BRIGHTEN: dc_printf( "Lighting mode is: light\n" ); break; case LM_DARKEN: dc_printf( "Lighting mode is: darken\n" ); break; default: dc_printf( "Lighting mode is: UNKNOWN\n" ); break; } } } void light_reset() { int idx; // reset static (sun) lights for(idx=0; idx<MAX_STATIC_LIGHTS; idx++){ Static_light[idx] = NULL; } Static_light_count = 0; Num_lights = 0; light_filter_reset(); if(!Cmdline_nohtl) { for(int i = 0; i<MAX_LIGHTS; i++)gr_destroy_light(i); } } extern vector Object_position; // Rotates the light into the current frame of reference void light_rotate(light * l) { switch( l->type ) { case LT_DIRECTIONAL: // Rotate the light direction into local coodinates if(!Cmdline_nohtl) { light_data L = *(light_data*)(void*)l; gr_modify_light(&L,l->instance, 2); } vm_vec_rotate(&l->local_vec, &l->vec, &Light_matrix ); break; case LT_POINT: { vector tempv; // Rotate the point into local coordinates vm_vec_sub(&tempv, &l->vec, &Light_base ); vm_vec_rotate(&l->local_vec, &tempv, &Light_matrix ); if(!Cmdline_nohtl) { light_data L = *(light_data*)(void*)l; gr_modify_light(&L,l->instance, 2); } } break; case LT_TUBE:{ vector tempv; // Rotate the point into local coordinates vm_vec_sub(&tempv, &l->vec, &Light_base ); vm_vec_rotate(&l->local_vec, &tempv, &Light_matrix ); // Rotate the point into local coordinates vm_vec_sub(&tempv, &l->vec2, &Light_base ); vm_vec_rotate(&l->local_vec2, &tempv, &Light_matrix ); if(!Cmdline_nohtl) { //move the point to the neares to the object on the line vector pos; /* vm_vec_unrotate(&temp2, &temp, &obj->orient); vm_vec_add2(&temp, &temp2); vm_vec_scale_add(&temp, &temp2, &obj->orient.vec.fvec, Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].b_info.range); */ switch(vm_vec_dist_to_line(&Object_position, &l->local_vec, &l->local_vec2, &pos, NULL)){ // behind the beam, so use the start pos case -1: pos = l->vec; break; // use the closest point case 0: // already calculated in vm_vec_dist_to_line(...) break; // past the beam, so use the shot pos case 1: pos = l->vec2; break; } light_data L = *(light_data*)(void*)l; L.vec = pos; L.local_vec = pos; gr_modify_light(&L,l->instance, 2); } } break; default: Int3(); // Invalid light type } } // Sets the ambient lighting level. // Ignored for now. void light_set_ambient(float ambient_light) { } void light_add_directional( vector *dir, float intensity, float r, float g, float b, float spec_r, float spec_g, float spec_b, bool specular ) { if(!specular){ spec_r = r; spec_g = g; spec_b = b; } light * l; if ( Lighting_off ) return; if ( Num_lights >= MAX_LIGHTS ) return; l = &Lights[Num_lights++]; l->type = LT_DIRECTIONAL; if ( Lighting_mode == LM_BRIGHTEN ) { vm_vec_copy_scale( &l->vec, dir, -1.0f ); } else { vm_vec_copy_scale( &l->vec, dir, 1.0f ); } l->r = r; l->g = g; l->b = b; l->spec_r = spec_r; l->spec_g = spec_g; l->spec_b = spec_b; l->intensity = intensity; l->rad1 = 0.0f; l->rad2 = 0.0f; l->rad1_squared = l->rad1*l->rad1; l->rad2_squared = l->rad2*l->rad2; l->ignore_objnum = -1; l->affected_objnum = -1; l->instance = Num_lights-1; Assert( Num_light_levels <= 1 ); // Relevent_lights[Num_relevent_lights[Num_light_levels-1]++][Num_light_levels-1] = l; if(Static_light_count < MAX_STATIC_LIGHTS){ Static_light[Static_light_count++] = l; } if(!Cmdline_nohtl) { light_data *L = (light_data*)(void*)l; gr_make_light(L,Num_lights-1, 1); } } void light_add_point( vector * pos, float rad1, float rad2, float intensity, float r, float g, float b, int ignore_objnum, float spec_r, float spec_g, float spec_b, bool specular ) { if(!specular){ spec_r = r; spec_g = g; spec_b = b; } light * l; if ( Lighting_off ) return; if (!Lighting_flag) return; // if ( keyd_pressed[KEY_LSHIFT] ) return; if ( Num_lights >= MAX_LIGHTS ) { mprintf(( "Out of lights!\n" )); return; } l = &Lights[Num_lights++]; l->type = LT_POINT; l->vec = *pos; l->r = r; l->g = g; l->b = b; l->spec_r = spec_r; l->spec_g = spec_g; l->spec_b = spec_b; l->intensity = intensity; l->rad1 = rad1; l->rad2 = rad2; l->rad1_squared = l->rad1*l->rad1; l->rad2_squared = l->rad2*l->rad2; l->ignore_objnum = ignore_objnum; l->affected_objnum = -1; l->instance = Num_lights-1; Assert( Num_light_levels <= 1 ); if(!Cmdline_nohtl) { light_data *L = (light_data*)(void*)l; gr_make_light(L,Num_lights-1, 2); } // Relevent_lights[Num_relevent_lights[Num_light_levels-1]++][Num_light_levels-1] = l; // light_data *L = (light_data*)(void*)l; // l->API_index = gr_make_light(L); } void light_add_point_unique( vector * pos, float rad1, float rad2, float intensity, float r, float g, float b, int affected_objnum, float spec_r, float spec_g, float spec_b, bool specular ) { if(!specular){ spec_r = r; spec_g = g; spec_b = b; } light * l; if ( Lighting_off ) return; if (!Lighting_flag) return; // if ( keyd_pressed[KEY_LSHIFT] ) return; if ( Num_lights >= MAX_LIGHTS ) { mprintf(( "Out of lights!\n" )); return; } l = &Lights[Num_lights++]; l->type = LT_POINT; l->vec = *pos; l->r = r; l->g = g; l->b = b; l->spec_r = spec_r; l->spec_g = spec_g; l->spec_b = spec_b; l->intensity = intensity; l->rad1 = rad1; l->rad2 = rad2; l->rad1_squared = l->rad1*l->rad1; l->rad2_squared = l->rad2*l->rad2; l->ignore_objnum = -1; l->affected_objnum = affected_objnum; l->instance = Num_lights-1; Assert( Num_light_levels <= 1 ); if(!Cmdline_nohtl) { light_data *L = (light_data*)(void*)l; gr_make_light(L,Num_lights-1, 2); } // light_data *L = (light_data*)(void*)l; // l->API_index = gr_make_light(L); } // for now, tube lights only affect one ship (to keep the filter stuff simple) void light_add_tube(vector *p0, vector *p1, float r1, float r2, float intensity, float r, float g, float b, int affected_objnum, float spec_r, float spec_g, float spec_b, bool specular ) { if(!specular){ spec_r = r; spec_g = g; spec_b = b; } light * l; if ( Lighting_off ) return; if (!Lighting_flag) return; // if ( keyd_pressed[KEY_LSHIFT] ) return; if ( Num_lights >= MAX_LIGHTS ) { mprintf(( "Out of lights!\n" )); return; } l = &Lights[Num_lights++]; l->type = LT_TUBE; l->vec = *p0; l->vec2 = *p1; l->r = r; l->g = g; l->b = b; l->spec_r = spec_r; l->spec_g = spec_g; l->spec_b = spec_b; l->intensity = intensity; l->rad1 = r1; l->rad2 = r2; l->rad1_squared = l->rad1*l->rad1; l->rad2_squared = l->rad2*l->rad2; l->ignore_objnum = -1; l->affected_objnum = affected_objnum; l->instance = Num_lights-1; Assert( Num_light_levels <= 1 ); if(!Cmdline_nohtl) { light_data *L = (light_data*)(void*)l; gr_make_light(L,Num_lights-1, 3); } // light_data *L = (light_data*)(void*)l; // l->API_index = gr_make_light(L); } // Reset the list of lights to point to all lights. void light_filter_reset() { int i; light *l; if ( Lighting_off ) return; Num_light_levels = 1; int n = Num_light_levels-1; Num_relevent_lights[n] = 0; l = Lights; for (i=0; i<Num_lights; i++, l++ ) { Relevent_lights[Num_relevent_lights[n]++][n] = l; } } // Makes a list of only the lights that will affect // the sphere specified by 'pos' and 'rad' and 'objnum' int light_filter_push( int objnum, vector *pos, float rad ) { int i; light *l; if ( Lighting_off ) return 0; light_filter_reset(); int n1,n2; n1 = Num_light_levels-1; n2 = Num_light_levels; Num_light_levels++; Assert( Num_light_levels < MAX_LIGHT_LEVELS ); Num_relevent_lights[n2] = 0; for (i=0; i<Num_relevent_lights[n1]; i++ ) { l = Relevent_lights[i][n1]; switch( l->type ) { case LT_DIRECTIONAL: //Relevent_lights[Num_relevent_lights[n2]++][n2] = l; break; case LT_POINT: { // if this is a "unique" light source, it only affects one guy if(l->affected_objnum >= 0){ if(objnum == l->affected_objnum){ vector to_light; float dist_squared, max_dist_squared; vm_vec_sub( &to_light, &l->vec, pos ); dist_squared = vm_vec_mag_squared(&to_light); max_dist_squared = l->rad2+rad; max_dist_squared *= max_dist_squared; if ( dist_squared < max_dist_squared ) { Relevent_lights[Num_relevent_lights[n2]++][n2] = l; } } } // otherwise check all relevant objects else { // if ( (l->ignore_objnum<0) || (l->ignore_objnum != objnum) ) { vector to_light; float dist_squared, max_dist_squared; vm_vec_sub( &to_light, &l->vec, pos ); dist_squared = vm_vec_mag_squared(&to_light); max_dist_squared = l->rad2+rad; max_dist_squared *= max_dist_squared; if ( dist_squared < max_dist_squared ) { Relevent_lights[Num_relevent_lights[n2]++][n2] = l; } // } } } break; // hmm. this could probably be more optimal case LT_TUBE: // all tubes are "unique" light sources for now if((l->affected_objnum >= 0) && (objnum == l->affected_objnum)){ Relevent_lights[Num_relevent_lights[n2]++][n2] = l; } break; default: Int3(); // Invalid light type } } return Num_relevent_lights[n2]; } int is_inside( vector *min, vector *max, vector * p0, float rad ) { float *origin = (float *)&p0->xyz.x; float *minB = (float *)min; float *maxB = (float *)max; int i; for (i=0; i<3; i++ ) { if ( origin[i] < minB[i] - rad ) { return 0; } else if (origin[i] > maxB[i] + rad ) { return 0; } } return 1; } int light_filter_push_box( vector *min, vector *max ) { int i; light *l; if ( Lighting_off ) return 0; int n1,n2; n1 = Num_light_levels-1; n2 = Num_light_levels; Num_light_levels++; // static int mll = -1; // if ( Num_light_levels > mll ) { // mll = Num_light_levels; // mprintf(( "Max level = %d\n", mll )); // } Assert( Num_light_levels < MAX_LIGHT_LEVELS ); Num_relevent_lights[n2] = 0; for (i=0; i<Num_relevent_lights[n1]; i++ ) { l = Relevent_lights[i][n1]; switch( l->type ) { case LT_DIRECTIONAL: Int3(); //Relevent_lights[Num_relevent_lights[n2]++][n2] = l; break; case LT_POINT: { // l->local_vec if ( is_inside( min, max, &l->local_vec, l->rad2 ) ) { Relevent_lights[Num_relevent_lights[n2]++][n2] = l; } } break; case LT_TUBE: if ( is_inside(min, max, &l->local_vec, l->rad2) || is_inside(min, max, &l->local_vec2, l->rad2) ) { Relevent_lights[Num_relevent_lights[n2]++][n2] = l; } break; default: Int3(); // Invalid light type } } return Num_relevent_lights[n2]; } void light_filter_pop() { if ( Lighting_off ) return; Num_light_levels--; Assert( Num_light_levels > 0 ); } int l_num_points=0, l_num_lights=0; void light_rotate_all() { int i; light *l; if ( Lighting_off ) return; int n = Num_light_levels-1; l = Lights; for (i=0; i<Num_relevent_lights[n]; i++ ) { l = Relevent_lights[i][n]; light_rotate(l); } for(i=0; i<Static_light_count; i++){ light_rotate(Static_light[i]); } // l = Lights; // for (i=0; i<Num_lights; i++, l++ ) { // light_rotate(l); // } } // return the # of global light sources int light_get_global_count() { return Static_light_count; } int light_get_global_dir(vector *pos, int n) { if((n > MAX_STATIC_LIGHTS) || (n > Static_light_count-1)){ return 0; } if ( Static_light[n] == NULL ) { return 0; } if (pos) { *pos = Static_light[n]->vec; if ( Lighting_mode != LM_DARKEN ) { vm_vec_scale( pos, -1.0f ); } } return 1; } void light_set_shadow( int state ) { Light_in_shadow = state; } void light_set_all_relevent(){ int i = 0; gr_reset_lighting(); for(int idx=0; idx<Static_light_count; idx++)gr_set_light((light_data*)(void*)Static_light[idx]); // for simplicity sake were going to forget about dynamic lights for the moment int n = Num_light_levels-1; for( i=0; i<Num_relevent_lights[n]; i++ )gr_set_light((light_data*)(void*)Relevent_lights[i][n]); } ubyte light_apply( vector *pos, vector * norm, float static_light_level ) { int i, idx; float lval; light *l; if (Detail.lighting==0) { // No static light ubyte l = ubyte(fl2i(static_light_level*255.0f)); return l; } if ( Lighting_off ) return 191; // Factor in ambient light lval = Ambient_light; // Factor in light from suns if there are any if ( !Light_in_shadow ){ // apply all sun lights for(idx=0; idx<Static_light_count; idx++){ float ltmp; // sanity if(Static_light[idx] == NULL){ continue; } // calculate light from surface normal ltmp = -vm_vec_dot(&Static_light[idx]->local_vec, norm )*Static_light[idx]->intensity*Reflective_light; // reflective light switch(Lighting_mode) { case LM_BRIGHTEN: if ( ltmp > 0.0f ) lval += ltmp; break; case LM_DARKEN: if ( ltmp > 0.0f ) lval -= ltmp; if ( lval < 0.0f ) lval = 0.0f; break; } } } // At this point, l must be between 0 and 0.75 (0.75-1.0 is for dynamic light only) if ( lval < 0.0f ) { lval = 0.0f; } else if ( lval > 0.75f ) { lval = 0.75f; } lval *= static_light_level; int n = Num_light_levels-1; l_num_lights += Num_relevent_lights[n]; l_num_points++; for (i=0; i<Num_relevent_lights[n]; i++ ) { l = Relevent_lights[i][n]; vector to_light; float dot, dist; vm_vec_sub( &to_light, &l->local_vec, pos ); dot = vm_vec_dot(&to_light, norm ); if ( dot > 0.0f ) { dist = vm_vec_mag_squared(&to_light); if ( dist < l->rad1_squared ) { lval += l->intensity*dot; } else if ( dist < l->rad2_squared ) { // dist from 0 to float n = dist - l->rad1_squared; float d = l->rad2_squared - l->rad1_squared; float ltmp = (1.0f - n / d )*dot*l->intensity; lval += ltmp; } if ( lval > 1.0f ) { return 255; } } } return ubyte(fl2i(lval*255.0f)); } int spec = 0; float static_light_factor = 1.0f; float static_tube_factor = 1.0f; float static_point_factor = 1.0f; double specular_exponent_value = 16.0; void light_apply_specular(ubyte *param_r, ubyte *param_g, ubyte *param_b, vector *pos, vector * norm, vector * cam){ light *l; float rval = 0, gval = 0, bval = 0; if ( Cmdline_nospec ) { *param_r = 0; *param_g = 0; *param_b = 0; return; } if (Detail.lighting==0) { *param_r = 0; *param_g = 0; *param_b = 0; return; } if ( Lighting_off ) { *param_r = 0; *param_g = 0; *param_b = 0; return; } vector V, N; vm_vec_sub(&V, cam,pos); vm_vec_normalize(&V); if (!Fred_running) { N = *norm; vm_vec_normalize(&N); } // Factor in light from sun if there is one // apply all sun lights for(int idx=0; idx<Static_light_count; idx++){ float ltmp; // sanity if(Static_light[idx] == NULL){ continue; } vector R; vm_vec_sub(&R,&V, &Static_light[idx]->local_vec); vm_vec_normalize(&R); ltmp = (float)pow((double)vm_vec_dot(&R, &N ), specular_exponent_value) * Static_light[idx]->intensity * static_light_factor; // reflective light switch(Lighting_mode) { case LM_BRIGHTEN: if ( ltmp > 0.0f ) { rval += Static_light[idx]->spec_r * ltmp; gval += Static_light[idx]->spec_g * ltmp; bval += Static_light[idx]->spec_b * ltmp; } break; case LM_DARKEN: if ( ltmp > 0.0f ) { rval -= ltmp; if ( rval < 0.0f ) rval = 0.0f; gval -= ltmp; if ( gval < 0.0f ) gval = 0.0f; bval -= ltmp; if ( bval < 0.0f ) bval = 0.0f; } break; } } if ( rval < 0.0f ) { rval = 0.0f; } else if ( rval > 0.75f ) { rval = 0.75f; } if ( gval < 0.0f ) { gval = 0.0f; } else if ( gval > 0.75f ) { gval = 0.75f; } if ( bval < 0.0f ) { bval = 0.0f; } else if ( bval > 0.75f ) { bval = 0.75f; } //dynamic lights int n = Num_light_levels-1; l_num_lights += Num_relevent_lights[n]; l_num_points++; vector to_light; float dot, dist; vector temp; float factor = 1.0f; for ( int i=0; i<Num_relevent_lights[n]; i++ ) { l = Relevent_lights[i][n]; dist = -1.0f; switch(l->type){ // point lights case LT_POINT: vm_vec_sub( &to_light, &l->local_vec, pos ); factor = static_point_factor; break; // tube lights case LT_TUBE: if(vm_vec_dist_to_line(pos, &l->local_vec, &l->local_vec2, &temp, &dist) != 0){ continue; } factor = static_tube_factor; vm_vec_sub(&to_light, &temp, pos); dist *= dist; // since we use radius squared break; // others. BAD default: Int3(); } vector R; vm_vec_normalize(&to_light); vm_vec_add(&R,&V, &to_light); vm_vec_normalize(&R); dot = (float)pow((double)vm_vec_dot(&R, &N ), specular_exponent_value) * l->intensity * factor; // reflective light if ( dot > 0.0f ) { // indicating that we already calculated the distance (vm_vec_dist_to_line(...) does this for us) if(dist < 0.0f){ dist = vm_vec_mag_squared(&to_light); } if ( dist < l->rad1_squared ) { float ratio; ratio = l->intensity*dot*factor; ratio *= 0.25f; rval += l->spec_r*ratio; gval += l->spec_g*ratio; bval += l->spec_b*ratio; } else if ( dist < l->rad2_squared ) { float ratio; // dist from 0 to float n = dist - l->rad1_squared; float d = l->rad2_squared - l->rad1_squared; ratio = (1.0f - n / d)*dot*l->intensity*factor; ratio *= 0.25f; rval += l->spec_r*ratio; gval += l->spec_g*ratio; bval += l->spec_b*ratio; } } } if ( rval < 0.0f ) { rval = 0.0f; } else if ( rval > 1.0f ) { rval = 1.0f; } if ( gval < 0.0f ) { gval = 0.0f; } else if ( gval > 1.0f ) { gval = 1.0f; } if ( bval < 0.0f ) { bval = 0.0f; } else if ( bval > 1.0f ) { bval = 1.0f; } *param_r = ubyte(fl2i(rval*254.0f)); *param_g = ubyte(fl2i(gval*254.0f)); *param_b = ubyte(fl2i(bval*254.0f)); } void light_apply_rgb( ubyte *param_r, ubyte *param_g, ubyte *param_b, vector *pos, vector * norm, float static_light_level ) { int i, idx; float rval, gval, bval; light *l; if (Detail.lighting==0) { // No static light ubyte l = ubyte(fl2i(static_light_level*255.0f)); *param_r = l; *param_g = l; *param_b = l; return; } if ( Lighting_off ) { *param_r = 255; *param_g = 255; *param_b = 255; return; } // Factor in ambient light rval = Ambient_light; gval = Ambient_light; bval = Ambient_light; // Factor in light from sun if there is one if ( !Light_in_shadow ){ // apply all sun lights for(idx=0; idx<Static_light_count; idx++){ float ltmp; // sanity if(Static_light[idx] == NULL){ continue; } // calculate light from surface normal ltmp = -vm_vec_dot(&Static_light[idx]->local_vec, norm )*Static_light[idx]->intensity*Reflective_light; // reflective light switch(Lighting_mode) { case LM_BRIGHTEN: if ( ltmp > 0.0f ) { rval += Static_light[idx]->r * ltmp; gval += Static_light[idx]->g * ltmp; bval += Static_light[idx]->b * ltmp; } break; case LM_DARKEN: if ( ltmp > 0.0f ) { rval -= ltmp; if ( rval < 0.0f ) rval = 0.0f; gval -= ltmp; if ( gval < 0.0f ) gval = 0.0f; bval -= ltmp; if ( bval < 0.0f ) bval = 0.0f; } break; } } } // At this point, l must be between 0 and 0.75 (0.75-1.0 is for dynamic light only) if ( rval < 0.0f ) { rval = 0.0f; } else if ( rval > 0.75f ) { rval = 0.75f; } if ( gval < 0.0f ) { gval = 0.0f; } else if ( gval > 0.75f ) { gval = 0.75f; } if ( bval < 0.0f ) { bval = 0.0f; } else if ( bval > 0.75f ) { bval = 0.75f; } rval *= static_light_level; gval *= static_light_level; bval *= static_light_level; int n = Num_light_levels-1; l_num_lights += Num_relevent_lights[n]; l_num_points++; vector to_light; float dot, dist; vector temp; for (i=0; i<Num_relevent_lights[n]; i++ ) { l = Relevent_lights[i][n]; break; dist = -1.0f; switch(l->type){ // point lights case LT_POINT: vm_vec_sub( &to_light, &l->local_vec, pos ); break; // tube lights case LT_TUBE: if(vm_vec_dist_to_line(pos, &l->local_vec, &l->local_vec2, &temp, &dist) != 0){ continue; } vm_vec_sub(&to_light, &temp, pos); dist *= dist; // since we use radius squared break; // others. BAD default: Int3(); } dot = vm_vec_dot(&to_light, norm); // dot = 1.0f; if ( dot > 0.0f ) { // indicating that we already calculated the distance (vm_vec_dist_to_line(...) does this for us) if(dist < 0.0f){ dist = vm_vec_mag_squared(&to_light); } if ( dist < l->rad1_squared ) { float ratio; ratio = l->intensity*dot; ratio *= 0.25f; rval += l->r*ratio; gval += l->g*ratio; bval += l->b*ratio; } else if ( dist < l->rad2_squared ) { float ratio; // dist from 0 to float n = dist - l->rad1_squared; float d = l->rad2_squared - l->rad1_squared; ratio = (1.0f - n / d)*dot*l->intensity; ratio *= 0.25f; rval += l->r*ratio; gval += l->g*ratio; bval += l->b*ratio; } } } float m = rval; if ( gval > m ) m = gval; if ( bval > m ) m = bval; if ( m > 1.0f ) { float im = 1.0f / m; rval *= im; gval *= im; bval *= im; } if ( rval < 0.0f ) { rval = 0.0f; } else if ( rval > 1.0f ) { rval = 1.0f; } if ( gval < 0.0f ) { gval = 0.0f; } else if ( gval > 1.0f ) { gval = 1.0f; } if ( bval < 0.0f ) { bval = 0.0f; } else if ( bval > 1.0f ) { bval = 1.0f; } *param_r = ubyte(fl2i(rval*255.0f)); *param_g = ubyte(fl2i(gval*255.0f)); *param_b = ubyte(fl2i(bval*255.0f)); } /* float light_apply( vector *pos, vector * norm ) { #if 1 float r,g,b; light_apply_rgb( &r, &g, &b, pos, norm ); return (r+g+b) / 3.0f; #else return light_apply_ramp( pos, norm ); #endif } */
[ [ [ 1, 1414 ] ] ]
7d9078b081096aadddbe4e9cde92d0712148fcd5
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/BroadPhase/hkpBroadPhaseHandlePair.h
ff01b76f6a2d50db2891091537b06fa3d64a90f3
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_COLLIDE2_BROAD_PHASE_HANDLE_PAIR_H #define HK_COLLIDE2_BROAD_PHASE_HANDLE_PAIR_H class hkpBroadPhaseHandle; /// A structure holding the result of a broadphase query. class hkpBroadPhaseHandlePair { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BROAD_PHASE, hkpBroadPhaseHandlePair ); hkpBroadPhaseHandle* m_a; hkpBroadPhaseHandle* m_b; }; #endif // HK_COLLIDE2_BROAD_PHASE_HANDLE_PAIR_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 38 ] ] ]
9255b7f2ea67261b8e16076910e708aa8da4f253
ed9ecdcba4932c1adacac9218c83e19f71695658
/PhysicsDemo2/PhysicsDemo2/particlecontact.cpp
1f4e279ab55ef9836413a8d2e28112c6edb81889
[]
no_license
karansapra/futurattack
59cc71d2cc6564a066a8e2f18e2edfc140f7c4ab
81e46a33ec58b258161f0dd71757a499263aaa62
refs/heads/master
2021-01-10T08:47:01.902600
2010-09-20T20:25:04
2010-09-20T20:25:04
45,804,375
0
0
null
null
null
null
UTF-8
C++
false
false
1,497
cpp
#include "particlecontact.h" void ParticleContact::Resolve(REAL dt) { ResolveVelocity(dt); ResolveInterpretation(dt); } REAL ParticleContact::CalculateSeparatingVelocity() const { Vector3 relative_velocity = particles[0]->velocity; if (particles[1]) relative_velocity -= particles[1]->velocity; return relative_velocity * contact_normal; } void ParticleContact::ResolveVelocity(REAL dt) { REAL sep_vel = CalculateSeparatingVelocity(); if (sep_vel>0) return; REAL new_sep = -sep_vel*restitution; REAL dvel = new_sep - sep_vel; REAL total_inv_mass = particles[0]->GetInvMass(); if (particles[1]) total_inv_mass += particles[1]->GetInvMass(); if (total_inv_mass<=0) return; REAL impulse = dvel/total_inv_mass; Vector3 impulse_per_mass = contact_normal * impulse; particles[0]->velocity += impulse_per_mass*particles[0]->GetInvMass(); if (particles[1]) particles[1]->velocity -= impulse_per_mass*particles[1]->GetInvMass(); } void ParticleContact::ResolveInterpretation(REAL dt) { if (penetration<=0) return; REAL total_inv_mass = particles[0]->GetInvMass(); if (particles[1]) total_inv_mass += particles[1]->GetInvMass(); if (total_inv_mass<=0) return; Vector3 move_per_mass = contact_normal * (-penetration/total_inv_mass); particles[0]->position += move_per_mass*particles[0]->GetInvMass(); if (particles[1]) particles[1]->position += move_per_mass*particles[1]->GetInvMass(); }
[ "clems71@52ecbd26-af3e-11de-a2ab-0da4ed5138bb" ]
[ [ [ 1, 61 ] ] ]
8b4b7c8343689c424abf5eb165be8c006e0d6ed8
f69b9ae8d4c17d3bed264cefc5a82a0d64046b1c
/src/ImageSeriesSet.h
d0a6884a83848ec3a9717835e5b9ec9b86b78b3d
[]
no_license
lssgufeng/proteintracer
611501cf8001ff9d4bf5e7aa645c24069cce675f
055cc953d6bf62d17eb9435117f44b3f3d9b8f3f
refs/heads/master
2016-08-09T22:20:40.978584
2009-06-07T22:08:14
2009-06-07T22:08:14
55,025,270
0
0
null
null
null
null
UTF-8
C++
false
false
5,741
h
/*============================================================================== Copyright (c) 2009, André Homeyer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ==============================================================================*/ #ifndef ImageSeriesSet_h #define ImageSeriesSet_h #include <map> #include <common.h> namespace PT { struct ImageLocation { short well; short position; short slide; ImageLocation() : well(-1), position(-1), slide(-1) {} ImageLocation(short w, short p, short s) : well(w), position(p), slide(s) {} bool operator<(const ImageLocation& location) const { short result = well - location.well; if (result == 0) { result = position - location.position; if (result == 0) { result = slide - location.slide; } } return result < 0; } bool operator!=(const ImageLocation& location) const { return well != location.well || position != location.position || slide != location.slide; } bool operator==(const ImageLocation& location) const { return well == location.well && position == location.position && slide == location.slide; } bool operator<=(const ImageLocation& location) const { return (operator==(location) || operator<(location)); } void invalidate() { well = -1; position = -1; slide = -1; } bool isValid() const { return well > -1 && position > -1 && slide > -1; } }; struct ImageKey { ImageLocation location; short time; ImageKey() : time(-1) {} ImageKey(ImageLocation l, short t) : location(l), time(t) {} void operator=(const ImageKey& key) { location = key.location; time = key.time; } bool operator<(const ImageKey& key) const { short result = location.well - key.location.well; if (result == 0) { result = location.position - key.location.position; if (result == 0) { result = location.slide - key.location.slide; if (result == 0) { result = time - key.time; } } } return result < 0; } bool operator!=(const ImageKey& key) const { return location != key.location || time != key.time; } bool operator==(const ImageKey& key) const { return location == key.location && time == key.time; } bool operator<=(const ImageKey& key) const { return (operator==(key) || operator<(key)); } ImageKey previous() { return ImageKey(location, this->time - 1); } ImageKey next() { return ImageKey(location, this->time + 1); } void invalidate() { location.invalidate(); time = -1; } bool isValid() const { return location.isValid() && time > -1; } }; class ImageSeries { public: typedef Range<short> TimeRange; ImageSeries(const ImageLocation& loc, const TimeRange& tr = TimeRange()) : location(loc), timeRange(tr) { } ImageKey getImageKey(short time) const { return ImageKey(location, time); } ImageLocation location; TimeRange timeRange; }; class ImageSeriesSet { protected: typedef std::map<ImageLocation, ImageSeries> ImageSeriesMap; inline static const ImageSeries& constDerefImageSeries(ImageSeriesMap::const_iterator& it) { return (*it).second; } public: typedef IteratorWrapper<ImageSeriesMap::const_iterator, const ImageSeries, const ImageSeries&, &constDerefImageSeries> ImageSeriesConstIterator; virtual ~ImageSeriesSet() {} const ImageSeries& getImageSeries(const ImageLocation& location) const; ImageSeriesConstIterator getImageSeriesStart() const { return ImageSeriesConstIterator(imageSeriesMap_.begin()); } ImageSeriesConstIterator getImageSeriesEnd() const { return ImageSeriesConstIterator(imageSeriesMap_.end()); } protected: ImageSeriesMap imageSeriesMap_; }; } #endif
[ "andre.homeyer@localhost" ]
[ [ [ 1, 220 ] ] ]
6925016500087c5af5919a506ff1b2bba07a281c
9d6d89a97c85abbfce7e2533d133816480ba8e11
/src/GameType/Classic/Classic.cpp
8e6dca128759979845fc5fac19cee470bf23112a
[]
no_license
polycraft/Bomberman-like-reseau
1963b79b9cf5d99f1846a7b60507977ba544c680
27361a47bd1aa4ffea972c85b3407c3c97fe6b8e
refs/heads/master
2020-05-16T22:36:22.182021
2011-06-09T07:37:01
2011-06-09T07:37:01
1,564,502
1
2
null
null
null
null
UTF-8
C++
false
false
10,444
cpp
#include "Classic.h" #include "../../Type/ManagerExplosion.h" #include "../../Type/ExplosionFlare.h" #include "../../Game.h" #include "../../Map.h" #include "../../CollisionDetector.h" #include "../../Type/Bomb.h" #include "../../Type/Bomberman.h" #include "../../Type/StaticBloc.h" #include "Initialisation.h" #include "Running.h" #include "HurryUp.h" #include "Dead.h" #include "Ending.h" using namespace Engine; namespace GameTypeSpace { using namespace ClassicSpace; Classic::Classic(Game *game, Engine::Socket *socket, int idBomber):GameType(game,10, socket),font("src/ressource/font/font.ttf",10) { srand ( time(NULL) ); this->player = new Bomberman(idBomber); phaseCurrent=P_Initialisation; collision=new CollisionDetector(game->getMap()); phase[P_Initialisation-2]=new Initialisation(this,collision, idBomber); phase[P_Running-2]=new Running(this,collision); phase[P_Dead-2]=new Dead(this,collision); phase[P_HurryUp-2]=new HurryUp(this,collision); phase[P_Ending-2]=new Ending(this,collision); game->getEngine()->getGengine()->getManagerText().addFont(&font); this->game->getEngine()->getEventEngine()->addListener(this); } Classic::~Classic() { delete collision; delete phase[P_Initialisation-2]; delete phase[P_Running-2]; delete phase[P_HurryUp-2]; } void Classic::update() { EPhase nextPhase=static_cast<EPhase>(getPhase(phaseCurrent)->update()); int tmp; switch(nextPhase) { case P_Current: break; case P_Next: tmp=phaseCurrent+1; phaseCurrent=static_cast<EPhase>(tmp); break; default: phaseCurrent=nextPhase; break; } } void Classic::explode(Bomb* bomb,int speed,int power) { int tmpX=bomb->getTransX();tmpX=tmpX/10-1; int tmpY=bomb->getTransY();tmpY=tmpY/10-1; this->game->getMap()->set(NULL,tmpX,tmpY); new ManagerExplosion(tmpX,tmpY,bomb->getIdOwner(), speed, power, this); } void Classic::updateExplosion(ExplosionFlare *flare,int power,int x,int y) { if(flare->getType()==T_Emitter) { flare->endExplose(); } else { switch(flare->getType()) { case T_Left: x-=power; break; case T_Right: x+=power; break; case T_Up: y+=power; break; case T_Down: y-=power; break; default: break; } Type *object; switch(this->collision->detect(T_Explosion,x,y)) { case C_Explose: object=this->game->getMap()->get(x,y); if(object->getType()==T_Bomb) { dynamic_cast<Bomb*>(this->game->getMap()->get(x,y))->explode(); } else if(object->getType()==T_BreakableBloc) { this->game->getMap()->set(NULL,x,y); /*PaquetBonus paquetBonus={'u', Engine::Timer::getTimer()->getTime(),0,x,y}; this->socket->sendData<PaquetBonus>(&paquetBonus);*/ //créer bonus=> remplace la caisse /*EBonus random = this->randomBonus(); if(random != T_None) { this->game->getMap()->addObject(new Bonus(random),x,y,T_Map); } else this->game->getMap()->set(NULL,x,y); object->destroy();*/ } flare->endExplose(); break; case C_Kill: /*object=this->game->getMap()->get(x,y); this->game->getMap()->set(NULL,x,y); object->destroyTimeAnim(); object->destroy();*/ flare->nextExplose(); break; case C_Block: flare->endExplose(); break; case C_Nothing: flare->nextExplose(); break; default: break; } for(std::set<Bonus*>::iterator it=waitingBonus.begin(); it!=waitingBonus.end(); ++it) { int tmpX=(*it)->getTransX(); int tmpY=(*it)->getTransY(); if(tmpX==x && tmpY==y) { if((*it)->getTypeBonus()!=T_None) { this->game->getMap()->addObject(*it,x,y,T_Map); } else { this->game->getMap()->set(NULL,x,y); } waitingBonus.erase(it); break; } } } } EBonus Classic::randomBonus() { return (EBonus)(rand() % this->nbBonus); } void Classic::destroyManagerExplosion(ManagerExplosion* manager) { delete manager; player->setProperty<int>(PB_nbBomb,player->getProperty<int>(PB_nbBomb)+1); } Bomberman* Classic::getPlayer() { return player; } void Classic::setPlayer(Bomberman* bomber) { player=bomber; } vector<Bomberman*>& Classic::getPlayerNetwork() { return playerNetwork; } Phase* Classic::getPhase(EPhase phase) { switch(phase) { case P_Current: return this->phase[phaseCurrent-2]; break; case P_Next: return this->phase[phaseCurrent+1-2]; break; default: return this->phase[phase-2]; break; } } void Classic::executeAction(Engine::stateEvent &event) { this->phase[phaseCurrent-2]->executeAction(event); } void Classic::updateRecv(Socket *socket,Paquet& paquet) { dynamic_cast<PhaseClassic*>(this->phase[phaseCurrent-2])->updateRecv(socket,paquet); char type=(paquet.getData())[0]; //cout << type << endl << endl; switch(type) { case 'b'://Bombe { PaquetBomb *paquetBomb=paquet.getData<PaquetBomb*>(); Bomb* bomb=new Bomb( this, paquetBomb->idBomber, paquetBomb->explodeTime, paquetBomb->vitesseExplode, paquetBomb->power); this->getGame()->getMap()->addObject(bomb,paquetBomb->x,paquetBomb->y,T_Dyn); if(this->getPlayer()->getProperty<int>(PB_id)==paquetBomb->idBomber) { this->getPlayer()->setProperty<int>(PB_nbBomb,this->getPlayer()->getProperty<int>(PB_nbBomb)-1); } } break; case 'm'://Movements { PaquetMove *paquetMove=paquet.getData<PaquetMove*>(); //On cherche le Bomberman concerné vector<Bomberman*>::iterator it; for ( it=playerNetwork.begin() ; it < playerNetwork.end(); it++ ) { if((*it)->getProperty<int>(PB_id)==paquetMove->idBomber) { //On le déplace (*it)->setTransX(paquetMove->x); (*it)->setTransY(paquetMove->y); (*it)->setRotation(0,0,paquetMove->rotation); } } } break; case 'u': //Bonus { PaquetBonus *paquetBonus=paquet.getData<PaquetBonus*>(); //obtiens lobjet deja présent Object *object = this->game->getMap()->get(paquetBonus->x,paquetBonus->y); EBonus typeBonus = static_cast<EBonus>(paquetBonus->bonus); Bonus* bonus=new Bonus(typeBonus); if(object==NULL) { //On affiche le bonus if(typeBonus != T_None) { this->game->getMap()->addObject(bonus,paquetBonus->x,paquetBonus->y,T_Map); } } else { bonus->setTransX(paquetBonus->x); bonus->setTransY(paquetBonus->y); //On l'ajoute dans le tampon waitingBonus.insert(bonus); } } break; case 'p': { PaquetPhase *paquetPhase=paquet.getData<PaquetPhase*>(); phaseCurrent = static_cast<EPhase>(paquetPhase->phase); } break; case 'd': { PaquetDeconnect *paquetDeconnect=paquet.getData<PaquetDeconnect*>(); vector<Bomberman*>::iterator it; for ( it=playerNetwork.begin() ; it < playerNetwork.end(); it++ ) { if((*it)->getProperty<int>(PB_id)==paquetDeconnect->idBomber) { Bomberman* bomberman=*it; playerNetwork.erase(it); font.removeText(bomberman->getName()); bomberman->destroy(); break; } } } break; case 'o': { PaquetRound *paquetRound=paquet.getData<PaquetRound*>(); phase[P_Initialisation-2]->setEtat(E_Init); phase[P_Initialisation-2]->end(P_Initialisation); phase[P_Running-2]->setEtat(E_Init); phase[P_Running-2]->end(P_Running); phase[P_HurryUp-2]->setEtat(E_Init); phase[P_HurryUp-2]->end(P_HurryUp); phase[P_Ending-2]->setEtat(E_Init); phase[P_Ending-2]->end(P_Ending); phaseCurrent = P_Initialisation; } break; } } ManagerFont& Classic::getFont() { return font; } void Classic::updateTimer(unsigned int delay) { if(delay == this->timeServerMovement) { PaquetMove paquetMove={'m', Engine::Timer::getTimer()->getTime(), this->player->getProperty<int>(PB_id), this->player->getTransX(), this->player->getTransY(), this->player->getRotateZ() }; this->socket->sendData<PaquetMove>(&paquetMove); } } ClassicSpace::EPhase Classic::getPhaseCurrent() { return this->phaseCurrent; } int Classic::getTimeServMove() { return this->timeServerMovement; } }
[ [ [ 1, 2 ], [ 10, 10 ], [ 20, 21 ], [ 25, 26 ], [ 32, 32 ], [ 37, 38 ], [ 40, 40 ], [ 42, 45 ], [ 50, 52 ], [ 54, 54 ], [ 71, 74 ], [ 81, 81 ], [ 84, 84 ], [ 86, 86 ], [ 88, 88 ], [ 92, 92 ], [ 124, 131 ], [ 134, 134 ], [ 138, 139 ], [ 141, 141 ], [ 144, 144 ], [ 147, 147 ], [ 176, 180 ], [ 185, 185 ], [ 226, 241 ], [ 246, 246 ], [ 248, 249 ], [ 265, 265 ], [ 267, 267 ], [ 270, 271 ], [ 292, 292 ], [ 319, 332 ], [ 334, 335 ], [ 342, 363 ], [ 365, 365 ] ], [ [ 3, 9 ], [ 11, 19 ], [ 22, 24 ], [ 27, 31 ], [ 33, 36 ], [ 39, 39 ], [ 41, 41 ], [ 46, 49 ], [ 53, 53 ], [ 55, 70 ], [ 75, 80 ], [ 82, 83 ], [ 85, 85 ], [ 87, 87 ], [ 89, 91 ], [ 93, 123 ], [ 132, 133 ], [ 135, 137 ], [ 140, 140 ], [ 142, 143 ], [ 145, 146 ], [ 148, 175 ], [ 181, 184 ], [ 186, 225 ], [ 242, 245 ], [ 247, 247 ], [ 250, 264 ], [ 266, 266 ], [ 268, 269 ], [ 272, 291 ], [ 293, 318 ], [ 333, 333 ], [ 336, 341 ], [ 364, 364 ], [ 366, 366 ] ] ]
53aaa2e587c1c89e95c152ad05fad03b61c11b53
27651c3f5f829bff0720d7f835cfaadf366ee8fa
/QBluetooth/LocalDevice/Impl/QBtLocalDevice_stub.cpp
770b6bdefff28f1880080b7370b770fd735d9186
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
cpscotti/Push-Snowboarding
8883907e7ee2ddb9a013faf97f2d9673b9d0fad5
cc3cc940292d6d728865fe38018d34b596943153
refs/heads/master
2021-05-27T16:35:49.846278
2011-07-08T10:25:17
2011-07-08T10:25:17
1,395,155
1
1
null
null
null
null
UTF-8
C++
false
false
2,007
cpp
/* * QBtLocalDevice_stub.cpp * * * Author: Ftylitakis Nikolaos * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../QBtLocalDevice_stub.h" TBool QBtLocalDevicePrivate::isBluetoothSupported() { return false; } void QBtLocalDevicePrivate::AskUserTurnOnBtPower() { return; } bool QBtLocalDevicePrivate::GetBluetoothPowerState() { return false; } bool QBtLocalDevicePrivate::SetBluetoothPowerState (bool value) { return false; } QBtAddress QBtLocalDevicePrivate::GetLocalDeviceAddress() { return QBtAddress(); } bool QBtLocalDevicePrivate::GetLimitedDiscoverableStatus() { return false; } void QBtLocalDevicePrivate::SetLimitedDiscoverableStatus(bool isDiscoverabilityLimited) { } QBtDevice::DeviceMajor QBtLocalDevicePrivate::GetDeviceClass() { return QBtDevice::Uncategorized; } void QBtLocalDevicePrivate::SetDeviceClass(QBtDevice::DeviceMajor classId) { } void QBtLocalDevicePrivate::SetLocalDeviceName(const QString & deviceName) { } QString QBtLocalDevicePrivate::GetLocalDeviceName() { return ""; } bool QBtLocalDevicePrivate::AddNewDevice(const QBtDevice& device) { return false; } bool QBtLocalDevicePrivate::DeleteDevice(const QBtDevice& device) { return false; } bool QBtLocalDevicePrivate::DeleteDevice(const QBtAddress& address) { return false; } bool QBtLocalDevicePrivate::UnpairDevice(const QBtDevice& device) { return false; }
[ "cpscotti@c819a03f-852d-4de4-a68c-c3ac47756727" ]
[ [ [ 1, 97 ] ] ]
e0b26358bdc76749c3bb8b863af7f25c619dd76f
184455acbcc5ee6b2ee0c77c66b436375e1171e9
/src/Music.cpp
a6a065a5a8d39c17c41a754478323314efc331d5
[]
no_license
Karkasos/Core512
d996d40e57be899e6c4c9aec106e371356152b36
b83151ab284b7cf2e058fdd218dcc676946f43aa
refs/heads/master
2020-04-07T14:19:51.907224
2011-11-01T06:46:20
2011-11-01T06:46:20
2,753,621
0
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
#include "Core512.h" #include "Music.h" const bool UseMusic = false; Music::Music() : hStream(NULL) { if(UseMusic) hStream = exHGE->Stream_Load("Res\\TheFallen.mp3"); } Music::~Music() { if(hStream) exHGE->Stream_Free(hStream); } void Music::Play() { if(hStream) exHGE->Stream_Play(hStream, true); }
[ [ [ 1, 22 ] ] ]
740ad39b22a293a182b0e0d8d3cae0a9b66d01e1
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/rules/include/JumpToTargetMovement.h
55ffee6bc0cad35efae870089cc835f3ca88c01e
[ "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
1,417
h
/* 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. */ #ifndef __JumpToTargetMovement_H__ #define __JumpToTargetMovement_H__ #include "JumpLongMovement.h" namespace rl { class JumpToTargetMovement : public JumpLongMovement { public: JumpToTargetMovement(CreatureController *creature); virtual CreatureController::MovementType getId() const {return CreatureController::MT_ZIELSPRUNG;} virtual CreatureController::MovementType getFallBackMovement() const {return CreatureController::MT_STEHEN;} virtual bool calculateBaseVelocity(Ogre::Real &velocity); virtual void activate(); virtual bool run(Ogre::Real elapsedTime, Ogre::Vector3 direction, Ogre::Vector3 rotation); }; } #endif
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 38 ] ] ]
268780aad7c14e116d84c3810b2138e86eab3135
b8ac0bb1d1731d074b7a3cbebccc283529b750d4
/Code/controllers/OdometryCalibration/behaviours/AbstractBehaviour.cpp
23ddb63dcfad894f44384102ea5b2d81b49ce62b
[]
no_license
dh-04/tpf-robotica
5efbac38d59fda0271ac4639ea7b3b4129c28d82
10a7f4113d5a38dc0568996edebba91f672786e9
refs/heads/master
2022-12-10T18:19:22.428435
2010-11-05T02:42:29
2010-11-05T02:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,336
cpp
#include "AbstractBehaviour.h" #include <robotapi/IRobot.h> #include <robotapi/IDistanceSensor.h> #include <vector> #include <sstream> namespace behaviours { int nextid = 0; robotapi::IRobot * myIRobot = NULL; int stimuli_present = 0; GarbageCleaner * myGarbageCleaner = NULL; AbstractBehaviour::AbstractBehaviour(char * name){ behaviour_id = nextid; if ( nextid == 0 ) nextid = 1; else nextid = 2 * nextid; std::stringstream lStream; lStream << name; lStream << " , Id: "; lStream << behaviour_id; this->s.append(lStream.str()); } std::string AbstractBehaviour::toString(){ return s; } AbstractBehaviour::~AbstractBehaviour(){} void AbstractBehaviour::act() // don't delete the following line as it's needed to preserve source code of this autogenerated element // section -64--88-1-100--1230920c:125cb7ecd6f:-8000:0000000000000DCB begin { if ( isMyAction() ){ /* if ( lastStimuli != behaviour_id ){ setBehaviourChanged(true); backupLastStimuli(lastStimuli); } else setBehaviourChanged(false); setLastStimuli(behaviour_id); */ printf("Stimulus Present: %s\n",this->s.c_str()); action(); } } // section -64--88-1-100--1230920c:125cb7ecd6f:-8000:0000000000000DCB end // don't delete the previous line as it's needed to preserve source code of this autogenerated element bool AbstractBehaviour::isMyAction() // don't delete the following line as it's needed to preserve source code of this autogenerated element // section -64--88-1-100--1230920c:125cb7ecd6f:-8000:0000000000000DCD begin { int aux = stimuli_present - behaviour_id; return aux == 0 || ( aux > 0 && aux < behaviour_id); } // section -64--88-1-100--1230920c:125cb7ecd6f:-8000:0000000000000DCD end // don't delete the previous line as it's needed to preserve source code of this autogenerated element void AbstractBehaviour::setStimulusPresent(){ stimuli_present = stimuli_present | behaviour_id; } void AbstractBehaviour::resetStimulusPresent(){ stimuli_present = 0; } void AbstractBehaviour::setGarbageCleaner(GarbageCleaner * garbageCleaner){ if ( myGarbageCleaner == NULL ) myGarbageCleaner = garbageCleaner; } } /* End of namespace behaviours */
[ "guicamest@d69ea68a-f96b-11de-8cdf-e97ad7d0f28a" ]
[ [ [ 1, 78 ] ] ]
79b4da92e6bd238e1be47991892dcbc811c1fe8b
619843aa55e023fe4eb40a3f1b59da6bcb993a54
/reactor/event_demultiplexer.h
981be3a8b54679fb9f08015aa972ee62e4ffb062
[]
no_license
pengvan/xiao5geproject
82271ceb18d2c9ea7abb960c41e883ad54a7e8c6
3e28c80f0af5d11eb1c03c569e040dda33966e4a
refs/heads/master
2016-09-11T02:19:09.285543
2011-06-17T07:05:34
2011-06-17T07:05:34
38,201,768
0
0
null
null
null
null
GB18030
C++
false
false
3,782
h
#ifndef REACTOR_EVENT_DEMULTIPLEXER_H_ #define REACTOR_EVENT_DEMULTIPLEXER_H_ #include <set> #include <map> #include "reactor.h" /// @file event_demultiplexer.h /// @brief 事件多路分发器类 /// @author zeshengwu<[email protected]> /// @date 2011-03-20 namespace reactor { class EventDemultiplexer { public: /// 析构函数 virtual ~EventDemultiplexer() {} /// 获取并处理有事件发生的所有句柄上的事件 /// @param handlers 事件处理器集合 /// @param timeout 超时时间 /// @retval = 0 没有发生事件的句柄(超时) /// @retval > 0 发生事件的句柄个数 /// @retval < 0 发生错误 virtual int WaitEvents(std::map<handle_t, EventHandler *> * handlers, int timeout = 0) = 0; /// 设置句柄handle关注evt事件 /// @retval = 0 设置成功 /// @retval < 0 设置出错 virtual int RequestEvent(handle_t handle, event_t evt) = 0; /// 撤销句柄handle对事件的关注 /// @retval = 0 撤销成功 /// @retval < 0 撤销出错 virtual int UnrequestEvent(handle_t handle) = 0; }; /////////////////////////////////////////////////////////////////////////////// /// 由select实现的多路事件分发器 class SelectDemultiplexer : public EventDemultiplexer { public: /// 构造函数 SelectDemultiplexer(); /// 获取并处理有事件发生的所有句柄上的事件 /// @param handlers 事件处理器集合 /// @param timeout 超时时间 /// @retval = 0 没有发生事件的句柄(超时) /// @retval > 0 发生事件的句柄个数 /// @retval < 0 发生错误 virtual int WaitEvents(std::map<handle_t, EventHandler *> * handlers, int timeout = 0); /// 设置句柄handle关注evt事件 /// @retval = 0 设置成功 /// @retval < 0 设置出错 virtual int RequestEvent(handle_t handle, event_t evt); /// 撤销句柄handle对事件的关注 /// @retval = 0 撤销成功 /// @retval < 0 撤销出错 virtual int UnrequestEvent(handle_t handle); private: /// 清空所有的fd集合 void Clear(); private: fd_set m_read_set; ///< 读事件fd集合 fd_set m_write_set; ///< 写事件fd集合 fd_set m_except_set; ///< 异常事件fd集合 timeval m_timeout; ///< 超时 }; /////////////////////////////////////////////////////////////////////////////// /// 由epoll实现的多路事件分发器 class EpollDemultiplexer : public EventDemultiplexer { public: /// 构造函数 EpollDemultiplexer(); /// 析构函数 ~EpollDemultiplexer(); /// 获取并处理有事件发生的所有句柄上的事件 /// @param handlers 事件处理器集合 /// @param timeout 超时时间 /// @retval = 0 没有发生事件的句柄(超时) /// @retval > 0 发生事件的句柄个数 /// @retval < 0 发生错误 virtual int WaitEvents(std::map<handle_t, EventHandler *> * handlers, int timeout = 0); /// 设置句柄handle关注evt事件 /// @retval = 0 设置成功 /// @retval < 0 设置出错 virtual int RequestEvent(handle_t handle, event_t evt); /// 撤销句柄handle对事件的关注 /// @retval = 0 撤销成功 /// @retval < 0 撤销出错 virtual int UnrequestEvent(handle_t handle); private: int m_epoll_fd; ///< epoll自身的fd int m_fd_num; ///< 所有fd的个数 }; } // namespace reactor #endif // REACTOR_EVENT_DEMULTIPLEXER_H_
[ "wuzesheng86@a907dffe-942c-7992-d486-e995bdc504d8" ]
[ [ [ 1, 123 ] ] ]
918af8ba350cac61a68f3151a7be471e8ca3ec52
4891542ea31c89c0ab2377428e92cc72bd1d078f
/KOUTSOP.TEST/Face.cpp
ec19f85a78fcaa8cee20188f423b12793d1ef8d8
[]
no_license
koutsop/arcanoid
aa32c46c407955a06c6d4efe34748e50c472eea8
5bfef14317e35751fa386d841f0f5fa2b8757fb4
refs/heads/master
2021-01-18T14:11:00.321215
2008-07-17T21:50:36
2008-07-17T21:50:36
33,115,792
0
0
null
null
null
null
UTF-8
C++
false
false
8,829
cpp
//----------------------------------------------------------------------------- // File: CreateDevice.cpp // // Desc: This is the first tutorial for using Direct3D. In this tutorial, all // we are doing is creating a Direct3D device and using it to clear the // window. // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #include <d3d9.h> #pragma warning( disable : 4996 ) // disable deprecated warning #include <strsafe.h> #pragma warning( default : 4996 ) #include <assert.h> //----------------------------------------------------------------------------- // Global variables //----------------------------------------------------------------------------- LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device //---------------Code injection ----------------------------------- const int g_width=20000; const int g_height = 480; struct point_vertex{ float x, y, z, rhw; // The transformed(screen space) position for the vertex. DWORD colour; // The vertex colour. }; const DWORD point_fvf=D3DFVF_XYZRHW|D3DFVF_DIFFUSE; point_vertex random_data[g_width]; int index=0; void draw_point(int x, int y){ if(index == g_width){ assert(0); } random_data[++index].x = x; random_data[index].y = y; random_data[index].z=1.0f; random_data[index].rhw=1.0f; random_data[index].colour=D3DCOLOR_XRGB(200,200,200); return ; } void midpoint_ellipse(int a, int b, int centerX, int centerY, int xmask, int ymask){ double d2; float x=0; float y=b;//(float)b; double d1=(b*b)-((a*a)*b)+(0.25*(a*a)); double tmp; draw_point(xmask*x+centerX,ymask*y+centerY); tmp =(a*a)*(y-0.5)-(b*b)*(x+1); while(tmp>0){ if(d1<0) d1+=(b*b)*(2*x+3); else{ d1+=(b*b)*(2*x+3)+(a*a)*(2-2*y); y--; } x++; draw_point(xmask*x+centerX,ymask*y+centerY); tmp =(a*a)*(y-0.5)-(b*b)*(x+1); } d2 = (b*b)*((x+0.5)*(x+0.5)) + (a*a)*((y-1)*(y-1)) - (a*a)*(b*b); while(y>0){ if(d2<0){ d2+=(b*b)*(2*x+2)+(a*a)*(3-2*y); x++; } else d2+=(a*a)*(3-2*y); y--; draw_point(xmask*x+centerX,ymask*y+centerY); } return ; } //---------------------------------------------------- //---------------------------------------------- // MakeEclipse //------------------------------------------ void MakeEclipse(int a, int b, int centerX, int centerY){ midpoint_ellipse(a, b, centerX, centerY, 1, 1); midpoint_ellipse(a, b, centerX, centerY, 1, -1); midpoint_ellipse(a, b, centerX, centerY, -1, 1); midpoint_ellipse(a, b, centerX, centerY, -1, -1); return; } //----------------------------------------------------- // MakeHorLine //---------------------------------------------------- void MakeHorLine(int startX, int startY, int width){ for(int y=startX;y < startX+width;++y) draw_point(y, startY); return; } //----------------------------------------------------------------------------- // Name: InitD3D() // Desc: Initializes Direct3D //----------------------------------------------------------------------------- HRESULT InitD3D( HWND hWnd ) { // Create the D3D object, which is needed to create the D3DDevice. if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) return E_FAIL; // Set up the structure used to create the D3DDevice. Most parameters are // zeroed out. We set Windowed to TRUE, since we want to do D3D in a // window, and then set the SwapEffect to "discard", which is the most // efficient method of presenting the back buffer to the display. And // we request a back buffer format that matches the current desktop display // format. D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp) ); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // Create the Direct3D device. Here we are using the default adapter (most // systems only have one, unless they have multiple graphics hardware cards // installed) and requesting the HAL (which is saying we want the hardware // device rather than a software one). Software vertex processing is // specified since we know it will work on all cards. On cards that support // hardware vertex processing, though, we would see a big performance gain // by specifying hardware vertex processing. if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice ) ) ) { return E_FAIL; } // Device state would normally be set here g_pd3dDevice->SetFVF(point_fvf); return S_OK; } //----------------------------------------------------------------------------- // Name: Cleanup() // Desc: Releases all previously initialized objects //----------------------------------------------------------------------------- VOID Cleanup() { if( g_pd3dDevice != NULL) g_pd3dDevice->Release(); if( g_pD3D != NULL) g_pD3D->Release(); } //----------------------------------------------------------------------------- // Name: Render() // Desc: Draws the scene //----------------------------------------------------------------------------- VOID Render() { if( NULL == g_pd3dDevice ) return; // Clear the backbuffer to a blue color g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 ); // Begin the scene g_pd3dDevice->BeginScene(); // Rendering of scene objects can happen here MakeEclipse(150, 100, 400, 300); //face MakeEclipse( 20, 20, 300, 330); // left eye MakeEclipse( 20, 20, 500, 300); // right eye MakeEclipse( 0, 20, 400, 300); // Nose MakeHorLine(330, 350, 100); // MakeEclipse( 20, 0, 400, 350); // Nose g_pd3dDevice->DrawPrimitiveUP(D3DPT_POINTLIST, //PrimitiveType g_width, //PrimitiveCount random_data, //pVertexStreamZeroData sizeof(point_vertex)); //VertexStreamZeroStride // End the scene g_pd3dDevice->EndScene(); // Present the backbuffer contents to the display g_pd3dDevice->Present( NULL, NULL, NULL, NULL ); } //----------------------------------------------------------------------------- // Name: MsgProc() // Desc: The window's message handler //----------------------------------------------------------------------------- LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: Cleanup(); PostQuitMessage( 0 ); return 0; case WM_PAINT: Render(); ValidateRect( hWnd, NULL ); return 0; } return DefWindowProc( hWnd, msg, wParam, lParam ); } //----------------------------------------------------------------------------- // Name: wWinMain() // Desc: The application's entry point //---------------------------------------------------------------------------- INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT ) { // Register the window class WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, L"D3D Tutorial", NULL }; RegisterClassEx( &wc ); // Create the application's window HWND hWnd = CreateWindow( L"D3D Tutorial", L"FaCe", WS_OVERLAPPEDWINDOW, 100, 100, 800, 600, NULL, NULL, wc.hInstance, NULL ); // Initialize Direct3D if( SUCCEEDED( InitD3D( hWnd ) ) ) { // Show the window ShowWindow( hWnd, SW_SHOWDEFAULT ); UpdateWindow( hWnd ); // Enter the message loop MSG msg; while( GetMessage( &msg, NULL, 0, 0 ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } } UnregisterClass( L"D3D Tutorial", wc.hInstance ); return 0; }
[ "[email protected]@5c4dd20e-9542-0410-abe3-ad2d610f3ba4" ]
[ [ [ 1, 268 ] ] ]
fc8eab72edf84d1711028e1e30e6595ca77dcc47
4561a0f9a0de6a9b75202e1c05a4bd6ba7adabcf
/ofstream.cpp
a20d317e62f40bf98e7cd5287acc0223580a4931
[ "MIT" ]
permissive
embarkmobile/ustl-symbian
3a2471a0487ae8d834f44a69debdb4e093215ce0
6d108f5683677d1d6b57705ac08cf1a4f5a37204
refs/heads/master
2020-04-23T15:37:30.148583
2010-12-10T15:35:16
2010-12-10T15:35:16
898,964
1
0
null
null
null
null
UTF-8
C++
false
false
3,929
cpp
// This file is part of the ustl library, an STL implementation. // // Copyright (C) 2005 by Mike Sharov <[email protected]> // This file is free software, distributed under the MIT License. // // ofstream.cc // #include "ofstream.h" #include "ustring.h" #include "uexception.h" #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdarg.h> namespace ustl { //---------------------------------------------------------------------- ifstream cin (STDIN_FILENO); ofstream cout (STDOUT_FILENO); ofstream cerr (STDERR_FILENO); //---------------------------------------------------------------------- /// Default constructor. ofstream::ofstream (void) : ostringstream (), m_File () { reserve (255); } /// Constructs a stream for writing to \p Fd. ofstream::ofstream (int Fd) : ostringstream (), m_File (Fd) { clear (m_File.rdstate()); reserve (255); } /// Constructs a stream for writing to \p filename. ofstream::ofstream (const char* filename, openmode mode) : ostringstream (), m_File (filename, mode) { clear (m_File.rdstate()); } /// Default destructor. ofstream::~ofstream (void) { try { close(); } catch (...) {} } /// Flushes the buffer to the file. void ofstream::flush (void) { while (pos() && overflow (remaining())) ; m_File.sync(); clear (m_File.rdstate()); } /// Seeks to \p p based on \p d. void ofstream::seekp (off_t p, seekdir d) { flush(); m_File.seekp (p, d); clear (m_File.rdstate()); } /// Called when more buffer space (\p n bytes) is needed. ofstream::size_type ofstream::overflow (size_type n) { if (eof() || (n > remaining() && n < capacity() - pos())) return (ostringstream::overflow (n)); size_type bw = m_File.write (cdata(), pos()); clear (m_File.rdstate()); erase (begin(), bw); if (remaining() < n) ostringstream::overflow (n); return (remaining()); } //---------------------------------------------------------------------- /// Constructs a stream to read from \p Fd. ifstream::ifstream (int Fd) : istringstream (), m_Buffer (255), m_File (Fd) { link (m_Buffer.data(), 0U); } /// Constructs a stream to read from \p filename. ifstream::ifstream (const char* filename, openmode mode) : istringstream (), m_Buffer (255), m_File (filename, mode) { clear (m_File.rdstate()); link (m_Buffer.data(), 0U); } /// Reads at least \p n more bytes and returns available bytes. ifstream::size_type ifstream::underflow (size_type n) { if (eof()) return (istringstream::underflow (n)); const ssize_t freeSpace = m_Buffer.size() - pos(); const ssize_t neededFreeSpace = max (n, m_Buffer.size() / 2); const size_t oughtToErase = Align (max ((ssize_t)0, neededFreeSpace - freeSpace)); const size_t nToErase = min (pos(), oughtToErase); m_Buffer.memlink::erase (m_Buffer.begin(), nToErase); const uoff_t oldPos (pos() - nToErase); size_type br = oldPos; if (m_Buffer.size() - br < n) { m_Buffer.resize (br + neededFreeSpace); link (m_Buffer.data(), 0U); } cout.flush(); while (br - oldPos < n && m_File.good()) br += m_File.readsome (m_Buffer.begin() + br, m_Buffer.size() - br); clear (m_File.rdstate()); m_Buffer[br] = string::c_Terminator; link (m_Buffer.data(), br); seek (oldPos); return (remaining()); } /// Flushes the input. void ifstream::sync (void) { istringstream::sync(); underflow (0U); m_File.sync(); clear (m_File.rdstate()); } /// Seeks to \p p based on \p d. void ifstream::seekg (off_t p, seekdir d) { m_Buffer.clear(); link (m_Buffer); m_File.seekg (p, d); clear (m_File.rdstate()); } //---------------------------------------------------------------------- } // namespace ustl
[ [ [ 1, 160 ] ] ]
76be5ea34e3cad0112bc86462bc0537743651a66
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/sqlexpr.hpp
3b1dd8c5c62a7555f194ec2bece55dfc8f7895bc
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
29,043
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'SqlExpr.pas' rev: 6.00 #ifndef SqlExprHPP #define SqlExprHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <SqlTimSt.hpp> // Pascal unit #include <DBXpress.hpp> // Pascal unit #include <DBCommon.hpp> // Pascal unit #include <DB.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <Variants.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Sqlexpr { //-- type declarations ------------------------------------------------------- typedef int TLocaleCode; #pragma option push -b- enum TSQLExceptionType { exceptConnection, exceptCommand, exceptCursor, exceptMetaData, exceptUseLast }; #pragma option pop #pragma option push -b- enum TSQLTraceFlag { traceQPREPARE, traceQEXECUTE, traceERROR, traceSTMT, traceCONNECT, traceTRANSACT, traceBLOB, traceMISC, traceVENDOR, traceDATAIN, traceDATAOUT }; #pragma option pop typedef Set<TSQLTraceFlag, traceQPREPARE, traceDATAOUT> TSQLTraceFlags; class DELPHICLASS TSQLBlobStream; class DELPHICLASS TCustomSQLDataSet; class DELPHICLASS TSQLConnection; #pragma option push -b- enum TConnectionState { csStateClosed, csStateOpen, csStateConnecting, csStateExecuting, csStateFetching, csStateDisconnecting }; #pragma option pop typedef void __fastcall (__closure *TSQLConnectionLoginEvent)(TSQLConnection* Database, Classes::TStrings* LoginParams); #pragma option push -b- enum TTableScope { tsSynonym, tsSysTable, tsTable, tsView }; #pragma option pop typedef Set<TTableScope, tsSynonym, tsView> TTableScopes; #pragma option push -b- enum TSchemaType { stNoSchema, stTables, stSysTables, stProcedures, stColumns, stProcedureParams, stIndexes }; #pragma option pop #pragma option push -b- enum EConnectFlag { eConnect, eReconnect, eDisconnect }; #pragma option pop class PASCALIMPLEMENTATION TSQLConnection : public Db::TCustomConnection { typedef Db::TCustomConnection inherited; private: unsigned FActiveStatements; bool FAutoClone; TSQLConnection* FCloneParent; TConnectionState FConnectionState; AnsiString FConnectionName; AnsiString FConnectionRegistryFile; AnsiString FDriverName; AnsiString FDriverRegistryFile; AnsiString FGetDriverFunc; int FTransactionCount; bool FIsCloned; Dbxpress::_di_ISQLConnection FISQLConnection; bool FKeepConnection; AnsiString FLastError; AnsiString FLibraryName; bool FLoadParamsOnConnect; Classes::TList* FMonitorUsers; TSQLConnectionLoginEvent FOnLogin; Classes::TStrings* FParams; bool FParamsLoaded; unsigned FMaxStmtsPerConn; AnsiString FQuoteChar; int FRefCount; unsigned FSQLDllHandle; Dbxpress::_di_ISQLDriver FSQLDriver; bool FSQLHourGlass; Dbxpress::_di_ISQLMetaData FSQLMetaData; BOOL FSupportsMultiTrans; TTableScopes FTableScope; Dbxpress::TSQLCallbackEvent FTraceCallbackEvent; int FTraceClientData; BOOL FTransactionsSupported; AnsiString FVendorLib; void __fastcall CheckActive(void); void __fastcall CheckInactive(void); void __fastcall CheckLoginParams(void); void __fastcall ClearConnectionUsers(void); void __fastcall ClearMonitors(void); void __fastcall FreeSchemaTable(TCustomSQLDataSet* DataSet); TSQLConnection* __fastcall GetConnectionForStatement(void); AnsiString __fastcall GetConnectionName(); AnsiString __fastcall GetFDriverRegistryFile(); int __fastcall GetLocaleCode(void); bool __fastcall GetInTransaction(void); AnsiString __fastcall GetLibraryName(); void __fastcall GetLoginParams(Classes::TStrings* LoginParams); AnsiString __fastcall GetQuoteChar(); AnsiString __fastcall GetVendorLib(); void __fastcall Login(Classes::TStrings* LoginParams); TCustomSQLDataSet* __fastcall OpenSchemaTable(TSchemaType eKind, AnsiString SInfo, AnsiString SQualifier = ""); void __fastcall RegisterTraceMonitor(System::TObject* Client); void __fastcall RegisterTraceCallback(bool Value); void __fastcall SetConnectionParams(void); void __fastcall SetConnectionName(AnsiString Value); void __fastcall SetDriverName(AnsiString Value); void __fastcall SetKeepConnection(bool Value); void __fastcall SetParams(Classes::TStrings* Value); void __fastcall SetCursor(int CursorType); void __fastcall SetLocaleCode(int Value); void __fastcall UnregisterTraceMonitor(System::TObject* Client); protected: Word __fastcall Check(Word status); void __fastcall CheckConnection(EConnectFlag eFlag); virtual void __fastcall CheckDisconnect(void); virtual void __fastcall ConnectionOptions(void); virtual void __fastcall DoConnect(void); virtual void __fastcall DoDisconnect(void); virtual bool __fastcall GetConnected(void); HIDESBASE TCustomSQLDataSet* __fastcall GetDataSet(int Index); virtual void __fastcall Loaded(void); void __fastcall LoadSQLDll(void); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); void __fastcall OpenSchema(TSchemaType eKind, AnsiString sInfo, Classes::TStrings* List); void __fastcall SQLError(Word OpStatus, TSQLExceptionType eType, const Dbxpress::_di_ISQLCommand Command = (void *)(0x0)); __property Dbxpress::_di_ISQLConnection Connection = {read=FISQLConnection}; __property AnsiString ConnectionRegistryFile = {read=FConnectionRegistryFile}; __property Dbxpress::_di_ISQLDriver Driver = {read=FSQLDriver}; __property AnsiString DriverRegistryFile = {read=GetFDriverRegistryFile}; __property AnsiString LastError = {read=FLastError, write=FLastError}; __property AnsiString QuoteChar = {read=FQuoteChar}; __property unsigned SQLDllHandle = {read=FSQLDllHandle, write=FSQLDllHandle, nodefault}; public: __fastcall virtual TSQLConnection(Classes::TComponent* AOwner); __fastcall virtual ~TSQLConnection(void); TSQLConnection* __fastcall CloneConnection(void); void __fastcall CloseDataSets(void); void __fastcall Commit(const Dbxpress::TTransactionDesc &TransDesc); int __fastcall Execute(const AnsiString SQL, Db::TParams* Params, void * ResultSet = (void *)(0x0)); unsigned __fastcall ExecuteDirect(const AnsiString SQL); void __fastcall GetFieldNames(const AnsiString TableName, Classes::TStrings* List); void __fastcall GetIndexNames(const AnsiString TableName, Classes::TStrings* List); void __fastcall GetProcedureNames(Classes::TStrings* List); void __fastcall GetProcedureParams(AnsiString ProcedureName, Classes::TList* List); void __fastcall GetTableNames(Classes::TStrings* List, bool SystemTables = false); void __fastcall LoadParamsFromIniFile(AnsiString FFileName = ""); void __fastcall Rollback(const Dbxpress::TTransactionDesc &TransDesc); void __fastcall SetTraceCallbackEvent(Dbxpress::TSQLCallbackEvent Event, int IClientInfo); void __fastcall StartTransaction(const Dbxpress::TTransactionDesc &TransDesc); __property unsigned ActiveStatements = {read=FActiveStatements, nodefault}; __property bool AutoClone = {read=FAutoClone, write=FAutoClone, default=1}; __property TConnectionState ConnectionState = {read=FConnectionState, write=FConnectionState, nodefault}; __property TCustomSQLDataSet* DataSets[int Index] = {read=GetDataSet}; __property bool InTransaction = {read=GetInTransaction, nodefault}; __property int LocaleCode = {read=GetLocaleCode, write=SetLocaleCode, default=0}; __property unsigned MaxStmtsPerConn = {read=FMaxStmtsPerConn, nodefault}; __property Dbxpress::_di_ISQLMetaData MetaData = {read=FSQLMetaData}; __property bool ParamsLoaded = {read=FParamsLoaded, write=FParamsLoaded, nodefault}; __property Dbxpress::_di_ISQLConnection SQLConnection = {read=FISQLConnection, write=FISQLConnection}; __property bool SQLHourGlass = {read=FSQLHourGlass, write=FSQLHourGlass, default=1}; __property Dbxpress::TSQLCallbackEvent TraceCallbackEvent = {read=FTraceCallbackEvent}; __property BOOL TransactionsSupported = {read=FTransactionsSupported, nodefault}; __published: __property Connected = {default=0}; __property AnsiString ConnectionName = {read=GetConnectionName, write=SetConnectionName}; __property AnsiString DriverName = {read=FDriverName, write=SetDriverName}; __property AnsiString GetDriverFunc = {read=FGetDriverFunc, write=FGetDriverFunc}; __property bool KeepConnection = {read=FKeepConnection, write=SetKeepConnection, default=1}; __property AnsiString LibraryName = {read=GetLibraryName, write=FLibraryName}; __property bool LoadParamsOnConnect = {read=FLoadParamsOnConnect, write=FLoadParamsOnConnect, default=0}; __property LoginPrompt = {default=1}; __property Classes::TStrings* Params = {read=FParams, write=SetParams}; __property TTableScopes TableScope = {read=FTableScope, write=FTableScope, default=12}; __property AnsiString VendorLib = {read=GetVendorLib, write=FVendorLib}; __property AfterConnect ; __property AfterDisconnect ; __property BeforeConnect ; __property BeforeDisconnect ; __property TSQLConnectionLoginEvent OnLogin = {read=FOnLogin, write=FOnLogin}; }; #pragma option push -b- enum TSQLCommandType { ctQuery, ctTable, ctStoredProc }; #pragma option pop #pragma pack(push, 4) struct TSQLSchemaInfo { TSchemaType FType; AnsiString ObjectName; AnsiString Pattern; } ; #pragma pack(pop) typedef DynamicArray<Dbxpress::FLDDesc > TFieldDescList; class PASCALIMPLEMENTATION TCustomSQLDataSet : public Db::TDataSet { typedef Db::TDataSet inherited; private: DynamicArray<Byte > FBlobBuffer; char *FCalcFieldsBuffer; bool FCheckRowsAffected; TSQLConnection* FClonedConnection; AnsiString FCommandText; TSQLCommandType FCommandType; unsigned FCurrentBlobSize; Db::TDataLink* FDataLink; AnsiString FDesignerData; char *FFieldBuffer; bool FGetNextRecordSet; Db::TIndexDefs* FIndexDefs; bool FIndexDefsLoaded; AnsiString FLastError; int FMaxBlobSize; unsigned FMaxColSize; AnsiString FNativeCommand; bool FNoMetadata; bool FParamCheck; int FParamCount; Db::TParams* FParams; bool FPrepared; Classes::TList* FProcParams; int FRecords; int FRowsAffected; TSQLSchemaInfo FSchemaInfo; AnsiString FSortFieldNames; Dbxpress::_di_ISQLCommand FSQLCommand; TSQLConnection* FSQLConnection; Dbxpress::_di_ISQLCursor FSQLCursor; bool FStatementOpen; short FTransactionLevel; bool __fastcall CheckFieldNames(const AnsiString FieldNames); void __fastcall CheckConnection(EConnectFlag eFlag); AnsiString __fastcall CheckDetail(AnsiString SQL); void __fastcall CheckStatement(bool ForSchema = false); bool __fastcall GetCalculatedField(Db::TField* Field, void * &Buffer); TCustomSQLDataSet* __fastcall GetDataSetFromSQL(AnsiString TableName); Classes::TList* __fastcall GetProcParams(void); TSQLConnection* __fastcall GetInternalConnection(void); virtual int __fastcall GetObjectProcParamCount(void); virtual int __fastcall GetParamCount(void); virtual AnsiString __fastcall GetQueryFromType(); int __fastcall GetRowsAffected(void); void __fastcall InitBuffers(void); void __fastcall LoadFieldDef(Word FieldID, Dbxpress::FLDDesc &FldDesc); void __fastcall ReadDesignerData(Classes::TReader* Reader); void __fastcall RefreshParams(void); virtual void __fastcall SetConnection(const TSQLConnection* Value); void __fastcall SetCurrentBlobSize(unsigned Value); void __fastcall SetDataSource(Db::TDataSource* Value); void __fastcall SetParameters(const Db::TParams* Value); void __fastcall SetParamsFromProcedure(void); void __fastcall SetParamsFromSQL(Db::TDataSet* DataSet, bool bFromFields); void __fastcall SetPrepared(bool Value); virtual void __fastcall SetCommandType(const TSQLCommandType Value); void __fastcall WriteDesignerData(Classes::TWriter* Writer); protected: virtual void __fastcall PSEndTransaction(bool Commit); virtual void __fastcall PSExecute(void); virtual int __fastcall PSExecuteStatement(const AnsiString ASQL, Db::TParams* AParams, void * ResultSet = (void *)(0x0)); virtual void __fastcall PSGetAttributes(Classes::TList* List); virtual Db::TIndexDef* __fastcall PSGetDefaultOrder(void); virtual AnsiString __fastcall PSGetKeyFields(); virtual Db::TIndexDefs* __fastcall PSGetIndexDefs(Db::TIndexOptions IndexTypes); virtual Db::TParams* __fastcall PSGetParams(void); virtual AnsiString __fastcall PSGetQuoteChar(); virtual AnsiString __fastcall PSGetTableName(); virtual Db::EUpdateError* __fastcall PSGetUpdateException(Sysutils::Exception* E, Db::EUpdateError* Prev); virtual bool __fastcall PSInTransaction(void); virtual bool __fastcall PSIsSQLBased(void); virtual bool __fastcall PSIsSQLSupported(void); virtual void __fastcall PSReset(void); virtual void __fastcall PSSetCommandText(const AnsiString ACommandText); virtual void __fastcall PSSetParams(Db::TParams* AParams); virtual void __fastcall PSStartTransaction(void); virtual bool __fastcall PSUpdateRecord(Db::TUpdateKind UpdateKind, Db::TDataSet* Delta); virtual void __fastcall InternalClose(void); virtual void __fastcall InternalHandleException(void); virtual void __fastcall InternalInitFieldDefs(void); virtual void __fastcall InternalOpen(void); virtual bool __fastcall IsCursorOpen(void); void __fastcall AddFieldDesc(TFieldDescList FieldDescs, int DescNo, int &FieldID, Classes::TBits* RequiredFields, Db::TFieldDefs* FieldDefs); void __fastcall AddIndexDefs(TCustomSQLDataSet* SourceDS, AnsiString IndexName = ""); Word __fastcall Check(Word status); void __fastcall CheckPrepareError(void); void __fastcall ClearIndexDefs(void); virtual void __fastcall CloseCursor(void); void __fastcall CloseStatement(void); virtual void __fastcall DefineProperties(Classes::TFiler* Filer); virtual int __fastcall ExecSQL(bool ExecDirect = false); void __fastcall ExecuteStatement(void); void __fastcall FreeCursor(void); void __fastcall FreeBuffers(void); void __fastcall FreeStatement(void); virtual bool __fastcall GetCanModify(void); virtual Db::TDataSource* __fastcall GetDataSource(void); void __fastcall GetObjectTypeNames(Db::TFields* Fields); void __fastcall GetOutputParams(Classes::TList* AProcParams); virtual Db::TGetResult __fastcall GetRecord(char * Buffer, Db::TGetMode GetMode, bool DoCheck); AnsiString __fastcall GetSortFieldNames(); virtual void __fastcall InitRecord(char * Buffer); virtual void __fastcall InternalRefresh(void); virtual void __fastcall Loaded(void); virtual void __fastcall OpenCursor(bool InfoQuery); virtual void __fastcall OpenSchema(void); virtual void __fastcall PrepareStatement(void); void __fastcall PropertyChanged(void); virtual void __fastcall SetBufListSize(int Value); virtual void __fastcall SetCommandText(const AnsiString Value); virtual void __fastcall SetFieldData(Db::TField* Field, void * Buffer)/* overload */; void __fastcall SetParamsFromCursor(void); void __fastcall SetSortFieldNames(AnsiString Value); void __fastcall SQLError(Word OpStatus, TSQLExceptionType eType); virtual void __fastcall UpdateIndexDefs(void); __property Db::TBlobByteData BlobBuffer = {read=FBlobBuffer, write=FBlobBuffer}; __property unsigned CurrentBlobSize = {read=FCurrentBlobSize, write=SetCurrentBlobSize, nodefault}; __property Db::TDataLink* DataLink = {read=FDataLink}; __property TSQLConnection* InternalConnection = {read=GetInternalConnection}; __property AnsiString LastError = {read=FLastError, write=FLastError}; __property AnsiString NativeCommand = {read=FNativeCommand, write=FNativeCommand}; __property Classes::TList* ProcParams = {read=GetProcParams, write=FProcParams}; __property int RowsAffected = {read=GetRowsAffected, nodefault}; void __fastcall SetMaxBlobSize(int MaxSize); void __fastcall SetFCommandText(const AnsiString Value); __property int ParamCount = {read=GetParamCount, nodefault}; __property TSQLSchemaInfo SchemaInfo = {read=FSchemaInfo, write=FSchemaInfo}; __property AnsiString CommandText = {read=FCommandText, write=SetCommandText}; __property TSQLCommandType CommandType = {read=FCommandType, write=SetCommandType, default=0}; __property Db::TDataSource* DataSource = {read=GetDataSource, write=SetDataSource}; __property int MaxBlobSize = {read=FMaxBlobSize, write=SetMaxBlobSize, default=-1}; virtual int __fastcall GetRecordCount(void); __property Db::TParams* Params = {read=FParams, write=SetParameters}; __property bool ParamCheck = {read=FParamCheck, write=FParamCheck, default=1}; __property AnsiString SortFieldNames = {read=GetSortFieldNames, write=SetSortFieldNames}; public: __fastcall virtual TCustomSQLDataSet(Classes::TComponent* AOwner); __fastcall virtual ~TCustomSQLDataSet(void); virtual Classes::TStream* __fastcall CreateBlobStream(Db::TField* Field, Db::TBlobStreamMode Mode); virtual int __fastcall GetBlobFieldData(int FieldNo, Db::TBlobByteData &Buffer); virtual void __fastcall GetDetailLinkFields(Classes::TList* MasterFields, Classes::TList* DetailFields); virtual bool __fastcall GetFieldData(int FieldNo, void * Buffer)/* overload */; virtual bool __fastcall GetFieldData(Db::TField* Field, void * Buffer)/* overload */; int __fastcall GetKeyFieldNames(Classes::TStrings* List); virtual AnsiString __fastcall GetQuoteChar(); Db::TParam* __fastcall ParamByName(const AnsiString Value); __property Db::TIndexDefs* IndexDefs = {read=FIndexDefs, write=FIndexDefs}; virtual bool __fastcall IsSequenced(void); void __fastcall SetSchemaInfo(TSchemaType SchemaType, AnsiString SchemaObjectName, AnsiString SchemaPattern); __property bool Prepared = {read=FPrepared, write=SetPrepared, default=0}; __property AnsiString DesignerData = {read=FDesignerData, write=FDesignerData}; __property int RecordCount = {read=GetRecordCount, nodefault}; __property short TransactionLevel = {read=FTransactionLevel, write=FTransactionLevel, default=0}; __published: __property Active = {default=0}; __property bool NoMetadata = {read=FNoMetadata, write=FNoMetadata, default=0}; __property ObjectView = {default=0}; __property BeforeOpen ; __property AfterOpen ; __property BeforeClose ; __property AfterClose ; __property BeforeScroll ; __property AfterScroll ; __property BeforeRefresh ; __property AfterRefresh ; __property OnCalcFields ; __property TSQLConnection* SQLConnection = {read=FSQLConnection, write=SetConnection}; /* Hoisted overloads: */ protected: inline void __fastcall SetFieldData(Db::TField* Field, void * Buffer, bool NativeFormat){ TDataSet::SetFieldData(Field, Buffer, NativeFormat); } public: inline bool __fastcall GetFieldData(Db::TField* Field, void * Buffer, bool NativeFormat){ return TDataSet::GetFieldData(Field, Buffer, NativeFormat); } }; class PASCALIMPLEMENTATION TSQLBlobStream : public Classes::TMemoryStream { typedef Classes::TMemoryStream inherited; private: TCustomSQLDataSet* FDataSet; Db::TBlobField* FField; int FFieldNo; public: __fastcall TSQLBlobStream(Db::TBlobField* Field, Db::TBlobStreamMode Mode); __fastcall virtual ~TSQLBlobStream(void); void __fastcall ReadBlobData(void); }; #pragma option push -b- enum TConnectionUserType { eUserMonitor, eUserDataSet }; #pragma option pop struct SQLTRACEDesc; typedef SQLTRACEDesc *pSQLTRACEDesc; #pragma pack(push, 1) struct SQLTRACEDesc { char pszTrace[1024]; int eTraceCat; int ClientData; Word uTotalMsgLen; } ; #pragma pack(pop) typedef void __fastcall (__closure *TTraceEvent)(System::TObject* Sender, pSQLTRACEDesc CBInfo, bool &LogTrace); typedef void __fastcall (__closure *TTraceLogEvent)(System::TObject* Sender, pSQLTRACEDesc CBInfo); class DELPHICLASS TSQLMonitor; class PASCALIMPLEMENTATION TSQLMonitor : public Classes::TComponent { typedef Classes::TComponent inherited; private: bool FActive; bool FAutoSave; AnsiString FFileName; bool FKeepConnection; int FMaxTraceCount; TTraceEvent FOnTrace; TTraceLogEvent FOnLogTrace; TSQLConnection* FSQLConnection; bool FStreamedActive; TSQLTraceFlags FTraceFlags; Classes::TStrings* FTraceList; void __fastcall CheckInactive(void); int __fastcall GetTraceCount(void); protected: Dbxpress::CBRType __stdcall InvokeCallBack(int CallType, void * CBInfo); void __fastcall SetActive(bool Value); void __fastcall SetSQLConnection(TSQLConnection* Value); void __fastcall SetStreamedActive(void); void __fastcall SetTraceList(Classes::TStrings* Value); void __fastcall SetFileName(const AnsiString Value); void __fastcall SwitchConnection(const TSQLConnection* Value); public: __fastcall virtual TSQLMonitor(Classes::TComponent* AOwner); __fastcall virtual ~TSQLMonitor(void); void __fastcall LoadFromFile(AnsiString AFileName); void __fastcall SaveToFile(AnsiString AFileName); __property int MaxTraceCount = {read=FMaxTraceCount, write=FMaxTraceCount, nodefault}; __property int TraceCount = {read=GetTraceCount, nodefault}; __published: __property bool Active = {read=FActive, write=SetActive, default=0}; __property bool AutoSave = {read=FAutoSave, write=FAutoSave, default=0}; __property AnsiString FileName = {read=FFileName, write=SetFileName}; __property TTraceLogEvent OnLogTrace = {read=FOnLogTrace, write=FOnLogTrace}; __property TTraceEvent OnTrace = {read=FOnTrace, write=FOnTrace}; __property Classes::TStrings* TraceList = {read=FTraceList, write=SetTraceList, stored=false}; __property TSQLConnection* SQLConnection = {read=FSQLConnection, write=SetSQLConnection}; }; typedef void *TLocale; typedef void __fastcall (__closure *TLoginEvent)(System::TObject* Sender, AnsiString Username, AnsiString Password); typedef void __fastcall (__closure *TConnectChangeEvent)(System::TObject* Sender, bool Connecting); class DELPHICLASS TSQLDataLink; class PASCALIMPLEMENTATION TSQLDataLink : public Db::TDetailDataLink { typedef Db::TDetailDataLink inherited; private: TCustomSQLDataSet* FSQLDataSet; protected: virtual void __fastcall ActiveChanged(void); virtual void __fastcall CheckBrowseMode(void); virtual Db::TDataSet* __fastcall GetDetailDataSet(void); virtual void __fastcall RecordChanged(Db::TField* Field); public: __fastcall TSQLDataLink(TCustomSQLDataSet* ADataSet); public: #pragma option push -w-inl /* TDataLink.Destroy */ inline __fastcall virtual ~TSQLDataLink(void) { } #pragma option pop }; class DELPHICLASS TSQLDataSet; class PASCALIMPLEMENTATION TSQLDataSet : public TCustomSQLDataSet { typedef TCustomSQLDataSet inherited; public: __fastcall virtual TSQLDataSet(Classes::TComponent* AOwner); virtual int __fastcall ExecSQL(bool ExecDirect = false); __published: __property CommandText ; __property CommandType = {default=0}; __property DataSource ; __property MaxBlobSize = {default=-1}; __property ParamCheck = {default=1}; __property Params ; __property SortFieldNames ; public: #pragma option push -w-inl /* TCustomSQLDataSet.Destroy */ inline __fastcall virtual ~TSQLDataSet(void) { } #pragma option pop }; class DELPHICLASS TSQLQuery; class PASCALIMPLEMENTATION TSQLQuery : public TCustomSQLDataSet { typedef TCustomSQLDataSet inherited; private: Classes::TStrings* FSQL; AnsiString FText; void __fastcall QueryChanged(System::TObject* Sender); void __fastcall SetSQL(Classes::TStrings* Value); public: __fastcall virtual TSQLQuery(Classes::TComponent* AOwner); __fastcall virtual ~TSQLQuery(void); virtual int __fastcall ExecSQL(bool ExecDirect = false); virtual void __fastcall PrepareStatement(void); __property RowsAffected ; __property AnsiString Text = {read=FText}; __published: __property DataSource ; __property MaxBlobSize = {default=-1}; __property ParamCheck = {default=1}; __property Params ; __property Classes::TStrings* SQL = {read=FSQL, write=SetSQL}; }; class DELPHICLASS TSQLStoredProc; class PASCALIMPLEMENTATION TSQLStoredProc : public TCustomSQLDataSet { typedef TCustomSQLDataSet inherited; private: AnsiString FStoredProcName; void __fastcall SetStoredProcName(AnsiString Value); public: __fastcall virtual TSQLStoredProc(Classes::TComponent* AOwner); virtual int __fastcall ExecProc(void); TCustomSQLDataSet* __fastcall NextRecordSet(void); virtual void __fastcall PrepareStatement(void); __published: __property MaxBlobSize = {default=-1}; __property ParamCheck = {default=1}; __property Params ; __property AnsiString StoredProcName = {read=FStoredProcName, write=SetStoredProcName}; public: #pragma option push -w-inl /* TCustomSQLDataSet.Destroy */ inline __fastcall virtual ~TSQLStoredProc(void) { } #pragma option pop }; class DELPHICLASS TSQLTable; class PASCALIMPLEMENTATION TSQLTable : public TCustomSQLDataSet { typedef TCustomSQLDataSet inherited; private: bool FIsDetail; Classes::TList* FIndexFields; AnsiString FIndexFieldNames; AnsiString FIndexName; Db::TMasterDataLink* FMasterLink; AnsiString FTableName; int FIndexFieldCount; void __fastcall AddParamsToQuery(void); AnsiString __fastcall GetMasterFields(); Db::TField* __fastcall GetIndexField(int Index); int __fastcall GetIndexFieldCount(void); int __fastcall RefreshIndexFields(void); void __fastcall SetIndexFieldNames(AnsiString Value); void __fastcall SetIndexName(AnsiString Value); void __fastcall SetMasterFields(AnsiString Value); void __fastcall SetTableName(AnsiString Value); virtual AnsiString __fastcall GetQueryFromType(); HIDESBASE void __fastcall SetDataSource(Db::TDataSource* Value); protected: virtual void __fastcall OpenCursor(bool InfoQuery); void __fastcall SetIndexField(int Index, Db::TField* Value); __property Db::TMasterDataLink* MasterLink = {read=FMasterLink}; public: __fastcall virtual TSQLTable(Classes::TComponent* AOwner); __fastcall virtual ~TSQLTable(void); void __fastcall DeleteRecords(void); void __fastcall GetIndexNames(Classes::TStrings* List); virtual void __fastcall PrepareStatement(void); __property Db::TField* IndexFields[int Index] = {read=GetIndexField, write=SetIndexField}; __property int IndexFieldCount = {read=GetIndexFieldCount, nodefault}; __published: __property Active = {default=0}; __property AnsiString IndexFieldNames = {read=FIndexFieldNames, write=SetIndexFieldNames}; __property AnsiString IndexName = {read=FIndexName, write=SetIndexName}; __property AnsiString MasterFields = {read=GetMasterFields, write=SetMasterFields}; __property Db::TDataSource* MasterSource = {read=GetDataSource, write=SetDataSource}; __property MaxBlobSize = {default=-1}; __property AnsiString TableName = {read=FTableName, write=SetTableName}; }; //-- var, const, procedure --------------------------------------------------- #define SSelect "select" #define SSelectStar " select * " #define SSelectStarFrom " select * from " #define SWhere " where " #define SAnd " and " #define SOrderBy " order by " static const char SParam = '\x3f'; static const Shortint DefaultCursor = 0x0; static const Shortint HourGlassCursor = 0xfffffff5; static const Shortint DefaultMaxBlobSize = 0xffffffff; static const Shortint DefaultRowsetSize = 0x14; static const Word TErrorMessageSize = 0x800; extern PACKAGE Byte FldTypeMap[38]; extern PACKAGE Word FldSubTypeMap[38]; extern PACKAGE Db::TFieldType DataTypeMap[26]; extern PACKAGE Db::TFieldType BlobTypeMap[15]; extern PACKAGE Word __stdcall (*GetDriver)(char * SVendorLib, char * SResourceFile, /* out */ void *Obj); extern PACKAGE unsigned DllHandle; extern PACKAGE HRESULT __stdcall (*DllGetClassObject)(const GUID &CLSID, const GUID &IID, void *Obj); extern PACKAGE AnsiString __fastcall GetDriverRegistryFile(bool DesignMode = false); extern PACKAGE AnsiString __fastcall GetConnectionRegistryFile(bool DesignMode = false); extern PACKAGE void __fastcall GetDriverNames(Classes::TStrings* List, bool DesignMode = true); extern PACKAGE void __fastcall GetConnectionNames(Classes::TStrings* List, AnsiString Driver = "", bool DesignMode = true); extern PACKAGE void __fastcall FreeProcParams(Classes::TList* &ProcParams); extern PACKAGE void __fastcall LoadParamListItems(Db::TParams* Params, Classes::TList* ProcParams); extern PACKAGE void __fastcall RegisterDbXpressLib(void * GetClassProc); } /* namespace Sqlexpr */ using namespace Sqlexpr; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // SqlExpr
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 686 ] ] ]
0d11a7ce1d7f3044da6f5987a7735ee29ace62ec
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_gui_extra/code_editor/juce_CodeDocument.cpp
1ca11f84250f30b37f288e42575be95dc7827cac
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
28,184
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== class CodeDocumentLine { public: CodeDocumentLine (const String::CharPointerType& line_, const int lineLength_, const int numNewLineChars, const int lineStartInFile_) : line (line_, (size_t) lineLength_), lineStartInFile (lineStartInFile_), lineLength (lineLength_), lineLengthWithoutNewLines (lineLength_ - numNewLineChars) { } static void createLines (Array <CodeDocumentLine*>& newLines, const String& text) { String::CharPointerType t (text.getCharPointer()); int charNumInFile = 0; bool finished = false; while (! (finished || t.isEmpty())) { String::CharPointerType startOfLine (t); int startOfLineInFile = charNumInFile; int lineLength = 0; int numNewLineChars = 0; for (;;) { const juce_wchar c = t.getAndAdvance(); if (c == 0) { finished = true; break; } ++charNumInFile; ++lineLength; if (c == '\r') { ++numNewLineChars; if (*t == '\n') { ++t; ++charNumInFile; ++lineLength; ++numNewLineChars; } break; } if (c == '\n') { ++numNewLineChars; break; } } newLines.add (new CodeDocumentLine (startOfLine, lineLength, numNewLineChars, startOfLineInFile)); } jassert (charNumInFile == text.length()); } bool endsWithLineBreak() const noexcept { return lineLengthWithoutNewLines != lineLength; } void updateLength() noexcept { lineLength = 0; lineLengthWithoutNewLines = 0; String::CharPointerType t (line.getCharPointer()); for (;;) { const juce_wchar c = t.getAndAdvance(); if (c == 0) break; ++lineLength; if (c != '\n' && c != '\r') lineLengthWithoutNewLines = lineLength; } } String line; int lineStartInFile, lineLength, lineLengthWithoutNewLines; }; //============================================================================== CodeDocument::Iterator::Iterator (CodeDocument* const document_) : document (document_), charPointer (nullptr), line (0), position (0) { } CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other) : document (other.document), charPointer (other.charPointer), line (other.line), position (other.position) { } CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) noexcept { document = other.document; charPointer = other.charPointer; line = other.line; position = other.position; return *this; } CodeDocument::Iterator::~Iterator() noexcept { } juce_wchar CodeDocument::Iterator::nextChar() { for (;;) { if (charPointer.getAddress() == nullptr) { CodeDocumentLine* const l = document->lines[line]; if (l == nullptr) return 0; charPointer = l->line.getCharPointer(); } const juce_wchar result = charPointer.getAndAdvance(); if (result == 0) { ++line; charPointer = nullptr; } else { ++position; return result; } } } void CodeDocument::Iterator::skip() { nextChar(); } void CodeDocument::Iterator::skipToEndOfLine() { if (charPointer.getAddress() == nullptr) { CodeDocumentLine* const l = document->lines[line]; if (l == nullptr) return; charPointer = l->line.getCharPointer(); } position += (int) charPointer.length(); ++line; charPointer = nullptr; } juce_wchar CodeDocument::Iterator::peekNextChar() const { if (charPointer.getAddress() == nullptr) { CodeDocumentLine* const l = document->lines[line]; if (l == nullptr) return 0; charPointer = l->line.getCharPointer(); } const juce_wchar c = *charPointer; if (c != 0) return c; CodeDocumentLine* const l = document->lines [line + 1]; return l == nullptr ? 0 : l->line[0]; } void CodeDocument::Iterator::skipWhitespace() { while (CharacterFunctions::isWhitespace (peekNextChar())) skip(); } bool CodeDocument::Iterator::isEOF() const noexcept { return charPointer.getAddress() == nullptr && line >= document->lines.size(); } //============================================================================== CodeDocument::Position::Position() noexcept : owner (0), characterPos (0), line (0), indexInLine (0), positionMaintained (false) { } CodeDocument::Position::Position (const CodeDocument* const ownerDocument, const int line_, const int indexInLine_) noexcept : owner (const_cast <CodeDocument*> (ownerDocument)), characterPos (0), line (line_), indexInLine (indexInLine_), positionMaintained (false) { setLineAndIndex (line_, indexInLine_); } CodeDocument::Position::Position (const CodeDocument* const ownerDocument, const int characterPos_) noexcept : owner (const_cast <CodeDocument*> (ownerDocument)), positionMaintained (false) { setPosition (characterPos_); } CodeDocument::Position::Position (const Position& other) noexcept : owner (other.owner), characterPos (other.characterPos), line (other.line), indexInLine (other.indexInLine), positionMaintained (false) { jassert (*this == other); } CodeDocument::Position::~Position() { setPositionMaintained (false); } CodeDocument::Position& CodeDocument::Position::operator= (const Position& other) { if (this != &other) { const bool wasPositionMaintained = positionMaintained; if (owner != other.owner) setPositionMaintained (false); owner = other.owner; line = other.line; indexInLine = other.indexInLine; characterPos = other.characterPos; setPositionMaintained (wasPositionMaintained); jassert (*this == other); } return *this; } bool CodeDocument::Position::operator== (const Position& other) const noexcept { jassert ((characterPos == other.characterPos) == (line == other.line && indexInLine == other.indexInLine)); return characterPos == other.characterPos && line == other.line && indexInLine == other.indexInLine && owner == other.owner; } bool CodeDocument::Position::operator!= (const Position& other) const noexcept { return ! operator== (other); } void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine) { jassert (owner != nullptr); if (owner->lines.size() == 0) { line = 0; indexInLine = 0; characterPos = 0; } else { if (newLineNum >= owner->lines.size()) { line = owner->lines.size() - 1; CodeDocumentLine* const l = owner->lines.getUnchecked (line); jassert (l != nullptr); indexInLine = l->lineLengthWithoutNewLines; characterPos = l->lineStartInFile + indexInLine; } else { line = jmax (0, newLineNum); CodeDocumentLine* const l = owner->lines.getUnchecked (line); jassert (l != nullptr); if (l->lineLengthWithoutNewLines > 0) indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine); else indexInLine = 0; characterPos = l->lineStartInFile + indexInLine; } } } void CodeDocument::Position::setPosition (const int newPosition) { jassert (owner != nullptr); line = 0; indexInLine = 0; characterPos = 0; if (newPosition > 0) { int lineStart = 0; int lineEnd = owner->lines.size(); for (;;) { if (lineEnd - lineStart < 4) { for (int i = lineStart; i < lineEnd; ++i) { CodeDocumentLine* const l = owner->lines.getUnchecked (i); int index = newPosition - l->lineStartInFile; if (index >= 0 && (index < l->lineLength || i == lineEnd - 1)) { line = i; indexInLine = jmin (l->lineLengthWithoutNewLines, index); characterPos = l->lineStartInFile + indexInLine; } } break; } else { const int midIndex = (lineStart + lineEnd + 1) / 2; CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex); if (newPosition >= mid->lineStartInFile) lineStart = midIndex; else lineEnd = midIndex; } } } } void CodeDocument::Position::moveBy (int characterDelta) { jassert (owner != nullptr); if (characterDelta == 1) { setPosition (getPosition()); // If moving right, make sure we don't get stuck between the \r and \n characters.. if (line < owner->lines.size()) { CodeDocumentLine* const l = owner->lines.getUnchecked (line); if (indexInLine + characterDelta < l->lineLength && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1) ++characterDelta; } } setPosition (characterPos + characterDelta); } const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const { CodeDocument::Position p (*this); p.moveBy (characterDelta); return p; } const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const { CodeDocument::Position p (*this); p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine()); return p; } const juce_wchar CodeDocument::Position::getCharacter() const { const CodeDocumentLine* const l = owner->lines [line]; return l == nullptr ? 0 : l->line [getIndexInLine()]; } String CodeDocument::Position::getLineText() const { const CodeDocumentLine* const l = owner->lines [line]; return l == nullptr ? String::empty : l->line; } void CodeDocument::Position::setPositionMaintained (const bool isMaintained) { if (isMaintained != positionMaintained) { positionMaintained = isMaintained; if (owner != nullptr) { if (isMaintained) { jassert (! owner->positionsToMaintain.contains (this)); owner->positionsToMaintain.add (this); } else { // If this happens, you may have deleted the document while there are Position objects that are still using it... jassert (owner->positionsToMaintain.contains (this)); owner->positionsToMaintain.removeValue (this); } } } } //============================================================================== CodeDocument::CodeDocument() : undoManager (std::numeric_limits<int>::max(), 10000), currentActionIndex (0), indexOfSavedState (-1), maximumLineLength (-1), newLineChars ("\r\n") { } CodeDocument::~CodeDocument() { } String CodeDocument::getAllContent() const { return getTextBetween (Position (this, 0), Position (this, lines.size(), 0)); } String CodeDocument::getTextBetween (const Position& start, const Position& end) const { if (end.getPosition() <= start.getPosition()) return String::empty; const int startLine = start.getLineNumber(); const int endLine = end.getLineNumber(); if (startLine == endLine) { CodeDocumentLine* const line = lines [startLine]; return (line == nullptr) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine()); } MemoryOutputStream mo; mo.preallocate ((size_t) (end.getPosition() - start.getPosition() + 4)); const int maxLine = jmin (lines.size() - 1, endLine); for (int i = jmax (0, startLine); i <= maxLine; ++i) { const CodeDocumentLine* line = lines.getUnchecked(i); int len = line->lineLength; if (i == startLine) { const int index = start.getIndexInLine(); mo << line->line.substring (index, len); } else if (i == endLine) { len = end.getIndexInLine(); mo << line->line.substring (0, len); } else { mo << line->line; } } return mo.toString(); } int CodeDocument::getNumCharacters() const noexcept { const CodeDocumentLine* const lastLine = lines.getLast(); return (lastLine == nullptr) ? 0 : lastLine->lineStartInFile + lastLine->lineLength; } String CodeDocument::getLine (const int lineIndex) const noexcept { const CodeDocumentLine* const line = lines [lineIndex]; return (line == nullptr) ? String::empty : line->line; } int CodeDocument::getMaximumLineLength() noexcept { if (maximumLineLength < 0) { maximumLineLength = 0; for (int i = lines.size(); --i >= 0;) maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength); } return maximumLineLength; } void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition) { remove (startPosition.getPosition(), endPosition.getPosition(), true); } void CodeDocument::insertText (const Position& position, const String& text) { insert (text, position.getPosition(), true); } void CodeDocument::replaceAllContent (const String& newContent) { remove (0, getNumCharacters(), true); insert (newContent, 0, true); } bool CodeDocument::loadFromStream (InputStream& stream) { remove (0, getNumCharacters(), false); insert (stream.readEntireStreamAsString(), 0, false); setSavePoint(); clearUndoHistory(); return true; } bool CodeDocument::writeToStream (OutputStream& stream) { for (int i = 0; i < lines.size(); ++i) { String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string. const char* utf8 = temp.toUTF8(); if (! stream.write (utf8, (int) strlen (utf8))) return false; } return true; } void CodeDocument::setNewLineCharacters (const String& newLineChars_) noexcept { jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r"); newLineChars = newLineChars_; } void CodeDocument::newTransaction() { undoManager.beginNewTransaction (String::empty); } void CodeDocument::undo() { newTransaction(); undoManager.undo(); } void CodeDocument::redo() { undoManager.redo(); } void CodeDocument::clearUndoHistory() { undoManager.clearUndoHistory(); } void CodeDocument::setSavePoint() noexcept { indexOfSavedState = currentActionIndex; } bool CodeDocument::hasChangedSinceSavePoint() const noexcept { return currentActionIndex != indexOfSavedState; } //============================================================================== namespace CodeDocumentHelpers { int getCharacterType (const juce_wchar character) noexcept { return (CharacterFunctions::isLetterOrDigit (character) || character == '_') ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1); } } const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const noexcept { Position p (position); const int maxDistance = 256; int i = 0; while (i < maxDistance && CharacterFunctions::isWhitespace (p.getCharacter()) && (i == 0 || (p.getCharacter() != '\n' && p.getCharacter() != '\r'))) { ++i; p.moveBy (1); } if (i == 0) { const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter()); while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter())) { ++i; p.moveBy (1); } while (i < maxDistance && CharacterFunctions::isWhitespace (p.getCharacter()) && (i == 0 || (p.getCharacter() != '\n' && p.getCharacter() != '\r'))) { ++i; p.moveBy (1); } } return p; } const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const noexcept { Position p (position); const int maxDistance = 256; int i = 0; bool stoppedAtLineStart = false; while (i < maxDistance) { const juce_wchar c = p.movedBy (-1).getCharacter(); if (c == '\r' || c == '\n') { stoppedAtLineStart = true; if (i > 0) break; } if (! CharacterFunctions::isWhitespace (c)) break; p.moveBy (-1); ++i; } if (i < maxDistance && ! stoppedAtLineStart) { const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()); while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter())) { p.moveBy (-1); ++i; } } return p; } void CodeDocument::checkLastLineStatus() { while (lines.size() > 0 && lines.getLast()->lineLength == 0 && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak())) { // remove any empty lines at the end if the preceding line doesn't end in a newline. lines.removeLast(); } const CodeDocumentLine* const lastLine = lines.getLast(); if (lastLine != nullptr && lastLine->endsWithLineBreak()) { // check that there's an empty line at the end if the preceding one ends in a newline.. lines.add (new CodeDocumentLine (String::empty.getCharPointer(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength)); } } //============================================================================== void CodeDocument::addListener (CodeDocument::Listener* const listener) noexcept { listeners.add (listener); } void CodeDocument::removeListener (CodeDocument::Listener* const listener) noexcept { listeners.remove (listener); } void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine) { Position startPos (this, startLine, 0); Position endPos (this, endLine, 0); listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos); } //============================================================================== class CodeDocumentInsertAction : public UndoableAction { public: CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) noexcept : owner (owner_), text (text_), insertPos (insertPos_) { } bool perform() { owner.currentActionIndex++; owner.insert (text, insertPos, false); return true; } bool undo() { owner.currentActionIndex--; owner.remove (insertPos, insertPos + text.length(), false); return true; } int getSizeInUnits() { return text.length() + 32; } private: CodeDocument& owner; const String text; int insertPos; JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction); }; void CodeDocument::insert (const String& text, const int insertPos, const bool undoable) { if (text.isEmpty()) return; if (undoable) { undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos)); } else { Position pos (this, insertPos); const int firstAffectedLine = pos.getLineNumber(); int lastAffectedLine = firstAffectedLine + 1; CodeDocumentLine* const firstLine = lines [firstAffectedLine]; String textInsideOriginalLine (text); if (firstLine != nullptr) { const int index = pos.getIndexInLine(); textInsideOriginalLine = firstLine->line.substring (0, index) + textInsideOriginalLine + firstLine->line.substring (index); } maximumLineLength = -1; Array <CodeDocumentLine*> newLines; CodeDocumentLine::createLines (newLines, textInsideOriginalLine); jassert (newLines.size() > 0); CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0); newFirstLine->lineStartInFile = firstLine != nullptr ? firstLine->lineStartInFile : 0; lines.set (firstAffectedLine, newFirstLine); if (newLines.size() > 1) { for (int i = 1; i < newLines.size(); ++i) { CodeDocumentLine* const l = newLines.getUnchecked (i); lines.insert (firstAffectedLine + i, l); } lastAffectedLine = lines.size(); } int i, lineStart = newFirstLine->lineStartInFile; for (i = firstAffectedLine; i < lines.size(); ++i) { CodeDocumentLine* const l = lines.getUnchecked (i); l->lineStartInFile = lineStart; lineStart += l->lineLength; } checkLastLineStatus(); const int newTextLength = text.length(); for (i = 0; i < positionsToMaintain.size(); ++i) { CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i); if (p->getPosition() >= insertPos) p->setPosition (p->getPosition() + newTextLength); } sendListenerChangeMessage (firstAffectedLine, lastAffectedLine); } } //============================================================================== class CodeDocumentDeleteAction : public UndoableAction { public: CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) noexcept : owner (owner_), startPos (startPos_), endPos (endPos_) { removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos), CodeDocument::Position (&owner, endPos)); } bool perform() { owner.currentActionIndex++; owner.remove (startPos, endPos, false); return true; } bool undo() { owner.currentActionIndex--; owner.insert (removedText, startPos, false); return true; } int getSizeInUnits() { return removedText.length() + 32; } private: CodeDocument& owner; int startPos, endPos; String removedText; JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction); }; void CodeDocument::remove (const int startPos, const int endPos, const bool undoable) { if (endPos <= startPos) return; if (undoable) { undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos)); } else { Position startPosition (this, startPos); Position endPosition (this, endPos); maximumLineLength = -1; const int firstAffectedLine = startPosition.getLineNumber(); const int endLine = endPosition.getLineNumber(); int lastAffectedLine = firstAffectedLine + 1; CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine); if (firstAffectedLine == endLine) { firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine()) + firstLine->line.substring (endPosition.getIndexInLine()); firstLine->updateLength(); } else { lastAffectedLine = lines.size(); CodeDocumentLine* const lastLine = lines.getUnchecked (endLine); jassert (lastLine != nullptr); firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine()) + lastLine->line.substring (endPosition.getIndexInLine()); firstLine->updateLength(); int numLinesToRemove = endLine - firstAffectedLine; lines.removeRange (firstAffectedLine + 1, numLinesToRemove); } int i; for (i = firstAffectedLine + 1; i < lines.size(); ++i) { CodeDocumentLine* const l = lines.getUnchecked (i); const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1); l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength; } checkLastLineStatus(); const int totalChars = getNumCharacters(); for (i = 0; i < positionsToMaintain.size(); ++i) { CodeDocument::Position* p = positionsToMaintain.getUnchecked(i); if (p->getPosition() > startPosition.getPosition()) p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos)); if (p->getPosition() > totalChars) p->setPosition (totalChars); } sendListenerChangeMessage (firstAffectedLine, lastAffectedLine); } } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 969 ] ] ]
a216912efed08d3a9d9cad048c4063e700f24195
0bff1a85c6e6f2563f66fc60fc01963254f88691
/src/Document.h
f5522a2987fe324186a041e23752af8b06e8e665
[ "LicenseRef-scancode-scintilla" ]
permissive
djs/notepad2-scintilla
fa4226435cad7235b502a51664c020b8f961d4c0
68a66a4ab32b68eabf4ce54b652521b922cdbb75
refs/heads/master
2016-08-04T01:34:57.200720
2010-05-17T02:30:38
2010-05-17T02:30:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,941
h
// Scintilla source code edit control /** @file Document.h ** Text document that handles notifications, DBCS, styling, words and end of line. **/ // Copyright 1998-2003 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #ifndef DOCUMENT_H #define DOCUMENT_H #ifdef SCI_NAMESPACE namespace Scintilla { #endif /** * A Position is a position within a document between two characters or at the beginning or end. * Sometimes used as a character index where it identifies the character after the position. */ typedef int Position; const Position invalidPosition = -1; /** * The range class represents a range of text in a document. * The two values are not sorted as one end may be more significant than the other * as is the case for the selection where the end position is the position of the caret. * If either position is invalidPosition then the range is invalid and most operations will fail. */ class Range { public: Position start; Position end; Range(Position pos=0) : start(pos), end(pos) { }; Range(Position start_, Position end_) : start(start_), end(end_) { }; bool Valid() const { return (start != invalidPosition) && (end != invalidPosition); } // Is the position within the range? bool Contains(Position pos) const { if (start < end) { return (pos >= start && pos <= end); } else { return (pos <= start && pos >= end); } } // Is the character after pos within the range? bool ContainsCharacter(Position pos) const { if (start < end) { return (pos >= start && pos < end); } else { return (pos < start && pos >= end); } } bool Contains(Range other) const { return Contains(other.start) && Contains(other.end); } bool Overlaps(Range other) const { return Contains(other.start) || Contains(other.end) || other.Contains(start) || other.Contains(end); } }; class DocWatcher; class DocModification; class Document; /** * Interface class for regular expression searching */ class RegexSearchBase { public: virtual ~RegexSearchBase() {} virtual long FindText(Document *doc, int minPos, int maxPos, const char *s, bool caseSensitive, bool word, bool wordStart, int flags, int *length) = 0; ///@return String with the substitutions, must remain valid until the next call or destruction virtual const char *SubstituteByPosition(Document *doc, const char *text, int *length) = 0; }; /// Factory function for RegexSearchBase extern RegexSearchBase *CreateRegexSearch(CharClassify *charClassTable); struct StyledText { size_t length; const char *text; bool multipleStyles; size_t style; const unsigned char *styles; StyledText(size_t length_, const char *text_, bool multipleStyles_, int style_, const unsigned char *styles_) : length(length_), text(text_), multipleStyles(multipleStyles_), style(style_), styles(styles_) { } // Return number of bytes from start to before '\n' or end of text. // Return 1 when start is outside text size_t LineLength(size_t start) const { size_t cur = start; while ((cur < length) && (text[cur] != '\n')) cur++; return cur-start; } size_t StyleAt(size_t i) const { return multipleStyles ? styles[i] : style; } }; class CaseFolder { public: virtual ~CaseFolder() { }; virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed) = 0; }; class CaseFolderTable : public CaseFolder { protected: char mapping[256]; public: CaseFolderTable(); virtual ~CaseFolderTable(); virtual size_t Fold(char *folded, size_t sizeFolded, const char *mixed, size_t lenMixed); void SetTranslation(char ch, char chTranslation); void StandardASCII(); }; /** */ class Document : PerLine { public: /** Used to pair watcher pointer with user data. */ class WatcherWithUserData { public: DocWatcher *watcher; void *userData; WatcherWithUserData() { watcher = 0; userData = 0; } }; enum charClassification { ccSpace, ccNewLine, ccWord, ccPunctuation }; private: int refCount; CellBuffer cb; CharClassify charClass; char stylingMask; int endStyled; int styleClock; int enteredModification; int enteredStyling; int enteredReadOnlyCount; WatcherWithUserData *watchers; int lenWatchers; // ldSize is not real data - it is for dimensions and loops enum lineData { ldMarkers, ldLevels, ldState, ldMargin, ldAnnotation, ldSize }; PerLine *perLineData[ldSize]; bool matchesValid; RegexSearchBase *regex; public: int stylingBits; int stylingBitsMask; int eolMode; /// Can also be SC_CP_UTF8 to enable UTF-8 mode int dbcsCodePage; int tabInChars; int indentInChars; int actualIndentInChars; bool useTabs; bool tabIndents; bool backspaceUnindents; DecorationList decorations; Document(); virtual ~Document(); int AddRef(); int Release(); virtual void Init(); virtual void InsertLine(int line); virtual void RemoveLine(int line); int LineFromPosition(int pos) const; int ClampPositionIntoDocument(int pos); bool IsCrLf(int pos); int LenChar(int pos); bool InGoodUTF8(int pos, int &start, int &end); int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true); // Gateways to modifying document void ModifiedAt(int pos); void CheckReadOnly(); bool DeleteChars(int pos, int len); bool InsertString(int position, const char *s, int insertLength); int Undo(); int Redo(); bool CanUndo() { return cb.CanUndo(); } bool CanRedo() { return cb.CanRedo(); } void DeleteUndoHistory() { cb.DeleteUndoHistory(); } bool SetUndoCollection(bool collectUndo) { return cb.SetUndoCollection(collectUndo); } bool IsCollectingUndo() { return cb.IsCollectingUndo(); } void BeginUndoAction() { cb.BeginUndoAction(); } void EndUndoAction() { cb.EndUndoAction(); } void AddUndoAction(int token, bool mayCoalesce) { cb.AddUndoAction(token, mayCoalesce); } void SetSavePoint(); bool IsSavePoint() { return cb.IsSavePoint(); } const char *BufferPointer() { return cb.BufferPointer(); } int GetLineIndentation(int line); void SetLineIndentation(int line, int indent); int GetLineIndentPosition(int line) const; int GetColumn(int position); int FindColumn(int line, int column); void Indent(bool forwards, int lineBottom, int lineTop); static char *TransformLineEnds(int *pLenOut, const char *s, size_t len, int eolMode); void ConvertLineEnds(int eolModeSet); void SetReadOnly(bool set) { cb.SetReadOnly(set); } bool IsReadOnly() { return cb.IsReadOnly(); } bool InsertChar(int pos, char ch); bool InsertCString(int position, const char *s); void ChangeChar(int pos, char ch); void DelChar(int pos); void DelCharBack(int pos); char CharAt(int position) { return cb.CharAt(position); } void GetCharRange(char *buffer, int position, int lengthRetrieve) { cb.GetCharRange(buffer, position, lengthRetrieve); } char StyleAt(int position) { return cb.StyleAt(position); } int GetMark(int line); int AddMark(int line, int markerNum); void AddMarkSet(int line, int valueSet); void DeleteMark(int line, int markerNum); void DeleteMarkFromHandle(int markerHandle); void DeleteAllMarks(int markerNum); int LineFromHandle(int markerHandle); int LineStart(int line) const; int LineEnd(int line) const; int LineEndPosition(int position) const; bool IsLineEndPosition(int position) const; int VCHomePosition(int position) const; int SetLevel(int line, int level); int GetLevel(int line); void ClearLevels(); int GetLastChild(int lineParent, int level=-1); int GetFoldParent(int line); void Indent(bool forwards); int ExtendWordSelect(int pos, int delta, bool onlyWordCharacters=false); int NextWordStart(int pos, int delta); int NextWordEnd(int pos, int delta); int Length() const { return cb.Length(); } void Allocate(int newSize) { cb.Allocate(newSize); } size_t ExtractChar(int pos, char *bytes); bool MatchesWordOptions(bool word, bool wordStart, int pos, int length); long FindText(int minPos, int maxPos, const char *search, bool caseSensitive, bool word, bool wordStart, bool regExp, int flags, int *length, CaseFolder *pcf); const char *SubstituteByPosition(const char *text, int *length); int LinesTotal() const; void ChangeCase(Range r, bool makeUpperCase); void SetDefaultCharClasses(bool includeWordClass); void SetCharClasses(const unsigned char *chars, CharClassify::cc newCharClass); void SetStylingBits(int bits); void StartStyling(int position, char mask); bool SetStyleFor(int length, char style); bool SetStyles(int length, const char *styles); int GetEndStyled() { return endStyled; } void EnsureStyledTo(int pos); int GetStyleClock() { return styleClock; } void IncrementStyleClock(); void DecorationFillRange(int position, int value, int fillLength); int SetLineState(int line, int state); int GetLineState(int line); int GetMaxLineState(); StyledText MarginStyledText(int line); void MarginSetStyle(int line, int style); void MarginSetStyles(int line, const unsigned char *styles); void MarginSetText(int line, const char *text); int MarginLength(int line) const; void MarginClearAll(); bool AnnotationAny() const; StyledText AnnotationStyledText(int line); void AnnotationSetText(int line, const char *text); void AnnotationSetStyle(int line, int style); void AnnotationSetStyles(int line, const unsigned char *styles); int AnnotationLength(int line) const; int AnnotationLines(int line) const; void AnnotationClearAll(); bool AddWatcher(DocWatcher *watcher, void *userData); bool RemoveWatcher(DocWatcher *watcher, void *userData); const WatcherWithUserData *GetWatchers() const { return watchers; } int GetLenWatchers() const { return lenWatchers; } bool IsWordPartSeparator(char ch); int WordPartLeft(int pos); int WordPartRight(int pos); int ExtendStyleRange(int pos, int delta, bool singleLine = false); bool IsWhiteLine(int line) const; int ParaUp(int pos); int ParaDown(int pos); int IndentSize() { return actualIndentInChars; } int BraceMatch(int position, int maxReStyle); private: CharClassify::cc WordCharClass(unsigned char ch); bool IsWordStartAt(int pos); bool IsWordEndAt(int pos); bool IsWordAt(int start, int end); void NotifyModifyAttempt(); void NotifySavePoint(bool atSavePoint); void NotifyModified(DocModification mh); }; class UndoGroup { Document *pdoc; bool groupNeeded; public: UndoGroup(Document *pdoc_, bool groupNeeded_=true) : pdoc(pdoc_), groupNeeded(groupNeeded_) { if (groupNeeded) { pdoc->BeginUndoAction(); } } ~UndoGroup() { if (groupNeeded) { pdoc->EndUndoAction(); } } bool Needed() const { return groupNeeded; } }; /** * To optimise processing of document modifications by DocWatchers, a hint is passed indicating the * scope of the change. * If the DocWatcher is a document view then this can be used to optimise screen updating. */ class DocModification { public: int modificationType; int position; int length; int linesAdded; /**< Negative if lines deleted. */ const char *text; /**< Only valid for changes to text, not for changes to style. */ int line; int foldLevelNow; int foldLevelPrev; int annotationLinesAdded; int token; DocModification(int modificationType_, int position_=0, int length_=0, int linesAdded_=0, const char *text_=0, int line_=0) : modificationType(modificationType_), position(position_), length(length_), linesAdded(linesAdded_), text(text_), line(line_), foldLevelNow(0), foldLevelPrev(0), annotationLinesAdded(0), token(0) {} DocModification(int modificationType_, const Action &act, int linesAdded_=0) : modificationType(modificationType_), position(act.position), length(act.lenData), linesAdded(linesAdded_), text(act.data), line(0), foldLevelNow(0), foldLevelPrev(0), annotationLinesAdded(0), token(0) {} }; /** * A class that wants to receive notifications from a Document must be derived from DocWatcher * and implement the notification methods. It can then be added to the watcher list with AddWatcher. */ class DocWatcher { public: virtual ~DocWatcher() {} virtual void NotifyModifyAttempt(Document *doc, void *userData) = 0; virtual void NotifySavePoint(Document *doc, void *userData, bool atSavePoint) = 0; virtual void NotifyModified(Document *doc, DocModification mh, void *userData) = 0; virtual void NotifyDeleted(Document *doc, void *userData) = 0; virtual void NotifyStyleNeeded(Document *doc, void *userData, int endPos) = 0; }; #ifdef SCI_NAMESPACE } #endif #endif
[ [ [ 1, 426 ] ] ]
041d83d42b1c9bdf4b65b1a7836f9a2f3c8c64bd
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/01032005/vfs/VFSPlugin_BIN.h
78381d1682bb5c54e6bea1db8b163b2110fe60fa
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
790
h
#ifndef _VFSPLUGIN_BIN_H_ #define _VFSPLUGIN_BIN_H_ #include <vfs/VirtualFS.h> VFSPlugin * CreateBinaryPlugin( Fusion *f ); /** @ingroup VFSPlugin_BIN_Group * @brief File format plugin to read/write unformatted (or preformatted) binary data */ class VFSPlugin_BIN: public VFSPlugin { protected: /** @var BinaryFileInfo *m_fileinfo * @brief Structure to store the unformatted data */ BinaryFileInfo *m_fileinfo; public: VFSPlugin_BIN (); virtual ~VFSPlugin_BIN (); virtual void AddFilter ( VFSFilter *filter ); virtual FileInfo * Read ( unsigned char *buffer, unsigned int length ); virtual char * Write ( FileInfo *data, unsigned int &length ); virtual std::string Type ( void ); }; #endif // #ifndef _VFSPLUGIN_BIN_H_
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 30 ] ] ]
35cffce5dccf0229abf99380104df6775089c2cc
50c10c208dc64d362a02d680388a944f7da16cbc
/Principal/interfazRMN2/instruction_list.cpp
38caf1b7a2aa7ea5909db04ebbbf549114914058
[]
no_license
raulmonti/generador-de-pulsos-2011
c18e9938f9f28651a995677414ebc8d29f0c2dcc
3634a47bcf2fb01cba4d9f8c84928ca2eb60646c
refs/heads/master
2020-04-14T15:09:01.914839
2011-03-23T22:03:20
2011-03-23T22:03:20
33,492,955
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
#include "instruction_list.h" instruction_list::instruction_list(void){ count = 0; } void instruction_list::add (instruction *i){ lista.push_back(i); count++; } unsigned int instruction_list::length (void){ return count; } void instruction_list::std_out_print (unsigned int times){ int i = 0, j = 0; for(j=0;j<times;j++){ for(i=0;i<this->length();i++){ this->nth_item(i)->std_out_print(); } } } instruction* instruction_list::nth_item(unsigned int n){ list<instruction*>::iterator i = lista.begin(); advance(i, n); return *i; } list<instruction*> instruction_list::get_list(void){ return lista; }
[ "[email protected]@d9bf8441-58a9-7046-d6f0-32bbd92d4940" ]
[ [ [ 1, 35 ] ] ]
dc5fe3aed14b6fcad7b057f7d26e6c63962f79bc
8a0a81978126520c0bfa0d2ad6bd1d35236f1aa2
/SegmentationRegional/Dep/qwtplot3d-0.2.7/qwtplot3d/examples/autoswitch/autoswitch.cpp
9936f6272cdb26a8e5e8bd7e06f15e4e65648281
[ "Zlib" ]
permissive
zjucsxxd/BSplineLevelSetRegionalSegmentation
a64b4a096f65736659b6c74dce7cd973815b9a2c
a320ade9386861657476cca7fce97315de5e3e31
refs/heads/master
2021-01-20T23:03:26.244747
2011-12-10T13:10:56
2011-12-10T13:10:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
#include <qapplication.h> #include <qsplitter.h> #include <qtimer.h> #include "autoswitch.h" using namespace Qwt3D; //-------------------------------------------------------------------- // autoswitch.cpp // // Demonstrates autoswitching axes with a cutted saddle as data //-------------------------------------------------------------------- Plot2D::Plot2D(QWidget* pw, int updateinterval) :SurfacePlot(pw) { setRotation(30,0,15); setShift(0.1,0,0); setZoom(0.8); coordinates()->setNumberFont("Courier",8); for (unsigned i=0; i!=coordinates()->axes.size(); ++i) { coordinates()->axes[i].setMajors(7); coordinates()->axes[i].setMinors(4); } coordinates()->axes[Qwt3D::X1].setLabelString("x"); coordinates()->axes[Y1].setLabelString("y"); coordinates()->axes[Z1].setLabelString("z"); coordinates()->axes[X2].setLabelString("x"); coordinates()->axes[Y2].setLabelString("y"); coordinates()->axes[Z2].setLabelString("z"); coordinates()->axes[X3].setLabelString("x"); coordinates()->axes[Y3].setLabelString("y"); coordinates()->axes[Z3].setLabelString("z"); coordinates()->axes[X4].setLabelString("x"); coordinates()->axes[Y4].setLabelString("y"); coordinates()->axes[Z4].setLabelString("z"); QTimer* timer = new QTimer( this ); connect( timer, SIGNAL(timeout()), this, SLOT(rotate()) ); timer->start(updateinterval); } void Plot2D::rotate() { int prec = 3; setRotation( (int(prec*xRotation() + 2) % (360*prec))/double(prec), (int(prec*yRotation() + 2) % (360*prec))/double(prec), (int(prec*zRotation() + 2) % (360*prec))/double(prec) ); } int main(int argc, char **argv) { QApplication a(argc, argv); #if QT_VERSION < 0x040000 QSplitter* spl = new QSplitter(QSplitter::Horizontal); #else QSplitter* spl = new QSplitter(Qt::Horizontal); #endif Plot2D* plot1 = new Plot2D(spl,30); plot1->setFloorStyle(FLOORISO); plot1->setCoordinateStyle(BOX); Saddle saddle(*plot1); saddle.create(); plot1->setTitle("Autoswitching axes"); plot1->setBackgroundColor(RGBA(1,1, 157./255)); plot1->makeCurrent(); plot1->updateData(); plot1->updateGL(); Plot2D* plot2 = new Plot2D(spl,80); plot2->setZoom(0.8); Hat hat(*plot2); hat.create(); plot2->setPlotStyle(HIDDENLINE); plot2->setFloorStyle(FLOORDATA); plot2->setCoordinateStyle(FRAME); plot2->setBackgroundColor(RGBA(1,1, 157./255)); plot2->makeCurrent(); plot2->updateData(); plot2->updateGL(); #if QT_VERSION < 0x040000 a.setMainWidget(spl); #endif spl->resize(800,400); spl->show(); return a.exec(); }
[ [ [ 1, 102 ] ] ]
670a0c349461f6b5e32d555dd82acbc7cc82fb21
f3ed6f9abb7be30e410c733cbcf7923dbefdbc32
/enemy.h
7361aa40fec6ed87974f40973d6b1a1dbc672fb4
[]
no_license
walle/exoudus
8f045b534408034a513fe25fc97ba725df998ab3
344b79c44eeb2d1500e36cc0eefa972a7fe0d288
refs/heads/master
2018-12-29T02:00:46.191421
2010-11-16T22:48:39
2010-11-22T20:02:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#ifndef ENEMY_H #define ENEMY_H class cEnemy : public cShip { public: cEnemy(); ~cEnemy(); //private: int hits; int life; int speed; bool visible; }; #endif
[ [ [ 1, 17 ] ] ]
26e41cf21855d0c497df876683777ab0f2d16a44
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/v100/ok/10048/c.cpp
7920f6a2987e8dfcbc5561bbc8c9142015162464
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,918
cpp
#include <iostream> using namespace std; int c,s,q; long mat[200][200]; bool con[200][200]; long max(long v1,long v2) { return v1>v2?v1:v2; } long min(long v1,long v2) { return v1<v2?v1:v2; } void le() { int i,j,k,l; for(i=0;i!=c+1;i++) { for(j=0;j!=c+1;j++) { mat[i][j] = -1; con[i][j] = false; } con[i][i] = true; mat[i][i] = 0; } for(i=0;i!=s;i++) { cin >> j >> k >> l; if(!con[j][k] || mat[j][k]<l) { mat[j][k] = mat[k][j] = l; con[j][k] = con[k][j] = true; } } } void executa() { for(int i=0;i!=q;i++) { int j,k; cin >> j >> k; if(!con[j][k]) { cout << "no path" << endl; } else { cout << mat[j][k] << endl; } } } void floyd() { int i,j,k,l; for(i=0;i!=c+1;i++) { for(j=0;j!=c+1;j++) { if(i==j || !con[j][i]) continue; for(k=0;k!=c+1;k++) { if(i==k || i==j || !con[i][k]) continue; if(!con[j][k]) mat[j][k] = max(mat[j][i],mat[i][k]); else mat[j][k] = min(max(mat[j][i],mat[i][k]),mat[j][k]); con[j][k] = true; } } } } int main() { int inst = 0; while(true) { cin >> c >> s >> q; if(!c && !q && !s) return 0; if(inst) cout << endl; cout << "Case #" << ++inst << endl; le(); floyd(); executa(); } return 0; }
[ [ [ 1, 75 ] ] ]