blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
16
author_lines
sequencelengths
1
16
226951ba72f926d9b0072e56f079d2da6ff96dd6
847cccd728e768dc801d541a2d1169ef562311cd
/src/GfxSystem/GfxRenderer.h
a78cec2789d8c9ba93d4e1dc792fde6292af1e21
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,464
h
/// @file /// Entry point to the rendering subsystem. #ifndef _GFXRENDERER_H_ #define _GFXRENDERER_H_ #include "Base.h" #include "GfxStructures.h" #include "GfxViewport.h" #include "RenderTarget.h" /// Macro for easier use. #define gGfxRenderer GfxSystem::GfxRenderer::GetSingleton() /// Rendering capabilities of the engine. namespace GfxSystem { /// Rendering of everything except GUI. The rendering is done via rendering targets which define a viewport in the output /// device and a camera to use while rendering. class GfxRenderer : public Singleton<GfxRenderer> { public: /// Default constructor. GfxRenderer(); /// Default destructor. virtual ~GfxRenderer(); /// Intializes the renderer. virtual void Init() = 0; /// Prepares renderer for drawing. bool BeginRendering(); /// Finilizes drawing of everything this frame (swap buffers etc ...). void EndRendering(); /// Finalizes drawing of the current viewpoint inline void FinalizeRenderTarget() const; /// Adds a new render target to the list. Returns the ID of the added target. Mustn't be called while rendering. /// Returns InvalidRenderTargetID if something was wrong. RenderTargetID AddRenderTarget(const GfxViewport& viewport, const EntitySystem::EntityHandle camera); /// Removes the specified render target from the list. Returns false if there was no such. bool RemoveRenderTarget(const RenderTargetID toRemove); /// Sets the current render target. Returns false if no such exists. bool SetCurrentRenderTarget(const RenderTargetID toSet); /// Returns true if the render target is valid. bool IsRenderTargetValid(const RenderTargetID toCheck); /// Returns the current scene manager. inline GfxSceneMgr* GetSceneManager() const { return mSceneMgr; } /// Makes the subsequent calls to draw to be overlayed on top of the previously drawn graphics. virtual void FlushGraphics() const = 0; public: /// Loads an image from RAM into the platform specific texture. /// \param buffer the image data in RAM just as if it were still in a file /// \param buffer_length the size of the buffer in bytes /// \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA /// \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture) /// \param width, height returns size of texture /// \return 0-failed, otherwise returns the OpenGL texture handle virtual TextureHandle LoadTexture(const uint8* const buffer, const int32 buffer_length, const ePixelFormat force_channels, const uint32 reuse_texture_ID, int32* width, int32* height) const = 0; /// Creates a texture into which it can be rendered. virtual TextureHandle CreateRenderTexture(const uint32 width, const uint32 height) const = 0; /// Deletes the texture from the memory. virtual void DeleteTexture(const TextureHandle& handle) const = 0; /// Adds a textured quad to the queue for rendering. void QueueTexturedQuad(const TexturedQuad spr); /// Draws all visible entities. void DrawEntities(); /// Draws a quad with its texture. virtual void DrawTexturedQuad(const TexturedQuad& quad) const = 0; /// Draws a 3d model. virtual void DrawTexturedMesh(const TexturedMesh& mesh) const = 0; /// Draws a sprite component. void DrawSprite(const EntitySystem::Component* sprite, const EntitySystem::Component* transform) const; /// Draws a 3d model component. void DrawModel(const EntitySystem::Component* model, const EntitySystem::Component* transform) const; /// Draws a single entity. void DrawEntity(const EntitySystem::EntityHandle entity) const; /// Draws a line. Verts must be an array of 2 Vector2s. inline virtual void DrawLine(const Vector2* verts, const Color& color, const float32 width = 1.0f) const; /// Draws a line. virtual void DrawLine(const Vector2& a, const Vector2& b, const Color& color, const float32 width = 1.0f) const = 0; /// Draws a polygon. Verts must be an array of n Vector2s defining the polygon. virtual void DrawPolygon(const Vector2* verts, const int32 n, const Color& color, const bool fill, const float32 outlineWidth = 1.0f) const = 0; /// Draws a circle. virtual void DrawCircle(const Vector2& position, const float32 radius, const Color& color, const bool fill) const = 0; /// Draws a rectangle. Rotation is given in radians. virtual void DrawRect(const Vector2& topleft, const Vector2& bottomright, const float32 rotation, const Color& color, const bool fill) const = 0; /// Clears the screen with the given color. virtual void ClearScreen(const Color& color) const = 0; /// Clears the designated render target with the given color. void ClearRenderTarget(const RenderTargetID target, const Color& color) const; /// Clears the current render target with the given color. void ClearCurrentRenderTarget(const Color& color) const; /// Clears the given viewport with the given color. virtual void ClearViewport(const GfxViewport& viewport, const Color& color) const = 0; public: /// Converts coordinates from the screen space to the world space. /// Returns false if the conversion failed (for example, the screen position was not in any of the viewports). /// The result is returned in the second parameter. /// As a last parameter the desired render target can be specified. bool ConvertScreenToWorldCoords(const Point& screenCoords, Vector2& worldCoords, const RenderTargetID renderTarget = InvalidRenderTargetID) const; /// Returns a pointer to the viewport associated with a render target, or NULL if render target does not exist. GfxViewport* GetRenderTargetViewport(const RenderTargetID renderTarget) const; /// Returns the camera associated with a render target. EntitySystem::EntityHandle GetRenderTargetCamera(const RenderTargetID renderTarget) const; /// Returns the camera zoom of a render target. float32 GetRenderTargetCameraZoom(const RenderTargetID renderTarget) const; /// Sets position of camera associated with render target. Returns false if render target does not exist. bool SetRenderTargetCameraZoom(const RenderTargetID renderTarget, float32 newZoom) const; /// Returns the camera rotation of a render target. float32 GetRenderTargetCameraRotation(const RenderTargetID renderTarget) const; /// Returns the camera position of a render target. Vector2 GetRenderTargetCameraPosition(const RenderTargetID renderTarget) const; /// Sets position of camera associated with render target. Returns false if render target does not exist. bool SetRenderTargetCameraPosition(const RenderTargetID renderTarget, Vector2 newPosition) const; /// Retrieves render targets camera view boundaries in world space. void CalculateRenderTargetWorldBoundaries( const RenderTargetID renderTarget, Vector2& topleft, Vector2& bottomright ) const; protected: /// Called when the rendering is started. virtual bool BeginRenderingImpl() const = 0; /// Called when the rendering is finished. virtual void EndRenderingImpl() const = 0; /// Finish rendering of the current viewpoint. virtual void FinalizeRenderTargetImpl() const = 0; /// Called when the current viewport is changed. virtual void SetViewportImpl(const GfxViewport* viewport) = 0; /// Called when the current camera is changed. virtual void SetCameraImpl(const Vector2& position, const float32 zoom, const float32 rotation) const = 0; private: // Render targets. typedef vector<RenderTarget*> RenderTargetsVector; RenderTargetsVector mRenderTargets; RenderTargetID mCurrentRenderTargetID; private: /// Converts coordinates from the screen space to the world space. /// Returns false if the conversion failed (for example, the screen position was not in any of the viewports). /// The result is returned in the second parameter. /// As a last parameter the desired render target must be specified. bool ConvertScreenToWorldCoords( const Point& screenCoords, Vector2& worldCoords, const RenderTarget& renderTarget ) const; /// Does inverse camera transformation on the given vector and returns result. Vector2 GetInverseCameraTranform( const EntitySystem::EntityHandle& camera, const Vector2& vec ) const; /// Draws grid (defined in viewport) ontop of everything. void DrawGrid( const RenderTargetID renderTargetID ) const; public: /// Constant which binds pixel and world units together. And image of this size will be 1.0 units big in the world. static const float32 PIXELS_PER_WORLD_UNIT; protected: /// True if the rendering began but still didn't finish. bool mIsRendering; /// Scene management. GfxSceneMgr* mSceneMgr; private: /// Disabled. GfxRenderer(const GfxRenderer&); GfxRenderer& operator=(const GfxRenderer&); }; } //----------------------------------------------------------------------------- // Implementation void GfxSystem::GfxRenderer::FinalizeRenderTarget() const { DrawGrid( mCurrentRenderTargetID ); FinalizeRenderTargetImpl(); } void GfxSystem::GfxRenderer::DrawLine( const Vector2* verts, const Color& color, const float32 width ) const { DrawLine(verts[0], verts[1], color, width); } #endif
[ [ [ 1, 1 ], [ 3, 3 ], [ 20, 20 ], [ 35, 35 ], [ 39, 39 ], [ 51, 51 ], [ 79, 79 ], [ 85, 85 ], [ 100, 100 ], [ 106, 106 ], [ 112, 112 ], [ 115, 115 ], [ 138, 138 ], [ 143, 147 ], [ 152, 159 ], [ 178, 178 ], [ 183, 184 ], [ 193, 198 ], [ 204, 204 ], [ 236, 236 ] ], [ [ 2, 2 ], [ 4, 19 ], [ 21, 34 ], [ 36, 37 ], [ 40, 50 ], [ 52, 78 ], [ 80, 84 ], [ 86, 99 ], [ 101, 105 ], [ 107, 111 ], [ 113, 114 ], [ 116, 136 ], [ 140, 142 ], [ 148, 151 ], [ 160, 177 ], [ 179, 182 ], [ 185, 192 ], [ 199, 203 ], [ 205, 235 ] ], [ [ 38, 38 ], [ 137, 137 ], [ 139, 139 ] ] ]
6ddbddda3ab7be00bbf7a12cb0faf7ca6e71ead1
0bab4267636e3b06cb0e73fe9d31b0edd76260c2
/freewar-alpha/src/ActionsBind/manage_events.cpp
190f27f306c08b6613aeb5900cd5f26178f8dcdf
[]
no_license
BackupTheBerlios/freewar-svn
15fafedeed3ea1d374500d3430ff16b412b2f223
aa1a28f19610dbce12be463d5ccd98f712631bc3
refs/heads/master
2021-01-10T19:54:11.599797
2006-12-10T21:45:11
2006-12-10T21:45:11
40,725,388
0
0
null
null
null
null
UTF-8
C++
false
false
2,138
cpp
// revoir rapidement ce fichier avant de faire une // crise cardiaque #include "freewar.h" #define NB_OFF_MOVE (5) int get_pos(t_engine *e, int xfin, int yfin) { int flag; flag = 0; if (xfin <= SCROLL_X) { e->g.off_arena.x -= NB_OFF_MOVE; if (e->g.off_arena.x < 0) { e->g.pos_arena.x--; e->g.off_arena.x += CASE_SIZE_X; } if (e->g.pos_arena.x < 0) { e->g.pos_arena.x = 0; e->g.off_arena.x = 0; } flag = 1; } else if (xfin >= e->g.w_main - SCROLL_X) { e->g.off_arena.x += NB_OFF_MOVE; if (e->g.off_arena.x > CASE_SIZE_X) { e->g.pos_arena.x++; e->g.off_arena.x -= CASE_SIZE_X; } flag = 1; } if (yfin <= SCROLL_Y) { e->g.off_arena.y -= NB_OFF_MOVE; if (e->g.off_arena.y < 0) { e->g.pos_arena.y--; e->g.off_arena.y += CASE_SIZE_Y; } if (e->g.pos_arena.y < 0) { e->g.pos_arena.y = 0; e->g.off_arena.y = 0; } return (1); } else if (yfin >= e->g.h_main - SCROLL_Y) { e->g.off_arena.y += NB_OFF_MOVE; if (e->g.off_arena.y > CASE_SIZE_Y) { e->g.pos_arena.y++; e->g.off_arena.y -= CASE_SIZE_Y; } return (1); } return(flag); } void manage_events(t_engine *e) { //if (e->events->mousepose[0].button) //{ get_pos(e, e->events->xfin / CASE_SIZE_X, e->events->yfin / CASE_SIZE_Y); //} //else if (is_valid_trame(&trame, TAG_EXECUTION)) // ; //else if (is_valid_trame(&trame, TAG_INFO_SCALE)) // req_info_scale(e, &trame, t); //else if (is_valid_trame(&trame, TAG_SELECT_MOVE)) // req_select_move(e, &trame, t); //else if (is_valid_trame(&trame, TAG_SELECT_ATTACK)) // req_select_attack(e, &trame, t); //else if (is_valid_trame(&trame, TAG_SELECT_CREATE_UNITS)) // req_select_create_units(e, &trame, t); //else if (is_valid_trame(&trame, TAG_SELECT_CREATE_BUILDING)) // req_select_create_building(e, &trame, t); //else if (is_valid_trame(&trame, TAG_SELECT)) // { // puts("SELECT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); // manage_selection(e, &trame, t); // } }
[ "doomsday@b2c3ed95-53e8-0310-b220-efb193137011" ]
[ [ [ 1, 89 ] ] ]
3980e0dbec4b1cad401092ceb26054a4d8501da8
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/ClientWeaponAllocator.h
54e68017a43c759b5d4947725df65032e8a67c08
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
817
h
#ifndef _ClientWeaponAllocator_h_INCLUDED_ #define _ClientWeaponAllocator_h_INCLUDED_ // // This is an abstract class whose sole purpose is // to create each instance of the ClientWeapon. It will // take a type and match it to a class. // // See the ClientWeapon stuff for an example of its // implementation. Specifically, CCreator, // CStandardCreator, the derived classes of ClientWeaponAllocator // (CTRONClientWeaponAllocator and CTO2ClientWeaponAllocator), // and CPlayerMgr (as well as derived classes // CTRONPlayerMgr or CTO2PlayerMgr). // // forward declaration to reduce header dependancies class IClientWeaponBase; class CClientWeaponAllocator { public: virtual IClientWeaponBase *New( int nClientWeaponType ) const = 0; }; #endif //_ClientWeaponAllocator_h_INCLUDED_
[ [ [ 1, 27 ] ] ]
0628a98ffb568a0373e2cd7173e3c6b22a47dc89
c7fd308ee062c23e1b036b84bbf890c3f7e74fc4
/simple3/main.cpp
dc9b32f40793f2e54b15d3d3d3efd0ea5050c8c6
[]
no_license
truenite/truenite-opengl
805881d06a5f6ef31c32235fb407b9a381a59ed9
157b0e147899f95445aed8f0d635848118fce8b6
refs/heads/master
2021-01-10T01:59:35.796094
2011-05-06T02:03:16
2011-05-06T02:03:16
53,160,700
0
0
null
null
null
null
UTF-8
C++
false
false
997
cpp
#include <windows.h> #include <GL/glut.h> void dibujarFiguras(){ glBegin(GL_POINTS); glVertex2f(0,.8); glEnd(); glBegin(GL_LINES); glVertex2f(-.5,.5); glVertex2f(.5,.5); glEnd(); glBegin(GL_LINE_STRIP); glVertex2f(-.5,.2); glVertex2f(0,0); glVertex2f(.5,.2); glEnd(); glBegin(GL_LINE_LOOP); glVertex2f(-.5,-.2); glVertex2f(0,-.5); glVertex2f(.5,-.2); glEnd(); } void myDisplay(){ glClear(GL_COLOR_BUFFER_BIT); dibujarFiguras(); glFlush(); } void initValores(){ glClearColor(0,0,0,1); glColor3f(1,1,1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); } main( ){ glutInitDisplayMode(GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple3"); glutDisplayFunc(myDisplay); initValores(); glutMainLoop(); }
[ [ [ 1, 55 ] ] ]
1d555a696ebdfed8cfb5138b1dfb68b35fbf8a71
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/proto/compiler/fold.hpp
0d2159cc5d4f2eda648c15e95312c5c8120b68ab
[ "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,184
hpp
/////////////////////////////////////////////////////////////////////////////// /// \file fold.hpp /// A special-purpose proto compiler for merging sequences of binary operations. /// It compiles the right operand and passes the result as state while compiling /// the left. Or, it might do the left first, if you choose. // // 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_PROTO_COMPILER_FOLD_HPP_EAN_04_01_2005 #define BOOST_PROTO_COMPILER_FOLD_HPP_EAN_04_01_2005 #include <boost/xpressive/proto/proto_fwd.hpp> namespace boost { namespace proto { /////////////////////////////////////////////////////////////////////////////// // fold_compiler // Compiles the right side and passes the result as state while compiling the left. // This is useful for serializing a tree. template<typename OpTag, typename DomainTag, bool RightFirst> struct fold_compiler { // sample compiler implementation for sequencing template<typename Op, typename State, typename Visitor> struct apply { typedef typename right_type<Op>::type right_type; typedef typename left_type<Op>::type left_type; // compile the right branch typedef typename compiler<typename tag_type<right_type>::type, DomainTag>:: BOOST_NESTED_TEMPLATE apply < right_type , State , Visitor >::type right_compiled_type; // forward the result of the right branch to the left typedef typename compiler<typename tag_type<left_type>::type, DomainTag>:: BOOST_NESTED_TEMPLATE apply < left_type , right_compiled_type , Visitor >::type type; }; template<typename Op, typename State, typename Visitor> static typename apply<Op, State, Visitor>::type call(Op const &op, State const &state, Visitor &visitor) { return proto::compile( proto::left(op) , proto::compile(proto::right(op), state, visitor, DomainTag()) , visitor , DomainTag() ); } }; /////////////////////////////////////////////////////////////////////////////// // fold_compiler // Compiles the left side and passes the result as state while compiling the right. // This is useful for serializing a tree. template<typename OpTag, typename DomainTag> struct fold_compiler<OpTag, DomainTag, false> { // sample compiler implementation for sequencing template<typename Op, typename State, typename Visitor> struct apply { typedef typename right_type<Op>::type right_type; typedef typename left_type<Op>::type left_type; // compile the right branch typedef typename compiler<typename tag_type<left_type>::type, DomainTag>:: BOOST_NESTED_TEMPLATE apply < left_type , State , Visitor >::type left_compiled_type; // forward the result of the right branch to the left typedef typename compiler<typename tag_type<right_type>::type, DomainTag>:: BOOST_NESTED_TEMPLATE apply < right_type , left_compiled_type , Visitor >::type type; }; template<typename Op, typename State, typename Visitor> static typename apply<Op, State, Visitor>::type call(Op const &op, State const &state, Visitor &visitor) { return proto::compile( proto::right(op) , proto::compile(proto::left(op), state, visitor, DomainTag()) , visitor , DomainTag() ); } }; }} #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 113 ] ] ]
16e50560f23181349156fe65ad609a39572309f2
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/LiteEditor/tags_options_dlg.cpp
2b1c3c553697a6797aa9fac5205c8364cf2d3314
[]
no_license
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
7,864
cpp
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Jun 6 2007) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #ifdef WX_PRECOMP #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //__BORLANDC__ #else #include <wx/wx.h> #endif //WX_PRECOMP #include "tags_options_dlg.h" #include "macros.h" //--------------------------------------------------------- TagsOptionsDlg::TagsOptionsDlg( wxWindow* parent, const TagsOptionsData& data, int id, wxString title, wxPoint pos, wxSize size, int style ) : wxDialog( parent, id, title, pos, size, style ) , m_data(data) { this->SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* mainSizer; mainSizer = new wxBoxSizer( wxVERTICAL ); long bookStyle = wxFNB_FF2 | wxFNB_NO_NAV_BUTTONS | wxFNB_NO_X_BUTTON | wxFNB_BACKGROUND_GRADIENT; m_mainBook = new wxFlatNotebook( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, bookStyle); m_generalPage = new wxPanel( m_mainBook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer4; bSizer4 = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer* sbSizer2; sbSizer2 = new wxStaticBoxSizer( new wxStaticBox( m_generalPage, -1, wxT("General:") ), wxVERTICAL ); m_checkParseComments = new wxCheckBox( m_generalPage, wxID_ANY, wxT("Parse comments"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer2->Add( m_checkParseComments, 0, wxALL, 5 ); m_checkDisplayComments = new wxCheckBox( m_generalPage, wxID_ANY, wxT("Display comments in tooltip"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer2->Add( m_checkDisplayComments, 0, wxALL, 5 ); m_checkDisplayTypeInfo = new wxCheckBox( m_generalPage, wxID_ANY, wxT("Display type info tooltips"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer2->Add( m_checkDisplayTypeInfo, 0, wxALL, 5 ); m_checkDisplayFunctionTip = new wxCheckBox( m_generalPage, wxID_ANY, wxT("Display function calltip"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer2->Add( m_checkDisplayFunctionTip, 0, wxALL, 5 ); bSizer4->Add( sbSizer2, 0, wxEXPAND, 5 ); wxStaticBoxSizer* sbSizer21; sbSizer21 = new wxStaticBoxSizer( new wxStaticBox( m_generalPage, -1, wxT("External Symbols Database:") ), wxVERTICAL ); m_checkLoadLastDB = new wxCheckBox( m_generalPage, wxID_ANY, wxT("Automatically load the recently used additional symbols database"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer21->Add( m_checkLoadLastDB, 0, wxALL, 5 ); m_checkLoadToMemory = new wxCheckBox( m_generalPage, wxID_ANY, wxT("Load external database symbols to memory"), wxDefaultPosition, wxDefaultSize, 0 ); sbSizer21->Add( m_checkLoadToMemory, 0, wxALL, 5 ); bSizer4->Add( sbSizer21, 0, wxEXPAND, 5 ); m_generalPage->SetSizer( bSizer4 ); m_generalPage->Layout(); bSizer4->Fit( m_generalPage ); m_mainBook->AddPage( m_generalPage, wxT("CodeLite"), false ); m_ctagsPage = new wxPanel( m_mainBook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL ); wxBoxSizer* bSizer6; bSizer6 = new wxBoxSizer( wxVERTICAL ); wxFlexGridSizer* fgSizer2; fgSizer2 = new wxFlexGridSizer( 2, 2, 0, 0 ); fgSizer2->AddGrowableCol( 1 ); fgSizer2->SetFlexibleDirection( wxBOTH ); fgSizer2->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_staticText1 = new wxStaticText( m_ctagsPage, wxID_ANY, wxT("Preprocessor file:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText1->Wrap( -1 ); fgSizer2->Add( m_staticText1, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_filePicker = new FilePicker(m_ctagsPage, wxID_ANY); fgSizer2->Add( m_filePicker, 0, wxEXPAND|wxALL, 5 ); m_staticText3 = new wxStaticText( m_ctagsPage, wxID_ANY, wxT("File Types:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText3->Wrap( -1 ); fgSizer2->Add( m_staticText3, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_textFileSpec = new wxTextCtrl( m_ctagsPage, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); fgSizer2->Add( m_textFileSpec, 0, wxALL|wxEXPAND, 5 ); m_staticText5 = new wxStaticText( m_ctagsPage, wxID_ANY, wxT("Force Language:"), wxDefaultPosition, wxDefaultSize, 0 ); m_staticText5->Wrap( -1 ); fgSizer2->Add( m_staticText5, 1, wxALL|wxALIGN_CENTER_VERTICAL, 5 ); m_comboBoxLang = new wxComboBox( m_ctagsPage, wxID_ANY, wxT("C++"), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY ); m_comboBoxLang->Append( wxT("C++") ); m_comboBoxLang->Append( wxT("Java") ); fgSizer2->Add( m_comboBoxLang, 0, wxALL|wxEXPAND, 5 ); bSizer6->Add( fgSizer2, 0, wxEXPAND, 5 ); m_checkFilesWithoutExt = new wxCheckBox( m_ctagsPage, wxID_ANY, wxT("Parse files without extension"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer6->Add( m_checkFilesWithoutExt, 0, wxALL, 5 ); m_ctagsPage->SetSizer( bSizer6 ); m_ctagsPage->Layout(); bSizer6->Fit( m_ctagsPage ); m_mainBook->AddPage( m_ctagsPage, wxT("ctags"), true ); mainSizer->Add( m_mainBook, 1, wxEXPAND | wxALL, 5 ); m_staticline1 = new wxStaticLine( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); mainSizer->Add( m_staticline1, 0, wxEXPAND | wxALL, 5 ); wxBoxSizer* bSizer3; bSizer3 = new wxBoxSizer( wxHORIZONTAL ); m_buttonOK = new wxButton( this, wxID_OK, wxT("&OK"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer3->Add( m_buttonOK, 0, wxALL, 5 ); m_buttonCancel = new wxButton( this, wxID_CANCEL, wxT("Close"), wxDefaultPosition, wxDefaultSize, 0 ); bSizer3->Add( m_buttonCancel, 0, wxALL, 5 ); mainSizer->Add( bSizer3, 0, wxALIGN_RIGHT, 5 ); this->SetSizer( mainSizer ); this->Layout(); InitValues(); ConnectButton(m_buttonOK, TagsOptionsDlg::OnButtonOK); } void TagsOptionsDlg::InitValues() { //initialize the CodeLite page m_checkParseComments->SetValue(m_data.GetFlags() & CC_PARSE_COMMENTS ? true : false); m_checkDisplayFunctionTip->SetValue(m_data.GetFlags() & CC_DISP_FUNC_CALLTIP ? true : false); m_checkLoadLastDB->SetValue(m_data.GetFlags() & CC_LOAD_EXT_DB ? true : false); m_checkDisplayTypeInfo->SetValue(m_data.GetFlags() & CC_DISP_TYPE_INFO ? true : false); m_checkDisplayComments->SetValue(m_data.GetFlags() & CC_DISP_COMMENTS ? true : false); m_checkLoadToMemory->SetValue(m_data.GetFlags() & CC_LOAD_EXT_DB_TO_MEMORY ? true : false); //initialize the ctags page m_filePicker->SetPath(m_data.GetPreprocessorFilename().GetFullPath()); m_textFileSpec->SetValue(m_data.GetFileSpec()); m_comboBoxLang->Clear(); m_comboBoxLang->Append(m_data.GetLanguages()); wxString lan = m_data.GetLanguages().Item(0); m_comboBoxLang->SetStringSelection(lan); } void TagsOptionsDlg::OnButtonOK(wxCommandEvent &event) { wxUnusedVar(event); CopyData(); EndModal(wxID_OK); } void TagsOptionsDlg::CopyData() { //save data to the interal member m_data SetFlag(CC_DISP_COMMENTS, m_checkDisplayComments->IsChecked()); SetFlag(CC_DISP_FUNC_CALLTIP, m_checkDisplayFunctionTip->IsChecked()); SetFlag(CC_DISP_TYPE_INFO, m_checkDisplayTypeInfo->IsChecked()); SetFlag(CC_LOAD_EXT_DB, m_checkLoadLastDB->IsChecked()); SetFlag(CC_PARSE_COMMENTS, m_checkParseComments->IsChecked()); SetFlag(CC_LOAD_EXT_DB_TO_MEMORY, m_checkLoadToMemory->IsChecked()); m_data.SetFileSpec(m_textFileSpec->GetValue()); m_data.SetPreprocessorFilename(m_filePicker->GetPath()); m_data.SetLanguages(m_comboBoxLang->GetStrings()); m_data.SetLanguageSelection(m_comboBoxLang->GetStringSelection()); } void TagsOptionsDlg::SetFlag(CodeCompletionOpts flag, bool set) { if(set){ m_data.SetFlags(m_data.GetFlags() | flag); }else{ m_data.SetFlags(m_data.GetFlags() & ~(flag)); } }
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
[ [ [ 1, 197 ] ] ]
74e4907c1c166154480271a1cdfa7148a6647aa6
c0bd82eb640d8594f2d2b76262566288676b8395
/src/game/WorldSocket.h
309f69644fa710dca1e32b488bf67d862d209336
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
3,053
h
/************************************************************************/ /* Copyright (C) 2006 Burlex */ /************************************************************************/ // Class WorldSocket - Main network code functions, handles // reading/writing of all packets. #ifndef __WORLDSOCKET_H #define __WORLDSOCKET_H #define WORLDSOCKET_SENDBUF_SIZE 65535 #define WORLDSOCKET_RECVBUF_SIZE 32768 class WorldPacket; class SocketHandler; class WorldSession; class WorldSocket : public BaseSocket { public: WorldSocket(SocketHolder &SH); ~WorldSocket(); // vs8 fix - send null on empty buffer inline void SendPacket(WorldPacket* packet) { if(!packet) return; OutPacket(packet->GetOpcode(), packet->size(), (packet->size() ? (const void*)packet->contents() : NULL)); } void __fastcall OutPacket(uint16 opcode, uint16 len, const void* data); inline uint32 GetLatency() { return _latency; } void Close(); void Delete(); void Disconnect(); void Authenticate(); void InformationRetreiveCallback(WorldPacket & recvData, uint32 requestid); void __fastcall UpdateQueuePosition(uint32 Position); void OnReceive(const u16 Size); void OnConnect(); void OnDisconnect(); inline void SetSession(WorldSession * session) { mSession = session; } protected: void _HandleAuthSession(WorldPacket* recvPacket); void _HandlePing(WorldPacket* recvPacket); private: uint32 mOpcode; uint32 mRemaining; uint32 mSize; uint32 mSeed; uint32 mClientSeed; uint32 mClientBuild; uint32 mRequestID; WorldSession *mSession; WorldPacket * pAuthenticationPacket; WowCrypt _crypt; uint32 _latency; bool mQueued; }; inline void FastGUIDPack(ByteBuffer & buf, const uint64 & oldguid) { // hehe speed freaks uint8 guidmask = 0; uint8 guidfields[8] = {0,0,0,0,0,0,0,0}; int j = 1; uint8 * test = (uint8*)&oldguid; if (*test) //7*8 { guidfields[j] = *test; guidmask |= 1; j++; } if (*(test+1)) //6*8 { guidfields[j] = *(test+1); guidmask |= 2; j++; } if (*(test+2)) //5*8 { guidfields[j] = *(test+2); guidmask |= 4; j++; } if (*(test+3)) //4*8 { guidfields[j] = *(test+3); guidmask |= 8; j++; } if (*(test+4)) //3*8 { guidfields[j] = *(test+4); guidmask |= 16; j++; } if (*(test+5))//2*8 { guidfields[j] = *(test+5); guidmask |= 32; j++; } if (*(test+6))//1*8 { guidfields[j] = *(test+6); guidmask |= 64; j++; } if (*(test+7)) //0*8 { guidfields[j] = *(test+7); guidmask |= 128; j++; } guidfields[0] = guidmask; buf.append(guidfields,j); } #endif
[ [ [ 1, 129 ] ] ]
34acbab18ff0a0dff203668042deb7a2af1e9770
fdda82630e68e3953878770d8ef81cba7c6b6772
/cqt/modules/bt_pvt.h
6a211c639cf1b15f9216f8ecad48e2af74b3f219
[]
no_license
bettiah/qt4-ruby
cbf9337b845ae7a6596016bb059ac43636810756
3ef75de65d229fbd23b020f0f1419965227e2263
refs/heads/master
2016-09-05T18:12:22.197962
2007-09-02T19:32:59
2007-09-02T19:32:59
32,118,806
0
0
null
null
null
null
UTF-8
C++
false
false
728
h
#include <QObject> #include <winsock2.h> class Private; class LocatorProxy : public QObject { Q_OBJECT friend class QBtLocator; public: LocatorProxy(); ~LocatorProxy(); public slots: void startLookup(); void findNext(); signals: void proxyFoundDevice(QString name, QByteArray btAddr); void proxyRequestComplete(int error); private: Private* pvt; }; WCHAR *GetLastErrorMessage(DWORD last_error); void AllocMemory(PWSAQUERYSET& addr, int size); QString AddressAsString(qlonglong remoteAddress, SOCKET *s, WSAPROTOCOL_INFO* protocolInfo, int* protocolInfoSize); int bt_open_socket(SOCKET *s, WSAPROTOCOL_INFO* protocolInfo, int* protocolInfoSize); void getAttributes(const BLOB *pBlob);
[ "bettiah@47233f48-bd19-0410-af3c-33b5cb0f13b4" ]
[ [ [ 1, 30 ] ] ]
31dd1f6d38fd4b38645550ddfbbbf3bfa87258d7
252e638cde99ab2aa84922a2e230511f8f0c84be
/reflib/src/BusProcessForm.cpp
35494b6363ff913537753bda8c55316572204d25
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,335
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "StdTool.h" #include "TourTool.h" #include "BusProcessForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "TableGridProcessForm" #pragma link "VStringStorage" #pragma resource "*.dfm" TTourRefBookBusProcessForm *TourRefBookBusProcessForm; enum TourRefBookBusProcessStringTypes { TourRefBookBusModelStr = TourRefBookProcessStringTypesEnumCount, TourRefBookBusModelInvalidSpeedFactorMessageStr, TourRefBookBusModelInvalidCapacityMessageStr }; #define GetTranslatedStr(Index) VStringStorage->Lines->Strings[Index] //--------------------------------------------------------------------------- __fastcall TTourRefBookBusProcessForm::TTourRefBookBusProcessForm(TComponent* Owner) : TTourRefBookTableGridProcessForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTourRefBookBusProcessForm::FormCloseQuery(TObject *Sender, bool &CanClose) { Boolean ResultFlag; ResultFlag = true; CanClose = false; FunctionArgUsedSkip(Sender); if (ModalResult == mrOk) { if (BusModelDBEdit->Text.IsEmpty()) { ResultFlag = false; TourShowDialogError (AnsiString(GetTranslatedStr(TourRefBookInputFieldMessageStr) + GetTranslatedStr(TourRefBookBusModelStr)).c_str()); BusModelDBEdit->SetFocus(); } if (ResultFlag) { if (!BusSpeedFactorDBEdit->Text.IsEmpty()) { try { if (StrToFloat(BusSpeedFactorDBEdit->Text) < 0) { ResultFlag = false; TourShowDialogError (AnsiString(GetTranslatedStr (TourRefBookBusModelInvalidSpeedFactorMessageStr)).c_str()); BusSpeedFactorDBEdit->SetFocus(); } } catch (...) { ResultFlag = false; TourShowDialogError (AnsiString(GetTranslatedStr (TourRefBookBusModelInvalidSpeedFactorMessageStr)).c_str()); BusSpeedFactorDBEdit->SetFocus(); } } } if (ResultFlag) { if (!BusCapacityDBEdit->Text.IsEmpty()) { try { if (StrToInt(BusCapacityDBEdit->Text) < 0) { ResultFlag = false; TourShowDialogError (AnsiString(GetTranslatedStr (TourRefBookBusModelInvalidCapacityMessageStr)).c_str()); BusCapacityDBEdit->SetFocus(); } } catch (...) { ResultFlag = false; TourShowDialogError (AnsiString(GetTranslatedStr (TourRefBookBusModelInvalidCapacityMessageStr)).c_str()); BusCapacityDBEdit->SetFocus(); } } } if (ResultFlag) { CanClose = true; } } else { CanClose = true; } } //--------------------------------------------------------------------------- #undef GetTranslatedStr(Index)
[ [ [ 1, 127 ] ] ]
68e30cda2353267c0ccfe74253eb9d69fad2b775
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/graph/example/dijkstra-example-listS.cpp
bdf380c5ec65d184bcedb90506b3fa69bf587cfe
[ "Artistic-2.0", "LicenseRef-scancode-public-domain", "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,420
cpp
//======================================================================= // Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, // // 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 <boost/config.hpp> #include <iostream> #include <fstream> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> using namespace boost; int main(int, char *[]) { typedef adjacency_list_traits<listS, listS, directedS>::vertex_descriptor vertex_descriptor; typedef adjacency_list < listS, listS, directedS, property<vertex_index_t, int, property<vertex_name_t, char, property<vertex_distance_t, int, property<vertex_predecessor_t, vertex_descriptor> > > >, property<edge_weight_t, int> > graph_t; typedef graph_traits<graph_t>::edge_descriptor edge_descriptor; typedef std::pair<int, int> Edge; const int num_nodes = 5; enum nodes { A, B, C, D, E }; Edge edge_array[] = { Edge(A, C), Edge(B, B), Edge(B, D), Edge(B, E), Edge(C, B), Edge(C, D), Edge(D, E), Edge(E, A), Edge(E, B) }; int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1 }; int num_arcs = sizeof(edge_array) / sizeof(Edge); graph_traits<graph_t>::vertex_iterator i, iend; #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 graph_t g(num_nodes); property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g); std::vector<vertex_descriptor> msvc_vertices; for (tie(i, iend) = vertices(g); i != iend; ++i) msvc_vertices.push_back(*i); for (std::size_t j = 0; j < num_arcs; ++j) { edge_descriptor e; bool inserted; tie(e, inserted) = add_edge(msvc_vertices[edge_array[j].first], msvc_vertices[edge_array[j].second], g); weightmap[e] = weights[j]; } #else graph_t g(edge_array, edge_array + num_arcs, weights, num_nodes); property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g); #endif // Manually intialize the vertex index and name maps property_map<graph_t, vertex_index_t>::type indexmap = get(vertex_index, g); property_map<graph_t, vertex_name_t>::type name = get(vertex_name, g); int c = 0; for (tie(i, iend) = vertices(g); i != iend; ++i, ++c) { indexmap[*i] = c; name[*i] = 'A' + c; } vertex_descriptor s = vertex(A, g); property_map<graph_t, vertex_distance_t>::type d = get(vertex_distance, g); property_map<graph_t, vertex_predecessor_t>::type p = get(vertex_predecessor, g); #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 // VC++ has trouble with the named parameters mechanism property_map<graph_t, vertex_index_t>::type indexmap = get(vertex_index, g); dijkstra_shortest_paths(g, s, p, d, weightmap, indexmap, std::less<int>(), closed_plus<int>(), (std::numeric_limits<int>::max)(), 0, default_dijkstra_visitor()); #else dijkstra_shortest_paths(g, s, predecessor_map(p).distance_map(d)); #endif std::cout << "distances and parents:" << std::endl; graph_traits < graph_t >::vertex_iterator vi, vend; for (tie(vi, vend) = vertices(g); vi != vend; ++vi) { std::cout << "distance(" << name[*vi] << ") = " << d[*vi] << ", "; std::cout << "parent(" << name[*vi] << ") = " << name[p[*vi]] << std:: endl; } std::cout << std::endl; std::ofstream dot_file("figs/dijkstra-eg.dot"); dot_file << "digraph D {\n" << " rankdir=LR\n" << " size=\"4,3\"\n" << " ratio=\"fill\"\n" << " edge[style=\"bold\"]\n" << " node[shape=\"circle\"]\n"; graph_traits < graph_t >::edge_iterator ei, ei_end; for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) { graph_traits < graph_t >::edge_descriptor e = *ei; graph_traits < graph_t >::vertex_descriptor u = source(e, g), v = target(e, g); dot_file << name[u] << " -> " << name[v] << "[label=\"" << get(weightmap, e) << "\""; if (p[v] == u) dot_file << ", color=\"black\""; else dot_file << ", color=\"grey\""; dot_file << "]"; } dot_file << "}"; return EXIT_SUCCESS; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 118 ] ] ]
7a3da37ad777bf624a0dc63ddcf72b1c52f5deb5
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/namcofl.h
46e49c2260f126817fc83986a8a3b9ef86fe9735
[]
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
924
h
#define NAMCOFL_HTOTAL (288) /* wrong */ #define NAMCOFL_HBSTART (288) #define NAMCOFL_VTOTAL (262) /* needs to be checked */ #define NAMCOFL_VBSTART (224) #define NAMCOFL_TILEMASKREGION "tilemask" #define NAMCOFL_TILEGFXREGION "tile" #define NAMCOFL_SPRITEGFXREGION "sprite" #define NAMCOFL_ROTMASKREGION "rotmask" #define NAMCOFL_ROTGFXREGION "rot" #define NAMCOFL_TILEGFX 0 #define NAMCOFL_SPRITEGFX 1 #define NAMCOFL_ROTGFX 2 class namcofl_state : public driver_device { public: namcofl_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } emu_timer *m_raster_interrupt_timer; UINT32 *m_workram; UINT16 *m_shareram; UINT8 m_mcu_port6; UINT32 m_sprbank; }; /*----------- defined in video/namcofl.c -----------*/ VIDEO_START( namcofl ); SCREEN_UPDATE( namcofl ); WRITE32_HANDLER( namcofl_spritebank_w );
[ "Mike@localhost" ]
[ [ [ 1, 35 ] ] ]
4e71e142a0c9f3457b2cbf87c1c984f4c51aaf02
4b116281b895732989336f45dc65e95deb69917b
/Code Base/GSP410-Project2/EnemyUnit.h
5b3c50d945bc6150a9162067b46375e046e5f6fb
[]
no_license
Pavani565/gsp410-spaceshooter
1f192ca16b41e8afdcc25645f950508a6f9a92c6
c299b03d285e676874f72aa062d76b186918b146
refs/heads/master
2021-01-10T00:59:18.499288
2011-12-12T16:59:51
2011-12-12T16:59:51
33,170,205
0
0
null
null
null
null
UTF-8
C++
false
false
673
h
#pragma once #include "Unit.h" class CEnemyUnit : public CUnit { private: // Enemy Unit Variables // int m_ShipEnergy; // The Enemy Unit's Shield's Energy // bool m_CombatState; // The Enemy Unit's Combat State // public: // Enemy Unit Constants // static const int m_MaxEnergy; // Max Energy An Enemy Unit Can Have // // Set Functions For Enemy Unit // void setShipEnergry(int newShipEnergy); void setCombatStateOn(void); void setCombatStateOff(void); // Get Functions For Enemy Unit // int getShipEnergy(void); bool getCombatState(void); // Constructor & Destructor// CEnemyUnit(void); ~CEnemyUnit(void); };
[ "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7" ]
[ [ [ 1, 26 ] ] ]
3286dbd78981101e570f5ec6d94b1db26ed95ed1
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Client/Source/UserCommandHandler.h
b9c1e7dbc84ffd7639fec7aadb5fcefbf6688a8b
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#pragma once #include "CommandHandler.h" namespace Kylin { class UserCommandHandler : public CommandHandler { public: virtual KVOID PrintHelpInfo() { CommandHandler::PrintHelpInfo(); DebugConsole* pConsole = GET_GUI_PTR(DebugConsole); if (pConsole) { pConsole->PrintLine(">change_scene - switch scene (scene id)"); pConsole->PrintLine("================================================================"); } } virtual KVOID Execute(KSTR sCmdLine) { CommandHandler::Execute(sCmdLine); Ogre::vector<Ogre::String>::type kCmd = Interpret(sCmdLine); if(kCmd.size() > 0) { Ogre::StringUtil::toLowerCase(kCmd[0]); if (kCmd[0] == "change_scene") { if (kCmd.size() < 2) return; KUINT uSceneID = atoi(kCmd[1].data()); if (uSceneID > 0) KylinRoot::GetSingletonPtr()->SwitchScene(uSceneID); } else if (kCmd[0] == "show_box") { if (kCmd.size() < 2) return; if (kCmd[1] == "true") KylinRoot::GetSingletonPtr()->DebugShowBoundingBox(true); else KylinRoot::GetSingletonPtr()->DebugShowBoundingBox(false); } } } }; }
[ "[email protected]", "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 13 ], [ 15, 37 ], [ 47, 50 ] ], [ [ 14, 14 ], [ 38, 46 ] ] ]
99163fb2e4bdbf7b282d8394228407200e65352b
8a3fce9fb893696b8e408703b62fa452feec65c5
/业余时间学习笔记/IOCP/Ipc/Ipc/stdafx.cpp
ec549466ea791ab46d1dd31ac16917f5c3a918fc
[]
no_license
win18216001/tpgame
bb4e8b1a2f19b92ecce14a7477ce30a470faecda
d877dd51a924f1d628959c5ab638c34a671b39b2
refs/heads/master
2021-04-12T04:51:47.882699
2011-03-08T10:04:55
2011-03-08T10:04:55
42,728,291
0
2
null
null
null
null
GB18030
C++
false
false
263
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // Ipc.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ [ [ 1, 8 ] ] ]
2ca3c1032b5104f87c4818a5dbcfb7220275f773
f96efcf47a7b6a617b5b08f83924c7384dcf98eb
/tags/mucc_1_0_5_10/ChatWindow.cpp
e2adc7e6c89713b0cf7e41af5621d61d45b8fa96
[]
no_license
BackupTheBerlios/mtlen-svn
0b4e7c53842914416ed3f6b1fa02c3f1623cac44
f0ea6f0cec85e9ed537b89f7d28f75b1dc108554
refs/heads/master
2020-12-03T19:37:37.828462
2011-12-07T20:02:16
2011-12-07T20:02:16
40,800,938
0
0
null
null
null
null
UTF-8
C++
false
false
62,767
cpp
/* MUCC Group Chat GUI Plugin for Miranda IM Copyright (C) 2004 Piotr Piastucki This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "ChatWindow.h" #include "HelperDialog.h" #include "Utils.h" #include "Options.h" #include "m_smileyadd.h" static int logPixelSY; static BOOL CALLBACK LogDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); static void __cdecl StartThread(void *vChat); static void JabberStringAppend(char **str, int *sizeAlloced, const char *fmt, ...); static char *JabberRtfEscape(char *str); COLORREF ChatWindow::colorListBg, ChatWindow::colorListText, ChatWindow::colorListGroupText; HFONT ChatWindow::hListGroupFont=NULL; HFONT ChatWindow::hListFont=NULL; ChatWindow * ChatWindow::list = NULL; bool ChatWindow::released = false; CRITICAL_SECTION ChatWindow::mutex; static WNDPROC oldSplitterWndProc, oldEditWndProc; static HCURSOR hCurSplitNS, hCurSplitWE; void ChatWindow::release() { released = true; for (ChatWindow *ptr2, *ptr = list; ptr!=NULL; ptr=ptr2) { ptr2 = ptr->getNext(); //SendMessage(ptr->getHWND(), WM_CLOSE, 0, 0); } DeleteCriticalSection(&mutex); } void ChatWindow::init() { hCurSplitNS = LoadCursor(NULL, IDC_SIZENS); hCurSplitWE = LoadCursor(NULL, IDC_SIZEWE); released = false; InitializeCriticalSection(&mutex); } ChatWindow::ChatWindow(MUCCWINDOW *mucw) { prev = next = NULL; adminWindow = NULL; hWnd = NULL; module = roomId = roomName = topic = NULL; hSplitterPos = 0; vSplitterPos = 0; wasFirstMessage = 0; isStarted = 0; options = Options::getChatWindowOptions(); bBold = bItalic = bUnderline = 0; hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); hEditFont = NULL; userMe = NULL; users = NULL; for (int i=0;i<5;i++) { hUserGroups[i] = NULL; } setModule(mucw->pszModule); setRoomId(mucw->pszID); setRoomName(mucw->pszName); EnterCriticalSection(&mutex); setNext(list); if (next!=NULL) { next->setPrev(this); } list = this; LeaveCriticalSection(&mutex); container = ChatContainer::getWindow(); hWnd = container->remoteCreateChild(LogDlgProc, this); container->remoteAddChild(this); } ChatWindow::~ChatWindow () { if (!released) { EnterCriticalSection(&mutex); if (getPrev()!=NULL) { getPrev()->setNext(next); } else if (list==this) { list = getNext(); } if (getNext()!=NULL) { getNext()->setPrev(prev); } LeaveCriticalSection(&mutex); } if (adminWindow!=NULL) { delete adminWindow; } if (hEvent!=NULL) { CloseHandle(hEvent); } while (users!=NULL) { ChatUser *user = users; users = users->getNext(); delete user; } if (module!=NULL) { delete module; } if (roomId!=NULL) { delete roomId; } if (roomName!=NULL) { delete roomName; } if (topic!=NULL) { delete topic; } container->remoteRemoveChild(this); }; void ChatWindow::setPrev(ChatWindow *prev) { this->prev = prev; } ChatWindow * ChatWindow::getPrev() { return prev; } void ChatWindow::setNext(ChatWindow *next) { this->next = next; } ChatWindow * ChatWindow::getNext() { return next; } void ChatWindow::setHWND(HWND hWnd) { this->hWnd = hWnd; } HWND ChatWindow::getHWND() { return hWnd; } HANDLE ChatWindow::getEvent() { return hEvent; } ChatContainer * ChatWindow::getContainer() { return container; } void ChatWindow::setAdminWindow(AdminWindow *aw) { this->adminWindow = aw; } AdminWindow* ChatWindow::getAdminWindow() { return adminWindow; } void ChatWindow::setModule(const char *module) { Utils::copyString(&this->module, module); } const char * ChatWindow::getModule() { return module; } void ChatWindow::setRoomId(const char *roomId) { Utils::copyString(&this->roomId, roomId); } const char * ChatWindow::getRoomId() { return roomId; } void ChatWindow::setRoomName(const char *roomName) { // char str[300]; Utils::copyString(&this->roomName, roomName); // sprintf(str, "%s %08X", roomName, roomFlags); // SetWindowText(hWnd, str); SetWindowText(hWnd, roomName); } void ChatWindow::setRoomFlags(int flags) { // char str[300]; roomFlags = flags; // sprintf(str, "%s %08X", roomName, roomFlags); // SetWindowText(hWnd, str); } int ChatWindow::getRoomFlags() { return roomFlags; } const char * ChatWindow::getRoomName() { return roomName; } void ChatWindow::setOptions(int options) { if (options != this->options) { this->options = options; rebuildLog(); } } int ChatWindow::getOptions() { return options; } static void __cdecl StartThread(void *vChat) { OleInitialize(NULL); DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_GROUPCHAT_LOG), NULL, LogDlgProc, (LPARAM) vChat); OleUninitialize(); } static void __cdecl StartAdminThread(void *vChat) { ChatWindow *chat = (ChatWindow *)vChat; chat->getAdminWindow()->start(); } void ChatWindow::startAdminDialog(int mode) { if (adminWindow==NULL) { ChatUser *user = getSelectedUser(); if (user != NULL) { adminWindow = new AdminWindow(this, user->getId(), mode); } else { adminWindow = new AdminWindow(this, "", mode); } Utils::forkThread((void (__cdecl *)(void *))StartAdminThread, 0, (void *) this); } } void ChatWindow::addUser(ChatUser *user) { user->setNext(users); users = user; } void ChatWindow::removeUser(ChatUser *user) { ChatUser *user2; for (user2=users;user2!=NULL;user2=user2->getNext()) { if (user2->getNext()==user) break; } if (user2!=NULL) { user2->setNext(user->getNext()); } else if (users==user) { users = user->getNext(); } } ChatUser * ChatWindow::getMe() { return userMe; } ChatUser * ChatWindow::findUser(const char *userId) { ChatUser *user; for (user=users;user!=NULL;user=user->getNext()) { if (!(strcmp(user->getId(), userId))) break; } return user; } ChatUser * ChatWindow::findUserByNick(const char *nick) { ChatUser *user; for (user=users;user!=NULL;user=user->getNext()) { if (!(strcmp(user->getNick(), nick))) break; } return user; } ChatUser *ChatWindow::getSelectedUser() { HTREEITEM hTreeItem = TreeView_GetSelection(GetDlgItem(hWnd, IDC_TREELIST)); if (hTreeItem!=NULL) { TVITEM tvi; tvi.mask = TVIF_PARAM; tvi.hItem = hTreeItem; TreeView_GetItem(GetDlgItem(hWnd, IDC_TREELIST), &tvi); return (ChatUser *) tvi.lParam; } return NULL; } int ChatWindow::startPriv() { ChatUser *user = getSelectedUser(); if (user!=NULL) { MUCCEVENT mucce; mucce.iType = MUCC_EVENT_START_PRIV; mucce.pszModule = getModule(); mucce.pszID = getRoomId(); mucce.pszUID = user->getId(); NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce); } return 0; } int ChatWindow::unban(const char *id) { if (id!=NULL) { MUCCEVENT mucce; mucce.iType = MUCC_EVENT_UNBAN; mucce.pszModule = getModule(); mucce.pszID = getRoomId(); mucce.pszUID = id; NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce); } return 0; } int ChatWindow::kickAndBan(const char *id, int time, const char *reason) { if (id!=NULL) { MUCCEVENT mucce; mucce.iType = MUCC_EVENT_KICK_BAN; mucce.pszModule = getModule(); mucce.pszID = getRoomId(); mucce.pszUID = id; mucce.dwData = time; mucce.pszText = reason; NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce); } return 0; } int ChatWindow::kickAndBan(int time) { ChatUser *user = getSelectedUser(); if (user!=NULL) { kickAndBan(user->getId(), time, ""); } return 0; } int ChatWindow::setRights(const char *id, int flags) { if (id!=NULL) { MUCCEVENT mucce; mucce.iType = MUCC_EVENT_SET_USER_ROLE; mucce.pszModule = getModule(); mucce.pszID = getRoomId(); mucce.pszUID = id; mucce.dwFlags = flags; NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce); } return 0; } int ChatWindow::setRights(int flags) { ChatUser *user = getSelectedUser(); if (user!=NULL) { setRights(user->getId(), flags); } return 0; } int ChatWindow::getUserGroup(ChatUser *user) { int group = 4; if (user->getFlags()&MUCC_EF_USER_GLOBALOWNER) { group = 0; } else if (user->getFlags()&MUCC_EF_USER_OWNER) { group = 1; } else if (user->getFlags()&MUCC_EF_USER_ADMIN) { group = 2; } else if (user->getFlags()&MUCC_EF_USER_MODERATOR) { group = 3; } return group; } int ChatWindow::changePresence(const MUCCEVENT *event) { int i, group, bLogEvent = FALSE; const char *groupNames[] = {"Global Owners", "Owners", "Admins", "Moderators", "Users"}; ChatUser *user = findUser(event->pszUID); if (event->dwData == ID_STATUS_ONLINE || (user!=NULL && event->dwData!=ID_STATUS_OFFLINE)) { Utils::log("new status: %d, %d", event->dwData, user); if (user == NULL) { user = new ChatUser(); user->setId(event->pszUID); user->setNick(event->pszNick); user->setFlags(event->dwFlags); user->setMe(event->bIsMe); addUser(user); if (user->isMe()) { userMe = user; } bLogEvent = TRUE; } else { group = getUserGroup(user); user->setFlags(event->dwFlags); TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), user->getHTreeItem()); if (TreeView_GetChild(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group))==NULL) { TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group)); setTreeItem(group, NULL); } } if (user->isMe()) { if (user->getFlags() & MUCC_EF_USER_OWNER) { EnableWindow(GetDlgItem(hWnd, IDC_TOPIC_BUTTON), TRUE); } else { EnableWindow(GetDlgItem(hWnd, IDC_TOPIC_BUTTON), FALSE); } } group = getUserGroup(user); TVINSERTSTRUCT tvis; if (getTreeItem(group)==NULL) { for (i=group-1;i>=0;i--) { if (getTreeItem(i)!=NULL) break; } tvis.hParent = NULL; if (i>=0) { tvis.hInsertAfter = getTreeItem(i); } else { tvis.hInsertAfter = TVI_FIRST; } tvis.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_CHILDREN; tvis.item.lParam = (LPARAM) NULL; tvis.item.cChildren = 1; tvis.item.pszText = (char *)Translate(groupNames[group]); tvis.item.state = INDEXTOSTATEIMAGEMASK(1); tvis.item.stateMask = TVIS_STATEIMAGEMASK ; setTreeItem(group, TreeView_InsertItem(GetDlgItem(hWnd, IDC_TREELIST), &tvis)); } tvis.hParent = getTreeItem(group); tvis.hInsertAfter = TVI_SORT; tvis.item.mask = TVIF_TEXT | TVIF_PARAM; tvis.item.pszText = (char *)user->getNick(); tvis.item.lParam = (LPARAM) user; user->setHTreeItem(TreeView_InsertItem(GetDlgItem(hWnd, IDC_TREELIST), &tvis)); TreeView_Expand(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group), TVE_EXPAND); } else { if (user != NULL) { group = getUserGroup(user); TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), user->getHTreeItem()); if (TreeView_GetChild(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group))==NULL) { TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group)); setTreeItem(group, NULL); } removeUser(user); delete user; bLogEvent = TRUE; } } if (bLogEvent && wasFirstMessage) { logEvent(event); } return 1; } int ChatWindow::changeTopic(const MUCCEVENT *event) { SetDlgItemText(hWnd, IDC_TOPIC, event->pszText); //if (wasFirstMessage) { logEvent(event); // } return 1; } int ChatWindow::changeRoomInfo(const MUCCEVENT *event) { Utils::log("setting room info !"); setRoomName(event->pszName); setRoomFlags(event->dwFlags); return 1; } const char * ChatWindow::getFontName(int index) { const char *fontNames[] = {"Arial", "Comic Sans MS", "Courier New", "Impact", "Lucida Console", "MS Sans Serif", "Tahoma", "Times New Roman", "Trebuchet MS", "Verdana"}; if (index>9 || index<0) index = 0; return fontNames[index]; } int ChatWindow::getFontNameNum() { return 10; } int ChatWindow::getFontSize(int index) { return index+7; } int ChatWindow::getFontSizeNum() { return 10; } void ChatWindow::refreshSettings() { SendDlgItemMessage(hWnd, IDC_LOG, EM_SETBKGNDCOLOR , 0, Options::getLogBgColor()); SendDlgItemMessage(hWnd, IDC_TREELIST, TVM_SETBKCOLOR, 0, Options::getListBgColor()); eventList.setMaxSize(Options::getLogLimit()); } void ChatWindow::refreshSettings(int force) { if (hListFont!=NULL && !force) { return; } EnterCriticalSection(&mutex); if (hListFont!=NULL) { DeleteObject(hListFont); } if (hListGroupFont!=NULL) { DeleteObject(hListGroupFont); } Font * font = Options::getFont(Options::FONT_USERLIST); colorListText = font->getColor(); hListFont = CreateFont (font->getSize(), 0, 0, 0, font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL, font->getStyle() & Font::ITALIC ? 1 : 0, font->getStyle() & Font::UNDERLINE ? 1 : 0, 0, font->getCharSet(), OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_ROMAN, font->getFace()); font = Options::getFont(Options::FONT_USERLISTGROUP); colorListGroupText = font->getColor(); hListGroupFont = CreateFont (font->getSize(), 0, 0, 0, font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL, font->getStyle() & Font::ITALIC ? 1 : 0, font->getStyle() & Font::UNDERLINE ? 1 : 0, 0, font->getCharSet(), OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_ROMAN, font->getFace()); for (ChatWindow *ptr=list;ptr!=NULL;ptr=ptr->getNext()) { ptr->refreshSettings(); InvalidateRect(ptr->getHWND(), NULL, FALSE); } LeaveCriticalSection(&mutex); } HFONT ChatWindow::getListFont() { return hListFont; } HFONT ChatWindow::getListGroupFont() { return hListGroupFont; } COLORREF ChatWindow::getListTextColor() { return colorListText; } COLORREF ChatWindow::getListGroupTextColor() { return colorListGroupText; } HTREEITEM ChatWindow::getTreeItem(int index) { return hUserGroups[index]; } void ChatWindow::setTreeItem(int index, HTREEITEM hTreeItem) { hUserGroups[index]=hTreeItem; } int ChatWindow::getDefaultOptions() { return FLAG_SHOW_NICKNAMES | FLAG_SHOW_TIMESTAMP | FLAG_FORMAT_ALL | FLAG_LOG_MESSAGES | FLAG_OPT_SENDONENTER; } void ChatWindow::rebuildLog() { int nMin, nMax; HWND hwndLog; SetDlgItemText(getHWND(), IDC_LOG, ""); for (ChatEvent* event=eventList.getEvents();event!=NULL;event=event->getNext()) { if (event->getEvent()->iType == MUCC_EVENT_MESSAGE) { appendMessage(event->getEvent()); } else { appendEvent(event->getEvent()); } } if (ServiceExists(MS_SMILEYADD_REPLACESMILEYS)) PostMessage(getHWND(), WM_TLEN_SMILEY, 0, 0); hwndLog = GetDlgItem(getHWND(), IDC_LOG); GetScrollRange(hwndLog, SB_VERT, &nMin, &nMax); SetScrollPos(hwndLog, SB_VERT, nMax, TRUE); PostMessage(hwndLog, WM_VSCROLL, MAKEWPARAM(SB_THUMBPOSITION, nMax), (LPARAM) NULL); } int ChatWindow::logEvent(const MUCCEVENT *event) { int nMin, nMax; HWND hwndLog; if (event->iType != MUCC_EVENT_ERROR) { if (eventList.addEvent(event)) { rebuildLog(); return 1; } } if (event->iType == MUCC_EVENT_MESSAGE) { wasFirstMessage = 1; appendMessage(event); } else { appendEvent(event); } if (ServiceExists(MS_SMILEYADD_REPLACESMILEYS)) PostMessage(getHWND(), WM_TLEN_SMILEY, 0, 0); hwndLog = GetDlgItem(getHWND(), IDC_LOG); GetScrollRange(hwndLog, SB_VERT, &nMin, &nMax); SetScrollPos(hwndLog, SB_VERT, nMax, TRUE); PostMessage(hwndLog, WM_VSCROLL, MAKEWPARAM(SB_THUMBPOSITION, nMax), (LPARAM) NULL); return 1; } int ChatWindow::appendEvent(const MUCCEVENT *event) { char *rtf, *escapedStr; char timestampStr[100], str[512]; Font *fontTimestamp, *fontPrefix, *fontMessage; int msgSize, iFontSize, bItalic, bBold, bUnderline; HWND hwndLog; CHARRANGE sel; SETTEXTEX stt; DBTIMETOSTRING dbtts; DWORD color; if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_ONLINE && !(getOptions() & FLAG_LOG_JOINED)) { return 0; } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_OFFLINE && !(getOptions() & FLAG_LOG_LEFT)) { return 0; } else if (event->iType==MUCC_EVENT_TOPIC && !(getOptions() & FLAG_LOG_TOPIC)) { return 0; }/* else if (event->iType==MUCC_EVENT_TOPIC && !(getFlags() & FLAG_LOG_TOPIC) { return 0; } */ fontTimestamp = FontList::getFont(FontList::FONT_TIMESTAMP); fontPrefix = FontList::getFont(FontList::FONT_ERROR); rtf = NULL; JabberStringAppend(&rtf, &msgSize, "{\\rtf1\\ansi\\deff0{\\fonttbl"); if (event->iType == MUCC_EVENT_ERROR) { fontMessage = FontList::getFont(FontList::FONT_ERROR); escapedStr = JabberRtfEscape((char *)event->pszText); } else if (event->iType == MUCC_EVENT_STATUS) { if (event->dwData == ID_STATUS_ONLINE) { fontMessage = FontList::getFont(FontList::FONT_JOINED); _snprintf(str, sizeof(str), "%s has joined.", event->pszNick); } else { fontMessage = FontList::getFont(FontList::FONT_LEFT); _snprintf(str, sizeof(str), "%s has left.", event->pszNick); } escapedStr = JabberRtfEscape(str); } else if (event->iType == MUCC_EVENT_TOPIC) { fontMessage = FontList::getFont(FontList::FONT_TOPIC); _snprintf(str, sizeof(str), "The topic is %s.", event->pszText); escapedStr = JabberRtfEscape(str); } else { return 0; } JabberStringAppend(&rtf, &msgSize, "{\\f0\\fnil\\fcharset%u %s;}", fontTimestamp->getCharSet(), fontTimestamp->getFace()); JabberStringAppend(&rtf, &msgSize, "{\\f1\\fnil\\fcharset%u %s;}", fontPrefix->getCharSet(), fontPrefix->getFace()); JabberStringAppend(&rtf, &msgSize, "{\\f2\\fnil\\fcharset%u %s;}", fontMessage->getCharSet(), fontMessage->getFace()); JabberStringAppend(&rtf, &msgSize, "}{\\colortbl "); color = fontTimestamp->getColor(); JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF); color = fontPrefix->getColor(); JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF); color = fontMessage->getColor(); JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF); JabberStringAppend(&rtf, &msgSize, "}"); if (event->iType == MUCC_EVENT_ERROR) { bBold = fontPrefix->getStyle() & Font::BOLD ? 1 : 0; bItalic = fontPrefix->getStyle() & Font::ITALIC ? 1 : 0; bUnderline = fontPrefix->getStyle() & Font::UNDERLINE ? 1 : 0; iFontSize = fontPrefix->getSize(); iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY; JabberStringAppend(&rtf, &msgSize, "\\f1\\cf1\\fs%d\\b%d\\i%d%s %s: ", iFontSize, bBold, bItalic, bUnderline?"\\ul":"", Translate("Error")); } else { if (getOptions()&FLAG_SHOW_DATE || getOptions()&FLAG_SHOW_TIMESTAMP) { bBold = fontTimestamp->getStyle() & Font::BOLD ? 1 : 0; bItalic = fontTimestamp->getStyle() & Font::ITALIC ? 1 : 0; bUnderline = fontTimestamp->getStyle() & Font::UNDERLINE ? 1 : 0; iFontSize = fontTimestamp->getSize(); iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY; dbtts.cbDest = 90; dbtts.szDest = timestampStr; timestampStr[0]='\0'; //time_t time = time if (getOptions()&FLAG_SHOW_DATE && getOptions()&FLAG_SHOW_TIMESTAMP) { if (getOptions()&FLAG_LONG_DATE) { dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"D s" : (char *)"D t"; } else { dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"d s" : (char *)"d t"; } } else if (getOptions()&FLAG_SHOW_DATE) { dbtts.szFormat = getOptions()&FLAG_LONG_DATE ? (char *)"D" : (char *)"d"; } else if (getOptions()&FLAG_SHOW_TIMESTAMP) { dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"s" : (char *)"t"; } else { dbtts.szFormat = (char *)""; } CallService(MS_DB_TIME_TIMESTAMPTOSTRING, (WPARAM)event->time, (LPARAM) & dbtts); JabberStringAppend(&rtf, &msgSize, "\\f0\\cf0\\fs%d\\b%d\\i%d%s %s ", iFontSize, bBold, bItalic, bUnderline?"\\ul":"", timestampStr); } } bBold = fontMessage->getStyle() & Font::BOLD ? 1 : 0; bItalic = fontMessage->getStyle() & Font::ITALIC ? 1 : 0; bUnderline = fontMessage->getStyle() & Font::UNDERLINE ? 1 : 0; iFontSize = fontMessage->getSize(); iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY; JabberStringAppend(&rtf, &msgSize, "\\f2\\cf2\\fs%d\\b%d\\i%d%s %s", iFontSize, bBold, bItalic, bUnderline?"\\ul":"", escapedStr); JabberStringAppend(&rtf, &msgSize, "\\par}"); hwndLog = GetDlgItem(getHWND(), IDC_LOG); sel.cpMin = sel.cpMax = GetWindowTextLength(hwndLog); SendMessage(hwndLog, EM_EXSETSEL, 0, (LPARAM) &sel); stt.flags = ST_SELECTION; stt.codepage = CP_ACP; SendMessage(hwndLog, EM_SETTEXTEX, (WPARAM) &stt, (LPARAM) rtf); //Utils::log("%s", rtf); free(rtf); free(escapedStr); return 1; } int ChatWindow::appendMessage(const MUCCEVENT *event) { char timestampStr[100]; char *rtf, *escapedStr, *escapedNick; Font *fontTimestamp, *fontName, *fontMessage; //*fontColon, int msgSize; DWORD color; int iFontSize, bItalic, bBold, bUnderline; HWND hwndLog; DBTIMETOSTRING dbtts; CHARRANGE sel; SETTEXTEX stt; tm *ltime; if (!(getOptions() & FLAG_LOG_MESSAGES)) return 0; escapedStr=JabberRtfEscape((char *)event->pszText); escapedNick=JabberRtfEscape((char *)event->pszNick); ltime = localtime(&event->time); rtf = NULL; JabberStringAppend(&rtf, &msgSize, "{\\rtf1\\ansi\\deff0{\\fonttbl"); fontTimestamp = FontList::getFont(FontList::FONT_TIMESTAMP); // fontColon = FontList::getFont(FontList::FONT_COLON); if (event->bIsMe) { fontName = FontList::getFont(FontList::FONT_MYNAME); fontMessage = FontList::getFont(FontList::FONT_OUTMESSAGE); } else { fontName = FontList::getFont(FontList::FONT_OTHERSNAMES); fontMessage = FontList::getFont(FontList::FONT_INMESSAGE); } JabberStringAppend(&rtf, &msgSize, "{\\f0\\fnil\\fcharset%u %s;}", fontTimestamp->getCharSet(), fontTimestamp->getFace()); JabberStringAppend(&rtf, &msgSize, "{\\f1\\fnil\\fcharset%u %s;}", fontName->getCharSet(), fontName->getFace()); if (getOptions()&FLAG_FORMAT_FONT) { JabberStringAppend(&rtf, &msgSize, "{\\f2\\fnil\\fcharset%u %s;}", fontMessage->getCharSet(), getFontName(event->iFont)); } else { JabberStringAppend(&rtf, &msgSize, "{\\f2\\fnil\\fcharset%u %s;}", fontMessage->getCharSet(), fontMessage->getFace()); } JabberStringAppend(&rtf, &msgSize, "}{\\colortbl "); color = fontTimestamp->getColor(); JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF); color = fontName->getColor(); JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF); if (getOptions()&FLAG_FORMAT_COLOR && event->color!=0xFFFFFFFF) { color = event->color; } else { color = fontMessage->getColor(); } JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF); JabberStringAppend(&rtf, &msgSize, "}"); if (getOptions()&FLAG_SHOW_DATE || getOptions()&FLAG_SHOW_TIMESTAMP) { bBold = fontTimestamp->getStyle() & Font::BOLD ? 1 : 0; bItalic = fontTimestamp->getStyle() & Font::ITALIC ? 1 : 0; bUnderline = fontTimestamp->getStyle() & Font::UNDERLINE ? 1 : 0; iFontSize = fontTimestamp->getSize(); iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY; dbtts.cbDest = 90; dbtts.szDest = timestampStr; timestampStr[0]='\0'; //time_t time = time if (getOptions()&FLAG_SHOW_DATE && getOptions()&FLAG_SHOW_TIMESTAMP) { if (getOptions()&FLAG_LONG_DATE) { dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"D s" : (char *)"D t"; } else { dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"d s" : (char *)"d t"; } } else if (getOptions()&FLAG_SHOW_DATE) { dbtts.szFormat = getOptions()&FLAG_LONG_DATE ? (char *)"D" : (char *)"d"; } else if (getOptions()&FLAG_SHOW_TIMESTAMP) { dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"s" : (char *)"t"; } else { dbtts.szFormat = (char *)""; } CallService(MS_DB_TIME_TIMESTAMPTOSTRING, (WPARAM)event->time, (LPARAM) & dbtts); JabberStringAppend(&rtf, &msgSize, "\\f0\\cf0\\fs%d\\b%d\\i%d%s %s ", iFontSize, bBold, bItalic, bUnderline?"\\ul":"", timestampStr); } bBold = fontName->getStyle() & Font::BOLD ? 1 : 0; bItalic = fontName->getStyle() & Font::ITALIC ? 1 : 0; bUnderline = fontName->getStyle() & Font::UNDERLINE ? 1 : 0; iFontSize = fontName->getSize(); iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY; if (getOptions()&FLAG_SHOW_NICKNAMES) { JabberStringAppend(&rtf, &msgSize, "\\f1\\cf1\\fs%d\\b%d\\i%d%s %s: ", iFontSize, bBold, bItalic, bUnderline?"\\ul":"", escapedNick); } bBold = fontMessage->getStyle() & Font::BOLD ? 1 : 0; bItalic = fontMessage->getStyle() & Font::ITALIC ? 1 : 0; bUnderline = fontMessage->getStyle() & Font::UNDERLINE ? 1 : 0; iFontSize = fontMessage->getSize(); iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY; if (getOptions()&FLAG_FORMAT_STYLE) { bBold = bItalic = bUnderline = 0; if (event->dwFlags & MUCC_EF_FONT_BOLD) bBold = 1; if (event->dwFlags & MUCC_EF_FONT_ITALIC) bItalic = 1; if (event->dwFlags & MUCC_EF_FONT_UNDERLINE) bUnderline = 1; } if (getOptions()&FLAG_FORMAT_SIZE) { if (event->iFontSize != 0) iFontSize = 2 * event->iFontSize; } if (getOptions()&FLAG_MSGINNEWLINE) { JabberStringAppend(&rtf, &msgSize, "\\line"); } JabberStringAppend(&rtf, &msgSize, "\\f2\\cf2\\fs%d\\b%d\\i%d%s %s", iFontSize, bBold, bItalic, bUnderline?"\\ul":"", escapedStr); JabberStringAppend(&rtf, &msgSize, "\\par}"); //MUCCLog("%s", rtf); hwndLog = GetDlgItem(getHWND(), IDC_LOG); sel.cpMin = sel.cpMax = GetWindowTextLength(hwndLog); SendMessage(hwndLog, EM_EXSETSEL, 0, (LPARAM) &sel); stt.flags = ST_SELECTION; stt.codepage = CP_ACP; SendMessage(hwndLog, EM_SETTEXTEX, (WPARAM) &stt, (LPARAM) rtf); free(rtf); free(escapedStr); free(escapedNick); return 1; } void ChatWindow::setFont(int font, int size, int bBold, int bItalic, int bUnderline, COLORREF color) { if (hEditFont!=NULL) { DeleteObject(hEditFont); } hEditFont = CreateFont (MulDiv(-size, logPixelSY, 74), 0, 0, 0, bBold?FW_BOLD:FW_NORMAL, bItalic, bUnderline, 0, 238, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_ROMAN, getFontName(font)); SendDlgItemMessage(hWnd, IDC_EDIT, WM_SETFONT, (WPARAM) hEditFont, TRUE); this->font = font; this->fontSize = size; this->bBold = bBold; this->bItalic = bItalic; this->bUnderline = bUnderline; this->fontColor = color; } int ChatWindow::getFontStyle() { int style = 0; if (bBold) style |= MUCC_EF_FONT_BOLD; if (bItalic) style |= MUCC_EF_FONT_ITALIC; if (bUnderline) style |= MUCC_EF_FONT_UNDERLINE; return style; } int ChatWindow::getFont() { return font; } int ChatWindow::getFontSize() { return fontSize; } COLORREF ChatWindow::getFontColor() { return fontColor; } void ChatWindow ::queryResultContacts(MUCCQUERYRESULT *queryResult) { HelperDialog::inviteDlg(this, queryResult); } void ChatWindow ::queryResultUsers(MUCCQUERYRESULT *queryResult) { if (adminWindow!=NULL) { adminWindow->queryResultUsers(queryResult); } } ChatWindow * ChatWindow::getWindow(const char *module, const char *roomId) { ChatWindow *ptr; EnterCriticalSection(&mutex); for (ptr=list;ptr!=NULL;ptr=ptr->getNext()) { if (strcmp(ptr->getRoomId(), roomId)==0 && strcmp(ptr->getModule(), module)==0) { break; } } LeaveCriticalSection(&mutex); return ptr; } static DWORD CALLBACK EditStreamCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG * pcb) { char *szFilename = (char *)dwCookie; FILE *file; file = fopen(szFilename, "ab"); if (file != NULL) { *pcb = fwrite(pbBuff, cb, 1, file); fclose(file); return 0; } return 1; } static BOOL CALLBACK EditWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { ChatWindow *chat; chat = (ChatWindow *) GetWindowLong(GetParent(hwnd), GWL_USERDATA); switch (msg) { // case WM_GETDLGCODE: // return DLGC_WANTALLKEYS; //DLGC_WANTARROWS|DLGC_WANTCHARS|DLGC_HASSETSEL|DLGC_WANTALLKEYS; case WM_CHAR: if (wParam=='\r' || wParam=='\n') { if (((GetKeyState(VK_CONTROL)&0x8000)==0) == ((Options::getChatWindowOptions() & ChatWindow::FLAG_OPT_SENDONENTER) != 0)) { PostMessage(GetParent(hwnd), WM_COMMAND, IDOK, 0); return FALSE; } } if (wParam == 1 && GetKeyState(VK_CONTROL) & 0x8000) { //ctrl-a SendMessage(hwnd, EM_SETSEL, 0, -1); return 0; } if (wParam == 23 && GetKeyState(VK_CONTROL) & 0x8000) { // ctrl-w SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0); return 0; } break; } return CallWindowProc(oldEditWndProc, hwnd, msg, wParam, lParam); } static BOOL CALLBACK SplitterWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { ChatWindow *chat; chat = (ChatWindow *) GetWindowLong(GetParent(hwnd), GWL_USERDATA); switch (msg) { case WM_NCHITTEST: return HTCLIENT; case WM_SETCURSOR: RECT rc; GetClientRect(hwnd, &rc); SetCursor(rc.right > rc.bottom ? hCurSplitNS : hCurSplitWE); return TRUE; case WM_LBUTTONDOWN: SetCapture(hwnd); return 0; case WM_MOUSEMOVE: if (GetCapture() == hwnd) { HWND hParent; RECT rc; POINT pt; hParent = GetParent(hwnd); GetClientRect(hwnd, &rc); if (rc.right < rc.bottom) { pt.x = LOWORD(GetMessagePos()); GetClientRect(hParent, &rc); ScreenToClient(hParent, &pt); if (pt.x < chat->vSplitterMinLeft) pt.x = chat->vSplitterMinLeft; if (rc.right-pt.x < chat->vSplitterMinRight) pt.x = rc.right-chat->vSplitterMinRight; if (chat->vSplitterPos != rc.right-pt.x) { chat->vSplitterPos = rc.right-pt.x; SendMessage(hParent, WM_SIZE, SIZE_RESTORED, (rc.bottom<<16)+rc.right); } } else { pt.y = HIWORD(GetMessagePos()); GetClientRect(hParent, &rc); ScreenToClient(hParent, &pt); if (pt.y < chat->hSplitterMinTop) pt.y = chat->hSplitterMinTop; if (rc.bottom-pt.y < chat->hSplitterMinBottom) pt.y = rc.bottom-chat->hSplitterMinBottom; if (chat->hSplitterPos != rc.bottom-pt.y) { chat->hSplitterPos = rc.bottom-pt.y; SendMessage(hParent, WM_SIZE, SIZE_RESTORED, (rc.bottom<<16)+rc.right); } } } return 0; case WM_LBUTTONUP: ReleaseCapture(); return 0; } return CallWindowProc(oldSplitterWndProc, hwnd, msg, wParam, lParam); } static BOOL CALLBACK LogDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { int i; MUCCEVENT muce; ChatWindow *chatWindow; chatWindow = (ChatWindow *) GetWindowLong(hwndDlg, GWL_USERDATA); if (msg!=WM_INITDIALOG && chatWindow==NULL) { return FALSE; } switch (msg) { case WM_INITDIALOG: HDC hdc; TranslateDialogDefault(hwndDlg); hdc = GetDC(NULL); logPixelSY = GetDeviceCaps(hdc, LOGPIXELSY); ReleaseDC(NULL, hdc); SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) muccIcon[MUCC_IDI_CHAT]); chatWindow = (ChatWindow *) lParam; chatWindow->setHWND(hwndDlg); ChatWindow::refreshSettings(0); oldSplitterWndProc = (WNDPROC)SetWindowLong(GetDlgItem(hwndDlg, IDC_HSPLIT), GWL_WNDPROC, (LONG) SplitterWndProc); oldSplitterWndProc = (WNDPROC)SetWindowLong(GetDlgItem(hwndDlg, IDC_VSPLIT), GWL_WNDPROC, (LONG) SplitterWndProc); oldEditWndProc = (WNDPROC)SetWindowLong(GetDlgItem(hwndDlg, IDC_EDIT), GWL_WNDPROC, (LONG) EditWndProc); ShowWindow(GetDlgItem(hwndDlg, IDC_LIST), SW_HIDE); chatWindow->hSplitterMinTop = 90; chatWindow->hSplitterMinBottom = 40; chatWindow->hSplitterPos=50; chatWindow->vSplitterMinLeft = 100; chatWindow->vSplitterMinRight = 80; chatWindow->vSplitterPos=110; SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) chatWindow); SetWindowLong(GetDlgItem(hwndDlg, IDC_EDIT), GWL_USERDATA, (LONG) chatWindow); chatWindow->refreshSettings(); SetWindowText(hwndDlg, chatWindow->getRoomName()); SendDlgItemMessage(hwndDlg, IDC_BOLD, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_BOLD]); SendDlgItemMessage(hwndDlg, IDC_ITALIC, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_ITALIC]); SendDlgItemMessage(hwndDlg, IDC_UNDERLINE, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_UNDERLINE]); SendDlgItemMessage(hwndDlg, IDC_SMILEYBTN, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_SMILEY]); SendDlgItemMessage(hwndDlg, IDC_LOG, EM_SETEVENTMASK, 0, ENM_MOUSEEVENTS | ENM_LINK); SendDlgItemMessage(hwndDlg, IDC_LOG, EM_SETUNDOLIMIT, 0, 0); SendDlgItemMessage(hwndDlg, IDC_LOG, EM_AUTOURLDETECT, (WPARAM) TRUE, 0); // LoadImage(hInst, smadd_iconinfo.SmileyIcon, IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0)); SendDlgItemMessage(hwndDlg, IDC_OPTIONS, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_OPTIONS]); SendDlgItemMessage(hwndDlg, IDC_INVITE, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_INVITE]); SendDlgItemMessage(hwndDlg, IDC_ROOMADMIN, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_ADMINISTRATION]); SendDlgItemMessage(hwndDlg, IDC_TOPIC_BUTTON, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_ROOMADMIN, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_INVITE, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_BOLD, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_BOLD, BUTTONSETASPUSHBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_ITALIC, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_ITALIC, BUTTONSETASPUSHBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_UNDERLINE, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_UNDERLINE, BUTTONSETASPUSHBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_OPTIONS, BUTTONSETASFLATBTN, 0, 0); SendDlgItemMessage(hwndDlg, IDC_SMILEYBTN, BUTTONSETASFLATBTN, 0, 0); SetWindowLong(GetDlgItem(hwndDlg,IDC_TREELIST),GWL_STYLE,GetWindowLong(GetDlgItem(hwndDlg,IDC_TREELIST),GWL_STYLE)|TVS_NOHSCROLL); SendDlgItemMessage(hwndDlg,IDC_TREELIST, CCM_SETVERSION,(WPARAM)5,0); TreeView_SetImageList(GetDlgItem(hwndDlg, IDC_TREELIST), hImageList, TVSIL_STATE); TreeView_SetItemHeight(GetDlgItem(hwndDlg, IDC_TREELIST), 16); TreeView_SetIndent(GetDlgItem(hwndDlg, IDC_TREELIST), 16); for(i=0;i<chatWindow->getFontSizeNum();i++) { char str[10]; sprintf(str, "%d", chatWindow->getFontSize(i)); int n = SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_ADDSTRING, 0, (LPARAM) str); SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_SETITEMDATA, n, chatWindow->getFontSize(i)); } SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_SETCURSEL, Options::getChatWindowFontSize(), 0); for(i=0;i<chatWindow->getFontNameNum();i++) { int n = SendDlgItemMessage(hwndDlg, IDC_FONT, CB_ADDSTRING, 0, (LPARAM) chatWindow->getFontName(i)); SendDlgItemMessage(hwndDlg, IDC_FONT, CB_SETITEMDATA, n, i); } SendDlgItemMessage(hwndDlg, IDC_FONT, CB_SETCURSEL, Options::getChatWindowFont(), 0); CheckDlgButton(hwndDlg, IDC_BOLD, Options::getChatWindowFontStyle()&Font::BOLD ? TRUE : FALSE); CheckDlgButton(hwndDlg, IDC_ITALIC, Options::getChatWindowFontStyle()&Font::ITALIC ? TRUE : FALSE); CheckDlgButton(hwndDlg, IDC_UNDERLINE, Options::getChatWindowFontStyle()&Font::UNDERLINE ? TRUE : FALSE); SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_SETCOLOUR, 0, (LPARAM)Options::getChatWindowFontColor()); chatWindow->setFont(Options::getChatWindowFont(), chatWindow->getFontSize(Options::getChatWindowFontSize()), Options::getChatWindowFontStyle()&Font::BOLD ? 1 : 0, Options::getChatWindowFontStyle()&Font::ITALIC ? 1 : 0, Options::getChatWindowFontStyle()&Font::UNDERLINE ? 1 : 0, Options::getChatWindowFontColor()); SetWindowPos(hwndDlg, HWND_TOP, 0, 0, 540, 370, SWP_NOMOVE | SWP_SHOWWINDOW); SetFocus(GetDlgItem(hwndDlg, IDC_EDIT)); SetEvent(chatWindow->getEvent()); return TRUE; break; case DM_CHAT_EVENT: MUCCEVENT *mucEvent; mucEvent = (MUCCEVENT *) lParam; switch (mucEvent->iType) { case MUCC_EVENT_MESSAGE: chatWindow->logEvent(mucEvent); break; case MUCC_EVENT_TOPIC: chatWindow->changeTopic(mucEvent); break; case MUCC_EVENT_STATUS: chatWindow->changePresence(mucEvent); break; case MUCC_EVENT_ERROR: chatWindow->logEvent(mucEvent); break; //case MUCC_EVENT_LEAVE: // DestroyWindow(hwndDlg); // break; case MUCC_EVENT_ROOM_INFO: chatWindow->changeRoomInfo(mucEvent); break; } return TRUE; case DM_CHAT_QUERY: MUCCQUERYRESULT *queryResult; queryResult = (MUCCQUERYRESULT *)lParam; switch (queryResult->iType) { case MUCC_EVENT_QUERY_CONTACTS: chatWindow->queryResultContacts(queryResult); break; case MUCC_EVENT_QUERY_USERS: chatWindow->queryResultUsers(queryResult); break; } return TRUE; case WM_SETFOCUS: SetFocus(GetDlgItem(hwndDlg, IDC_EDIT)); return TRUE; case WM_GETMINMAXINFO: MINMAXINFO *mmi; mmi = (MINMAXINFO *) lParam; mmi->ptMinTrackSize.x = 380; mmi->ptMinTrackSize.y = 130; return FALSE; case WM_SIZE: if (wParam!=SIZE_MINIMIZED) { int dlgWidth, dlgHeight; RECT rc; HDWP hdwp; GetClientRect(hwndDlg, &rc); dlgWidth = rc.right-rc.left; dlgHeight = rc.bottom-rc.top; if (dlgHeight-chatWindow->hSplitterPos < chatWindow->hSplitterMinTop) { chatWindow->hSplitterPos = dlgHeight-chatWindow->hSplitterMinTop; } if (chatWindow->hSplitterPos < chatWindow->hSplitterMinBottom) { chatWindow->hSplitterPos = chatWindow->hSplitterMinBottom; } if (dlgWidth-chatWindow->vSplitterPos < chatWindow->vSplitterMinLeft) { chatWindow->vSplitterPos = dlgWidth-chatWindow->vSplitterMinLeft; } if (chatWindow->vSplitterPos < chatWindow->vSplitterMinRight) { chatWindow->vSplitterPos = chatWindow->vSplitterMinRight; } hdwp = BeginDeferWindowPos(16); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_TOPIC), 0, 70, 7, dlgWidth-140, 18, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_LOG), 0, 0, 30, dlgWidth-(chatWindow->vSplitterPos)-2, dlgHeight-(chatWindow->hSplitterPos)-30-26-2, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_TREELIST), 0, dlgWidth-(chatWindow->vSplitterPos)+2, 30, (chatWindow->vSplitterPos)-2, dlgHeight-(chatWindow->hSplitterPos)-30-26-2, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_EDIT), 0, 0, dlgHeight-(chatWindow->hSplitterPos)+2, dlgWidth, (chatWindow->hSplitterPos)-5, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_INVITE), 0, dlgWidth-31, dlgHeight-(chatWindow->hSplitterPos)-26, 31, 24, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_ROOMADMIN), 0, dlgWidth-55, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_BOLD), 0, 0, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER ); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_ITALIC), 0, 24, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER ); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_UNDERLINE), 0, 48, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER ); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_COLOR), 0, 73, dlgHeight-(chatWindow->hSplitterPos)-25, 22, 22, SWP_NOZORDER ); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_FONT), 0, 98, dlgHeight-(chatWindow->hSplitterPos)-24, 110, 13, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_FONTSIZE), 0, 213, dlgHeight-(chatWindow->hSplitterPos)-24, 38, 13, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_SMILEYBTN), 0, 265, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_OPTIONS), 0, dlgWidth-79, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_VSPLIT), 0, dlgWidth-(chatWindow->vSplitterPos)-2, 30, 4, dlgHeight-(chatWindow->hSplitterPos)-30-26-2, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_HSPLIT), 0, 0, dlgHeight-(chatWindow->hSplitterPos)-2, dlgWidth-8, 4, SWP_NOZORDER); EndDeferWindowPos(hdwp); } break; /* case WM_SYSCOMMAND: if (wParam == SC_CLOSE) { SendMessage(hwndDlg, WM_CLOSE, 1, 0); // muce.iType = MUCC_EVENT_LEAVE; // muce.pszModule = chatWindow->getModule(); // muce.pszID = chatWindow->getRoomId(); // NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce); // delete chatWindow; return TRUE; } break; */ case WM_CLOSE: //if (wParam != 1) { // esc //return FALSE; //} DestroyWindow(hwndDlg); return TRUE; case WM_DESTROY: muce.iType = MUCC_EVENT_LEAVE; muce.pszModule = chatWindow->getModule(); muce.pszID = chatWindow->getRoomId(); NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce); SetWindowLong(hwndDlg, GWL_USERDATA, (LONG) NULL); SetWindowLong(GetDlgItem(hwndDlg, IDC_HSPLIT), GWL_WNDPROC, (LONG) oldSplitterWndProc); SetWindowLong(GetDlgItem(hwndDlg, IDC_VSPLIT), GWL_WNDPROC, (LONG) oldSplitterWndProc); SetWindowLong(GetDlgItem(hwndDlg, IDC_EDIT), GWL_WNDPROC, (LONG) oldEditWndProc); delete chatWindow; break; case WM_TLEN_SMILEY: if (ServiceExists(MS_SMILEYADD_REPLACESMILEYS)) { SMADD_RICHEDIT2 smre; smre.cbSize = sizeof(SMADD_RICHEDIT2); smre.hwndRichEditControl = GetDlgItem(hwndDlg, IDC_LOG); smre.Protocolname = (char *)chatWindow->getModule(); smre.rangeToReplace = NULL; smre.useSounds = FALSE; smre.disableRedraw = FALSE; CallService(MS_SMILEYADD_REPLACESMILEYS, 0, (LPARAM) &smre); } break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_OPTIONS: { HMENU hMenu; RECT rc; int iSelection; hMenu=GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)),0); CallService(MS_LANGPACK_TRANSLATEMENU,(WPARAM)hMenu,0); GetWindowRect(GetDlgItem(hwndDlg, IDC_OPTIONS), &rc); CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWNICKNAMES, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_NICKNAMES ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_MSGINNEWLINE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_MSGINNEWLINE ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWDATE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_DATE ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWTIMESTAMP, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_TIMESTAMP ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWSECONDS, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_USELONGDATE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LONG_DATE ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATFONT, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_FONT ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATSIZE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_SIZE ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATCOLOR, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_COLOR ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATSTYLE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_STYLE ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_LOGMESSAGES, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_MESSAGES ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_LOGJOINED, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_JOINED ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_LOGLEFT, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_LEFT ? MF_CHECKED : MF_UNCHECKED); CheckMenuItem(hMenu, ID_OPTIONMENU_LOGTOPIC, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_TOPIC ? MF_CHECKED : MF_UNCHECKED); iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, rc.left, rc.bottom, 0, hwndDlg, NULL); DestroyMenu(hMenu); switch (iSelection) { case ID_OPTIONMENU_SHOWNICKNAMES: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_NICKNAMES); break; case ID_OPTIONMENU_MSGINNEWLINE: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_MSGINNEWLINE); break; case ID_OPTIONMENU_SHOWDATE: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_DATE); break; case ID_OPTIONMENU_SHOWTIMESTAMP: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_TIMESTAMP); break; case ID_OPTIONMENU_SHOWSECONDS: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_SECONDS); break; case ID_OPTIONMENU_USELONGDATE: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LONG_DATE); break; case ID_OPTIONMENU_FORMATFONT: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_FONT); break; case ID_OPTIONMENU_FORMATSIZE: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_SIZE); break; case ID_OPTIONMENU_FORMATCOLOR: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_COLOR); break; case ID_OPTIONMENU_FORMATSTYLE: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_STYLE); break; case ID_OPTIONMENU_LOGMESSAGES: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_MESSAGES); break; case ID_OPTIONMENU_LOGJOINED: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_JOINED); break; case ID_OPTIONMENU_LOGLEFT: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_LEFT); break; case ID_OPTIONMENU_LOGTOPIC: chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_TOPIC); break; case ID_OPTIONMENU_SAVEDEFAULT: Options::setChatWindowOptions(chatWindow->getOptions()); Options::setChatWindowFont((int)SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0)); Options::setChatWindowFontSize((int)SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0)); Options::setChatWindowFontStyle( (IsDlgButtonChecked(hwndDlg, IDC_BOLD) ? Font::BOLD : 0) | (IsDlgButtonChecked(hwndDlg, IDC_ITALIC) ? Font::ITALIC : 0) | (IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE) ? Font::UNDERLINE : 0) ); Options::setChatWindowFontColor((COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0)); Options::saveSettings(); break; } } break; case IDC_SMILEYBTN: SMADD_SHOWSEL smaddInfo; RECT rc; smaddInfo.cbSize = sizeof(SMADD_SHOWSEL); smaddInfo.hwndTarget = GetDlgItem(hwndDlg, IDC_EDIT); smaddInfo.targetMessage = EM_REPLACESEL; smaddInfo.targetWParam = TRUE; smaddInfo.Protocolname = chatWindow->getModule(); GetWindowRect(GetDlgItem(hwndDlg, IDC_SMILEYBTN), &rc); smaddInfo.Direction = 0; smaddInfo.xPosition = rc.left; smaddInfo.yPosition = rc.top + 24; CallService(MS_SMILEYADD_SHOWSELECTION, 0, (LPARAM) &smaddInfo); break; case IDC_INVITE: { MUCCEVENT muce; muce.cbSize = sizeof(MUCCEVENT); muce.iType = MUCC_EVENT_QUERY_CONTACTS; muce.pszModule = chatWindow->getModule(); muce.pszID = chatWindow->getRoomId(); NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce); } break; case IDC_ROOMADMIN: { MUCCEVENT muce; HMENU hMenu; RECT rc; int iSelection; GetWindowRect(GetDlgItem(hwndDlg, IDC_ROOMADMIN), &rc); hMenu=GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)), 2); if (chatWindow->getMe()!=NULL) { if (chatWindow->getMe()->getFlags() & (MUCC_EF_USER_OWNER | MUCC_EF_USER_ADMIN)) { EnableMenuItem(hMenu, ID_ADMINMENU_ADMIN, MF_BYCOMMAND | MF_ENABLED); EnableMenuItem(hMenu, ID_ADMINMENU_BROWSE, MF_BYCOMMAND | MF_ENABLED); } if (chatWindow->getMe()->getFlags() & MUCC_EF_USER_OWNER) { EnableMenuItem(hMenu, ID_ADMINMENU_DESTROY, MF_BYCOMMAND | MF_ENABLED); } } iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, rc.left, rc.bottom, 0, hwndDlg, NULL); DestroyMenu(hMenu); switch (iSelection) { case ID_ADMINMENU_DESTROY: muce.cbSize = sizeof(MUCCEVENT); muce.iType = MUCC_EVENT_REMOVE_ROOM; muce.pszModule = chatWindow->getModule(); muce.pszID = chatWindow->getRoomId(); NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce); delete chatWindow; break; case ID_ADMINMENU_ADMIN: chatWindow->startAdminDialog(ChatWindow::ADMIN_MODE_KICK); break; case ID_ADMINMENU_BROWSE: chatWindow->startAdminDialog(ChatWindow::ADMIN_MODE_ROLE); break; case ID_ADMINMENU_SAVELOG: { char szFilename[MAX_PATH]; strcpy(szFilename, ""); OPENFILENAMEA ofn={0}; ofn.lStructSize=sizeof(OPENFILENAME); ofn.hwndOwner=hwndDlg; ofn.lpstrFile = szFilename; ofn.lpstrFilter = "Rich Text File\0*.rtf\0\0"; ofn.nMaxFile = MAX_PATH; ofn.nMaxFileTitle = MAX_PATH; ofn.Flags = OFN_HIDEREADONLY; ofn.lpstrDefExt = "rtf"; if (GetSaveFileNameA(&ofn)) { //remove(szFilename); EDITSTREAM stream = { 0 }; stream.dwCookie = (DWORD_PTR)szFilename; stream.dwError = 0; stream.pfnCallback = EditStreamCallback; SendDlgItemMessage(hwndDlg, IDC_LOG, EM_STREAMOUT, SF_RTF | SF_USECODEPAGE, (LPARAM) & stream); } } break; } } break; case IDC_TOPIC_BUTTON: HelperDialog::topicDlg(chatWindow); break; case IDCANCEL: DestroyWindow(hwndDlg); return TRUE; case IDOK: { char text[2048]; GetDlgItemText(hwndDlg, IDC_EDIT, text, sizeof(text)); SetDlgItemText(hwndDlg, IDC_EDIT, ""); muce.iType = MUCC_EVENT_MESSAGE; muce.pszModule = chatWindow->getModule(); muce.pszID = chatWindow->getRoomId(); muce.pszText = text; muce.iFont = chatWindow->getFont(); muce.iFontSize = chatWindow->getFontSize(); muce.dwFlags = chatWindow->getFontStyle(); muce.color = chatWindow->getFontColor(); NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce); } break; case IDC_BOLD: case IDC_ITALIC: case IDC_UNDERLINE: if (HIWORD(wParam)==BN_CLICKED) { chatWindow->setFont((int) SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0), 0), (int) SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0), 0), IsDlgButtonChecked(hwndDlg, IDC_BOLD), IsDlgButtonChecked(hwndDlg, IDC_ITALIC), IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE), (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0)); } case IDC_FONT: case IDC_FONTSIZE: if (HIWORD(wParam)==CBN_SELCHANGE) { chatWindow->setFont((int) SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0), 0), (int) SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0), 0), IsDlgButtonChecked(hwndDlg, IDC_BOLD), IsDlgButtonChecked(hwndDlg, IDC_ITALIC), IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE), (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0)); } break; case IDC_COLOR: if (HIWORD(wParam)==CPN_COLOURCHANGED) { InvalidateRect(GetDlgItem(hwndDlg, IDC_EDIT), NULL, FALSE); chatWindow->setFont((int) SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0), 0), (int) SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0), 0), IsDlgButtonChecked(hwndDlg, IDC_BOLD), IsDlgButtonChecked(hwndDlg, IDC_ITALIC), IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE), (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0)); } break; } break; case WM_CTLCOLOREDIT: if ((HWND) lParam == GetDlgItem(hwndDlg, IDC_EDIT)) { SetTextColor((HDC) wParam, (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0)); SetBkColor((HDC) wParam, Options::getInputBgColor()); //SelectObject((HDC) wParam, Options::getInputBgBrush()); return (BOOL) Options::getInputBgBrush(); } break; case WM_NOTIFY: LPNMHDR pNmhdr; pNmhdr = (LPNMHDR)lParam; if (pNmhdr->idFrom = IDC_TREELIST) { switch (pNmhdr->code) { case TVN_ITEMEXPANDING: { LPNMTREEVIEW pnmtv = (LPNMTREEVIEW) lParam; if (pnmtv->action==TVE_COLLAPSE) { SetWindowLong(hwndDlg,DWL_MSGRESULT, TRUE); return TRUE; } } break; case NM_RCLICK: { TVHITTESTINFO hti; hti.pt.x=(short)LOWORD(GetMessagePos()); hti.pt.y=(short)HIWORD(GetMessagePos()); ScreenToClient(pNmhdr->hwndFrom,&hti.pt); if(TreeView_HitTest(pNmhdr->hwndFrom, &hti) && hti.flags&TVHT_ONITEM) { TVITEM tvi = {0}; tvi.mask = TVIF_PARAM|TVIF_HANDLE; tvi.hItem = hti.hItem; TreeView_GetItem(pNmhdr->hwndFrom, &tvi); ChatUser *user = (ChatUser *) tvi.lParam; if (user!=NULL) { TreeView_Select(pNmhdr->hwndFrom, tvi.hItem, TVGN_CARET); if (!user->isMe()) { HMENU hMenu; int iSelection; hMenu = GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)),1); CallService(MS_LANGPACK_TRANSLATEMENU,(WPARAM)hMenu,0); if (chatWindow->getMe()!=NULL) { if (chatWindow->getMe()->getFlags() & MUCC_EF_USER_OWNER) { EnableMenuItem(hMenu, 2, MF_BYPOSITION | MF_ENABLED); EnableMenuItem(hMenu, 3, MF_BYPOSITION | MF_ENABLED); EnableMenuItem(hMenu, ID_USERMENU_ADMINISTRATION, MF_BYCOMMAND | MF_ENABLED); } else if (chatWindow->getMe()->getFlags() & MUCC_EF_USER_ADMIN) { if (!(user->getFlags() & (MUCC_EF_USER_OWNER | MUCC_EF_USER_OWNER))) { EnableMenuItem(hMenu, 2, MF_BYPOSITION | MF_ENABLED); //EnableMenuItem(hMenu, 3, MF_BYPOSITION | MF_ENABLED); EnableMenuItem(hMenu, ID_USERMENU_ADMINISTRATION, MF_BYCOMMAND | MF_ENABLED); } } } //CheckMenuItem(hMenu, ID_USERMENU_MESSAGE, MF_BYCOMMAND | MF_CHECKED : MF_UNCHECKED); //EnableMenuItem(hMenu, ID_USERMENU_MESSAGE, MF_BYCOMMAND | MF_GRAYED); iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, (short)LOWORD(GetMessagePos()), (short)HIWORD(GetMessagePos()), 0, hwndDlg, NULL); DestroyMenu(hMenu); if (iSelection == ID_USERMENU_MESSAGE) { chatWindow->startPriv(); } else if (iSelection >= ID_USERMENU_KICK_NO_BAN && iSelection <= ID_USERMENU_KICK_BAN_4_W) { int banTime[] = {0, 1, 5, 15, 30, 60, 360, 1440, 4320, 10080, 20160, 40320}; chatWindow->kickAndBan(banTime[iSelection-ID_USERMENU_KICK_NO_BAN] *60); } else if (iSelection == ID_USERMENU_RIGHTS_MEMBER) { chatWindow->setRights(MUCC_EF_USER_MEMBER); } else if (iSelection == ID_USERMENU_RIGHTS_ADMIN) { chatWindow->setRights(MUCC_EF_USER_ADMIN); } else if (iSelection == ID_USERMENU_RIGHTS_NO) { chatWindow->setRights(0); } else if (iSelection == ID_USERMENU_ADMINISTRATION) { chatWindow->startAdminDialog(ChatWindow::ADMIN_MODE_KICK); } } } } } break; case NM_CUSTOMDRAW: LPNMTVCUSTOMDRAW pCustomDraw = (LPNMTVCUSTOMDRAW)lParam; switch (pCustomDraw->nmcd.dwDrawStage) { case CDDS_PREPAINT: SetWindowLong(hwndDlg,DWL_MSGRESULT,CDRF_NOTIFYITEMDRAW); return TRUE; case CDDS_ITEMPREPAINT: { TVITEM tvi;; HICON hIcon; char str[200]; RECT rc = pCustomDraw->nmcd.rc; tvi.mask = TVIF_HANDLE | TVIF_STATE | TVIF_TEXT | TVIF_PARAM; tvi.pszText = str; tvi.cchTextMax = sizeof(str); tvi.hItem = (HTREEITEM)pCustomDraw->nmcd.dwItemSpec; TreeView_GetItem(pCustomDraw->nmcd.hdr.hwndFrom, &tvi); ChatUser * user= (ChatUser *)pCustomDraw->nmcd.lItemlParam; hIcon = NULL; pCustomDraw->clrTextBk = Options::getListBgColor(); switch (pCustomDraw->iLevel) { case 0: pCustomDraw->clrText = ChatWindow::getListGroupTextColor(); SelectObject(pCustomDraw->nmcd.hdc, ChatWindow::getListGroupFont()); break; case 1: pCustomDraw->clrText = ChatWindow::getListTextColor(); if (pCustomDraw->nmcd.uItemState & CDIS_SELECTED) { // selected (CDIS_FOCUS | pCustomDraw->clrTextBk = 0xDAC8C2; } else { pCustomDraw->clrTextBk = Options::getListBgColor(); } if (user!=NULL) { if (user->getFlags()&MUCC_EF_USER_GLOBALOWNER) { hIcon = muccIcon[MUCC_IDI_U_GLOBALOWNER]; } else if (user->getFlags()&MUCC_EF_USER_OWNER) { hIcon = muccIcon[MUCC_IDI_U_OWNER]; } else if (user->getFlags()&MUCC_EF_USER_ADMIN) { hIcon = muccIcon[MUCC_IDI_U_ADMIN]; } else if (user->getFlags()&MUCC_EF_USER_REGISTERED) { hIcon = muccIcon[MUCC_IDI_U_REGISTERED]; } } SelectObject(pCustomDraw->nmcd.hdc, ChatWindow::getListFont()); break; } if (rc.bottom-rc.top!=0 && rc.right-rc.left!=0) { HBRUSH hBr; hBr = CreateSolidBrush(pCustomDraw->clrTextBk); FillRect(pCustomDraw->nmcd.hdc, &rc, hBr); DeleteObject(hBr); if (hIcon!=NULL) { DrawIconEx(pCustomDraw->nmcd.hdc, rc.left, rc.top, hIcon, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0, NULL, DI_NORMAL); } SetBkMode(pCustomDraw->nmcd.hdc, TRANSPARENT); SetTextColor(pCustomDraw->nmcd.hdc, pCustomDraw->clrText); TextOut(pCustomDraw->nmcd.hdc, rc.left+pCustomDraw->iLevel*GetSystemMetrics(SM_CXSMICON)+2, rc.top, tvi.pszText, strlen(tvi.pszText)); } SetWindowLong(hwndDlg,DWL_MSGRESULT, CDRF_SKIPDEFAULT ); return TRUE; } } break; } } break; } return FALSE; } static char *JabberRtfEscape(char *str) { char *escapedStr; int size; char *p, *q; if (str == NULL) return NULL; for (p=str,size=0; *p!='\0'; p++) { if (*p=='\\' || *p=='{' || *p=='}') size += 2; else if (*p=='\n' || *p=='\t') size += 5; else size++; } if ((escapedStr=(char *)malloc(size+1)) == NULL) return NULL; for (p=str,q=escapedStr; *p!='\0'; p++) { if (strchr("\\{}", *p) != NULL) { *q++ = '\\'; *q++ = *p; } else if (*p == '\n') { strcpy(q, "\\par "); q += 5; } else if (*p == '\t') { strcpy(q, "\\tab "); q += 5; } else { *q++ = *p; } } *q = '\0'; return escapedStr; } static void JabberStringAppend(char **str, int *sizeAlloced, const char *fmt, ...) { va_list vararg; char *p; int size, len; if (str == NULL) return; if (*str==NULL || *sizeAlloced<=0) { *sizeAlloced = size = 2048; *str = (char *) malloc(size); len = 0; } else { len = strlen(*str); size = *sizeAlloced - strlen(*str); } p = *str + len; va_start(vararg, fmt); while (_vsnprintf(p, size, fmt, vararg) == -1) { size += 2048; (*sizeAlloced) += 2048; *str = (char *) realloc(*str, *sizeAlloced); p = *str + len; } va_end(vararg); }
[ "the_leech@3f195757-89ef-0310-a553-cc0e5972f89c" ]
[ [ [ 1, 1699 ] ] ]
ec5f7b6b0d47ca5448a86646009fb514093d827a
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Stellar_/code/Foundation/Utility/win32/win32guid.cc
b396762c33c06721c7840967f0b3564b55b6b955
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
5,002
cc
//------------------------------------------------------------------------------ // win32guid.cc // (C) 2006 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "utility/win32/win32guid.h" namespace Win32 { Memory::Heap* Win32Guid::ObjectHeap = 0; using namespace Util; //------------------------------------------------------------------------------ /** */ void Win32Guid::operator=(const Win32Guid& rhs) { if (this != &rhs) { this->uuid = rhs.uuid; } } //------------------------------------------------------------------------------ /** */ void Win32Guid::operator=(const String& rhs) { s_assert(!rhs.empty()); RPC_STATUS result = UuidFromString((RPC_CSTR) rhs.c_str(), &(this->uuid)); s_assert(RPC_S_INVALID_STRING_UUID != result); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::operator==(const Win32Guid& rhs) const { RPC_STATUS status; int result = UuidCompare(const_cast<UUID*>(&this->uuid), const_cast<UUID*>(&rhs.uuid), &status); return (0 == result); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::operator!=(const Win32Guid& rhs) const { RPC_STATUS status; int result = UuidCompare(const_cast<UUID*>(&this->uuid), const_cast<UUID*>(&rhs.uuid), &status); return (0 != result); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::operator<(const Win32Guid& rhs) const { RPC_STATUS status; int result = UuidCompare(const_cast<UUID*>(&this->uuid), const_cast<UUID*>(&rhs.uuid), &status); return (-1 == result); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::operator<=(const Win32Guid& rhs) const { RPC_STATUS status; int result = UuidCompare(const_cast<UUID*>(&this->uuid), const_cast<UUID*>(&rhs.uuid), &status); return ((-1 == result) || (0 == result)); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::operator>(const Win32Guid& rhs) const { RPC_STATUS status; int result = UuidCompare(const_cast<UUID*>(&this->uuid), const_cast<UUID*>(&rhs.uuid), &status); return (1 == result); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::operator>=(const Win32Guid& rhs) const { RPC_STATUS status; int result = UuidCompare(const_cast<UUID*>(&this->uuid), const_cast<UUID*>(&rhs.uuid), &status); return ((1 == result) || (0 == result)); } //------------------------------------------------------------------------------ /** */ bool Win32Guid::IsValid() const { RPC_STATUS status; int result = UuidIsNil(const_cast<UUID*>(&this->uuid), &status); return (TRUE != result); } //------------------------------------------------------------------------------ /** */ void Win32Guid::Generate() { UuidCreate(&this->uuid); } //------------------------------------------------------------------------------ /** */ String Win32Guid::AsString() const { const char* uuidStr; UuidToString((UUID*) &this->uuid, (RPC_CSTR*) &uuidStr); String result = uuidStr; RpcStringFree((RPC_CSTR*)&uuidStr); return result; } //------------------------------------------------------------------------------ /** This method allows read access to the raw binary data of the uuid. It returns the number of bytes in the buffer, and a pointer to the data. */ SizeT Win32Guid::AsBinary(const unsigned char*& outPtr) const { outPtr = (const unsigned char*) &this->uuid; return sizeof(UUID); } //------------------------------------------------------------------------------ /** */ Win32Guid Win32Guid::FromString(const Util::String& str) { Win32Guid newGuid; RPC_STATUS success = UuidFromString((RPC_CSTR)str.c_str(), &(newGuid.uuid)); s_assert(RPC_S_OK == success); return newGuid; } //------------------------------------------------------------------------------ /** Constructs the guid from binary data, as returned by the AsBinary(). */ Win32Guid Win32Guid::FromBinary(const unsigned char* ptr, SizeT numBytes) { s_assert((0 != ptr) && (numBytes == sizeof(UUID))); Win32Guid newGuid; Memory::Copy(ptr, &(newGuid.uuid), sizeof(UUID)); return newGuid; } //------------------------------------------------------------------------------ /** This method returns a hash code for the uuid, compatible with Util::HashTable. */ IndexT Win32Guid::HashCode() const { RPC_STATUS status; unsigned short hashCode = UuidHash((UUID*)&this->uuid, &status); return (IndexT) hashCode; } }; // namespace Win32
[ "ctuomail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 186 ] ] ]
f8421a2a6582894ffb9f168061777c6a27f2f81c
be78c6c17e74febd81d3f89e88347a0d009f4c99
/src/GoIO_cpp/MacOSX/GTextUtils_Mac.cpp
c922c806f8f64755be531a7fe8947e7a51a67a89
[]
no_license
concord-consortium/goio_sdk
87b3f816199e0bc3bd03cf754e0daf2b6a10f792
e371fd14b8962748e853f76a3a1b472063d12284
refs/heads/master
2021-01-22T09:41:53.246014
2011-07-14T21:33:34
2011-07-14T21:33:34
851,663
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
12,878
cpp
// GTextUtils_Mac.cpp #include "GTextUtils.h" // #include "GApplicationBrain.h" // #include "GDrawing.h" #include "GUtils.h" #include "GCharacters.h" // #include "MMacApp.h" // #include "MResourceConstants.h" // #include "MUtils.h" // #include <UScrap.h> using namespace std; void GTextUtils::OSInitResourceStrings(void) { /* unsigned int nTimeStamp = GUtils::OSGetTimeStamp(); bool bResult = false; cppstring sFileName = GetMacApp()->GetAppFolderPath() + "Contents:Resources:strings.txt"; #ifdef _DEBUG // The debug version first checks for files in the appropriate path cppstring sAppPath = GetMacApp()->GetAppFolderPath(); int npos = sAppPath.find("Product_LP:MacOS:Output:"); if (npos != cppstring::npos) { cppstring sOpusPath = sAppPath.substr(0, npos); bResult = ReadStringsFromFile(sOpusPath + "Core:Common:CoreStrings.txt"); bResult &= ReadStringsFromFile(sOpusPath + "Product_LP:Common:LPStrings.txt"); } if (!bResult) { m_mStringIndices.clear(); m_vStringData.clear(); bResult = ReadStringsFromFile(sFileName); } #else bResult = ReadStringsFromFile(sFileName); #endif if (!bResult) { GUtils::MessageBox("Error opening strings file: " + sFileName); GSTD_ASSERT(false); } // Now loop through the strings and do OS-specific processing cppstring sAmpersand = GSTD_STRING(IDSX_AMPERSAND_SUB); cppstring sOKDone = GSTD_STRING(IDSX_OK_DONE_SUB); cppstring sDone = GSTD_STRING(IDSX_DONE_REPLACEMENT); cppstring sDegreeCode = GSTD_S("&#176;"); cppstring sDegree = kDegreeChar; cppstring sAppName = GApplicationBrain::GetApplicationName(); cppstring sAppSub = GSTD_STRING(IDSX_APPNAME_SUB); for (size_t ix = 0; ix < m_vStringData.size(); ix++) { cppstring sText = m_vStringData[ix]; // Convert all newlines to OS specific if (!UEnvironment::IsRunningOSX()) sText = GTextUtils::StringReplace(sText, "\n", "\r"); // Revisit: find a faster way to convert the file // Convert Windows-1252 to MacRoman // sText = MUtils::ConvertStringEncodingToMac(sText); // Now replace IDSX_AMPERSAND_SUB sText = GTextUtils::StringReplace(sText, sAmpersand, GSTD_S("")); // Replace special characters sText = GTextUtils::StringReplace(sText, sDegreeCode, sDegree); sText = GTextUtils::StringReplace(sText, GSTD_S("&#153;"), GSTD_S("ª")); // Now convert "..." to "É" sText = GTextUtils::StringReplace(sText, GSTD_S("..."), GSTD_S("É")); // Replace %app (IDSX_APPNAME_SUB) with the actual application name sText = GTextUtils::StringReplace(sText, sAppSub, sAppName); // Now loop through and replace IDSX_OK_DONE_SUB m_vStringData[ix] = GTextUtils::StringReplace(sText, sOKDone, sDone); } cppsstream ss; ss << "Init: Reading strings file: " << (GUtils::OSGetTimeStamp() - nTimeStamp) << " ms"; GSTD_TRACE(ss.str()); */ } /* bool GTextUtils::OSGetOSStringByKey(const char * sKey, // ID of string to get OSStringPtr pOSString) // [out] return system string here { StringPtr pStr = (StringPtr) pOSString; cppstring s = GTextUtils::GetStringByKey(sKey); if (!s.empty() && (s.length() < 256)) { *pStr = (unsigned char)s.length(); strncpy((char *) pStr+1, s.c_str(), s.length()); return true; } return false; } */ /* bool GTextUtils::OSGetOSStringByIndex(int nID, // ID of string to get OSStringPtr pOSString) // [out] return system string here { StringPtr pStr = (StringPtr) pOSString; cppstring s = GTextUtils::GetStringByIndex(nID); if (!s.empty() && (s.length() < 256)) { *pStr = (unsigned char)s.length(); strncpy((char *) pStr+1, s.c_str(), s.length()); return true; } return false; } */ cppstring GTextUtils::OSConvertReturnLineFeed(cppstring sText) { // RETURN sText with all line feed return pairs in the proper format for Mac // replace all windows \n\n\r (where does extra \n come from?) with just \n sText = GTextUtils::StringReplace(sText, "\n\n\r", kOSNewlineString); // and get any remaining line windows line endings sText = GTextUtils::StringReplace(sText, "\r\n", kOSNewlineString); sText = GTextUtils::StringReplace(sText, "\n", kOSNewlineString); return sText; } cppstring GTextUtils::OSGetPathSeparator(void) { return ":"; } bool GTextUtils::OSTextDataToClipboard(const cppstring & sText, bool bClearClipboard) { bool bResult = true; /* if(sText.length() > 0) { narrowstring sAscii = GTextUtils::ConvertWideStringToNarrow(sText); try { UScrap::SetData(ResType_Text, sAscii.c_str(), sAscii.length(), bClearClipboard); } catch(LException) { bResult = false; ::SysBeep(1); } } */ return bResult; } bool GTextUtils::OSIsTextClipDataAvailable(long * pOutLength) { /* SInt32 nDataLength = UScrap::GetData(ResType_Text, NULL); if(pOutLength) *pOutLength = nDataLength; return (nDataLength > 0); */ return false; } bool GTextUtils::OSGetTextClipData(cppstring * pOutString) { /* if(!pOutString) return false; SInt32 nDataLength = UScrap::GetData(ResType_Text, NULL); if(nDataLength > 0) { Handle hBuffer = ::NewHandle(nDataLength + 1); nDataLength = UScrap::GetData(ResType_Text, hBuffer); ::HLock(hBuffer); (*hBuffer)[nDataLength] = '\0'; *pOutString = *hBuffer; DisposeHandle(hBuffer); } return (pOutString->length() > 0); */ return false; } bool GTextUtils::OSPrintPlainText(const cppstring & sText, bool bShowJobDialog) { // VERY LIMITED FUNCTIONALITY AT PRESENT! // We don't even support printing more than one page of text... /* bool bDidPrint = false; bool bShowWarmFuzzy = true; if (!GetMacApp()->IsPrinterInitialized()) GDrawing::InitializePrinter(); // Open a printing context... bool bWeStartedSession = false; bool bCreatedSession = false; LPrintSpec & theSpec = UPrinting::GetAppPrintSpec(); OSStatus err = noErr; PMPrintSession thePMSession = theSpec.GetPrintSession(); if (thePMSession == NULL) { err = PMCreateSession(&thePMSession); if (err == noErr) { GSTD_ASSERT(thePMSession != NULL); bCreatedSession = true; } } if ((err == noErr) && (thePMSession != NULL)) { if (!theSpec.IsInSession()) { theSpec.BeginSession(thePMSession); err = theSpec.GetError(); if (err == noErr) bWeStartedSession = true; } } if (bWeStartedSession) { Rect paperRect; theSpec.GetPaperRect(paperRect); Rect drawRect = paperRect; // We always use 1/2" margins... ::InsetRect(&drawRect, GDrawing::GetPrinterDPI() / 2, GDrawing::GetPrinterDPI() / 2); // We want a fresh print settings ::PMSessionDefaultPrintSettings(thePMSession, theSpec.GetPrintSettings()); ::PMSetPageRange(theSpec.GetPrintSettings(), 1, 1); bool bOKToPrint; if (!bShowJobDialog || UPrinting::AskPrintJob(theSpec)) { StPrintContext * pPrintContext; bool bTryAgain = false; do { try { GSTD_NEW(pPrintContext, (StPrintContext *), StPrintContext(theSpec)); pPrintContext->BeginPage(); bTryAgain = false; bOKToPrint = true; } catch (...) { pPrintContext = NULL; // This probably means there is no current printer set up if (!bShowJobDialog) { bShowWarmFuzzy = false; bOKToPrint = UPrinting::AskPrintJob(theSpec); if (bOKToPrint) bTryAgain = !bTryAgain; } } } while (bTryAgain); if (bOKToPrint && (pPrintContext != NULL)) { if (pPrintContext->GetGrafPtr()) { SInt16 nJust = UTextTraits::SetPortTextTraits(kTxtr_Courier12); ::TextSize(10); real fScale = GDrawing::GetPrinterDPI() / GDrawing::GetMonitorDPI(); if (fScale > 0.0 && fScale != 1.0) ::TextSize((fScale * 10.0)+0.5); UTextDrawing::DrawWithJustification(const_cast<char *> (sText.c_str()), sText.length(), drawRect, nJust); } pPrintContext->EndPage(); delete pPrintContext; bDidPrint = true; } } // End printing session... if (bWeStartedSession && theSpec.IsInSession()) theSpec.EndSession(); } else MUtils::HandleOSError(err); if (bCreatedSession && (thePMSession != NULL)) PMRelease(thePMSession); return (bDidPrint && bShowWarmFuzzy); */ return false; } short GTextUtils::OSApplyTextSize(short nNewSize, void *) { // Change the text size // ::TextSize(nNewSize); // return nNewSize; return 0; } bool GTextUtils::OSGetLine(cppsstream * pInStream, cppstring * pOutString) { bool bOK = false; if (std::getline(*pInStream, *pOutString, kOSNewlineChar)) { bOK = true; // getline paranoia - make sure we don't have any newlines *pOutString = GTextUtils::StringReplace(*pOutString, "\r", ""); *pOutString = GTextUtils::StringReplace(*pOutString, "\n", ""); } return bOK; } int GTextUtils::OSGetTextLength(cppstring sText) {// using the currect font return the horizontal space needed to draw sText // return GDrawing::OSCalcTextWidth(NULL,sText); return 0; } // list of chars to map to web entities for outgoing text StringVector * GTextUtils::GetOSOutgoingSpecialChars(void) { if (kvOutgoingSpecialChar.size() == 0) { cppstring s; // its important to list ampersand FIRST so that if the user has entered an ampersand it is converted before we convert // other special chars. When we switch back we convert the ampersand LAST so it doesn't get confused and read as part of // another entity. s += kAmpersandChar; kvOutgoingSpecialChar.push_back(s); s = GSTD_S(""); s += kGreaterThanChar; kvOutgoingSpecialChar.push_back(s); s = GSTD_S(""); s += kLessThanChar; kvOutgoingSpecialChar.push_back(s); s = GSTD_S(""); } return &kvOutgoingSpecialChar; } // list of web entities to map chars to StringVector * GTextUtils::GetOSOutgoingSpecialCharCodes(void) { if (kvOutgoingSpecialCharCode.size() == 0) { // its important to list ampersand FIRST so that if the user has entered an ampersand it is converted before we convert // other special chars. When we switch back we convert the ampersand LAST so it doesn't get confused and read as part of // another entity. kvOutgoingSpecialCharCode.push_back(GSTD_S("&#38;")); // ampersand (could also be &amp;) kvOutgoingSpecialCharCode.push_back(GSTD_S("&#62;")); // '>' (could also be &gt;) kvOutgoingSpecialCharCode.push_back(GSTD_S("&#60;")); // '<' (could also be &lt;) } return &kvOutgoingSpecialCharCode; } cppstring GTextUtils::OSGetNativeCharCodeForUTF8(unsigned short nUTF8Char) { // Typically a Windows-charset or MacRoman character equivalent to a UTF-8 char code. // NOTE that if controls & text displays have UTF-8 support this OS method should // not do anything, assuming we're also using wide strings. cppstring nChar = ""; switch(nUTF8Char) { case GUTF8CharCode::kAmpersand: nChar += '&'; break; case GUTF8CharCode::kCopyright: nChar += '©'; break; case GUTF8CharCode::kRegistered: nChar += '¨'; break; case GUTF8CharCode::kDegree: nChar += '¡'; break; case GUTF8CharCode::kPlusOrMinus: nChar += '±'; break; case GUTF8CharCode::kMu: nChar += 'µ'; break; case GUTF8CharCode::kBullet: nChar += '¥'; break; case GUTF8CharCode::kLowerCasePi: nChar += '¹'; break; case GUTF8CharCode::kSuperScriptTwo: nChar += kSuperScriptTwo; break; default: break; } return nChar; } unsigned short GTextUtils::OSGetUTF8CharCodeForNative(unsigned short nMacRomanChar) { unsigned short nChar = 0; switch((char)nMacRomanChar) { case '&': nChar = GUTF8CharCode::kAmpersand; break; case '©': nChar = GUTF8CharCode::kCopyright; break; case '¨': nChar = GUTF8CharCode::kRegistered; break; case '¡': nChar = GUTF8CharCode::kDegree; break; case '±': nChar = GUTF8CharCode::kPlusOrMinus; break; case 'µ': nChar = GUTF8CharCode::kMu; break; case '¥': nChar = GUTF8CharCode::kBullet; break; case '¹': nChar = GUTF8CharCode::kLowerCasePi; break; default: break; } return nChar; }
[ [ [ 1, 452 ] ] ]
8888adc07c5c780a7d03bff4138eca9fd71741fb
a7a890e753c6f69e8067d16a8cd94ce8327f80b7
/tserver/server.h
2ce52fc7fbf18fdedfda3d876d33e66978d2a055
[]
no_license
jbreslin33/breslinservergame
684ca8b97f36e265f30ae65e1a65435b2e7a3d8b
292285f002661c3d9483fb080845564145d47999
refs/heads/master
2021-01-21T13:11:50.223394
2011-03-14T11:33:30
2011-03-14T11:33:30
37,391,245
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
h
#ifndef SERVER_H #define SERVER_H #include "network.h" #include <string.h> typedef struct { float x; float y; } VECTOR2D; typedef struct { int key; // Pressed keys VECTOR2D vel; // Velocity VECTOR2D origin; // Position int msec; // How long to run command (in ms) } command_t; typedef struct clientData { command_t frame[COMMAND_HISTORY_SIZE]; command_t serverFrame; command_t command; long processedFrame; struct sockaddr address; dreamClient *netClient; VECTOR2D startPos; bool team; clientData *next; } clientData; class CArmyWarServer { private: dreamServer *networkServer; clientData *clientList; // Client list int clients; // Number of clients int realtime; // Real server up-time in ms int servertime; // Server frame * 100 ms float frametime; // Frame time in seconds char gamename[32]; int index; clientData *playerWithFlag; long framenum; public: CArmyWarServer(); ~CArmyWarServer(); // Network.cpp void ReadPackets(void); void SendCommand(void); void SendExitNotification(void); void ReadDeltaMoveCommand(dreamMessage *mes, clientData *client); void BuildMoveCommand(dreamMessage *mes, clientData *client); void BuildDeltaMoveCommand(dreamMessage *mes, clientData *client); // Server.cpp int InitNetwork(); void ShutdownNetwork(void); void CalculateVelocity(command_t *command, float frametime); void MovePlayers(void); void MovePlayer(clientData *client); void AddClient(void); void RemoveClient(struct sockaddr *address); void RemoveClients(void); void Frame(int msec); clientData *GetClientList(void) { return clientList; } void SetName(char *n) { strcpy(gamename, n); } char *GetName(void) { return gamename; } void SetIndex(int ind) { index = ind; } int GetIndex(void) { return index; } CArmyWarServer *next; }; #endif
[ "jbreslin33@localhost" ]
[ [ [ 1, 98 ] ] ]
d60e996826972f370b6179da2b7e0dedd0cf8dc5
a7a890e753c6f69e8067d16a8cd94ce8327f80b7
/jserver/main.cpp
20e16499f38d80271f499cb6692567bc906aefe2
[]
no_license
jbreslin33/breslinservergame
684ca8b97f36e265f30ae65e1a65435b2e7a3d8b
292285f002661c3d9483fb080845564145d47999
refs/heads/master
2021-01-21T13:11:50.223394
2011-03-14T11:33:30
2011-03-14T11:33:30
37,391,245
0
0
null
null
null
null
UTF-8
C++
false
false
6,381
cpp
/******************************************/ /* MMOG programmer's guide */ /* Tutorial game server */ /* Programming: */ /* Teijo Hakala */ /******************************************/ #ifdef WIN32 #ifndef _WINSOCKAPI_ #define _WINSOCKAPI_ #endif #include <windows.h> #endif #ifdef WIN32 #include <shellapi.h> #else #include <signal.h> #include <syslog.h> #include <errno.h> #include <unistd.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #endif #include <string.h> #include <stdlib.h> #include <stdio.h> // WIN32 only #ifdef WIN32 // UNIX only #else int runningDaemon; #endif #include "../dreamsock/DreamSock.h" #include "server.h" #include "../dreamsock/DreamServer.h" CArmyWarServer* game; #ifdef WIN32 //----------------------------------------------------------------------------- // Name: empty() // Desc: //----------------------------------------------------------------------------- LRESULT CALLBACK WindowProc(HWND WindowhWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Process Messages switch(Message) { case WM_CREATE: break; case WM_DESTROY: PostQuitMessage(0); break; default: break; } return DefWindowProc(WindowhWnd, Message, wParam, lParam); } //----------------------------------------------------------------------------- // Name: WinMain() // Desc: Windows app start position //----------------------------------------------------------------------------- int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASS WinClass; WinClass.style = 0; WinClass.lpfnWndProc = WindowProc; WinClass.cbClsExtra = 0; WinClass.cbWndExtra = 0; WinClass.hInstance = hInstance; WinClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); WinClass.hCursor = LoadCursor(NULL, IDC_ARROW); WinClass.hbrBackground = (HBRUSH) (COLOR_MENU); WinClass.lpszMenuName = 0; WinClass.lpszClassName = "WINCLASS1"; if(!RegisterClass(&WinClass)) return 0; HWND hwnd = CreateWindow(WinClass.lpszClassName, "dreamSock server", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 320, 240, 320, 240, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, SW_HIDE); StartLogConsole(); game = new CArmyWarServer(); if(game->InitNetwork() != 0) { LogString("Could not create game server"); } MSG WinMsg; bool done = false; int time, oldTime, newTime; // first peek the message without removing it PeekMessage(&WinMsg, hwnd, 0, 0, PM_NOREMOVE); oldTime = game->networkServer->dreamSock->dreamSock_GetCurrentSystemTime(); try { while(!done) { while (PeekMessage(&WinMsg, NULL, 0, 0, PM_NOREMOVE)) { if(!GetMessage(&WinMsg, NULL, 0, 0)) { game->networkServer->dreamSock->dreamSock_Shutdown(); done = true; } TranslateMessage(&WinMsg); DispatchMessage(&WinMsg); } do { newTime = game->networkServer->dreamSock->dreamSock_GetCurrentSystemTime(); time = newTime - oldTime; } while (time < 1); game->Frame(time); oldTime = newTime; } } catch(...) { LogString("Unknown Exception caught in main loop"); game->networkServer->dreamSock->dreamSock_Shutdown(); MessageBox(NULL, "Unknown Exception caught in main loop", "Error", MB_OK | MB_TASKMODAL); return -1; } return WinMsg.wParam; } #else //----------------------------------------------------------------------------- // Name: daemonInit() // Desc: Initialize UNIX daemon //----------------------------------------------------------------------------- static int daemonInit(void) { printf("Running daemon...\n\n"); runningDaemon = 1; pid_t pid; if((pid = fork()) < 0) { return -1; } else if(pid != 0) { exit(0); } setsid(); umask(0); close(1); close(2); close(3); return 0; } //----------------------------------------------------------------------------- // Name: keyPress() // Desc: Check for a keypress //----------------------------------------------------------------------------- int keyPress(void) { static char keypressed; struct timeval waittime; int num_chars_read; fd_set mask; FD_SET(0, &mask); waittime.tv_sec = 0; waittime.tv_usec = 0; if(select(1, &mask, 0, 0, &waittime)) { num_chars_read = read(0, &keypressed, 1); if(num_chars_read == 1) return ((int) keypressed); } return (-1); } //----------------------------------------------------------------------------- // Name: main() // Desc: UNIX app start position //----------------------------------------------------------------------------- int main(int argc, char **argv) { LogString("Welcome to Army War Server v2.0"); LogString("-------------------------------\n"); if(argc > 1) { if(strcmp(argv[1], "-daemon") == 0) { daemonInit(); } } // Ignore the SIGPIPE signal, so the program does not terminate if the // pipe gets broken signal(SIGPIPE, SIG_IGN); LogString("Init successful"); game = new CArmyWarServer(); game->InitNetwork(); int time, oldTime, newTime; oldTime = game->networkServer->dreamSock->dreamSock_GetCurrentSystemTime(); // App main loop try { if(runningDaemon) { // Keep server alive while(1) { do { newTime = game->networkServer->dreamSock->dreamSock_GetCurrentSystemTime(); time = newTime - oldTime; } while (time < 1); game->Frame(time); oldTime = newTime; } } else { // Keep server alive (wait for keypress to kill it) while(keyPress() == -1) { do { newTime = game->networkServer->dreamSock->dreamSock_GetCurrentSystemTime(); time = newTime - oldTime; } while (time < 1); game->Frame(time); oldTime = newTime; } } } catch(...) { game->networkServer->dreamSock->dreamSock_Shutdown(); LogString("Unknown Exception caught in main loop"); return -1; } LogString("Shutting down everything"); game->networkServer->dreamSock->dreamSock_Shutdown(); return 0; } #endif
[ "jbreslin33@localhost" ]
[ [ [ 1, 317 ] ] ]
603c62d9b4707432cf7f9e9922815f7fe6936b7d
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/ui/FontCache.cpp
00b3afcb0d8997fb58b8e028bd9d4fe3a4939098
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
2,196
cpp
// FontCache.cpp // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert 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, version 2 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #include "FontCache.h" #include <cstring> #include <stdexcept> #include "video/Renderer.h" #include "include/fcnc_endian.h" #include "include/Logger.h" #include "vfs/vfs.h" #include "include/sdllayer.h" #include "TFontImage.h" #include "Font.h" using namespace std; /** * Constructor */ FontCache::FontCache (void) { // We don't need to do this font_cache.empty(); } /** * Destructor */ FontCache::~FontCache (void) { for (unsigned int i = 0; i < font_cache.size(); i++){ if (font_cache[i].fontimg != NULL){ SDL_FreeSurface (font_cache[i].fontimg); } font_cache[i].fontimg = NULL; } } /** * Add a font to the cache */ void FontCache::Add (TFontImage Image) { font_cache.push_back (Image); } /** * Add a font to the cache */ void FontCache::Add (std::string fontname, SDL_Surface *img, std::vector<SDL_Rect> chrdest) { TFontImage FntImg; FntImg.fontname = fontname; FntImg.chrdest = chrdest; FntImg.fontimg = img; font_cache.push_back (FntImg); } /** Get a font from the cache*/ bool FontCache::Get (std::string fontname, SDL_Surface **fontimg, std::vector<SDL_Rect> &chrdest) { *fontimg = NULL; chrdest.empty(); for (unsigned int i = 0; i < font_cache.size(); i++){ if (font_cache[i].fontname == fontname){ chrdest = font_cache[i].chrdest; *fontimg = font_cache[i].fontimg; //printf ("Found font in new cache\n"); return true;; } } return false; }
[ [ [ 1, 90 ] ] ]
d6c1d607f73da7a318d45f50a5b9ee1bd6f62646
5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e
/Include/util/LinearTimeInterpolator.h
506250f738a09dbe0480d5e7d2dd9b78de256fa3
[ "BSD-3-Clause" ]
permissive
gui-works/ui
3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b
023faf07ff7f11aa7d35c7849b669d18f8911cc6
refs/heads/master
2020-07-18T00:46:37.172575
2009-11-18T22:05:25
2009-11-18T22:05:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
h
/* * Copyright (c) 2003-2006, Bram Stein * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LINEARTIMEINTERPOLATOR_H #define LINEARTIMEINTERPOLATOR_H #include "./TimeBasedInterpolator.h" namespace ui { namespace util { /** * Interpolates linear time. */ class LinearTimeInterpolator : public TimeBasedInterpolator { public: /** * Create a linear time interpolator. * @param * target Target value. * @param * totalTime the timespan the interpolator has to interpolate. * @param * start The base value to start interpolation at. * @param * end The end value, indicates where the interpolator stops interpolating. */ LinearTimeInterpolator(float totalTime, float start, float end); /** * Calculate the interpolation. */ void calculate(); private: float startValue, endValue; }; } } #endif
[ "bs@bram.(none)" ]
[ [ [ 1, 66 ] ] ]
3f1332cf6f6a75a9456009d6c87d9e202e0afa25
5e2940026151c566d2d979fbf776a4e62aa68099
/NetDiskToolView.cpp
0916c8b0e12b3e3a82d98bc48ff54b81aae8cd79
[]
no_license
MatthewChan/Softlumos
f2ed6627d7a77c21bb78c954e6314db46841567d
ede766095e155aa1004a5ccde2c867a18eb3d260
refs/heads/master
2020-04-06T07:04:18.348650
2010-12-06T09:37:59
2010-12-06T09:37:59
1,142,706
0
0
null
null
null
null
GB18030
C++
false
false
18,736
cpp
// NetDiskToolView.cpp : implementation of the CNetDiskToolView class // #include "stdafx.h" #include "NetDiskTool.h" #include "MainFrm.h" #include "NetDiskToolDoc.h" #include "NetDiskToolView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CNetDiskToolView IMPLEMENT_DYNCREATE(CNetDiskToolView, CView) BEGIN_MESSAGE_MAP(CNetDiskToolView, CView) //{{AFX_MSG_MAP(CNetDiskToolView) ON_WM_SETFOCUS() ON_WM_KILLFOCUS() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_SIZE() ON_WM_MOUSEWHEEL() ON_WM_HSCROLL() ON_WM_VSCROLL() ON_WM_CHAR() ON_WM_LBUTTONDBLCLK() ON_WM_GETDLGCODE() //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CNetDiskToolView construction/destruction CNetDiskToolView::CNetDiskToolView() { m_PageRows = 0; //一页的行数 m_PageCols = 0; //一页的列数 m_Rows = 0; //总的行数 m_TopLine = 0; //最上面的行 m_LeftChar = 0; //最左面的列 m_TextStart = 0; //开始显示ASCII数据的位置 m_HexStart = 0; //开始显示十六进数据的位置 m_LineHeight = 0; //行高 m_CharWidth = 0; //字符宽度 m_SelStart = 0; m_SelEnd = 0; //被选中的字符串 m_bEditHex = 0; //是否在编辑Hex, NOZERO时表示在编辑Hex数据 m_text = NULL; m_CharCount = 0; } CNetDiskToolView::~CNetDiskToolView() { } ///////////////////////////////////////////////////////////////////////////// // CNetDiskToolView drawing void CNetDiskToolView::OnDraw(CDC* pDC) { // CNetDiskToolDoc* pDoc = GetDocument(); // ASSERT_VALID(pDoc); // TODO: add draw code for native data here CRect rc; GetClientRect(rc); if(NULL == m_text || 0 >= m_CharCount) { pDC->FillRect(rc, &CBrush(RGB(255,255,255))); return; } CDC dc; dc.CreateCompatibleDC(pDC); CBitmap bm; bm.CreateCompatibleBitmap(pDC, rc.Width(), rc.Height()); dc.SelectObject(bm); dc.SetBoundsRect(&rc, DCB_DISABLE); CFont font; font.CreateFont ( m_LineHeight, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_MODERN, _T("FixedSys")); CFont* oldFont = dc.SelectObject ( &font ); CBrush bkBrush(RGB(255,255,255)); dc.FillRect(rc, &bkBrush); LONG lineCY, hexLineCX, textLineCX; LONG nPos; char currentchar[20]; m_HexStart = m_CharWidth * (8 - m_LeftChar);//计算二进制开始显示的位置 m_TextStart = m_HexStart + m_CharWidth * 50;//计算ASCII码开始显示的位置 for(LONG i = 0; i < m_PageRows; i++)//按行处理 { lineCY = i * m_LineHeight; sprintf(currentchar, "%03Xh:", (m_TopLine-1+i)*16); //chris // sprintf(currentchar, "%08Xh:", (m_TopLine+i)*16); dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT)); dc.SetBkColor(RGB(255,255,255)); dc.TextOut(m_CharWidth*(1-m_LeftChar), lineCY, currentchar);//显示地址 // memcpy(currentchar,&m_text[(m_TopLine+i-1)*16], 16); // currentchar[16] = '\0'; // // if((m_TopLine+i)*16 > m_CharCount) // { // currentchar[m_CharCount%16] = '\0'; // } // // dc.TextOut (m_TextStart, lineCY, currentchar);//先打印本行的字符串,这样可以显示非ASCII文本 for(UINT j = 0; j < 16; j++) { nPos = j + (m_TopLine+i-1)*16; // nPos = j + (m_TopLine+i)*16; //chris // if(nPos > (m_CharCount-1)) // if(nPos >= (m_CharCount-1)) //chris // goto bitblt; dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT)); dc.SetBkColor(RGB(255,255,255)); textLineCX = m_TextStart + j * m_CharWidth; sprintf(currentchar, "%c", m_text[nPos]); // dc.TextOut (textLineCX, lineCY, currentchar); dc.TextOut (textLineCX, lineCY, m_text[nPos]); if(nPos >= m_SelStart && nPos <= m_SelEnd)//被选中则反色处理 { dc.SetBkColor(::GetSysColor ( COLOR_HIGHLIGHT )); dc.SetTextColor(::GetSysColor ( COLOR_HIGHLIGHTTEXT )); // textLineCX = m_TextStart + j * m_CharWidth ; sprintf(currentchar, "%c", m_text[nPos]); // dc.TextOut (textLineCX, lineCY, currentchar); dc.TextOut (textLineCX, lineCY, m_text[nPos]); } else if (m_ModifyList.Find(nPos)) { dc.SetTextColor(RGB(255, 0, 0)); dc.SetBkColor(RGB(255,255,255)); } else { dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT)); dc.SetBkColor(RGB(255,255,255)); } hexLineCX = m_HexStart + j * m_CharWidth *3 ; sprintf(currentchar, "%02X", ((UCHAR *)m_text)[nPos]); dc.TextOut (hexLineCX, lineCY, currentchar); if(nPos == m_SelEnd)//计算当前要编辑的字符位置 { // dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT)); dc.SetTextColor(RGB(255, 255, 255)); //chirs dc.SetBkColor(RGB(0,0,255)); UCHAR cHex = m_text[nPos]; if (0 != m_bEditHex) { //光标在Hex区域时 if(m_bFirst) { cHex = cHex & 0xf0; cHex = cHex >> 4; sprintf(currentchar, "%X", cHex); dc.TextOut (hexLineCX, lineCY, currentchar); } else { hexLineCX = m_HexStart + j * m_CharWidth * 3 + m_CharWidth; cHex = cHex & 0x0f; sprintf(currentchar, "%X", cHex); dc.TextOut (hexLineCX, lineCY, currentchar); } } else { //光标在Text区域时 // sprintf(currentchar, "%c", m_text[nPos]); dc.TextOut (textLineCX, lineCY, cHex); } } if(nPos >= (m_CharCount-1)) //chris goto bitblt; } } bitblt: pDC->BitBlt(0, 0, rc.Width(), rc.Height(), &dc, 0, 0, SRCCOPY); dc.DeleteDC(); } ///////////////////////////////////////////////////////////////////////////// // CNetDiskToolView printing BOOL CNetDiskToolView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CNetDiskToolView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CNetDiskToolView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CNetDiskToolView diagnostics #ifdef _DEBUG void CNetDiskToolView::AssertValid() const { CView::AssertValid(); } void CNetDiskToolView::Dump(CDumpContext& dc) const { CView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CNetDiskToolView message handlers void CNetDiskToolView::SetText(char *input, int len) { if (NULL == input || 0 >= len) { m_text = NULL; m_CharCount = 0; return; } m_text = input; m_ModifyList.RemoveAll(); m_CharCount = len; m_Rows = m_CharCount/16; m_bEditHex = 1; m_TopLine = 1; m_LeftChar = 0; m_SelStart = 0; m_SelEnd = 0; m_StartDrag = FALSE; m_bFirst = TRUE; SetPositionInfo(m_SelStart); CFont font; m_LineHeight = 15; font.CreateFont ( m_LineHeight, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_MODERN, _T("FixedSys")); CFont* oldFont = GetDC()->SelectObject ( &font ); CSize size = GetDC()->GetTextExtent("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); m_LineHeight = size.cy; m_CharWidth = size.cx / 62; m_MaxCols = 75; GetPageRowCols(); SetVertScrollBar(); SetHorzScrollBar(); } void CNetDiskToolView::OnSetFocus(CWnd* pOldWnd) { CView::OnSetFocus(pOldWnd); m_bFocused = TRUE; } void CNetDiskToolView::OnKillFocus(CWnd* pNewWnd) { CView::OnKillFocus(pNewWnd); m_bFocused = FALSE; } //处理鼠标按键及拖动 void CNetDiskToolView::OnLButtonDown(UINT nFlags, CPoint point) { CView::OnLButtonDown(nFlags, point); m_StartDrag = TRUE; m_bFirst = TRUE; m_SelStart = m_SelEnd = Point2Pos(point); SetPositionInfo(m_SelStart); Invalidate(FALSE); } void CNetDiskToolView::OnLButtonUp(UINT nFlags, CPoint point) { CView::OnLButtonUp(nFlags, point); if(m_StartDrag) { m_SelEnd = Point2Pos(point); Invalidate(FALSE); m_StartDrag = FALSE; } } void CNetDiskToolView::OnLButtonDblClk(UINT nFlags, CPoint point) { CView::OnLButtonDblClk(nFlags, point); if (m_SelEnd == Point2Pos(point)) m_bFirst = !m_bFirst; Invalidate(FALSE); } void CNetDiskToolView::OnMouseMove(UINT nFlags, CPoint point) { CView::OnMouseMove(nFlags, point); if(m_StartDrag) { m_SelEnd = Point2Pos(point); Invalidate(FALSE); } } //根据鼠标位置计算对应的字符在缓冲区的位置 LONG CNetDiskToolView::Point2Pos( CPoint point ) { if(m_text == NULL) return 0; LONG line = m_TopLine + point.y / m_LineHeight - 1; LONG charset; m_bEditHex = 1; if (point.x < m_HexStart) { charset = 0; } else if (point.x < m_HexStart + m_CharWidth * 48) { charset = (point.x - m_HexStart) / (m_CharWidth * 3); } else if (point.x < m_TextStart) { charset = 15; } else if(point.x >= m_TextStart && point.x < m_TextStart + 16 * m_CharWidth) { charset = (point.x - m_TextStart)/m_CharWidth; m_bEditHex = 0; } else { charset = 15; m_bEditHex = 0; } return ((line * 16 + charset)>m_CharCount? m_CharCount-1 : (line * 16 + charset)); } void CNetDiskToolView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); if (NULL != m_text) { GetPageRowCols(); } SetVertScrollBar(); SetHorzScrollBar(); } //以下设置滚动条的位置等信息 void CNetDiskToolView::SetVertScrollBar() { if((m_Rows - m_TopLine + 2) < m_PageRows) m_TopLine = 1; SCROLLINFO si; ZeroMemory(&si,sizeof(si)); si.cbSize = sizeof(si); si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; si.nMin = 0; si.nMax = m_Rows-1; si.nPage = m_PageRows; si.nPos = m_TopLine-1; VERIFY(SetScrollInfo(SB_VERT, &si, TRUE)); Invalidate(FALSE); } void CNetDiskToolView::SetHorzScrollBar() { if((80 - m_LeftChar + 2) < m_PageCols) m_LeftChar = 0; SCROLLINFO si; ZeroMemory(&si,sizeof(si)); si.cbSize = sizeof(si); si.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; si.nMin = 0; si.nMax = m_MaxCols; si.nPage = m_PageCols; si.nPos = m_LeftChar; VERIFY(SetScrollInfo(SB_HORZ, &si, TRUE)); Invalidate(FALSE); } BOOL CNetDiskToolView::PreCreateWindow(CREATESTRUCT& cs) { CWnd *pParentWnd = CWnd::FromHandlePermanent(cs.hwndParent); if (pParentWnd == NULL || ! pParentWnd->IsKindOf(RUNTIME_CLASS(CSplitterWnd))) { // View must always create its own scrollbars, // if only it's not used within splitter cs.style |= (WS_HSCROLL | WS_VSCROLL); // cs.dwExStyle |= WS_EX_CONTROLPARENT; } cs.lpszClass = AfxRegisterWndClass(CS_DBLCLKS); return CView::PreCreateWindow(cs); } //处理鼠标滚轮 BOOL CNetDiskToolView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { if(zDelta > 0) { m_TopLine = --m_TopLine < 1 ? 1 : m_TopLine; } else { if((m_TopLine + m_PageRows -2) < m_Rows) m_TopLine+=1; } SetVertScrollBar(); SetHorzScrollBar(); return CView::OnMouseWheel(nFlags, zDelta, pt); } //计算没一页可显示的行数和列数 void CNetDiskToolView::GetPageRowCols() { CRect rc; if (NULL != m_text) { GetClientRect(rc); m_PageRows = rc.Height() / m_LineHeight; m_PageCols = rc.Width() / m_CharWidth; } } //下面是对滚动条的处理 void CNetDiskToolView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CView::OnHScroll(nSBCode, nPos, pScrollBar); SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; VERIFY(GetScrollInfo(SB_HORZ, &si)); switch (nSBCode) { case SB_LEFT: m_LeftChar = 0; break; case SB_BOTTOM: m_LeftChar = 80 - m_PageCols + 1; break; case SB_LINEUP: m_LeftChar = m_LeftChar - 1; break; case SB_LINEDOWN: m_LeftChar = m_LeftChar + 1; break; case SB_PAGEUP: m_LeftChar = m_LeftChar - si.nPage + 1; break; case SB_PAGEDOWN: m_LeftChar = m_LeftChar + si.nPage - 1; break; case SB_THUMBPOSITION: case SB_THUMBTRACK: m_LeftChar = si.nTrackPos; break; default: return; } if((m_LeftChar + m_PageCols - 2) > 80) m_LeftChar = 80 - m_PageCols +2; if(m_LeftChar < 0) m_LeftChar = 0; SetHorzScrollBar(); } void CNetDiskToolView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CView::OnVScroll(nSBCode, nPos, pScrollBar); SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; VERIFY(GetScrollInfo(SB_VERT, &si)); switch (nSBCode) { case SB_TOP: m_TopLine = 0; break; case SB_BOTTOM: m_TopLine = m_Rows - m_PageRows + 1; break; case SB_LINEUP: m_TopLine = m_TopLine - 1; break; case SB_LINEDOWN: m_TopLine = m_TopLine + 1; break; case SB_PAGEUP: m_TopLine = m_TopLine - si.nPage + 1; break; case SB_PAGEDOWN: m_TopLine = m_TopLine + si.nPage - 1; break; case SB_THUMBPOSITION: case SB_THUMBTRACK: m_TopLine = si.nTrackPos+1; break; default: return; } if((m_TopLine + m_PageRows -2) > m_Rows) m_TopLine = m_Rows - m_PageRows + 2; if(m_TopLine < 1) m_TopLine = 1; SetVertScrollBar(); } //0-9a-fA-F键的处理 void CNetDiskToolView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { CView::OnChar(nChar, nRepCnt, nFlags); UINT input; UCHAR cHex = m_text[m_SelEnd]; // InsterModifyIndex(m_SelEnd); if(NULL == m_ModifyList.Find(m_SelEnd)) m_ModifyList.AddHead(m_SelEnd); //用输入的字符替换对应位置的数据 if (0 != m_bEditHex) { //光标在Hex区域时 if(nChar > 47 && nChar < 58) { input = nChar - 48; } else if (nChar > 64 && nChar < 71) { input = nChar - 64 + 9; } else if (nChar > 96 && nChar < 103) { input = nChar - 96 + 9; } else { return; } if(m_bFirst) { input = input << 4; cHex = cHex & 0x0f; cHex = cHex | input; m_bFirst = FALSE; m_text[m_SelEnd] = cHex; } else { cHex = cHex & 0xf0; cHex = cHex | input; m_text[m_SelEnd] = cHex; if (m_SelEnd < SECTOR_SIZE -1) //chris:不能超扇区的SIZE { m_bFirst = TRUE; m_SelEnd ++; } } } else { //光标在Text区域时 m_text[m_SelEnd] = nChar; if (m_SelEnd < SECTOR_SIZE -1) //chris:不能超扇区的SIZE { m_SelEnd ++; } } if(m_SelEnd == m_CharCount) { m_CharCount = m_SelEnd + 1; m_Rows = m_CharCount/16; } m_SelStart = m_SelEnd; ChangeTop(); ChangeLeft(); Invalidate(FALSE); GetDocument()->SetModifiedFlag(TRUE); } //#define VK_PRIOR 0x21 //#define VK_NEXT 0x22 BOOL CNetDiskToolView::PreTranslateMessage(MSG* pMsg) { if(pMsg->message == WM_KEYDOWN) { switch (LOWORD(pMsg->wParam)) { case VK_LEFT: OnCharLeft(); break; case VK_RIGHT: OnCharRight(); break; case VK_UP: OnLineUp(); break; case VK_DOWN: OnLineDown(); break; case VK_PRIOR: OnShortcutOpenSector(FALSE); TRACE("KeyDown with VK_PRIOR\n"); // OnPrevSector(); break; case VK_NEXT: OnShortcutOpenSector(TRUE); TRACE("KeyDown with VK_NEXT\n"); // OnNextSector(); break; default: break; } } if (WM_KEYUP == pMsg->message) { switch (LOWORD(pMsg->wParam)) { case VK_PRIOR: case VK_NEXT: OnUpdateSectorUI(); break; default: break; } } return CView::PreTranslateMessage(pMsg); } //下面四个是对上下左右键的处理 void CNetDiskToolView::OnCharLeft() { if(m_bFirst && m_SelEnd > 0) { m_SelEnd --; m_bFirst = FALSE; } else { m_bFirst = TRUE; } ChangeTop(); ChangeLeft(); m_SelStart = m_SelEnd; Invalidate(FALSE); } void CNetDiskToolView::OnCharRight() { if(m_bFirst) { m_bFirst = FALSE; } else if( m_SelEnd < m_CharCount-1) { m_bFirst = TRUE; m_SelEnd++; } ChangeTop(); ChangeLeft(); m_SelStart = m_SelEnd; Invalidate(FALSE); } void CNetDiskToolView::OnLineUp() { if(m_SelEnd > 15) m_SelEnd = m_SelEnd - 16; ChangeTop(); ChangeLeft(); m_SelStart = m_SelEnd; Invalidate(FALSE); } void CNetDiskToolView::OnLineDown() { if(m_SelEnd + 16 < m_CharCount) m_SelEnd = m_SelEnd + 16; else m_SelEnd = m_CharCount-1; ChangeTop(); ChangeLeft(); m_SelStart = m_SelEnd; Invalidate(FALSE); } //计算显示的最上边字符位置 void CNetDiskToolView::ChangeTop() { int newtop = m_TopLine; if((m_SelEnd/16 + 1) < m_TopLine) { newtop = m_SelEnd/16 + 1; } if((m_SelEnd/16 + 2) > m_TopLine+m_PageRows) { newtop = m_SelEnd/16 + 2 - m_PageRows; } if(newtop != m_TopLine) { m_TopLine = newtop; SetVertScrollBar(); } } //计算显示的最左边字符位置 void CNetDiskToolView::ChangeLeft() { int currentcol = m_SelEnd % 16; if(currentcol*3 + 14 < m_LeftChar) { m_LeftChar = currentcol*3 + 14; SetHorzScrollBar(); } if(currentcol*3 + 14 - m_LeftChar+1 > m_PageCols) { m_LeftChar = currentcol*3 + 14 - m_PageCols +2; SetHorzScrollBar(); } } void CNetDiskToolView::OnShortcutOpenSector(BOOL bNext) { CNetDiskToolDoc *pDoc; pDoc = (CNetDiskToolDoc*)GetDocument(); if (NULL != pDoc) pDoc->ShortcutOpenSector(bNext); } void CNetDiskToolView::OnUpdateSectorUI() { CString szSector; CNetDiskToolDoc *pDoc; pDoc = (CNetDiskToolDoc*)GetDocument(); if (NULL != pDoc) pDoc->UpdateSectorUI(); } UINT CNetDiskToolView::OnGetDlgCode() { // TODO: Add your message handler code here and/or call default return DLGC_WANTARROWS | DLGC_WANTCHARS; // return CView::OnGetDlgCode(); } BOOL CNetDiskToolView::OnWndMsg( UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult ) { if (WM_CHAR == message && VK_TAB == wParam) return FALSE; if (0 > GetAsyncKeyState(VK_CONTROL)) return FALSE; if (0 > GetAsyncKeyState(VK_MENU)) return FALSE; return CView::OnWndMsg(message, wParam, lParam, pResult); } void CNetDiskToolView::SetPositionInfo(LONG nPosition) { CString szMsg; szMsg.Format(_T("Position:%03Xh"), nPosition); GetParentFrame()->SetMessageText(szMsg); }
[ [ [ 1, 854 ] ] ]
0c9ec99fe191c37d3459aafc8a705e542b26ae38
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/GuiLib/GuiLib/MenuBar.cpp
0f1fb42ac433ff1884dabce87ade5f8b28ea8336
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
91,645
cpp
/**************************************************************************** * * * 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 !!!!! * * * *--------------------------------------------------------------------------* * * * Bug Fixes and improvements : (Add your name) * * -Francisco Campos * * -igor1960 * ****************************************************************************/ // // Class : CMenuBar // // Version : 1.0 // // Created : Jan 14, 2001 // // Last Modified: Francisco Campos. // // CMenuBar class version 2.12 // simulates a Dev Studio style dockable menu bar. // based on PixieLib written by Paul DiLascia<www.dilascia.com> // // version history // 2.12 : support OLE menu carelessly. // 2.11 : WindowMenu fixed by VORGA. // 2.10 : CMenuDockBar's problem fixed again and again. // 2.08 : give up precise ComputeMenuTrackPoint // 2.07 : Sychronizing with frame activation problem fixed // 2.06 : CMenuItem::ComputeMenuTrackPoint fixed a little // 2.05 : CMenuDockBar fixed // : Inactive state problem fixed // 2.04 : bug with ::TrackPopupEx carelessly fixed // : synchronizing TrackPopup animation with win98 effect // // written by MB <[email protected]> 1999.11.27 // // // // CMenuBar version 2.13 #include "stdafx.h" #include "MenuBar.h" #include "resource.h" #include "GuiDockContext.h" #include <afxole.h> #include "Menubar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef _DEBUG const BOOL bTraceOn = FALSE; #define LTRACE if (bTraceOn) TRACE const BOOL bTraceOn2 = TRUE; #define LTRACE2 if (bTraceOn2) TRACE #else #define LTRACE #define LTRACE2 #endif BOOL bActivSystemMenu; ////////////////////////////////////////////////////////////////////// // I've found string resource of "More windows" in "user.exe". // But I can't load it, so please replace a following with your language. static const TCHAR _szMoreWindows[] = _T("&More windows..."); ////////////////////////////////////////////////////////////////////// // used for OLE menu (easy fix) static BOOL _bWindowMenuSendCmd = FALSE; static int _nPrevIndexForCmd = -1; ////////////////////////////////////////////////////////////////////// // hook static CMenuBar* g_pMenuBar = NULL; static HHOOK g_hMsgHook = NULL; // message const UINT CMenuBar::WM_GETMENU = ::RegisterWindowMessage(_T("CMenuBar::WM_GETMENU")); const UINT MB_SET_MENU_NULL = ::RegisterWindowMessage(_T("CMenuBar::MB_SET_MENU_NULL")); const int cxBorder2 = ::GetSystemMetrics(SM_CXBORDER)*2; const int cyBorder2 = ::GetSystemMetrics(SM_CYBORDER)*2; // common resources static CFont _fontHorzMenu, _fontVertMenu; static int _cyHorzFont, _cyMenuOnBar, _cyTextMargin; const int CXTEXTMARGIN = 5; DWORD dSt; COLORREF m_clrFace; int gbintHorz; //Horz=0, Vert=1 CRect rcMenu; //CRect of button static BOOL _InitCommonResources(BOOL bForce = FALSE) { if (bForce == FALSE && _fontHorzMenu.m_hObject != NULL) return TRUE;// no need to reinitialize // clean up _fontHorzMenu.DeleteObject(); _fontVertMenu.DeleteObject(); // create fonts NONCLIENTMETRICS info; info.cbSize = sizeof(info); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0); if (!_fontHorzMenu.CreateFontIndirect(&info.lfMenuFont)) return FALSE; // create vertical font info.lfMenuFont.lfEscapement = -900; info.lfMenuFont.lfOrientation = -900; strcpy(info.lfMenuFont.lfFaceName,"verdana"); if (!_fontVertMenu.CreateFontIndirect(&info.lfMenuFont)) return FALSE; // get font height _cyHorzFont = abs(info.lfMenuFont.lfHeight); // calc Y text margin _cyMenuOnBar = info.iMenuHeight; _cyMenuOnBar = max(_cyMenuOnBar, ::GetSystemMetrics(SM_CYSMICON)); _cyTextMargin = (_cyMenuOnBar - _cyHorzFont) / 2; return TRUE; } // I wanted to control popup point, but I've fount we can never get popupmenu rect before popup. // even if not owner draw menu... static CPoint _ComputeMenuTrackPoint(const CRect& rcItem, DWORD dwStyle, UINT& fuFlags, TPMPARAMS& tpm) { fuFlags = TPM_LEFTBUTTON | TPM_LEFTALIGN | TPM_HORIZONTAL; tpm.cbSize = sizeof(tpm); CPoint pt; CRect& rcExclude = (CRect&)tpm.rcExclude; CWnd::GetDesktopWindow()->GetWindowRect(&rcExclude); CRect rcFrame; AfxGetMainWnd()->GetWindowRect(&rcFrame); switch (dwStyle & CBRS_ALIGN_ANY) { case CBRS_ALIGN_RIGHT: case CBRS_ALIGN_LEFT: pt = CPoint(rcItem.right+1, rcItem.top-1); // to avoid strange menu flip, won't do : [rcExclude.right = rcItem.right+1;] // I want to use : fuFlags |= TPM_HORNEGANIMATION; break; default: // case CBRS_ALIGN_TOP: // changed by Manfred Drasch - start CRect rcTmpItem; rcTmpItem = rcItem; if(rcTmpItem.left < 0) { rcTmpItem.right = rcTmpItem.Width(); rcTmpItem.left = 0; } if(rcTmpItem.left > rcExclude.right) { rcTmpItem.right = rcExclude.right; rcTmpItem.left = rcTmpItem.right-rcTmpItem.Width(); } pt = CPoint(rcTmpItem.left-1, rcTmpItem.bottom); rcExclude.bottom = rcTmpItem.bottom+1;// <- insead of [fuFlags |= TPM_VERPOSANIMATION;] // changed by Manfred Drasch - end break; } return pt; } //****************************************************************** static int _CalcTextWidth(const CString& strText) { CWindowDC dc(NULL); CRect rcText(0, 0, 0, 0); CFont* pOldFont = dc.SelectObject(&_fontHorzMenu); dc.DrawText(strText, &rcText, DT_SINGLELINE | DT_CALCRECT); dc.SelectObject(pOldFont); return rcText.Width(); } //****************************************************************** // grippers pasted from MFC6 #define CX_GRIPPER 3 #define CY_GRIPPER 3 #define CX_BORDER_GRIPPER 2 #define CY_BORDER_GRIPPER 2 #define CX_GRIPPER_ALL CX_GRIPPER + CX_BORDER_GRIPPER*2 #define CY_GRIPPER_ALL CY_GRIPPER + CY_BORDER_GRIPPER*2 ///////////////////////////////////////////////////////////////////////////// // CMenuBar BEGIN_MESSAGE_MAP(CMenuBar, CControlBar) //{{AFX_MSG_MAP(CMenuBar) ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_CREATE() ON_WM_LBUTTONUP() ON_WM_LBUTTONDBLCLK() ON_WM_TIMER() ON_WM_DESTROY() ON_WM_NCCALCSIZE() ON_WM_NCPAINT() ON_WM_NCHITTEST() ON_WM_SIZE() ON_WM_SETCURSOR() ON_WM_SYSCOLORCHANGE() //}}AFX_MSG_MAP ON_REGISTERED_MESSAGE(MB_SET_MENU_NULL, OnSetMenuNull) ON_WM_PAINT() END_MESSAGE_MAP() IMPLEMENT_DYNAMIC(CMenuBar, CControlBar) ///////////////////////////////////////////////////////////////////////////// // CMenuBar Construction CMenuBar::CMenuBar() { m_nCurIndex = -1; m_nTrackingState = none; m_bProcessRightArrow = m_bProcessLeftArrow = TRUE; m_bIgnoreAlt = FALSE; m_hMenu = NULL; m_nIDEvent = NULL; szNameHistory.Empty(); bSaveHistory=FALSE; m_bChangeState=FALSE; m_bMDIMaximized = FALSE; m_hWndMDIClient = NULL; m_hWndActiveChild = NULL; m_pMenuIcon = NULL; m_pMenuControl = NULL; m_bDelayedButtonLayout = TRUE; m_dwExStyle = 0; m_bFrameActive = FALSE; m_bMDIApp = FALSE; m_bXP=FALSE; cmb=NULL; m_bCombo=FALSE;//combobox by default bIsTabbed=FALSE; m_MenuContext=NULL; m_StyleDisplay=GUISTYLE_XP; } //****************************************************************** BOOL CMenuBar::Create(CWnd* pParentWnd, DWORD dwStyle, UINT nID) { return CreateEx(pParentWnd, dwStyle, CRect(m_cxLeftBorder, m_cyTopBorder, m_cxRightBorder, m_cyBottomBorder), nID); } //****************************************************************** BOOL CMenuBar::CreateEx(CWnd* pParentWnd, DWORD dwStyle, CRect rcBorders, UINT nID) { ASSERT_VALID(pParentWnd);// must have a parent ASSERT (!((dwStyle & CBRS_SIZE_FIXED) && (dwStyle & CBRS_SIZE_DYNAMIC))); SetBorders(rcBorders); // save the original style m_dwExStyle = dwStyle; // save the style m_dwStyle = (dwStyle & CBRS_ALL);// ******fixed by Mark Gentry, thanx!****** dwStyle &= ~CBRS_ALL; dwStyle|=WS_CLIPCHILDREN | CCS_NOPARENTALIGN | CCS_NOMOVEY | CCS_NORESIZE; CString strClass = AfxRegisterWndClass( /*CS_HREDRAW | CS_VREDRAW |*/ CS_DBLCLKS,// don't forget! AfxGetApp()->LoadStandardCursor(IDC_ARROW), (HBRUSH)NULL); m_clrFace=GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style); return CWnd::Create(strClass, _T("MenuBar"), dwStyle, CRect(), pParentWnd, nID); } void CMenuBar::SetSaveHistory(CString sNameHistory,BOOL bsaveHistory) { szNameHistory=sNameHistory; bSaveHistory=bsaveHistory; } //****************************************************************** int CMenuBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CControlBar::OnCreate(lpCreateStruct) == -1) return -1; CWnd* pFrame = GetOwner(); ASSERT_VALID(pFrame); // hook frame window to trap WM_MENUSELECT //m_hookFrame.Install(this, pFrame->GetSafeHwnd()); // If this is an MDI app, hook client window to trap WM_MDISETMENU if (pFrame->IsKindOf(RUNTIME_CLASS(CMDIFrameWnd))) { m_bMDIApp = TRUE; m_hWndMDIClient = ((CMDIFrameWnd*)pFrame)->m_hWndMDIClient; ASSERT(::IsWindow(m_hWndMDIClient)); m_hookMDIClient.Install(this, m_hWndMDIClient); } if (m_pDockContext==NULL) m_pDockContext=new CGuiDockContext(this); ASSERT(m_pDockContext); if (!_InitCommonResources()) { TRACE(_T("Failed to create menubar resource\n")); return FALSE; } return 0; } void CMenuBar::OnSysColorChange( ) { CClientDC dc(this); m_clrFace=GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style); for (int i = 0; i < m_arrItem.GetSize(); ++i) m_arrItem[i]->UpdateClr(); CWnd::OnSysColorChange( ); /*if(m_pMenuControl != NULL) m_pMenuControl->SetColorButton(GuiDrawLayer::GetRGBColorFace()); if(m_pMenuIcon != NULL) { m_pMenuIcon->OnActivateChildWnd(); m_pMenuIcon->Update(&dc); }*/ } //****************************************************************** BOOL CMenuBar::CreateCombo(CComboBox* pControl,UINT nID,int iSize,DWORD dwStyle) { CFont m_Font; m_Font.CreateStockObject (DEFAULT_GUI_FONT); if(!pControl->Create(dwStyle, CRect(1,1,iSize,100), this, nID)) { TRACE(_T("Failed to create combo-box\n")); m_bCombo=FALSE; return FALSE; } m_bCombo=TRUE; cmb=(CGuiComboBoxExt*)pControl; cmb->ActiveHistory(TRUE); cmb->LoadHistory(szNameHistory,bSaveHistory); return TRUE; } //****************************************************************** void CMenuBar::OnSize(UINT nType, int cx, int cy) { RefreshBar(); if (m_bCombo==TRUE) DrawCombo(); } void CMenuBar::SetTabbed(BOOL bIstabed) { bIsTabbed=bIstabed; } //****************************************************************** BOOL CMenuBar::InitItems() { ASSERT(m_hMenu); // clean up all items DeleteItems(); // buttons for (int i = 0; i < ::GetMenuItemCount(m_hMenu); ++i) { m_arrItem.Add(new CMenuButton(m_hMenu, i,this)); } if (m_bMDIApp) { // icon CWnd* pFrame = GetTopLevelFrame(); ASSERT_VALID(pFrame); CMDIFrameWnd* pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pFrame); HWND hWndMDIClient = pMDIFrame->m_hWndMDIClient; ASSERT(::IsWindow(hWndMDIClient)); HWND hWndChild = (HWND)::SendMessage(hWndMDIClient, WM_MDIGETACTIVE, 0, 0); if ((!bIsTabbed) ) { m_pMenuIcon = new CMenuIcon(this); m_arrItem.InsertAt(0, m_pMenuIcon); // frame control m_pMenuControl = new CMenuControl(this); m_arrItem.Add(m_pMenuControl); // reinitializing m_pMenuIcon->OnActivateChildWnd(); m_pMenuControl->OnActivateChildWnd(); } } return TRUE; } //****************************************************************** BOOL CMenuBar::LoadMenuBar(UINT nIDResource) { ASSERT(m_hMenu == NULL); ASSERT_VALID(m_pDockSite); if (m_pDockSite->GetMenu()) { PostMessage(MB_SET_MENU_NULL, (WPARAM)m_pDockSite->GetSafeHwnd()); } m_hMenu = ::LoadMenu(AfxGetInstanceHandle(), MAKEINTRESOURCE(nIDResource)); if (m_hMenu == NULL) { TRACE(_T("Failed to load menu\n")); return FALSE; } return InitItems(); } //****************************************************************** HMENU CMenuBar::LoadMenu(HMENU hMenu, HMENU hWindowMenu) { ASSERT(::IsMenu(hMenu)); ASSERT_VALID(this); CFrameWnd* pFrame = GetParentFrame(); if (::GetMenu(pFrame->GetSafeHwnd()) != NULL) { // not to make MFC ignore SetMenu(NULL), post it. PostMessage(MB_SET_MENU_NULL, (WPARAM)pFrame->GetSafeHwnd()); } HMENU hOldMenu = m_hMenu; m_hMenu = hMenu;// menu is shared with MFC // initialize Items VERIFY(InitItems()); if (hMenu) { m_hWindowMenu = hWindowMenu; RefreshBar();// and menubar itself } return hOldMenu; } //****************************************************************** void CMenuBar::RefreshBar() { InvalidateRect(NULL); #if _MFC_VER >= 0x600 if (GetParent()->IsKindOf(RUNTIME_CLASS(CReBar))) { m_bDelayedButtonLayout = TRUE;// to avoid ASSERTION Layout(); } #endif CFrameWnd* pFrame = (CFrameWnd*)GetTopLevelFrame(); ASSERT_VALID(pFrame); ASSERT(pFrame->IsFrameWnd()); pFrame->RecalcLayout(); // floating frame CFrameWnd* pMiniFrame = GetParentFrame(); if (pMiniFrame->IsKindOf(RUNTIME_CLASS(CMiniFrameWnd))) pMiniFrame->RecalcLayout(); } ///////////////////////////////////////////////////////////////////////////// // CMenuBar clean up CMenuBar::~CMenuBar() { } //****************************************************************** void CMenuBar::DeleteItems() { for(int i = 0; i < m_arrItem.GetSize(); ++i) { CMenuItem* pItem = m_arrItem[i]; delete pItem; } m_arrItem.RemoveAll(); m_pMenuIcon = NULL; m_pMenuControl = NULL; } //****************************************************************** ///////////////////////////////////////////////////////////////////////////// // CMenuBar draw //****************************************************************** void CMenuBar::UpdateBar(TrackingState nState, int nNewIndex) { if (m_nTrackingState == buttonmouse) m_bIgnoreAlt = FALSE;// if prev state is BUTTONMOUSE, always should be FALSE! m_nTrackingState = nState; // clean up if (IsValidIndex(m_nCurIndex)) { CMenuItem* pItem = m_arrItem[m_nCurIndex]; CClientDC dc(this); pItem->ModifyState(MISTATE_HOT | MISTATE_PRESSED, 0); pItem->Update(&dc); // draw captions forcefully if (m_pMenuControl) { CRect rcCross = m_pMenuControl->GetRect() & m_arrItem[m_nCurIndex]->GetRect(); if (!rcCross.IsRectEmpty()) { m_pMenuControl->DrawControl(); if (m_bCombo==TRUE) DrawCombo(); } } m_nCurIndex = -1; } if (nState != none) { ASSERT(IsValidIndex(nNewIndex)); m_nCurIndex = nNewIndex; CMenuItem* pItem = m_arrItem[m_nCurIndex]; CClientDC dc(this); if (nState == button || nState == buttonmouse) { pItem->ModifyState(MISTATE_PRESSED, MISTATE_HOT); pItem->Update(&dc); } else if (nState == popup) { pItem->ModifyState(MISTATE_HOT, MISTATE_PRESSED); pItem->Update(&dc); } // draw captions forcefully if (m_pMenuControl) { CRect rcCross = m_pMenuControl->GetRect() & m_arrItem[m_nCurIndex]->GetRect(); if (!rcCross.IsRectEmpty()) { m_pMenuControl->DrawControl(); if (m_bCombo==TRUE) DrawCombo(); } } } else { // must be default parameter ASSERT(nNewIndex == -1); } m_bProcessRightArrow = m_bProcessLeftArrow = TRUE; } ///////////////////////////////////////////////////////////////////////////// // CMenuBar message handler int CMenuBar::HitTestOnTrack(CPoint point) { for (int i = 0; i < GetItemCount(); ++i) { CMenuItem* pItem = m_arrItem[i]; CRect rcItem = pItem->GetRect(); if ((pItem->GetStyle() & MISTYLE_TRACKABLE) && rcItem.PtInRect(point)) return i; } return -1; } //******************************************************************* void CMenuBar::OnLButtonDblClk(UINT nFlags, CPoint point) { } //****************************************************************** void CMenuBar::OnLButtonDown(UINT nFlags, CPoint point) { SetCursor (LoadCursor(NULL, IDC_SIZEALL)); //int nIndex = HitTestOnTrack(point); int nIndex=nFlags >= 100? nFlags-100: -1; if(m_bMDIApp && !bIsTabbed) { if (nFlags == 1000) nIndex=0; else if (nIndex == -1) nIndex=-2; else nIndex++; } if (IsValidIndex(nIndex) && (m_arrItem[nIndex]->GetStyle() & MISTYLE_TRACKABLE)) { UpdateBar(button, nIndex); TrackPopup(nIndex); return; // eat it! } CControlBar::OnLButtonDown(nFlags, point); } void CMenuBar::OnRButtonDown(UINT nFlags, CPoint point) { ClientToScreen (&point); CMenu m_menu; if (m_MenuContext!= NULL) { m_menu.LoadMenu(m_MenuContext); CMenu* m_SubMenu = m_menu.GetSubMenu(0); m_SubMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_VERTICAL, point.x, point.y-2, AfxGetMainWnd()); Invalidate(); UpdateWindow(); } // CMenuBar::OnRButtonDown(nFlags, point); } //****************************************************************** void CMenuBar::OnMouseMove(UINT nFlags, CPoint point) { int nIndex = HitTestOnTrack(point); if (!IsTopParentActive() || !GetTopLevelParent()->IsWindowEnabled()) return; if (IsValidIndex(nIndex)) { if (m_nCurIndex == -1 || m_nCurIndex != nIndex) {// if other button UpdateBar(buttonmouse, nIndex);// button made hot with mouse if (!m_nIDEvent) m_nIDEvent = SetTimer(1, 100, NULL); } } else { UpdateBar(); } CControlBar::OnMouseMove(nFlags, point); } //****************************************************************** LRESULT CMenuBar::OnSetMenuNull(WPARAM wParam, LPARAM) { HWND hWnd = (HWND)wParam; ASSERT(::IsWindow(hWnd)); ::SetMenu(hWnd, NULL); return 0; } //****************************************************************** LRESULT CMenuBar::OnSettingChange(WPARAM wParam, LPARAM lParam) { // reinitialize fonts etc if (!_InitCommonResources(TRUE)) { TRACE(_T("Failed to create bar resource\n")); return FALSE; } VERIFY(InitItems()); CFrameWnd* pFrame = GetParentFrame(); ASSERT_VALID(pFrame); pFrame->RecalcLayout(); return 0; } //****************************************************************** void CMenuBar::OnLButtonUp(UINT nFlags, CPoint point) { CControlBar::OnLButtonUp(nFlags, point); } //****************************************************************** void CMenuBar::CheckActiveChildWndMaximized() { if(!m_pMenuControl) return; if (!bIsTabbed) { ASSERT(m_pMenuControl); ASSERT(m_pMenuIcon); } BOOL bMaximized = FALSE; GetActiveChildWnd(bMaximized); if (m_bMDIMaximized != bMaximized) { LTRACE(_T("CMenuBar::CheckActiveChildWndMaximized---state changed, refreshing\n")); m_bMDIMaximized = bMaximized; if (!bIsTabbed) { m_pMenuControl->OnActivateChildWnd(); m_pMenuIcon->OnActivateChildWnd(); if(!m_bMDIMaximized ) { m_bChangeState=TRUE; m_pMenuControl->m_arrButton[0].ShowWindow(SW_HIDE); m_pMenuControl->m_arrButton[1].ShowWindow(SW_HIDE); m_pMenuControl->m_arrButton[2].ShowWindow(SW_HIDE); } else { m_bChangeState=TRUE; m_pMenuControl->m_arrButton[0].ShowWindow(SW_SHOW); m_pMenuControl->m_arrButton[1].ShowWindow(SW_SHOW); m_pMenuControl->m_arrButton[2].ShowWindow(SW_SHOW); } } if (m_bCombo==TRUE) DrawCombo(); RefreshBar(); } } //****************************************************************** void CMenuBar::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) { LTRACE(_T("CMenuBar::OnInitMenuPopup\n")); CMenu menu; menu.Attach((HMENU)m_hWindowMenu); // scan for first window command int n = menu.GetMenuItemCount(); BOOL bAddSeperator = TRUE; for (int iPos=0; iPos<n; iPos++) { if (menu.GetMenuItemID(iPos) >= AFX_IDM_FIRST_MDICHILD) { bAddSeperator = FALSE; break; } } while (iPos < (int)menu.GetMenuItemCount()) menu.RemoveMenu(iPos, MF_BYPOSITION); // get active window so I can check its menu item ASSERT(m_hWndMDIClient); HWND hwndActive = (HWND)::SendMessage(m_hWndMDIClient, WM_MDIGETACTIVE, 0, NULL); // append window names in the form "# title" // *****fixed by VORGA, thanks!***** int iWin; int nID = AFX_IDM_FIRST_MDICHILD; CString sWinName, sMenuItem; HWND hwnd; for (iWin = 1; iWin <= 10; iWin++, nID++) { hwnd = ::GetDlgItem(m_hWndMDIClient, nID); if (hwnd == NULL) break; if (bAddSeperator) { menu.InsertMenu(iPos++, MF_BYPOSITION | MF_SEPARATOR); bAddSeperator = FALSE; } if (iWin < 10) { CWnd::FromHandle(hwnd)->GetWindowText(sWinName); sMenuItem.Format(_T("&%d %s"), iWin, (LPCTSTR)sWinName); menu.InsertMenu(iPos, MF_BYPOSITION, nID, sMenuItem); if (hwnd == hwndActive) menu.CheckMenuItem(iPos, MF_BYPOSITION | MF_CHECKED); } else { menu.InsertMenu(iPos, MF_BYPOSITION, nID, _szMoreWindows); } iPos++; } menu.Detach(); } //****************************************************************** void CMenuBar::OnSetMenu(HMENU hNewMenu, HMENU hWindowMenu) { if (!bIsTabbed) ASSERT(m_pMenuIcon && m_pMenuControl); // We can get active MDI child window on this message! BOOL bMax = FALSE; HWND hWndChild = GetActiveChildWnd(bMax); if (!m_hWndActiveChild || m_hWndActiveChild != hWndChild) {// an active child window changed LTRACE(_T("CMenuBar::OnSetMenu---an active child window changed\n")); m_hWndActiveChild = hWndChild; // tell MenuIcon child window has been changed if (!bIsTabbed) m_pMenuIcon->OnActivateChildWnd(); } if (!m_hMenu || m_hMenu != hNewMenu) { // menu changed LTRACE(_T("CMenuBar::OnSetMenu---menu changed\n")); LoadMenu(hNewMenu, hWindowMenu); // set menubar menu GetOwner()->SetMenu(NULL); // clear frame menu } } //****************************************************************** BOOL CMenuBar::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { CPoint ptCurPos; CRect rc;GetClientRect(rc); GetCursorPos (&ptCurPos); ScreenToClient (&ptCurPos); if (m_dwStyle & CBRS_ORIENT_HORZ) { rc.right=rc.left+2; if (ptCurPos.x< 0) { SetCursor (LoadCursor(NULL, IDC_SIZEALL)); return TRUE; } } else { rc.bottom=rc.top+2; if (ptCurPos.y< 0) { SetCursor (LoadCursor(NULL, IDC_SIZEALL)); return TRUE; } } return CControlBar::OnSetCursor(pWnd, nHitTest, message); } //****************************************************************** void CMenuBar::OnNcPaint() { EraseNonClientEx(); } //****************************************************************** UINT CMenuBar::OnNcHitTest(CPoint point) { // make nonclient area clickable return HTCLIENT; } //****************************************************************** void CMenuBar::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp) { // calculate border space (will add to top/bottom, subtract from right/bottom) CRect rect; rect.SetRectEmpty(); BOOL bHorz = (m_dwStyle & CBRS_ORIENT_HORZ) != 0; _CalcInsideRect(rect, bHorz); if (!(m_dwStyle & CBRS_FLOATING)) { // adjust non-client area for border space lpncsp->rgrc[0].left += bHorz?rect.left+4:rect.left+1; lpncsp->rgrc[0].top += bHorz?rect.top+4:rect.top+2; } else { lpncsp->rgrc[0].left += rect.left; lpncsp->rgrc[0].top += rect.top+4; } lpncsp->rgrc[0].right += rect.right; lpncsp->rgrc[0].bottom += rect.bottom; } //****************************************************************** void CMenuBar::OnDestroy() { if(m_bCombo==TRUE) cmb->SaveHistory(szNameHistory,bSaveHistory); CControlBar::OnDestroy(); // TODO: DeleteItems(); if (m_nIDEvent) KillTimer(m_nIDEvent); // for SDI application if (m_bMDIApp == FALSE && m_hMenu != NULL) ::FreeResource(m_hMenu); } //****************************************************************** void CMenuBar::OnTimer(UINT nIDEvent) { if (m_nTrackingState == buttonmouse) { CPoint pt; ::GetCursorPos(&pt); CRect rect; GetWindowRect(&rect); if (!rect.PtInRect(pt)) { UpdateBar(); if (m_nIDEvent) { KillTimer(m_nIDEvent); m_nIDEvent = NULL; } } } CControlBar::OnTimer(nIDEvent); } //****************************************************************** HWND CMenuBar::GetActiveChildWnd(BOOL& bMaximized) { if (!m_hWndMDIClient) return NULL; BOOL bMax = FALSE; HWND hWnd = (HWND)::SendMessage(m_hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMax); bMaximized = bMax; return hWnd; } //****************************************************************** ///////////////////////////////////////////////////////////////////////////// // CMenuBar system hook void CMenuBar::OnMenuSelect(HMENU hMenu, UINT nIndex) { // LTRACE(_T("CMenuBar::OnMenuSelect\n")); if (m_nTrackingState == popup) { m_bProcessRightArrow = (::GetSubMenu(hMenu, nIndex) == NULL); HMENU hSubMenu = ::GetSubMenu(hMenu, m_nCurIndex); if (hSubMenu == NULL) return; m_bProcessLeftArrow = (hMenu == hSubMenu); } } //****************************************************************** void CMenuBar::OnFrameNcActivate(BOOL bActive) { CFrameWnd* pFrame = GetTopLevelFrame(); ASSERT_VALID(pFrame); if (pFrame->m_nFlags & WF_STAYACTIVE) bActive = TRUE; if (!pFrame->IsWindowEnabled()) bActive = FALSE; if (bActive == m_bFrameActive) return; if (!bActive) { for (int i = 0; i < GetItemCount(); ++i) { m_arrItem[i]->ModifyState(0, MISTATE_INACTIVE); } } else { for (int i = 0; i < GetItemCount(); ++i) { m_arrItem[i]->ModifyState(MISTATE_INACTIVE, 0); } } m_bFrameActive = bActive; // InvalidateRect(NULL); is better, but too late // while clicking the application title bar (like IE5) // so we have to redraw now! } //****************************************************************** LRESULT CALLBACK CMenuBar::MenuInputFilter(int code, WPARAM wParam, LPARAM lParam) { return ( code == MSGF_MENU && g_pMenuBar && g_pMenuBar->OnMenuInput( *((MSG*)lParam) ) ) ? TRUE : CallNextHookEx(g_hMsgHook, code, wParam, lParam); } //****************************************************************** void CMenuBar::TrackPopup(int nIndex) { ASSERT_VALID(this); m_nCurIndex = nIndex; m_bLoop = TRUE; while (m_bLoop == TRUE) { UpdateWindow(); // force to repaint when button hidden by other window UpdateBar(popup, m_nCurIndex); // install hook ASSERT(g_pMenuBar == NULL); g_pMenuBar = this; ASSERT(g_hMsgHook == NULL); m_bLoop = FALSE; g_hMsgHook = ::SetWindowsHookEx(WH_MSGFILTER, MenuInputFilter, NULL, AfxGetApp()->m_nThreadID);// m_bLoop may become TRUE // popup!! m_nTrackingState = popup; _nPrevIndexForCmd = m_nCurIndex; m_arrItem[m_nCurIndex]->TrackPopup(this, GetTopLevelParent()); // uninstall hook ::UnhookWindowsHookEx(g_hMsgHook); g_hMsgHook = NULL; g_pMenuBar = NULL; } UpdateBar(); } //****************************************************************** BOOL CMenuBar::OnMenuInput(MSG& m) { ASSERT_VALID(this); int nMsg = m.message; CPoint pt = m.lParam; ScreenToClient(&pt); switch (nMsg) { case WM_MOUSEMOVE: if (pt != m_ptMouse) { int nIndex = HitTestOnTrack(pt); if ((IsValidIndex(nIndex) && nIndex != m_nCurIndex ) ) { // defferent button clicked // Invalidate(); if (!bActivSystemMenu) AfxGetMainWnd()->PostMessage(WM_CANCELMODE); // destroy popupped menu if (bActivSystemMenu) PostMessage(WM_CANCELMODE); UpdateBar(button, nIndex); UpdateBar(); bActivSystemMenu=FALSE; m_nCurIndex = nIndex; m_bLoop = TRUE; // continue loop } m_ptMouse = pt; } break; case WM_LBUTTONDOWN: if ((HitTestOnTrack(pt) != -1 && HitTestOnTrack(pt) == m_nCurIndex)) { // same button clicked AfxGetMainWnd()->PostMessage(WM_CANCELMODE); // destroy popupped menu //PostMessage(WM_CANCELMODE); UpdateBar(button, m_nCurIndex); m_bLoop = FALSE; // out of loop return TRUE; // eat it! } break; case WM_KEYDOWN: { TCHAR vKey = m.wParam; if (m_dwStyle & CBRS_ORIENT_VERT) { // if vertical break; // do nothing } if ((vKey == VK_LEFT && m_bProcessLeftArrow) || (vKey == VK_RIGHT && m_bProcessRightArrow)) { // no submenu int nNewIndex = GetNextOrPrevButton(m_nCurIndex, vKey==VK_LEFT); AfxGetMainWnd()->PostMessage(WM_CANCELMODE); // destroy popupped menu UpdateBar(); m_nCurIndex = nNewIndex; m_bLoop = TRUE; // continue loop return TRUE; // eat it! } } break; case WM_SYSKEYDOWN: // LTRACE(_T(" m_bIgnore = TRUE\n")); m_bIgnoreAlt = TRUE; // next SysKeyUp will be ignored break; } return FALSE; // pass along... } //****************************************************************** BOOL CMenuBar::TranslateFrameMessage(MSG* pMsg) { ASSERT_VALID(this); ASSERT(pMsg); UINT nMsg = pMsg->message; if (WM_LBUTTONDOWN <= nMsg && nMsg <= WM_MOUSELAST) { if (pMsg->hwnd != m_hWnd && m_nTrackingState > 0) { // clicked outside UpdateBar(); } } else if (nMsg == WM_SYSKEYDOWN || nMsg == WM_SYSKEYUP || nMsg == WM_KEYDOWN) { BOOL bAlt = HIWORD(pMsg->lParam) & KF_ALTDOWN; // Alt key presed? TCHAR vkey = pMsg->wParam; // + X key if (vkey == VK_MENU || (vkey == VK_F10 && !((GetKeyState(VK_SHIFT) & 0x80000000) || (GetKeyState(VK_CONTROL) & 0x80000000) || bAlt))) { // only alt key pressed if (nMsg == WM_SYSKEYUP) { switch (m_nTrackingState) { case none: if (m_bIgnoreAlt == TRUE) { // LTRACE(_T(" ignore ALT key up\n")); m_bIgnoreAlt = FALSE; break; } if (m_bMDIApp) { UpdateBar(button, GetNextOrPrevButton(0, FALSE)); } else { UpdateBar(button, 0); } break; case button: UpdateBar(); break; case buttonmouse: break; // do nothing } } return TRUE; } else if ((nMsg == WM_SYSKEYDOWN || nMsg == WM_KEYDOWN)) { if (m_nTrackingState == button) { if (m_dwStyle & CBRS_ORIENT_HORZ) { // if horizontal switch (vkey) { case VK_LEFT: case VK_RIGHT: { int nNewIndex = GetNextOrPrevButton(m_nCurIndex, vkey == VK_LEFT); UpdateBar(button, nNewIndex); return TRUE; } case VK_SPACE: case VK_UP: case VK_DOWN: TrackPopup(m_nCurIndex); return TRUE; case VK_ESCAPE: UpdateBar(); return TRUE; } } else { // if vertical switch (vkey) { case VK_UP: case VK_DOWN:{ int nNewIndex = GetNextOrPrevButton(m_nCurIndex, vkey == VK_UP); UpdateBar(button, nNewIndex); return TRUE; } case VK_SPACE: case VK_RIGHT: case VK_LEFT: TrackPopup(m_nCurIndex); return TRUE; case VK_ESCAPE: UpdateBar(); return TRUE; } } } // Alt + X pressed if ((bAlt || m_nTrackingState == button) && _istalnum(vkey)) { int nIndex; if (MapAccessKey(vkey, nIndex) == TRUE) { UpdateBar(button, nIndex); UpdateBar(); TrackPopup(nIndex); return TRUE; // eat it! } else if (m_nTrackingState==button && !bAlt) { // MessageBeep(0); // if you want return TRUE; } } if (m_nTrackingState > 0) { // unknown key if (m_nTrackingState != buttonmouse) { // if tracked with mouse, don't update bar UpdateBar(); } } } } return FALSE; // pass along... } //****************************************************************** BOOL CMenuBar::MapAccessKey(TCHAR cAccessKey, int& nIndex) { for (int i = 0; i < GetItemCount(); ++i) { // fixing point TCHAR cKey = m_arrItem[i]->GetAccessKey(); if (toupper(cKey)/*_totupper(cKey)*/ == cAccessKey) {// *****fixed by andi, thanx!***** nIndex = i; return TRUE; } } return FALSE; } ///////////////////////////////////////////////////////////////////////////// // CMenuBar layout int CMenuBar::GetClipBoxLength(BOOL bHorz) { CFrameWnd* pFrame = GetTopLevelFrame(); ASSERT_VALID(pFrame); CRect rcFrame; pFrame->GetWindowRect(rcFrame); CWnd* pParent = GetParent(); ASSERT_VALID(pParent); CRect rcParent; pParent->GetWindowRect(rcParent); const int cxFrameBorder = ::GetSystemMetrics(SM_CXFRAME); int cxNonClient = cxFrameBorder*2 + m_cxLeftBorder + m_cxRightBorder; if (m_dwExStyle & CBRS_GRIPPER) cxNonClient += CX_GRIPPER_ALL; if (m_dwStyle & CBRS_SIZE_DYNAMIC) { if (bHorz) { return rcFrame.Width() - cxNonClient; } else { int nResult = rcParent.Height(); // I don't know the reason of the following code... nResult -= m_cxRightBorder + m_cxLeftBorder + cyBorder2*2; if (m_dwExStyle & CBRS_GRIPPER) nResult -= CY_GRIPPER_ALL; return nResult; } } else { CRect rect; GetClientRect(rect); if (bHorz) { return rect.Width(); } else { return rect.Height(); } } } //****************************************************************** CSize CMenuBar::CalcLayout(DWORD dwMode, int nLength) { ASSERT_VALID(this); ASSERT(::IsWindow(m_hWnd)); if (dwMode & LM_HORZDOCK) ASSERT(dwMode & LM_HORZ); // make SC_CLOSE button disable if (m_dwStyle & CBRS_FLOATING) { CFrameWnd* pMiniFrame = GetParentFrame(); ASSERT_KINDOF(CMiniFrameWnd, pMiniFrame); // Don't do this, cause right click menu turns unavairable // pMiniFrame->ModifyStyle(WS_SYSMENU, 0); CMenu* pSysMenu = pMiniFrame->GetSystemMenu(FALSE); ASSERT_VALID(pSysMenu); pSysMenu->EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_GRAYED); } int nCount = GetItemCount(); CSize sizeResult(0, 0); if (nCount > 0) { if (!(m_dwStyle & CBRS_SIZE_FIXED)) { BOOL bDynamic = m_dwStyle & CBRS_SIZE_DYNAMIC; if (bDynamic && (dwMode & LM_MRUWIDTH)) { LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_DYNAMIC)---LM_MRUWIDTH\n")); SizeMenuBar(m_nMRUWidth); CalcItemLayout(nCount);// added sizeResult = CalcSize(nCount); } else if (bDynamic && (dwMode & LM_HORZDOCK)) { LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_DYNAMIC)---LM_HORZDOCK\n")); if (IsFloating() || (m_dwStyle & CBRS_ORIENT_VERT)) { // I can't synchronize horz size on dragging with size on dock bar // as VC++ developer can't. SizeMenuBar(32767); } else { // Menu Button wrapped by frame width SizeMenuBar(GetClipBoxLength(TRUE)); } CalcItemLayout(nCount);// added sizeResult = CalcSize(nCount); if (!IsFloating() && !(m_dwStyle & CBRS_ORIENT_VERT)) { if (m_pDockContext->m_pDC) {// while dragging (m_pDockContext->m_bDragging is helpless) sizeResult.cx = GetClipBoxLength(TRUE); } } } else if (bDynamic && (dwMode & LM_VERTDOCK)) { LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_DYNAMIC)---LM_VERTDOCK\n")); //SizeMenuBar(0); CalcItemLayout(nCount, TRUE);// added sizeResult = CalcVertDockSize(nCount); if (!IsFloating() && !(m_dwStyle & CBRS_ORIENT_HORZ)) { if (m_pDockContext->m_pDC) {// while dragging sizeResult.cy = GetClipBoxLength(FALSE);//GetrcParent.Height() - m_cxRightBorder - m_cxLeftBorder; } } } else if (bDynamic && (nLength != -1)) { LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_DYNAMIC)---nLength != -1\n")); CRect rect; rect.SetRectEmpty(); _CalcInsideRect(rect, (dwMode & LM_HORZ)); BOOL bVert = (dwMode & LM_LENGTHY); int nLen = nLength + (bVert ? rect.Height() : rect.Width()); SizeMenuBar(nLen, bVert); CalcItemLayout(nCount, bVert);// added sizeResult = CalcSize(nCount); } else if (bDynamic && (m_dwStyle & CBRS_FLOATING)) { LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_DYNAMIC)---CBRS_FLOATING\n")); SizeMenuBar(m_nMRUWidth); CalcItemLayout(nCount);// added sizeResult = CalcSize(nCount); } else { if (!bDynamic) { InvalidateRect(NULL); goto Junk; } LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_DYNAMIC)---other\n")); BOOL bVert = !(dwMode & LM_HORZ); SizeMenuBar(GetClipBoxLength(TRUE)); CalcItemLayout(nCount, bVert);// added if (bVert) { InvalidateRect(NULL);// draw forcefully for captions sizeResult = CalcVertDockSize(nCount); // DockBar not replaced yet, so I can't get precise size sizeResult.cy = 10000; } else { sizeResult = CalcSize(nCount); sizeResult.cx = GetClipBoxLength(TRUE); } } } else {// CBRS_SIZE_FIXED LTRACE(_T("CMenuBar::CalcLayout(CBRS_SIZE_FIXED)\n")); Junk: BOOL bVert = !(dwMode & LM_HORZ); SizeMenuBar(32767); CalcItemLayout(nCount, bVert);// added if (bVert) { sizeResult = CalcVertDockSize(nCount); } else { sizeResult = CalcSize(nCount); } } if (dwMode & LM_COMMIT) { LTRACE(_T("CMenuBar::CalcLayout---LM_COMMIT\n")); int nControlCount = 0; BOOL bIsDelayed = m_bDelayedButtonLayout; m_bDelayedButtonLayout = FALSE; if ((m_dwStyle & CBRS_FLOATING) && (m_dwStyle & CBRS_SIZE_DYNAMIC)) m_nMRUWidth = sizeResult.cx; CalcItemLayout(nCount, dwMode); m_bDelayedButtonLayout = bIsDelayed; } } //BLOCK: Adjust Margins { CRect rect; rect.SetRectEmpty(); _CalcInsideRect(rect, (dwMode & LM_HORZ)); sizeResult.cy -= rect.Height(); sizeResult.cx -= rect.Width(); CSize size = CControlBar::CalcFixedLayout((dwMode & LM_STRETCH), (dwMode & LM_HORZ)); sizeResult.cx = max(sizeResult.cx, size.cx); sizeResult.cy = max(sizeResult.cy, size.cy); } if (dwMode & LM_HORZ) sizeResult.cy+=5; else sizeResult.cx+=3; return sizeResult; } //****************************************************************** CSize CMenuBar::CalcFixedLayout(BOOL bStretch, BOOL bHorz) { LTRACE(_T("CMenuBar::CalcFixedLayout\n")); ASSERT_VALID(this); ASSERT(::IsWindow(m_hWnd)); DWORD dwMode = bStretch ? LM_STRETCH : 0; dwMode |= bHorz ? LM_HORZ : 0; return CalcLayout(dwMode); } //****************************************************************** CSize CMenuBar::CalcDynamicLayout(int nLength, DWORD dwMode) { LTRACE(_T("CMenuBar::CalcDynamicLayout\n")); if ((nLength == -1) && !(dwMode & LM_MRUWIDTH) && !(dwMode & LM_COMMIT) && ((dwMode & LM_HORZDOCK) || (dwMode & LM_VERTDOCK))) { LTRACE(_T(" FixedLayout\n")); return CalcFixedLayout(dwMode & LM_STRETCH, dwMode & LM_HORZDOCK); } return CalcLayout(dwMode, nLength); } // set m_bWrapped by nWidth int CMenuBar::WrapMenuBar(int nCount, int nWidth) { // LTRACE(_T("CMenuBar::WrapMenuBar\n")); int nResult = 0; int x = 0; for (int i = 0; i < nCount; ++i) { CMenuItem* pItem = m_arrItem[i]; if (i+1 == nCount) return ++nResult; if (x + pItem->GetHorizontalSize().cx> nWidth) {// itself is over if (pItem->GetStyle() & MISTYLE_WRAPPABLE) { pItem->ModifyState(0, MISTATE_WRAP); ++nResult; x = 0; } } else if (x + pItem->GetHorizontalSize().cx + m_arrItem[i+1]->GetHorizontalSize().cx> nWidth) { if (pItem->GetStyle() & MISTYLE_WRAPPABLE) { pItem->ModifyState(0, MISTATE_WRAP); ++nResult; x = 0; } } else { pItem->ModifyState(MISTATE_WRAP, 0); x += pItem->GetHorizontalSize().cx; } } return nResult + 1; } //****************************************************************** // calc only size, by using m_bWrapped CSize CMenuBar::CalcSize(int nCount) { ASSERT(nCount > 0); CPoint cur(0,0); CSize sizeResult(0,0); int nWrap = 0; for (int i = 0; i < nCount; ++i) { CMenuItem* pItem = m_arrItem[i]; sizeResult.cx = max(cur.x + pItem->GetHorizontalSize().cx, sizeResult.cx); sizeResult.cy = max(cur.y + pItem->GetHorizontalSize().cy, sizeResult.cy); cur.x += pItem->GetHorizontalSize().cx; if (pItem->GetState() & MISTATE_WRAP) { //LTRACE(_T(" nIndex:%d is wrapped\n"), i); cur.x = 0;// reset x pos cur.y += pItem->GetHorizontalSize().cy; ++nWrap; } } return sizeResult; } //****************************************************************** void CMenuBar::Layout() { ASSERT(m_bDelayedButtonLayout); m_bDelayedButtonLayout = FALSE; BOOL bHorz = (m_dwStyle & CBRS_ORIENT_HORZ) != 0; if ((m_dwStyle & CBRS_FLOATING) && (m_dwStyle & CBRS_SIZE_DYNAMIC)) ((CMenuBar*)this)->CalcDynamicLayout(0, LM_HORZ | LM_MRUWIDTH | LM_COMMIT); else if (bHorz) ((CMenuBar*)this)->CalcDynamicLayout(0, LM_HORZ | LM_HORZDOCK | LM_COMMIT); else ((CMenuBar*)this)->CalcDynamicLayout(0, LM_VERTDOCK | LM_COMMIT); } //****************************************************************** void CMenuBar::SizeMenuBar(int nLength, BOOL bVert) { //LTRACE("CMenuBar::SizeMenuBar\n"); int nCount = GetItemCount(); ASSERT(nCount > 0); if (!bVert) { // nLength is horizontal length if (IsFloating()) { // half size wrapping CSize sizeMax, sizeMin, sizeMid; // Wrap MenuBar vertically WrapMenuBar(nCount, 0); sizeMin = CalcSize(nCount); // Wrap MenuBar horizontally WrapMenuBar(nCount, 32767); sizeMax = CalcSize(nCount); // we can never understand this algorithm :), see CToolBar implementation while (sizeMin.cx < sizeMax.cx) { // LTRACE("looping sizeMin.cx:%d < sizeMax.cx:%d\n", sizeMin.cx, sizeMax.cx); sizeMid.cx = (sizeMin.cx + sizeMax.cx) / 2; WrapMenuBar(nCount, sizeMid.cx); sizeMid = CalcSize(nCount); if (sizeMid.cx == sizeMax.cx) { // if you forget, it loops forever! return; } // LTRACE(" sizeMid : %d %d\n", sizeMid.cx, sizeMid.cy); if (nLength >= sizeMax.cx) { // LTRACE(" nLength:%d >= sizeMax.cx:%d\n", nLength, sizeMax.cx); if (sizeMin == sizeMid) { WrapMenuBar(nCount, sizeMax.cx); // LTRACE("out SizeMenuBar\n"); return; } sizeMin = sizeMid; } else if (nLength < sizeMax.cx) { // LTRACE(" nLength:%d < sizeMax.cx:%d\n", nLength, sizeMax.cx); sizeMax = sizeMid; } else { // LTRACE("out SizeMenuBar\n"); return; } } } else { // each one wrapping //LTRACE(" just each one wrapping\n"); WrapMenuBar(nCount, nLength); } } else { // nLength is vertical length CSize sizeMax, sizeMin, sizeMid; // Wrap MenuBar vertically WrapMenuBar(nCount, 0); sizeMin = CalcSize(nCount); // Wrap MenuBar horizontally WrapMenuBar(nCount, 32767); sizeMax = CalcSize(nCount); while (sizeMin.cx < sizeMax.cx) { sizeMid.cx = (sizeMin.cx + sizeMax.cx) / 2; WrapMenuBar(nCount, sizeMid.cx); sizeMid = CalcSize(nCount); if (sizeMid.cx == sizeMax.cx) { return; } if (nLength < sizeMid.cy) { if (sizeMin == sizeMid) { WrapMenuBar(nCount, sizeMax.cx); //LTRACE("out SizeMenuBar\n"); return; } sizeMin = sizeMid; } else if (nLength > sizeMid.cy) sizeMax = sizeMid; else { //LTRACE("out SizeMenuBar\n"); return; } } } //LTRACE("out SizeMenuBar\n"); } //*********************************************************************************** void CMenuBar::DrawCombo() { CRect rect; GetClientRect(rect); CalcSizeItem(); CWnd* pFrame = GetTopLevelFrame(); BOOL bMaximized = FALSE; //la idea es verificar que la ventana es MDI if (pFrame->IsKindOf(RUNTIME_CLASS(CMDIFrameWnd))) { ASSERT_VALID(pFrame); CMDIFrameWnd* pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pFrame); HWND hWndMDIClient = pMDIFrame->m_hWndMDIClient; ASSERT(::IsWindow(hWndMDIClient)); HWND hWndChild = (HWND)::SendMessage(hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized); } if ((m_dwStyle & CBRS_ORIENT_HORZ) && m_bCombo==TRUE && !(m_dwStyle & CBRS_FLOATING)) { CRect reccombo; cmb->GetClientRect (&reccombo); if (rect.Width() > m_sizex+(bMaximized?30:0)+reccombo.Width() ) { cmb->ShowWindow(SW_SHOW); CRect rctemp=rect; rctemp.top=-1; rctemp.bottom-=2; int nDif; if (!bIsTabbed) nDif=bMaximized?60:0; else nDif=0; rctemp.left=rctemp.right-reccombo.Width()- nDif; rctemp.right=rctemp.left+reccombo.Width(); cmb->MoveWindow(rctemp); } else { cmb->ShowWindow(SW_HIDE); } } } //****************************************************************** void CMenuBar::CalcSizeItem() { m_sizex=0; for(int i = 0; i < m_arrItem.GetSize(); ++i) { CMenuItem* pItem = m_arrItem[i]; m_sizex+=pItem->GetRect().Width(); } } //****************************************************************** CSize CMenuBar::CalcVertDockSize(int nCount) { ASSERT(nCount > 0); CSize sizeResult(0, 0); for (int i = 0; i < nCount; ++i) { CMenuItem* pItem = m_arrItem[i]; sizeResult.cy += pItem->GetRect().Height(); } sizeResult.cx = _cyMenuOnBar; return sizeResult; } //****************************************************************** void CMenuBar::CalcItemLayout(int nCount, BOOL bVert) { ASSERT(nCount > 0); int x = 0; int y = 0; if (!bVert) { for (int i = 0; i < nCount; ++i) { CMenuItem* pItem = m_arrItem[i]; CPoint ptItem(x, y); pItem->Layout(ptItem, TRUE);// layout by itself! if (pItem->GetState() & MISTATE_WRAP) { x = 0;// reset x to 0 y += pItem->GetRect().Height(); } else x += pItem->GetRect().Width(); } } else { for (int i = 0; i < nCount; ++i) { CMenuItem* pItem = m_arrItem[i]; CPoint ptItem(0, y); pItem->Layout(ptItem, FALSE); // layout by itself y += pItem->GetRect().Height(); } } } //****************************************************************** ////////////////////////////////////////////////////////////////////// // Added by Koay Kah Hoe. Thanx! void CMenuBar::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { if (m_bMDIApp) CheckActiveChildWndMaximized(); } //****************************************************************** ////////////////////////////////////////////////////////////////////// // CMenuBar decoration void CMenuBar::_DrawGripper(CWindowDC* dc,CRect* rcWin) { if (m_dwStyle & CBRS_FLOATING) return ; if(m_StyleDisplay == GUISTYLE_2003) //no es XP { if (m_dwStyle & CBRS_ORIENT_HORZ) { rcWin->top+=(rcWin->Height()/2)-4; rcWin->left+=7; rcWin->right=rcWin->left+2; rcWin->bottom-=8; CRect rcBlack; for (int i=0; i < rcWin->Height(); i+=4) { CRect rcWindow; CBrush cb; cb.CreateSolidBrush(::GetSysColor(COLOR_BTNHIGHLIGHT)); rcWindow=rcWin; rcWindow.top=rcWin->top+i; rcWindow.bottom=rcWindow.top+2; dc->FillRect(rcWindow,&cb); rcBlack=rcWindow; rcBlack.left-=1; rcBlack.top=(rcWin->top+i)-1; rcBlack.bottom=rcBlack.top+2; rcBlack.right=rcBlack.left+2; cb.DeleteObject(); cb.CreateSolidBrush(GuiDrawLayer::GetRGBColorShadow(m_StyleDisplay)); dc->FillRect(rcBlack,&cb); } } else { rcWin->top+=3; rcWin->left+=4; rcWin->right-=2; rcWin->bottom=rcWin->top+2; CRect rcBlack; for (int i=0; i < rcWin->Width(); i+=4) { CRect rcWindow; CBrush cb; cb.CreateSolidBrush(::GetSysColor(COLOR_BTNHIGHLIGHT)); rcWindow=rcWin; rcWindow.left=rcWindow.left+i; rcWindow.right=rcWindow.left+2; dc->FillRect(rcWindow,&cb); rcBlack=rcWindow; rcBlack.top-=1; rcBlack.left-=1; rcBlack.bottom=rcBlack.top+2; rcBlack.right=rcBlack.left+2; cb.DeleteObject(); cb.CreateSolidBrush(GuiDrawLayer::GetRGBColorShadow(m_StyleDisplay)); dc->FillRect(rcBlack,&cb); } } } else { if (m_dwStyle & CBRS_ORIENT_HORZ) { rcWin->top+=(rcWin->Height()/2)-4; rcWin->left+=7; rcWin->right=rcWin->left+3; rcWin->bottom-=6; for (int i=0; i < rcWin->Height(); i+=2) { CRect rcWindow; CBrush cb; cb.CreateSolidBrush(::GetSysColor(COLOR_BTNSHADOW)); rcWindow=rcWin; rcWindow.top=rcWin->top+i; rcWindow.bottom=rcWindow.top+1; dc->FillRect(rcWindow,&cb); } } else { rcWin->top+=2; rcWin->left+=2; rcWin->right-=2; rcWin->bottom=rcWin->top+3; for (int i=0; i < rcWin->Width(); i+=2) { CRect rcWindow; CBrush cb; cb.CreateSolidBrush(::GetSysColor(COLOR_BTNSHADOW)); rcWindow=rcWin; rcWindow.left=rcWindow.left+i; rcWindow.right=rcWindow.left+1; dc->FillRect(rcWindow,&cb); } } } } //****************************************************************** void CMenuBar::EraseNonClientEx() { // get window DC that is clipped to the non-client area CRect rcWindow; CRect rcClient; CWindowDC dc(this); GetWindowRect(&rcWindow); GetClientRect(&rcClient); CBrush cbr; cbr.CreateSolidBrush(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); rcClient.OffsetRect(-rcWindow.TopLeft()); rcWindow.OffsetRect(-rcWindow.TopLeft()); ScreenToClient(rcWindow); rcClient.OffsetRect(-rcWindow.left, - rcWindow.top); dc.ExcludeClipRect(rcClient); rcWindow.OffsetRect(-rcWindow.left, -rcWindow.top); int ibotton = rcWindow.bottom; rcWindow.top = rcWindow.bottom - 1; dc.FillRect(rcWindow, &cbr); rcWindow.top = 0; rcWindow.bottom += 3; dc.FillRect(rcWindow, &cbr); dc.FillSolidRect(0, rcWindow.top + 1, rcWindow.right + 1, 1, GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); cbr.DeleteObject(); // draw gripper in non-client area _DrawGripper(&dc, &rcWindow); } #define CX_BORDER 1 #define CY_BORDER 1 //****************************************************************** void CMenuBar::DrawRaisedBorders(CDC* pDC, CRect& rect) { ASSERT_VALID(this); ASSERT_VALID(pDC); DWORD dwStyle = m_dwStyle; if (!(dwStyle & CBRS_BORDER_ANY)) return; // prepare for dark lines ASSERT(rect.top == 0 && rect.left == 0); CRect rect1, rect2; rect1 = rect; rect2 = rect; COLORREF clrBtnShadow = GuiDrawLayer::GetRGBColorShadow(GuiDrawLayer::m_Style);//afxData.bWin4 ? afxData.clrBtnShadow : afxData.clrWindowFrame; COLORREF clrBtnFace = GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style); COLORREF clrBtnHilight = ::GetSysColor(COLOR_BTNHILIGHT); // draw dark line one pixel back/up if (dwStyle & CBRS_BORDER_3D) { rect1.right -= CX_BORDER; rect1.bottom -= CY_BORDER; } if (dwStyle & CBRS_BORDER_TOP) rect2.top += cyBorder2; if (dwStyle & CBRS_BORDER_BOTTOM) rect2.bottom -= cyBorder2; // draw left and top if (dwStyle & CBRS_BORDER_LEFT) pDC->FillSolidRect(0, rect2.top, CX_BORDER, rect2.Height(), clrBtnFace); if (dwStyle & CBRS_BORDER_TOP) pDC->FillSolidRect(0, 0, rect.right, CY_BORDER, clrBtnFace); // draw right and bottom if (dwStyle & CBRS_BORDER_RIGHT) pDC->FillSolidRect(rect1.right, rect2.top, -CX_BORDER, rect2.Height(), clrBtnShadow); if (dwStyle & CBRS_BORDER_BOTTOM) pDC->FillSolidRect(0, rect1.bottom, rect.right, -CY_BORDER, clrBtnShadow); if (dwStyle & CBRS_BORDER_3D) { // draw left and top if (dwStyle & CBRS_BORDER_LEFT) pDC->FillSolidRect(1, rect2.top, CX_BORDER, rect2.Height(), clrBtnHilight); if (dwStyle & CBRS_BORDER_TOP) pDC->FillSolidRect(0, 1, rect.right, CY_BORDER, clrBtnHilight); // draw right and bottom if (dwStyle & CBRS_BORDER_RIGHT) pDC->FillSolidRect(rect.right, rect2.top, -CX_BORDER, rect2.Height(), clrBtnFace); if (dwStyle & CBRS_BORDER_BOTTOM) pDC->FillSolidRect(0, rect.bottom, rect.right, -CY_BORDER, clrBtnFace); } if (dwStyle & CBRS_BORDER_LEFT) rect.left += cxBorder2; if (dwStyle & CBRS_BORDER_TOP) rect.top += cyBorder2; if (dwStyle & CBRS_BORDER_RIGHT) rect.right -= cxBorder2; if (dwStyle & CBRS_BORDER_BOTTOM) rect.bottom -= cyBorder2; } //****************************************************************** int CMenuBar::GetNextOrPrevButton(int nIndex, BOOL bPrev) { int nCount = GetItemCount(); if (bPrev) { // <- --nIndex; if (nIndex < 0) nIndex = nCount - 1; } else { // -> ++nIndex; if (nIndex >= nCount) nIndex = 0; } if (!(m_arrItem[nIndex]->GetStyle() & MISTYLE_TRACKABLE) || (m_arrItem[nIndex]->GetState() & MISTATE_HIDDEN)) { return GetNextOrPrevButton(nIndex, bPrev); } return nIndex; } //****************************************************************** ///////////////////////////////////////////////////////////////////////////// // CMenuBar OLE menu support // MFC does'nt do command routing for other process server. // ::TrackPopupMenuEx won't accept HWND of other process and // we have to determine a message target(ole server window or not) // as ::OleCreateMenuDescriptor do. // This is a hard coding. // First menu(ordinarily File menu) and WindowMenu regarded as container's own menu. // Some components can't update toolbar button and statusbar pane. HWND CMenuBar::OleMenuDescriptor(BOOL& bSend, UINT nMsg, WPARAM wParam, LPARAM lParam) { CWnd* pOleWnd = GetCmdSentOleWnd(); if (pOleWnd == NULL) return NULL; HWND hWndSentCmd = NULL; HMENU hMenu = NULL; if (nMsg == WM_INITMENUPOPUP || nMsg == WM_INITMENU) hMenu = (HMENU)wParam; else if (nMsg == WM_MENUSELECT) hMenu = (HMENU)lParam; switch (nMsg) { case WM_INITMENUPOPUP: case WM_INITMENU: case WM_MENUSELECT: bSend = TRUE; if (m_nTrackingState == popup) { LTRACE2(_T(" now popup\n")); if (m_bMDIApp) { LTRACE2(_T(" this is MDI\n")); if (m_nCurIndex == 0 || m_nCurIndex == 1 || hMenu == m_hWindowMenu) { LTRACE2(_T(" it's container menu, send to frame\n")); return NULL; } } else { LTRACE2(_T(" it's container menu, send to frame\n")); if (m_nCurIndex == 0) { return NULL; } } LTRACE2(_T(" it's server menu, send to server\n")); return pOleWnd->GetSafeHwnd(); } break; case WM_COMMAND: bSend = FALSE; if (m_bMDIApp) { LTRACE2(_T(" this is MDI\n")); if (_nPrevIndexForCmd == 0 || _nPrevIndexForCmd == 1 || _bWindowMenuSendCmd) { LTRACE2(_T(" it's container menu, send to frame\n")); return NULL; } } else { if (_nPrevIndexForCmd == 0) { LTRACE2(_T(" it's container menu, send to frame\n")); return NULL; } } LTRACE2(_T(" it's server menu, send to server\n")); return pOleWnd->GetSafeHwnd(); } return NULL;// send to frame } //****************************************************************** CWnd* CMenuBar::GetCmdSentOleWnd() { // *****fixed by VORGA, thanks!***** CWnd* pWnd = AfxGetMainWnd(); if (pWnd == NULL || !pWnd->IsFrameWnd()) return NULL; CFrameWnd* pFrame = NULL; if (m_bMDIApp) { CMDIFrameWnd *pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pWnd); if (pMDIFrame == NULL) return NULL; pFrame = pMDIFrame->GetActiveFrame(); } else { pFrame = STATIC_DOWNCAST(CFrameWnd, pWnd); } if (pFrame == NULL) return NULL; CDocument* pDoc = pFrame->GetActiveDocument(); if (pDoc != NULL && pDoc->IsKindOf(RUNTIME_CLASS(COleDocument))) { COleDocument* pOleDoc = STATIC_DOWNCAST(COleDocument, pDoc); ASSERT_VALID(pOleDoc); COleClientItem* pClientItem = pOleDoc->GetInPlaceActiveItem(pFrame); CWnd* pWnd = (pClientItem == NULL) ? NULL : pClientItem->GetInPlaceWindow(); if (pWnd != NULL) { return pWnd; } } return NULL; } //****************************************************************** ///////////////////////////////////////////////////////////////////////////// // CMDIClientHook CMDIClientHook::CMDIClientHook() { m_pMenuBar = NULL; } //****************************************************************** BOOL CMDIClientHook::Install(CMenuBar* pMenuBar, HWND hWndToHook) { ASSERT_VALID(pMenuBar); ASSERT(m_pMenuBar == NULL); m_pMenuBar = pMenuBar; return HookWindow(hWndToHook); } //****************************************************************** CMDIClientHook::~CMDIClientHook() { HookWindow((HWND)NULL); } //****************************************************************** LRESULT CMDIClientHook::WindowProc(UINT nMsg, WPARAM wParam, LPARAM lParam) { ASSERT_VALID(m_pMenuBar); switch (nMsg) { case WM_MDISETMENU: // only sent to MDI client window // Setting new frame/window menu: bypass MDI. wParam is new menu. if (wParam) { //LTRACE(_T("CMenuBar::WM_MDISETMENU 0x%04x\n"), wParam); m_pMenuBar->OnSetMenu((HMENU)wParam, (HMENU)lParam); } return 0; case WM_MDIREFRESHMENU: // only sent to MDI client window // Normally, would call DrawMenuBar, but I have the menu, so eat it. //LTRACE(_T("CMenuBar::WM_MDIREFRESHMENU\n")); return 0; } return CSubclassWnd::WindowProc(nMsg, wParam, lParam); } //****************************************************************** ///////////////////////////////////////////////////////////////////////////// // CMainFrameHook CMainFrameHook::CMainFrameHook() { m_pMenuBar = NULL; } //****************************************************************** BOOL CMainFrameHook::Install(CMenuBar* pMenuBar, HWND hWndToHook) { ASSERT_VALID(pMenuBar); ASSERT(m_pMenuBar == NULL); m_pMenuBar = pMenuBar; return HookWindow(hWndToHook); } //****************************************************************** CMainFrameHook::~CMainFrameHook() { } //****************************************************************** LRESULT CMainFrameHook::WindowProc(UINT nMsg, WPARAM wParam, LPARAM lParam) { ASSERT_VALID(m_pMenuBar); // be care for other windows(MainFrame) hooking // possible called when already this wnd destroyed (WM_NCACTIVATE is) if (!::IsWindow(m_pMenuBar->m_hWnd)) { return CSubclassWnd::WindowProc(nMsg, wParam, lParam); } BOOL bSend = FALSE; if (HWND hWndServer = m_pMenuBar->OleMenuDescriptor(bSend, nMsg, wParam, lParam)) { // OLE wnd will handle message if (bSend) return ::SendMessage(hWndServer, nMsg, wParam, lParam); else return ::PostMessage(hWndServer, nMsg, wParam, lParam); } switch (nMsg) { case WM_MENUSELECT: m_pMenuBar->OnMenuSelect((HMENU)lParam, (UINT)LOWORD(wParam)); break; case WM_INITMENUPOPUP: if (!HIWORD(lParam) && (HMENU)wParam == m_pMenuBar->m_hWindowMenu) m_pMenuBar->OnInitMenuPopup(CMenu::FromHandle((HMENU)wParam), LOWORD(lParam), (BOOL)HIWORD(lParam)); break; case WM_NCACTIVATE: m_pMenuBar->OnFrameNcActivate((BOOL)wParam); break; case WM_SYSCOLORCHANGE: case WM_SETTINGCHANGE: LTRACE(_T("CMenuBar::WM_SETTINGCHANGE\n")); // It's enough to reinitialize common resources once. m_pMenuBar->OnSettingChange(wParam, lParam); break; } if (nMsg == CMenuBar::WM_GETMENU) return (LRESULT)m_pMenuBar->m_hMenu; return CSubclassWnd::WindowProc(nMsg, wParam, lParam); } //****************************************************************** ////////////////////////////////////////////////////////////////////// // CMenuItem interface CMenuItem::CMenuItem() { m_fsStyle = 0; m_fsState = 0; m_rcItem.SetRectEmpty(); m_sizeHorz = CSize(0, 0); m_cAccessKey = 0; } //****************************************************************** void CMenuItem::ModifyState(BYTE fsRemove, BYTE fsAdd) { m_fsState = (m_fsState & ~fsRemove) | fsAdd; } //****************************************************************** CSize CMenuItem::GetHorizontalSize() const { if (m_fsState & MISTATE_HIDDEN) return CSize(0, 0); else return m_sizeHorz; } //----------------------------------------------------------------- CGuiMenuButton::CGuiMenuButton() { m_bHorz=TRUE; } CGuiMenuButton::~CGuiMenuButton() { } void CGuiMenuButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pdc= CDC::FromHandle(lpDrawItemStruct->hDC); CRect rc=lpDrawItemStruct->rcItem; UINT uState=lpDrawItemStruct->itemState; CBrush cb; if( uState & ODS_SELECTED) //the button is pressed cb.CreateSolidBrush(GuiDrawLayer::GetRGBPressBXP()); else if (m_bMouserOver) { if(m_StyleDisplay==GUISTYLE_2003) { if (GuiDrawLayer::m_Theme) { CGradient M(CSize(rc.Width(),rc.Height())); M.PrepareCaption(pdc,m_StyleDisplay); M.Draw(pdc,rc.left,rc.top,0,0,rc.Width(),rc.Height(),SRCCOPY); cb.CreateStockObject(NULL_BRUSH); } else cb.CreateSolidBrush(GuiDrawLayer::GetRGBFondoXP()); } else cb.CreateSolidBrush(GuiDrawLayer::GetRGBFondoXP()); } else { if(m_StyleDisplay==GUISTYLE_2003) cb.CreateSolidBrush(GuiDrawLayer::GetRGBColorFace(m_StyleDisplay)); else cb.CreateSolidBrush(m_clColor); } if (( uState == ODS_SELECTED) || m_bMouserOver ) { pdc->Draw3dRect(rc,GuiDrawLayer::GetRGBCaptionXP(),GuiDrawLayer::GetRGBCaptionXP()); rc.DeflateRect(1,1); } pdc->FillRect(rc,&cb); if (m_SizeText.cx > 2) { int nMode = pdc->SetBkMode(TRANSPARENT); if (m_bHorz) { CRect rectletra=rc; CPoint pt=CSize(rectletra.top+1,rectletra.left); if (uState & ODS_DISABLED) pdc->DrawState(pt, m_SizeText, m_szText, DSS_DISABLED, TRUE, 0, (CBrush*)NULL); else { if(m_bMouserOver != 1) pdc->SetTextColor(m_clrFont); pdc->DrawText(m_szText,rectletra,DT_SINGLELINE|DT_CENTER|DT_VCENTER); } } else { if (( uState == ODS_SELECTED) || m_bMouserOver ) rc.InflateRect(1,1); COLORREF clr = ::GetSysColor(COLOR_MENUTEXT); pdc->SetTextColor(clr); CPoint ptOffset=CPoint(1,1); CRect rcBtn = rc; int nLength = m_szText.GetLength(); int nIndex = m_szText.Find('&'); CString strBtn = m_szText.Left(nIndex) + m_szText.Right(nLength - (nIndex+1)); // fixed for WinNT. *****fixed by Simon, thanks!***** int iGraphicsMode = ::GetGraphicsMode(pdc->m_hDC); ::SetGraphicsMode(pdc->m_hDC, GM_ADVANCED); pdc->SetBkMode(TRANSPARENT); CFont* pOldFont = pdc->SelectObject(&_fontVertMenu); // I know precise text size //m_sizeHorz=((CMenuBar*)GetParent())->m_sizeHors; CSize m_sizeHorz; m_sizeHorz.cx = (_CalcTextWidth(m_szText) + CXTEXTMARGIN*2)+8; m_sizeHorz.cy = (_cyHorzFont + _cyTextMargin*2)+1; CRect rcString = CRect( CPoint(rcBtn.right - _cyTextMargin, rcBtn.top + CXTEXTMARGIN), m_sizeHorz); pdc->DrawText(strBtn, rcString + ptOffset, DT_SINGLELINE | DT_NOCLIP | DT_NOPREFIX);// don't forget DT_NOCLIP gbintHorz=-1; rcMenu=rcBtn; rcMenu.bottom-=3; pdc->SelectObject(pOldFont); // CDC::DrawText is poor, so we have to draw vertical line by ourselves CPen pen(PS_SOLID, 0, clr); CPen* pOldPen = pdc->SelectObject(&pen); CPoint m_ptLineFrom; CPoint m_ptLineTo; if (nIndex == 0) { m_ptLineFrom = CPoint(_cyTextMargin-1, CXTEXTMARGIN+1); m_ptLineTo = CPoint(_cyTextMargin-1, CXTEXTMARGIN + _CalcTextWidth(strBtn.Left(nIndex+1))); } else { m_ptLineFrom = CPoint(_cyTextMargin-1, CXTEXTMARGIN + _CalcTextWidth(strBtn.Left(nIndex+1))); m_ptLineTo = CPoint(_cyTextMargin-1, CXTEXTMARGIN + _CalcTextWidth(strBtn.Left(nIndex+1))); } pdc->MoveTo(rcBtn.TopLeft() + m_ptLineFrom); pdc->LineTo(rcBtn.TopLeft() + m_ptLineTo ); pdc->SelectObject(pOldPen); ::SetGraphicsMode( pdc->m_hDC, iGraphicsMode ); } } } BEGIN_MESSAGE_MAP(CGuiMenuButton,CGuiToolButton) ON_WM_LBUTTONDOWN() END_MESSAGE_MAP() void CGuiMenuButton::OnLButtonDown(UINT nFlags, CPoint point) { ShowWindow(SW_HIDE); ClientToScreen(&point); GetParent()->SendMessage(WM_LBUTTONDOWN,100+GetDlgCtrlID(),MAKEWPARAM(point.x,point.y)); } CGuiIconButton::CGuiIconButton() { } CGuiIconButton::~CGuiIconButton() { ::FreeResource(m_Icon); } void CGuiIconButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pdc= CDC::FromHandle(lpDrawItemStruct->hDC); CRect rc=lpDrawItemStruct->rcItem; UINT uState=lpDrawItemStruct->itemState; CBrush cb; cb.CreateSolidBrush(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); pdc->FillRect(rc,&cb); CPoint m_point=CPoint(1,1); if (m_SizeImage.cx > 2) { pdc->DrawState (m_point, m_SizeImage,m_Icon, (uState==ODS_DISABLED?DSS_DISABLED:DSS_NORMAL),(CBrush*)NULL); } } BEGIN_MESSAGE_MAP(CGuiIconButton,CGuiToolButton) ON_WM_LBUTTONDOWN() END_MESSAGE_MAP() void CGuiIconButton::OnLButtonDown(UINT nFlags, CPoint point) { ClientToScreen(&point); GetParent()->SendMessage(WM_LBUTTONDOWN,1000,MAKEWPARAM(point.x,point.y)); } //----------------------------------------------------------------- //****************************************************************** ////////////////////////////////////////////////////////////////////// // CMenuButton class CMenuButton::CMenuButton(HMENU hMenu, int nIndex,CWnd* pWnd) { ASSERT(::IsMenu(hMenu)); ASSERT(nIndex >= 0); pParent=pWnd; m_cfont.CreateFont(-11,0,0,0,400,0,0,0,0,1,2,1,34,"MS Sans Serif"); m_fsStyle |= (MISTYLE_TRACKABLE | MISTYLE_WRAPPABLE); m_bt.Create(_T(""), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_OWNERDRAW, CRect(0,0,0,0), pWnd, nIndex); m_bt.SetFont(&_fontHorzMenu); m_bt.StyleDispl(GuiDrawLayer::m_Style); m_bt.SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); InitButtonStringAndSubMenuHandle(hMenu, nIndex); InitHorizontalButtonSize(); InitAccessKeyAndVerticalLinePoint(); } //****************************************************************** // ERNESTO void CMenuButton::SetText(TCHAR *szText) { m_strBtn = szText; InitHorizontalButtonSize(); InitAccessKeyAndVerticalLinePoint(); } //****************************************************************** void CMenuButton::InitButtonStringAndSubMenuHandle(HMENU hMenu, int nIndex) { // get menu button Text TCHAR szText[256]; MENUITEMINFO info; ::memset(&info, 0, sizeof(MENUITEMINFO)); info.cbSize = sizeof(MENUITEMINFO); info.fMask = MIIM_ID | MIIM_TYPE; info.dwTypeData = szText; info.cch = sizeof(szText); ::GetMenuItemInfo(hMenu, nIndex, TRUE, &info); m_strBtn = CString(szText); m_bt.SetCaption(m_strBtn); m_hSubMenu = ::GetSubMenu(hMenu, nIndex); if (!m_hSubMenu) { m_nID = ::GetMenuItemID(hMenu, nIndex); ASSERT(m_nID != -1); } else { m_nID = -1; } } //****************************************************************** void CMenuButton::InitHorizontalButtonSize() { // get menu button Text size ASSERT(m_strBtn.IsEmpty() == FALSE); m_sizeHorz.cx = (_CalcTextWidth(m_strBtn) + CXTEXTMARGIN*2)+8; m_sizeHorz.cy = (_cyHorzFont + _cyTextMargin*2)+1; } //****************************************************************** void CMenuButton::InitAccessKeyAndVerticalLinePoint() { int nIndex = m_strBtn.Find('&'); if (nIndex + 1 == m_strBtn.GetLength()) { TRACE(_T("warning : & is bad position, access key is invalid.\n")); m_cAccessKey = 0; m_ptLineFrom = m_ptLineTo = CPoint(0, 0); return; } m_cAccessKey = m_strBtn[nIndex + 1];// -1 + 1 = 0; it's ok if (nIndex == -1) { m_ptLineFrom = m_ptLineTo = CPoint(0, 0); } else if (nIndex == 0) { m_ptLineFrom = CPoint(_cyTextMargin, CXTEXTMARGIN); m_ptLineTo = CPoint(_cyTextMargin, CXTEXTMARGIN + _CalcTextWidth(m_strBtn.Left(nIndex+2))); } else { m_ptLineFrom = CPoint(_cyTextMargin, CXTEXTMARGIN + _CalcTextWidth(m_strBtn.Left(nIndex))); m_ptLineTo = CPoint(_cyTextMargin, CXTEXTMARGIN + _CalcTextWidth(m_strBtn.Left(nIndex+2))); } } //****************************************************************** void CMenuButton::Layout(CPoint point, BOOL bHorz) { if (bHorz) m_fsState |= MISTATE_HORZ; else m_fsState &= ~MISTATE_HORZ; if (m_fsState & MISTATE_HIDDEN) { m_rcItem.SetRectEmpty(); return; } if (bHorz) { m_rcItem = CRect(point, m_sizeHorz); } else { m_rcItem = CRect(point, CSize(m_sizeHorz.cy, m_sizeHorz.cx)); } } //****************************************************************** void CMenuButton::Update(CDC* pDC) { if (m_fsState & MISTATE_HIDDEN) return; // clean background COLORREF clr = GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style ); pDC->FillSolidRect(m_rcItem, clr); if (m_fsState & MISTATE_HOT){ if (m_bt.IsWindowVisible()) m_bt.ShowWindow(SW_HIDE); DrawHot(pDC); } else if (m_fsState & MISTATE_PRESSED){ if (m_bt.IsWindowVisible()) m_bt.ShowWindow(SW_HIDE); DrawPressed(pDC); } else { DrawNone(pDC); } } //********************************************************* void CMenuButton::TrackPopup(CWnd* pBar, CWnd* pWndSentCmd) { LTRACE(_T("CMenuButton::TrackPopup\n")); ASSERT_VALID(pBar); ASSERT(!(m_fsState & MISTATE_HIDDEN)); pMenuBar = STATIC_DOWNCAST(CMenuBar, pBar); ASSERT_VALID(pMenuBar); // "! menu" (no sub menu) if (!m_hSubMenu) { ASSERT(m_nID != -1); pWndSentCmd->SendMessage(WM_COMMAND, (WPARAM)m_nID, (LPARAM)pBar->GetSafeHwnd()); return; } CRect rcItem(m_rcItem); pMenuBar->ClientToScreen(rcItem); UINT fuFlags; TPMPARAMS tpm; CPoint pt = _ComputeMenuTrackPoint(rcItem, pMenuBar->GetBarStyle(), fuFlags, tpm); if (m_hSubMenu == pMenuBar->m_hWindowMenu) _bWindowMenuSendCmd = TRUE; else _bWindowMenuSendCmd = FALSE; if (pMenuBar->GetBarStyle() & CBRS_ORIENT_HORZ) { pt.x+=1; pt.y-=2; } else { pt.x-=2; pt.y+=2; } ::TrackPopupMenuEx(m_hSubMenu, fuFlags, pt.x, pt.y, pWndSentCmd->GetSafeHwnd(), &tpm); gbintHorz=-1; rcMenu.SetRectEmpty(); } //**************************************************************** void CMenuButton::DrawHorzText(CDC* pDC, CPoint ptOffset) { COLORREF clr = (m_fsState & MISTATE_INACTIVE) ? ::GetSysColor(COLOR_GRAYTEXT) : ::GetSysColor(COLOR_MENUTEXT); pDC->SetTextColor(clr); CRect rcBtn = m_rcItem; rcBtn.right-=1; pDC->SetBkMode(TRANSPARENT); CFont* pOldFont = pDC->SelectObject(&_fontHorzMenu); // I know precise text size, but better to leave this job to Windows // *****fixed by andi, thanks!***** ptOffset.y-=1; ptOffset.x+=2; pDC->DrawText(m_strBtn, rcBtn + ptOffset, DT_SINGLELINE | DT_CENTER | DT_VCENTER); pDC->SelectObject(pOldFont); gbintHorz=0; rcMenu=rcBtn; rcMenu.right-=4; } //****************************************************************** void CMenuButton::DrawVertText(CDC* pDC, CPoint ptOffset) { COLORREF clr = (m_fsState & MISTATE_INACTIVE) ? ::GetSysColor(COLOR_GRAYTEXT) : ::GetSysColor(COLOR_MENUTEXT); pDC->SetTextColor(clr); CRect rcBtn = m_rcItem; int nLength = m_strBtn.GetLength(); int nIndex = m_strBtn.Find('&'); CString strBtn = m_strBtn.Left(nIndex) + m_strBtn.Right(nLength - (nIndex+1)); // fixed for WinNT. *****fixed by Simon, thanks!***** int iGraphicsMode = ::GetGraphicsMode(pDC->m_hDC); ::SetGraphicsMode(pDC->m_hDC, GM_ADVANCED); pDC->SetBkMode(TRANSPARENT); CFont* pOldFont = pDC->SelectObject(&_fontVertMenu); // I know precise text size CRect rcString = CRect( CPoint(rcBtn.right - _cyTextMargin, rcBtn.top + CXTEXTMARGIN), m_sizeHorz); pDC->DrawText(strBtn, rcString + ptOffset, DT_SINGLELINE | DT_NOCLIP | DT_NOPREFIX);// don't forget DT_NOCLIP gbintHorz=1; rcMenu=rcBtn; rcMenu.bottom-=3; pDC->SelectObject(pOldFont); // CDC::DrawText is poor, so we have to draw vertical line by ourselves CPen pen(PS_SOLID, 0, clr); CPen* pOldPen = pDC->SelectObject(&pen); rcBtn.left-=2; pDC->MoveTo(rcBtn.TopLeft() + m_ptLineFrom + ptOffset); pDC->LineTo(rcBtn.TopLeft() + m_ptLineTo + ptOffset); pDC->SelectObject(pOldPen); ::SetGraphicsMode( pDC->m_hDC, iGraphicsMode ); } //****************************************************************** void CMenuButton::DrawButton(CDC* pDC,WORD wState) { CBrush cblu; CRect rcBtn =m_rcItem; if (dSt & CBRS_ORIENT_HORZ ) rcBtn.right-=4; else rcBtn.bottom-=2; if (wState & BDR_RAISEDINNER) pDC->Draw3dRect(rcBtn,m_dw.GetRGBCaptionXP(),m_dw.GetRGBCaptionXP()); else { if (dSt & CBRS_ORIENT_HORZ ) rcBtn.bottom+=1; else rcBtn.bottom-=1; COLORREF ColBorder; if (GuiDrawLayer::m_Style==GUISTYLE_XP) ColBorder = GuiDrawLayer::GetRGBMenu(); else ColBorder=GuiDrawLayer::GetRGBColorShadow(GuiDrawLayer::m_Style); pDC->Draw3dRect(rcBtn,ColBorder,ColBorder); if (dSt & CBRS_ORIENT_HORZ ) rcBtn.bottom-=1; else rcBtn.bottom+=1; if (GuiDrawLayer::m_Style == GUISTYLE_2003) { CRect rcb=rcBtn; if (dSt & CBRS_ORIENT_HORZ) { CGradient M(CSize(rcb.Width(),rcb.Height())); M.PrepareVertical(pDC,GuiDrawLayer::m_Style); M.Draw(pDC,rcb.left+1,rcb.top+1,0,0,rcb.Width()-2,rcb.Height(),SRCCOPY); } else { CGradient M(CSize(rcb.Width(),rcb.Height())); M.PrepareHorizontal(pDC,GuiDrawLayer::m_Style); M.Draw(pDC,rcb.left+1,rcb.top+1,0,0,rcb.Width(),rcb.Height()-3,SRCCOPY); } } COLORREF ColB = GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style); CPen pen(PS_SOLID, 0, ColB); CPen* pOldPen = pDC->SelectObject(&pen); pDC->MoveTo(rcBtn.left, rcBtn.bottom); pDC->LineTo(rcBtn.right, rcBtn.bottom); COLORREF ColA = GetSysColor(COLOR_WINDOW); CRect rect = rcBtn; int X,Y; X=Y=0; int winH = rect.Height(); int winW = rect.Width(); if (dSt & CBRS_ORIENT_HORZ ) { rect.right+=4; // Simulate a shadow on right edge... for (X=1; X<=4 ;X++) { for (Y=0; Y<4 ;Y++) pDC->SetPixel(rect.right-X,Y+rect.top, ColB ); for (Y=4; Y<8 ;Y++) pDC->SetPixel(rect.right-X,Y+rect.top,GuiDrawLayer::DarkenColor(3 * X * (Y - 3), ColB)) ; for (Y=8; Y<=(winH-1) ;Y++) pDC->SetPixel(rect.right - X, Y+rect.top, GuiDrawLayer::DarkenColor(15 * X, ColB) ); } } else { rect.bottom+=2; for(Y=1; Y<=3 ;Y++) { for(X=0; X<=3 ;X++) { pDC->SetPixel(X,rect.bottom-Y,pDC->GetPixel(rect.left+X,rect.bottom-Y)) ; } for(X=4; X<=7 ;X++) { COLORREF c = pDC->GetPixel(rect.left + X, rect.bottom - Y) ; pDC->SetPixel(X, rect.bottom - Y, GuiDrawLayer::DarkenColor(3 * (X - 3) * Y, c)) ; } for(X=8; X<=(winW-2) ;X++) { COLORREF c = pDC->GetPixel(rect.left + X, rect.bottom - Y); pDC->SetPixel(X, rect.bottom- Y, GuiDrawLayer::DarkenColor(15 * Y, c)) ; } } } pDC->SelectObject(pOldPen); } rcBtn.DeflateRect(1,1); if (wState & BDR_RAISEDINNER) { cblu.CreateSolidBrush(m_dw.GetRGBFondoXP()); pDC->FillRect(rcBtn,&cblu); } } //****************************************************************** void CMenuButton::DrawHot(CDC* pDC) { if (m_fsState & MISTATE_HORZ) { // draw pressed button dSt=CBRS_ORIENT_HORZ; DrawButton(pDC,BDR_RAISEDINNER); //pDC->DrawEdge(m_rcItem, BDR_RAISEDINNER, BF_RECT); DrawHorzText(pDC,CPoint(-1, 1)); } else { dSt=CBRS_ORIENT_VERT; DrawButton(pDC,BDR_RAISEDINNER); //pDC->DrawEdge(m_rcItem, BDR_RAISEDINNER, BF_RECT); DrawVertText(pDC); } } //****************************************************************** void CMenuButton::DrawPressed(CDC* pDC) { if (m_fsState & MISTATE_HORZ) { DrawButton(pDC,BDR_SUNKENOUTER); //pDC->DrawEdge(m_rcItem, BDR_SUNKENOUTER, BF_RECT);// draw pressed button DrawHorzText(pDC, CPoint(-1, 1)); } else { DrawButton(pDC,BDR_SUNKENOUTER); //pDC->DrawEdge(m_rcItem, BDR_SUNKENOUTER, BF_RECT); DrawVertText(pDC, CPoint(1, 1)); } } //-------------------------------- //-------------------------------- //****************************************************************** void CMenuButton::DrawNone(CDC* pDC) { CRect rcBtn = m_rcItem; if (!m_bt.IsWindowVisible()) m_bt.ShowWindow(SW_SHOW); m_bt.MoveWindow(rcBtn); if (m_fsState & MISTATE_HORZ) { m_bt.SetHorzVert(); } else { CRect rcBtn = m_rcItem; m_bt.SetHorzVert(FALSE); } } void CMenuButton::UpdateButtons() { if (m_bt.IsWindowVisible()) { CRect rcBtn = m_rcItem; m_bt.ShowWindow(SW_SHOW); m_bt.MoveWindow(rcBtn); m_bt.Invalidate(); m_bt.UpdateWindow(); } } //****************************************************************** ////////////////////////////////////////////////////////////////////// // CMenuIcon class CMenuIcon::CMenuIcon(CWnd* pMenuBar) { ASSERT_VALID(pMenuBar); m_pMenuBar = pMenuBar; m_hIconWinLogo = AfxGetApp()->LoadStandardIcon(IDI_WINLOGO); ASSERT(m_hIconWinLogo); m_btnIcon.Create(_T(""), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_OWNERDRAW, CRect(0,0,0,0), pMenuBar, 0x999); m_btnIcon.ShowWindow(SW_HIDE); m_btnIcon.SetScrollButton(); m_fsStyle |= MISTYLE_TRACKABLE; m_fsState |= MISTATE_HIDDEN; m_sizeHorz = CSize(::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON)); } //****************************************************************** CMenuIcon::~CMenuIcon() { if (m_hIconWinLogo != NULL) ::FreeResource(m_hIconWinLogo); } //****************************************************************** void CMenuIcon::OnActivateChildWnd() { //LTRACE(_T("CMenuIcon::OnActivateChildWnd\n")); ASSERT_VALID(m_pMenuBar); CWnd* pFrame = m_pMenuBar->GetTopLevelFrame(); ASSERT_VALID(pFrame); CMDIFrameWnd* pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pFrame); HWND hWndMDIClient = pMDIFrame->m_hWndMDIClient; ASSERT(::IsWindow(hWndMDIClient)); BOOL bMaximized = FALSE; HWND hWndChild = (HWND)::SendMessage(hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized); if (bMaximized == FALSE) { //LTRACE(_T(" not maximized\n")); m_fsState |= MISTATE_HIDDEN; m_btnIcon.ShowWindow(SW_HIDE); } else { //LTRACE(_T(" maximized\n")); m_fsState &= ~MISTATE_HIDDEN; m_btnIcon.SethIcon(m_hDocIcon); m_btnIcon.ShowWindow(SW_SHOW); } m_hDocIcon = (HICON)::GetClassLong(hWndChild, GCL_HICONSM); if (m_hDocIcon == NULL) // if hWndChild doesn't have own icon m_hDocIcon = m_hIconWinLogo; } //****************************************************************** void CMenuIcon::Update(CDC* pDC) { if (m_fsState & MISTATE_HIDDEN) return; ASSERT(m_hDocIcon); ASSERT(m_rcItem.IsRectEmpty() == FALSE); m_btnIcon.MoveWindow(m_rcItem); ::DrawIconEx(pDC->m_hDC, m_rcItem.left, m_rcItem.top, m_hDocIcon, m_rcItem.Width(), m_rcItem.Height(), 0, NULL, DI_NORMAL); } void CMenuIcon::UpdateButtons() { } //****************************************************************** void CMenuIcon::TrackPopup(CWnd* pBar, CWnd* pWndSentCmd) { ASSERT(!(m_fsState & MISTATE_HIDDEN)); ASSERT_VALID(m_pMenuBar); CWnd* pFrame = m_pMenuBar->GetTopLevelFrame(); ASSERT_VALID(pFrame); CMDIFrameWnd* pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pFrame); HWND hWndMDIClient = pMDIFrame->m_hWndMDIClient; ASSERT(::IsWindow(hWndMDIClient)); BOOL bMaximized = FALSE; HWND hWndChild = (HWND)::SendMessage(hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized); ASSERT(bMaximized); HMENU hSysMenu = ::GetSystemMenu(hWndChild, FALSE); ASSERT(::IsMenu(hSysMenu)); CControlBar* pControlBar = STATIC_DOWNCAST(CControlBar, m_pMenuBar); ASSERT_VALID(pControlBar); CRect rcItem(m_rcItem); m_pMenuBar->ClientToScreen(rcItem); UINT fuFlags; TPMPARAMS tpm; bActivSystemMenu=TRUE; CPoint pt = _ComputeMenuTrackPoint(rcItem, pControlBar->GetBarStyle(), fuFlags, tpm); gbintHorz=-1; CRect rcBtn=CRect(0,0,0,0); CRect rcMenu=rcBtn; ::TrackPopupMenuEx(hSysMenu, fuFlags, pt.x, pt.y,m_pMenuBar->GetSafeHwnd(), &tpm); bActivSystemMenu=FALSE; } //****************************************************************** void CMenuIcon::Layout(CPoint point, BOOL bHorz) { if (bHorz) m_fsState |= MISTATE_HORZ; else m_fsState &= ~MISTATE_HORZ; if (m_fsState & MISTATE_HIDDEN) { m_rcItem.SetRectEmpty(); return; } m_rcItem = CRect(point, CSize(::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON))); } //****************************************************************** ////////////////////////////////////////////////////////////////////// // CMenuControl class #define CX_GAP_CAPTION 2 CMenuControl::CMenuControl(CWnd* pMenuBar) { ASSERT_VALID(pMenuBar); m_pMenuBar = pMenuBar; m_bDown = FALSE; m_nTracking = -1; m_fsState |= MISTATE_HIDDEN; if (!m_img.Create(IDB_GUI_MDIICONS,9,3,RGB(255,0,255))) { TRACE0("error"); } m_arrButton[2].Create(_T(""), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_OWNERDRAW, CRect(0,0,0,0),m_pMenuBar, SC_CLOSE); m_arrButton[2].SethIcon(m_img.ExtractIcon(2)); m_arrButton[2].SetToolTip("Close"); m_arrButton[2].SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); m_arrButton[2].ShowDark(FALSE); m_arrButton[1].Create(_T(""), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_OWNERDRAW, CRect(0,0,0,0),m_pMenuBar, SC_RESTORE); m_arrButton[1].SethIcon(m_img.ExtractIcon(1)); m_arrButton[1].SetToolTip("Restore"); m_arrButton[1].SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); m_arrButton[1].ShowDark(FALSE); m_arrButton[0].Create(_T(""), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_OWNERDRAW, CRect(0,0,0,0),m_pMenuBar,SC_MINIMIZE); m_arrButton[0].SethIcon(m_img.ExtractIcon(0)); m_arrButton[0].SetToolTip("Minimize"); m_arrButton[0].SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); m_arrButton[0].ShowDark(FALSE); CSize sizeCaption = GetCaptionSize(); m_sizeHorz = CSize(sizeCaption.cx*3 + CX_GAP_CAPTION + 1, sizeCaption.cy + 2); } void CMenuControl::SetColorButton(COLORREF clrBtn) { m_arrButton[2].SetColor(clrBtn); m_arrButton[1].SetColor(clrBtn); m_arrButton[0].SetColor(clrBtn); } //****************************************************************** void CMenuControl::Update(CDC* pDC) { // do nothing } void CMenuControl::UpdateButtons() { } //****************************************************************** void CMenuControl::Layout(CPoint point, BOOL bHorz) { //LTRACE(_T("CMenuControl::Layout bHorz:%d\n"), bHorz); if (bHorz) m_fsState |= MISTATE_HORZ; else m_fsState &= ~MISTATE_HORZ; if (m_fsState & MISTATE_HIDDEN) { m_rcItem.SetRectEmpty(); return; } // just layout easily if (bHorz) { m_rcItem = CRect(point, m_sizeHorz); } else { m_rcItem = CRect(point, CSize(m_sizeHorz.cy, m_sizeHorz.cx)); } } //****************************************************************** void CMenuControl::DelayLayoutAndDraw(CDC* pDC, CSize sizeBar,BOOL bFlota) { CSize sizeCaption = GetCaptionSize(); int cxCaption = sizeCaption.cx; int cyCaption = sizeCaption.cy; if (m_fsState & MISTATE_HORZ) { CRect rcCaption; rcCaption.right = !bFlota?sizeBar.cx-5:sizeBar.cx; rcCaption.bottom = sizeBar.cy-3; rcCaption.left = rcCaption.right - cxCaption; rcCaption.top = (rcCaption.bottom - cyCaption); m_arrCaption[0] = rcCaption; rcCaption -= CPoint(cxCaption+CX_GAP_CAPTION, 0); m_arrCaption[1] = rcCaption; rcCaption -= CPoint(cxCaption, 0); m_arrCaption[2] = rcCaption; m_rcItem = CRect(m_arrCaption[2].left, m_arrCaption[2].top, m_arrCaption[0].right, m_arrCaption[0].bottom); } else { CRect rcCaption; rcCaption.left = 0; rcCaption.bottom = sizeBar.cy-5; rcCaption.right = rcCaption.left + cxCaption; rcCaption.top = rcCaption.bottom - cyCaption; m_arrCaption[0] = rcCaption; rcCaption -= CPoint(0, cyCaption+CX_GAP_CAPTION); m_arrCaption[1] = rcCaption; rcCaption -= CPoint(0, cyCaption); m_arrCaption[2] = rcCaption; m_rcItem = CRect(m_arrCaption[2].left, m_arrCaption[2].top, m_arrCaption[0].right, m_arrCaption[0].bottom); } if (m_fsState & MISTATE_HIDDEN) { //LTRACE(_T(" hidden\n")); return; } // draw frame controls DrawControl(); } //****************************************************************** //****************************************************************** void CMenuControl::DrawControl() { CWnd* pFrame = m_pMenuBar->GetTopLevelFrame(); ASSERT_VALID(pFrame); CMDIFrameWnd* pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pFrame); HWND hWndMDIClient = pMDIFrame->m_hWndMDIClient; ASSERT(::IsWindow(hWndMDIClient)); BOOL bMaximized = FALSE; HWND hWndChild = (HWND)::SendMessage(hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized); if (bMaximized == TRUE) { m_arrButton[2].MoveWindow(m_arrCaption[0]); if (!(m_fsState & MISTATE_HORZ)) m_arrButton[0].SetSimpleButton(); else m_arrButton[2].SetSimpleButton(FALSE); m_arrButton[1].MoveWindow(m_arrCaption[1]); if (!(m_fsState & MISTATE_HORZ)) m_arrButton[1].SetSimpleButton(); else m_arrButton[1].SetSimpleButton(FALSE); m_arrButton[0].MoveWindow(m_arrCaption[2]); if (!(m_fsState & MISTATE_HORZ)) m_arrButton[2].SetSimpleButton(); else m_arrButton[0].SetSimpleButton(FALSE); } /* m_arrButton[2].SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); m_arrButton[1].SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); m_arrButton[0].SetColor(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); */ m_arrButton[2].Invalidate(); m_arrButton[1].Invalidate(); m_arrButton[0].Invalidate(); m_arrButton[2].UpdateWindow(); m_arrButton[1].UpdateWindow(); m_arrButton[0].UpdateWindow(); } //****************************************************************** //****************************************************************** void CMenuControl::OnActivateChildWnd() { //LTRACE(_T("CMenuControl::OnActivateChildWnd\n")); ASSERT_VALID(m_pMenuBar); CWnd* pFrame = m_pMenuBar->GetTopLevelFrame(); ASSERT_VALID(pFrame); CMDIFrameWnd* pMDIFrame = STATIC_DOWNCAST(CMDIFrameWnd, pFrame); HWND hWndMDIClient = pMDIFrame->m_hWndMDIClient; ASSERT(::IsWindow(hWndMDIClient)); BOOL bMaximized = FALSE; HWND hWndChild = (HWND)::SendMessage(hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized); if (bMaximized == FALSE) { m_fsState |= MISTATE_HIDDEN; } else { m_fsState &= ~MISTATE_HIDDEN; } } //****************************************************************** CSize CMenuControl::GetCaptionSize() { NONCLIENTMETRICS info; info.cbSize = sizeof(info); ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0); // due to my own feeling return CSize(info.iMenuHeight - info.iBorderWidth*2, info.iMenuHeight - info.iBorderWidth*4); } //****************************************************************** #if _MFC_VER < 0x0600 void CMenuBar::SetBorders(int cxLeft, int cyTop, int cxRight, int cyBottom) { ASSERT(cxLeft >= 0); ASSERT(cyTop >= 0); ASSERT(cxRight >= 0); ASSERT(cyBottom >= 0); m_cxLeftBorder = cxLeft; m_cyTopBorder = cyTop; m_cxRightBorder = cxRight; m_cyBottomBorder = cyBottom; } #endif //****************************************************************** // input CRect should be client rectangle size void CMenuBar::_CalcInsideRect(CRect& rect, BOOL bHorz) const { LTRACE(_T("CMenuBar::_CalcInsideRect\n")); ASSERT_VALID(this); DWORD dwStyle = m_dwStyle; if (dwStyle & CBRS_BORDER_LEFT) rect.left += cxBorder2; if (dwStyle & CBRS_BORDER_TOP) rect.top += cyBorder2; if (dwStyle & CBRS_BORDER_RIGHT) rect.right -= cxBorder2; if (dwStyle & CBRS_BORDER_BOTTOM) rect.bottom -= cyBorder2; BOOL bDrawGripper = !(m_dwStyle & CBRS_FLOATING) && (m_dwExStyle & CBRS_GRIPPER); // inset the top and bottom. if (bHorz) { rect.left += m_cxLeftBorder; rect.top += m_cyTopBorder; rect.right -= m_cxRightBorder; rect.bottom -= m_cyBottomBorder; if (bDrawGripper) rect.left += CX_GRIPPER_ALL; } else { rect.left += m_cyTopBorder; rect.top += m_cxLeftBorder; rect.right -= m_cyBottomBorder; rect.bottom -= m_cxRightBorder; if (bDrawGripper) rect.top += CY_GRIPPER_ALL; } } //****************************************************************** ///////////////////////////////////////////////////////////////////////////// // CMenuDockBar implementation // a little changed from CDockBar implementation static BOOL _IsMenuBar(int nPos, CPtrArray& arrBars) { if (nPos < arrBars.GetSize()) { CControlBar* pBar = (CControlBar*)arrBars[nPos]; if (pBar && pBar->GetDlgCtrlID() == AFX_IDW_MENUBAR) return TRUE; else return FALSE; } else return FALSE; } //****************************************************************** // ERNESTO BOOL CMenuBar::SetSubMenuText( int id, TCHAR *szText) { BOOL ret= FALSE; if( id >= m_arrItem.GetSize() ) return FALSE; CMenuButton *pMenu = (CMenuButton*)m_arrItem.GetAt(id); if( pMenu) { pMenu->SetText(szText); ret = TRUE; } else ret = FALSE; return ret; } //****************************************************************** void CMenuBar::OnPaint() { CPaintDC pDC(this); // device context for painting // TODO: Add your message handler code here // Do not call CControlBar::OnPaint() for painting messages CRect rect; GetClientRect(rect); BOOL bFlota=m_dwStyle & CBRS_FLOATING; // draw items m_sizex=0; CRect m_rect; GetClientRect(m_rect); CBrush cbr; cbr.CreateSolidBrush(GuiDrawLayer::GetRGBColorFace(GuiDrawLayer::m_Style)); pDC.FillRect(m_rect,&cbr); for (int i = 0; i < m_arrItem.GetSize(); ++i) { m_arrItem[i]->Update(&pDC); if (m_bChangeState) m_arrItem[i]->UpdateButtons(); } if (m_bChangeState) m_bChangeState=FALSE; // delay draw captions if (m_pMenuControl) { if (IsFloating()) { m_pMenuControl->DelayLayoutAndDraw(&pDC, rect.Size(),bFlota); } else { if (m_dwStyle & CBRS_ORIENT_HORZ) m_pMenuControl->DelayLayoutAndDraw(&pDC, CSize(GetClipBoxLength(TRUE), rect.Height()),bFlota); else m_pMenuControl->DelayLayoutAndDraw(&pDC, CSize(rect.Width(), GetClipBoxLength(FALSE)),bFlota); } } }
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 3311 ] ] ]
8804686a694af85f00d1a7ca97d9a65561d87563
c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac
/src/Engine/Resource/ResFactory.cpp
f20da91ee50b6b74ed0127aafb26115c9805e4ca
[]
no_license
ptrefall/smn6200fluidmechanics
841541a26023f72aa53d214fe4787ed7f5db88e1
77e5f919982116a6cdee59f58ca929313dfbb3f7
refs/heads/master
2020-08-09T17:03:59.726027
2011-01-13T22:39:03
2011-01-13T22:39:03
32,448,422
1
0
null
null
null
null
UTF-8
C++
false
false
1,659
cpp
#include "precomp.h" #include "ResFactory.h" #include "XMLResource.h" #include <Core/CoreMgr.h> using namespace Engine; std::map<CL_String, ResFactory::ResourceCreator>* ResFactory::creators; ResFactory::ResFactory(CoreMgr *coreMgr) { this->coreMgr = coreMgr; } ResFactory::~ResFactory() { if(creators) { creators->clear(); delete creators; creators = NULL; } } void ResFactory::registerResource(const CL_String &fileType, ResourceCreator functor) { if(creators == 0) creators = new std::map<CL_String, ResourceCreator>(); if(creators->find(fileType) == creators->end()) { std::pair<CL_String, ResourceCreator> value(fileType, functor); creators->insert(value); } } IResource *ResFactory::create(const CL_String &fileName, const CL_String &fileType) { if(creators == 0) throw CL_Exception("ResourceCreator map has not been instanciated!"); //If we're trying to create a resource, but it's already been loaded into memory, don't do it twice! bool isXml = false; if(fileType == XMLResource::getType()) { isXml = true; std::map<CL_String, IResource*>::iterator it = xmlResources.find(fileName); if(it != xmlResources.end()) { return it->second; } } std::map<CL_String, ResourceCreator>::iterator creatorIt = creators->find(fileType); if(creatorIt == creators->end()) throw CL_Exception(cl_format("%1 %2", "Unable to create resouce of type", fileType)); ResourceCreator creator = creatorIt->second; IResource *resource = creator(coreMgr, fileName); if(resource && isXml) { xmlResources[fileName] = resource; } return resource; }
[ "[email protected]@c628178a-a759-096a-d0f3-7c7507b30227" ]
[ [ [ 1, 67 ] ] ]
dbc655b7a94cd9af132163d4470b8e026426af6d
cfcd2a448c91b249ea61d0d0d747129900e9e97f
/thirdparty/OpenCOLLADA/COLLADAFramework/src/COLLADAFWSceneGraphInstance.cpp
b890fae6f6011ee7c76653a2369506e77fc9445c
[]
no_license
fire-archive/OgreCollada
b1686b1b84b512ffee65baddb290503fb1ebac9c
49114208f176eb695b525dca4f79fc0cfd40e9de
refs/heads/master
2020-04-10T10:04:15.187350
2009-05-31T15:33:15
2009-05-31T15:33:15
268,046
0
0
null
null
null
null
UTF-8
C++
false
false
666
cpp
/* Copyright (c) 2008 NetAllied Systems GmbH This file is part of COLLADAFramework. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #include "COLLADAFWStableHeaders.h" #include "COLLADAFWSceneGraphInstance.h" namespace COLLADAFW { //------------------------------ SceneGraphInstance::SceneGraphInstance( UniqueId instanciatedObjectId ) : mInstanciatedObjectId(instanciatedObjectId) { } //------------------------------ SceneGraphInstance::~SceneGraphInstance() { } } // namespace COLLADAFW
[ [ [ 1, 31 ] ] ]
cbb48ed3175ef63a62d0ebf4089a069e534fe01a
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/august/AugustMusic.cpp
b475805e9a4dc983b6d3d569b7d122c2e81146b1
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,149
cpp
////////////////////////////////////////////////////////// // // AugustMusic // - MglGraphicManager レイヤークラス // ////////////////////////////////////////////////////////// #include "stdafx.h" #include "AugustMusic.h" #include "MglCoManager.h" #include "AugustScreen2.h" using namespace agh; using namespace std; /////////////////////////////////////////////////////////////////////// // コンストラクタ CAugustMusic::CAugustMusic() : _BASE ("CAugustMusic") { m_pCore = new _MGL_AUGUST_MUSIC_CORE_IMPL(); } // デストラクタ CAugustMusic::~CAugustMusic() { delete m_pCore; } // 登録時にInitを呼び出す void CAugustMusic::OnRegist() { //CoInitialize(NULL); g_coManager.Init(); HWND hWnd = (HWND)MyuAssertNull(GetValPtr(MWLAGH_VALKEY_ROOT_WINDOW_HWND), "CAugustMusic::OnRegist() ウインドウハンドルのGetValPtr()に失敗"); #ifdef _AGM_USE_INHERIT CMglBgm::Init(hWnd); #else m_pCore->Init(hWnd); #endif // 2009/09/05 ウインドウを閉じる前にReleaseしてもらうようにする CAugustScreen2_X* pScreen = (CAugustScreen2_X*)MyuAssertNull(GetValPtr(AUGUST_VALKEY_SCREEN), "CAugustMusic::OnRegist() CAugustScreen2のGetValPtr()に失敗"); #ifdef _AGM_USE_INHERIT pScreen->AddToReleaseList( this ); #else pScreen->AddToReleaseList( m_pCore ); #endif } #ifndef _AGM_USE_INHERIT void CAugustMusic::Load( const char* szAudioFile){ RegistedCheck(); m_pCore->Load(szAudioFile); } void CAugustMusic::Unload(){ RegistedCheck(); m_pCore->Unload(); } void CAugustMusic::Play(){ RegistedCheck(); m_pCore->Play(); } void CAugustMusic::LoopPlay( int nLoopCnt ){ RegistedCheck(); m_pCore->LoopPlay(nLoopCnt); } void CAugustMusic::Stop(){ RegistedCheck(); m_pCore->Stop(); } void CAugustMusic::SetLastLoop(){ RegistedCheck(); m_pCore->SetLastLoop(); } void CAugustMusic::Pause(){ RegistedCheck(); m_pCore->Pause(); } void CAugustMusic::SetVolume( int nVolume ){ RegistedCheck(); m_pCore->SetVolume(nVolume); } void CAugustMusic::SetBalance( int nBalance ){ RegistedCheck(); m_pCore->SetBalance(nBalance); } #endif
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 70 ] ] ]
3cbd8cb9e9420049dff3979163de5afd11d3ac7e
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Animation/Animation/Animation/Mirrored/hkaMirroredSkeleton.h
4f008a2257936c8dd49b3e5cde9830063bdf3406
[]
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
7,543
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 HKANIMATION_ANIMATION_HKMIRROREDSKELETON_H #define HKANIMATION_ANIMATION_HKMIRROREDSKELETON_H #include <Animation/Animation/Animation/hkaSkeletalAnimation.h> #include <Common/Base/Math/Util/hkConvertCoordinateSpace.h> class hkaSkeleton; /// This is a helper class for the hkaMirroredSkeletalAnimation which encapsulates the 'mirroring' functionality /// and works at a per-bone level (rather than the per-track level of a hkaSkeletalAnimation). class hkaMirroredSkeleton : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RIG ); /// Constructor for hkaMirroredSkeletalAnimation /// \param skeleton Rig hierarchy hkaMirroredSkeleton( const hkaSkeleton *skeleton ); ~hkaMirroredSkeleton(); // MIRRORING SETTINGS /// Set the mirror axis /// \param v Axis to mirror about void setMirrorAxis( const hkVector4 &v ); /// Sets the mode to mix coordinate systems between left and right sides /// \param negate Enables/disables mixed mode void setMixedMode( hkBool mixed = true ); /// Set the default orientation of the root node /// \param T Transformation to account for an offset of the root void setRootOrientation( const hkQsTransform &T ); /// Set the default orientation of direct children of the root /// \param T Transformation to account for an offset of children of the root void setChildOrientation( const hkQsTransform &T ); /// Set an orientation for the nubs /// \param T Transformation to account for nub non-conformance void setNubOrientation( const hkQsTransform &T ); // PAIRING /// Allows the user to set bone pairing information /// \param bi Bone to pair with bj /// \param bj Bone to pair with bi void setBonePair( hkInt16 bi, hkInt16 bj ); /// Allows the user to set all of the bone pairing information at once /// \param bonePairMap The mapping of bones to their mirrored partners /// \param numBonePairMap The number of elements in bonePairMap void setBonePairMap( hkInt16* bonePairMap, int numBonePairMap ); /// Allows the user to query bone pairing information /// \return The paired bone for bi /// \param bi Bone to query pair information for hkInt16 getBonePair( hkInt16 bi ) const; #if !defined(HK_PLATFORM_SPU) /// Computes bone pairing information from unique substrings of bone names /// \param ltag Array of strings uniquely identifying left bones /// \param ltag Array of strings uniquely identifying right bones void computeBonePairingFromNames( const hkObjectArray< hkString > &ltag, const hkObjectArray< hkString > &rtag ); /// Computes bone pairing information from unique substrings of bone names /// \param ltag Array of strings uniquely identifying left bones /// \param ltag Array of strings uniquely identifying right bones /// \param skeleton The skeleton that is being mirrored /// \param bonePairMap The buffer for the resultant bone map static void HK_CALL computeBonePairingFromNames( const hkObjectArray< hkString > &ltag, const hkObjectArray< hkString > &rtag, const hkaSkeleton* skeleton, hkInt16 *bonePairMap ); #endif // MIRRORING /// Compute the new mirrored tranform for the paired bone of bone bi. This function is /// typically called by the hkaMirroredSkeletalAnimation class /// \param QInOut Contains the transform for bone bi, overwritten with new paired bj transform void mirrorPairedBone( hkQsTransform &QInOut, hkInt16 bi, hkBool additive ) const; /// Compute a new mirrored transform for extracted motion of the root /// typically called by the hkaMirroredSkeletalAnimation class /// \param QInOut Contains the original delta transform, overwritten by the mirrored transform /// \param additive True if this animation is additive void mirrorExtractedMotion( hkQsTransform &QInOut, hkBool additive ) const; // NOT FOR USER USE Accessors for static method hkaMirroredSkeletalAnimation::samplePartialWithDataChunks inline hkInt16* getBonePairMap() const { return m_bonePairMap; } inline hkBool* getBoneIsNubArray() const { return m_boneIsNub; } inline const hkaSkeleton* getSkeleton() const { return m_skeleton; } inline void reconstructFromDMAdData(hkInt16* bonePairMap, hkBool* boneIsNubArray, const hkaSkeleton* skeleton) { m_bonePairMap = bonePairMap; m_boneIsNub = boneIsNubArray; m_skeleton = skeleton; } private: /// Creates a mirroring transform /// \param v Axis to mirror about /// \return A mirroring transform about axis v hkConvertCS createMirroringCS( const hkVector4 &v ) const; /// Mirrors a bone transform about the chosen axis /// \param QInOut Tranform to mirror /// \param T Mirroring transform /// \return Mirrored version of Q static void HK_CALL mirrorTransform( hkQsTransform& QInOut, const hkConvertCS& T ); /// Mirrors a bone transform about the chosen axis with an offset transform /// \param QInOut TransformToMirror /// \param T Mirroring transform /// \param R Offset rotation static void HK_CALL mirrorTransform( hkQsTransform& QInOut, const hkConvertCS& T, const hkQsTransform& R ); /// Creates the proper mirroring transform for bone bi /// \param Q Input transform (current transform of paired bone) /// \param bi The bone to produce a mirroring transform for hkQsTransform mirrorTransform( hkQsTransform& QInOut, hkInt16 bi ) const; /// Updates all mirroring transforms void computeMirroringTransforms(); /// Computes which bones are nubs void computeBoneChildInfo(); /// Bone pairing information hkInt16 *m_bonePairMap; /// Keep track of which bones are nubs (those without a child) hkBool *m_boneIsNub; /// Skeleton, used to get the parent bone information const hkaSkeleton *m_skeleton; // Required Options /// Local axis of reflection hkVector4 m_axis; // Optional Options hkQsTransform m_rootOrientation; hkQsTransform m_childOrientation; hkQsTransform m_nubOrientation; hkBool m_mixed; // Values cached for efficiency hkConvertCS m_mirrorCS; hkConvertCS m_rootCS; hkConvertCS m_childCS; hkConvertCS m_nubCS; hkQuaternion m_rotateSide; }; #endif // HKANIMATION_ANIMATION_HKMIRROREDSKELETON_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, 186 ] ] ]
616e5684d14f3b0a345029855f3383d441998b0f
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/include/libOEMsg/OEMsgRenderState.h
08724224d581ea6d41feec6acebba224ed70ae8c
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
789
h
/*! * \file OEMsgRenderState.h * \date 10-29-2010 0:02:27 * * * \author zjhlogo ([email protected]) */ #ifndef __OEMSGRENDERSTATE_H__ #define __OEMSGRENDERSTATE_H__ #include "../libOEBase/IOEMsg.h" #include "../OECore/OERenderState.h" class COEMsgRenderState: public IOEMsg { public: COEMsgRenderState(const COERenderState& RenderState, const tstring& strCommon = EMPTY_STRING); COEMsgRenderState(COEDataBufferRead* pDBRead); virtual ~COEMsgRenderState(); COERenderState& GetRenderState(); const tstring& GetCommon(); protected: virtual bool FromBuffer(COEDataBufferRead* pDBRead); virtual bool ToBuffer(COEDataBufferWrite* pDBWrite); private: COERenderState m_RenderState; tstring m_strCommon; }; #endif // __OEMSGRENDERSTATE_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 34 ] ] ]
4db55140a0a74e55b07b395db95bf6f062e9222e
4d91ca4dcaaa9167928d70b278b82c90fef384fa
/AutoUpdateVersionGen/VersionGenerator/VersionGenerator/MainWindow.h
925a714b4ee17539c68201cd53a0647897aeff4c
[]
no_license
dannydraper/CedeCryptClassic
13ef0d5f03f9ff3a9a1fe4a8113e385270536a03
5f14e3c9d949493b2831710e0ce414a1df1148ec
refs/heads/master
2021-01-17T13:10:51.608070
2010-10-01T10:09:15
2010-10-01T10:09:15
63,413,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,325
h
#include <windows.h> #include <io.h> #include <commctrl.h> #include "UIWindow.h" #include "UIHandler.h" #include "ControlCreator.h" #include "UIPicButton.h" #include "UIBanner.h" #include "Diagnostics.h" #include "UILabel.h" #include "MenuHandler.h" #include "Stack.h" class MainWindow : public UIWindow { public: MainWindow (); ~MainWindow (); void Initialise (HWND hWnd); void SetDiagnostics (Diagnostics *pdiag); private: // Private Member Variables & objects bool OpenSingleFile (); bool SaveSingleFile (); void FormToFile (); void FileToForm (); char m_szInputfile[SIZE_STRING]; char m_szInputfiletitle[SIZE_STRING]; char m_szOutputfile[SIZE_STRING]; // The UI Handler required for multiple handling of custom controls. UIHandler m_uihandler; // The Control Creater required for fast creation of controls ControlCreator m_ccontrols; //A test stack Stack m_stack; // Global hwnd HWND m_hwnd; HWND m_webversion; HWND m_latestupdates; HWND m_numfiles; HWND m_localfile1; HWND m_weblocation1; HWND m_localfile2; HWND m_weblocation2; HWND m_localfile3; HWND m_weblocation3; HWND m_localfile4; HWND m_weblocation4; HWND m_localfile5; HWND m_weblocation5; HWND m_localfile6; HWND m_weblocation6; HWND m_localfile7; HWND m_weblocation7; HWND m_static; HWND m_btnsave; HWND m_btnload; // The header bitmap image UIBanner m_header; // The main menu class MenuHandler m_mainmenu; // Pointer to the global diagnostics window Diagnostics *m_pdiag; // Temporary input output buffers //MemoryBuffer m_inBuffer; //MemoryBuffer m_outBuffer; // event notification from base class void OnCreate (HWND hWnd); void OnNotify (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnCommand (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnUICommand (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnPaint (HWND hWnd); void OnTimer (WPARAM wParam); void OnMouseMove (HWND hWnd, int mouseXPos, int mouseYPos); void OnLButtonDown (HWND hWnd); void OnLButtonDblClick (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnCryptEvent (HWND hWnd, WPARAM wParam, LPARAM lParam); void OnLButtonUp (HWND hWnd); };
[ "ddraper@f12373e4-23ff-6a4a-9817-e77f09f3faef" ]
[ [ [ 1, 93 ] ] ]
2a9d69070d7a215e9a24151b9dc117fc5214f8e3
847cccd728e768dc801d541a2d1169ef562311cd
/src/Utils/Array.h
d49338ea06f3f3048c7d4b0972391732281fe18e
[]
no_license
aadarshasubedi/Ocerus
1bea105de9c78b741f3de445601f7dee07987b96
4920b99a89f52f991125c9ecfa7353925ea9603c
refs/heads/master
2021-01-17T17:50:00.472657
2011-03-25T13:26:12
2011-03-25T13:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
h
/// @file /// Templated representation of an array. #ifndef Array_h__ #define Array_h__ #include "Base.h" namespace Utils { /// Templated representation of an array with the information about its size. /// The array knows its size and it can be resized. The purpose of this class is to allow access /// to an array in the same way as to C++ objects and to access arrays from scripts. /// There should be no performance decrease since every method is inlined. template<typename T> class Array { public: /// Constructs an empty array. inline Array(void): mData(0), mSize(0) {} /// Constructs new array with a given size. explicit inline Array(const int32 size): mSize(size) { mData = new T[size]; } /// Destructs the array correctly. ~Array(void) { Clear(); } /// Destroys the data the array carries. void Clear(void) { if (mData) delete[] mData; mData = 0; mSize = 0; } /// Read accessor to an array item. inline T operator[](const int32 index) const { return mData[index]; } /// Write accessor to an array item. inline T& operator[](const int32 index) { return mData[index]; } /// Returns size of the array. inline int32 GetSize(void) const { return mSize; } /// Returns the C-like array pointer. inline T* GetRawArrayPtr(void) const { return mData; } /// Resize array to newSize. void Resize(const int32 newSize) { OC_ASSERT(newSize>=0); if (mSize == newSize) return; T* newData = new T[newSize]; // Copy old data to new array for (int32 i=0; i<newSize && i<mSize; ++i) { newData[i] = mData[i]; } if (mData) delete[] mData; mData = newData; mSize = newSize; } /// Makes a deep copy of the array. void CopyFrom(const Array<T>& toCopy) { if (this == &toCopy) return; Resize(toCopy.GetSize()); for (int32 i=0; i<mSize; ++i) { mData[i] = toCopy[i]; } } /// Comparison operator. bool operator==(const Array<T>& other) const { if (other.GetSize() != GetSize()) return false; for (int32 i=0; i<mSize; ++i) { if (!(mData[i] == other.mData[i])) return false; } return true; } private: T* mData; int32 mSize; /// Copy ctor and assignment operator are disabled. Array(const Array& rhs); Array& operator=(const Array& rhs); }; } #endif // Array_h__
[ [ [ 1, 10 ], [ 15, 20 ], [ 22, 23 ], [ 25, 47 ], [ 49, 53 ], [ 55, 56 ], [ 67, 67 ], [ 72, 74 ], [ 76, 95 ], [ 97, 104 ] ], [ [ 11, 14 ], [ 57, 66 ], [ 68, 71 ], [ 96, 96 ] ], [ [ 21, 21 ], [ 24, 24 ], [ 48, 48 ], [ 54, 54 ], [ 75, 75 ] ] ]
01c04deda4a6d657ba70d17c3a21c68e04da1805
83da738aa8446efa499555e0073a7215b3f874a3
/code/wxAwesomium.h
7eb067fbdbb49888102c29a2d4bb48d04a8dff0b
[]
no_license
duponamk/wxawesomium
38a65d1b775d8c8a2071740324c433ec6bfdce81
05bd19bd9f6abe2d998c1039f7da06b6e76b434e
refs/heads/master
2016-08-11T09:13:37.429058
2009-09-18T12:30:16
2009-09-18T12:30:16
44,711,453
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,857
h
///////////// Copyright © 2009 DesuraNet. All rights reserved. ///////////// // // Project : wxAwesomium // File : wxAwesomium.h // Description : // [TODO: Write the purpose of wxAwesomium.h.] // // Created On: 9/18/2009 2:17:56 PM // Created By: Mark Chandler <mailto:[email protected]> //////////////////////////////////////////////////////////////////////////// #ifndef DESURA_WXAWESOMIUM_H #define DESURA_WXAWESOMIUM_H #ifdef _WIN32 #pragma once #endif #include "wx/wx.h" #include "wxWebListener.h" #include "WebCore.h" class wxAwesomium : public wxPanel { public: wxAwesomium(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 500,300 ), long style = wxFULL_REPAINT_ON_RESIZE|wxWANTS_CHARS ); ~wxAwesomium(); void loadHtml(const wxString& html); void loadFile(const wxString& file); void loadUrl(const wxString& url); void stop(); void refresh(); void back(); void forward(); bool AcceptsFocus(); void registerJSCallBack(const wxString& callback); void addCookie(const wxString& url, const wxString& name, const wxString& value); protected: void onKeyPressed( wxKeyEvent& event ); void onKeyDown( wxKeyEvent& event ); void onKeyUp( wxKeyEvent& event ); void onMouseEvent( wxMouseEvent& event ); void onResize( wxSizeEvent& event ); void onBlur( wxFocusEvent& event ); void onFocus( wxFocusEvent& event ); void onPaint(wxPaintEvent& event); void onEraseBG( wxEraseEvent& event ){;} void onIdle( wxIdleEvent& event ); bool wxMouseToAMouse(int mouse, Awesomium::MouseButton& res); void changeCursor(const HCURSOR& cursor); private: Awesomium::WebView* m_pWebView; friend class wxWebViewListener; DECLARE_EVENT_TABLE(); }; #endif //DESURA_WXAWESOMIUM_H
[ "lodle.05@87dc4f06-a44e-11de-b1fe-bba1d6bec496" ]
[ [ [ 1, 70 ] ] ]
0d102d0c647a83c653d3f5c348563368e4dea225
dd3f4d317a0e363a866fa06e8a8fd4bc29d86805
/RakNet/RakNetStatistics.cpp
c94c338fe8eb9a08edee6db82657f38d3cfcf4fc
[]
no_license
Xaretius/vaultmp
23c0b3a5a5e623d5ac7ab70eab11a0142ff9edad
28f83a7068441a4120b086a1355462d2f26eaa3a
refs/heads/master
2021-01-10T14:40:34.980883
2011-05-18T13:09:30
2011-05-18T13:09:30
50,698,651
0
0
null
null
null
null
UTF-8
C++
false
false
6,269
cpp
/// \file /// /// This file is part of RakNet Copyright 2003 Jenkins Software LLC /// /// Usage of RakNet is subject to the appropriate license agreement. #include "RakNetStatistics.h" #include <stdio.h> // sprintf #include "GetTime.h" #include "RakString.h" using namespace RakNet; // Verbosity level currently supports 0 (low), 1 (medium), 2 (high) // Buffer must be hold enough to hold the output string. See the source to get an idea of how many bytes will be output void RAK_DLL_EXPORT RakNet::StatisticsToString( RakNetStatistics *s, char *buffer, int verbosityLevel ) { if ( s == 0 ) { sprintf( buffer, "stats is a NULL pointer in statsToString\n" ); return ; } if (verbosityLevel==0) { sprintf(buffer, "Bytes per second sent %"PRINTF_64_BIT_MODIFIER"u\n" "Bytes per second received %"PRINTF_64_BIT_MODIFIER"u\n" "Current packetloss %.0f%%\n", s->valueOverLastSecond[ACTUAL_BYTES_SENT], s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], s->packetlossLastSecond ); } else if (verbosityLevel==1) { sprintf(buffer, "Actual bytes per second sent %"PRINTF_64_BIT_MODIFIER"u\n" "Actual bytes per second received %"PRINTF_64_BIT_MODIFIER"u\n" "Message bytes per second pushed %"PRINTF_64_BIT_MODIFIER"u\n" "Total actual bytes sent %"PRINTF_64_BIT_MODIFIER"u\n" "Total actual bytes received %"PRINTF_64_BIT_MODIFIER"u\n" "Total message bytes pushed %"PRINTF_64_BIT_MODIFIER"u\n" "Current packetloss %.0f%%\n" "Average packetloss %.0f%%\n" "Elapsed connection time in seconds %"PRINTF_64_BIT_MODIFIER"u\n", s->valueOverLastSecond[ACTUAL_BYTES_SENT], s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], s->runningTotal[ACTUAL_BYTES_SENT], s->runningTotal[ACTUAL_BYTES_RECEIVED], s->runningTotal[USER_MESSAGE_BYTES_PUSHED], s->packetlossLastSecond, s->packetlossTotal, (uint64_t)((RakNet::GetTimeUS()-s->connectionStartTime)/1000000) ); if (s->BPSLimitByCongestionControl!=0) { char buff2[128]; sprintf(buff2, "Send capacity %"PRINTF_64_BIT_MODIFIER"u bytes per second (%.0f%%)\n", s->BPSLimitByCongestionControl, 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl ); strcat(buffer,buff2); } if (s->BPSLimitByOutgoingBandwidthLimit!=0) { char buff2[128]; sprintf(buff2, "Send limit %"PRINTF_64_BIT_MODIFIER"u (%.0f%%)\n", s->BPSLimitByOutgoingBandwidthLimit, 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit ); strcat(buffer,buff2); } } else { sprintf(buffer, "Actual bytes per second sent %"PRINTF_64_BIT_MODIFIER"u\n" "Actual bytes per second received %"PRINTF_64_BIT_MODIFIER"u\n" "Message bytes per second sent %"PRINTF_64_BIT_MODIFIER"u\n" "Message bytes per second resent %"PRINTF_64_BIT_MODIFIER"u\n" "Message bytes per second pushed %"PRINTF_64_BIT_MODIFIER"u\n" "Message bytes per second processed %"PRINTF_64_BIT_MODIFIER"u\n" "Message bytes per second ignored %"PRINTF_64_BIT_MODIFIER"u\n" "Total bytes sent %"PRINTF_64_BIT_MODIFIER"u\n" "Total bytes received %"PRINTF_64_BIT_MODIFIER"u\n" "Total message bytes sent %"PRINTF_64_BIT_MODIFIER"u\n" "Total message bytes resent %"PRINTF_64_BIT_MODIFIER"u\n" "Total message bytes pushed %"PRINTF_64_BIT_MODIFIER"u\n" "Total message bytes received %"PRINTF_64_BIT_MODIFIER"u\n" "Total message bytes ignored %"PRINTF_64_BIT_MODIFIER"u\n" "Messages in send buffer, by priority %i,%i,%i,%i\n" "Bytes in send buffer, by priority %i,%i,%i,%i\n" "Messages in resend buffer %i\n" "Bytes in resend buffer %"PRINTF_64_BIT_MODIFIER"u\n" "Current packetloss %.0f%%\n" "Average packetloss %.0f%%\n" "Elapsed connection time in seconds %"PRINTF_64_BIT_MODIFIER"u\n", s->valueOverLastSecond[ACTUAL_BYTES_SENT], s->valueOverLastSecond[ACTUAL_BYTES_RECEIVED], s->valueOverLastSecond[USER_MESSAGE_BYTES_SENT], s->valueOverLastSecond[USER_MESSAGE_BYTES_RESENT], s->valueOverLastSecond[USER_MESSAGE_BYTES_PUSHED], s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], s->valueOverLastSecond[USER_MESSAGE_BYTES_RECEIVED_IGNORED], s->runningTotal[ACTUAL_BYTES_SENT], s->runningTotal[ACTUAL_BYTES_RECEIVED], s->runningTotal[USER_MESSAGE_BYTES_SENT], s->runningTotal[USER_MESSAGE_BYTES_RESENT], s->runningTotal[USER_MESSAGE_BYTES_PUSHED], s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_PROCESSED], s->runningTotal[USER_MESSAGE_BYTES_RECEIVED_IGNORED], s->messageInSendBuffer[IMMEDIATE_PRIORITY],s->messageInSendBuffer[HIGH_PRIORITY],s->messageInSendBuffer[MEDIUM_PRIORITY],s->messageInSendBuffer[LOW_PRIORITY], (unsigned int) s->bytesInSendBuffer[IMMEDIATE_PRIORITY],(unsigned int) s->bytesInSendBuffer[HIGH_PRIORITY],(unsigned int) s->bytesInSendBuffer[MEDIUM_PRIORITY],(unsigned int) s->bytesInSendBuffer[LOW_PRIORITY], s->messagesInResendBuffer, s->bytesInResendBuffer, s->packetlossLastSecond, s->packetlossTotal, (uint64_t)((RakNet::GetTimeUS()-s->connectionStartTime)/1000000) ); if (s->BPSLimitByCongestionControl!=0) { char buff2[128]; sprintf(buff2, "Send capacity %"PRINTF_64_BIT_MODIFIER"u bytes per second (%.0f%%)\n", s->BPSLimitByCongestionControl, 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByCongestionControl ); strcat(buffer,buff2); } if (s->BPSLimitByOutgoingBandwidthLimit!=0) { char buff2[128]; sprintf(buff2, "Send limit %"PRINTF_64_BIT_MODIFIER"u (%.0f%%)\n", s->BPSLimitByOutgoingBandwidthLimit, 100.0f * s->valueOverLastSecond[ACTUAL_BYTES_SENT] / s->BPSLimitByOutgoingBandwidthLimit ); strcat(buffer,buff2); } } }
[ [ [ 1, 148 ] ] ]
a7f5e4f38ec631ce585e5fe0c2bba00adc25c250
011359e589f99ae5fe8271962d447165e9ff7768
/src/burner/Xbox360/burner_Xbox360.h
9aff441105e70d46ac3218937c5c5ebd3ed0a37a
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
11,432
h
#ifndef BURNER_WIN32_H #define BURNER_WIN32_H #define _WIN32_WINNT 0x0500 #define _WIN32_IE 0x0500 #ifdef _UNICODE #define UNICODE #endif #define WIN32_LEAN_AND_MEAN #define OEMRESOURCE #include <xtl.h> #include "main.h" // Additions to the Cygwin/MinGW win32 headers #ifdef __GNUC__ #include "mingw_win32.h" #endif // --------------------------------------------------------------------------- // use STL #include <string> #include <list> #include <set> #include <map> #include <string> #include <vector> #include <hash_map> #include <fstream> #include <stdio.h> using std::string; using std::list; using std::set; using std::map; using std::vector; using std::multimap; using std::ofstream; #if 0 //ndef NO_STLPORT using std::hash_map; #else using stdext::hash_map; #endif typedef std::basic_string<TCHAR> tstring; #ifndef MAX_PATH #define MAX_PATH (260) #endif // --------------------------------------------------------------------------- // Macro for releasing a COM object #define RELEASE(x) { if ((x)) (x)->Release(); (x) = NULL; } #define IDS_ERR_UNKNOWN "Unknown" #define KEY_DOWN(Code) ((GetAsyncKeyState(Code) & 0x8000) ? 1 : 0) // Macro used for re-initialiging video/sound/input //#define POST_INITIALISE_MESSAGE { dprintf(_T("*** (re-) initialising - %s %i\n"), _T(__FILE__), __LINE__); PostMessage(NULL, WM_APP + 0, 0, 0); } #define POST_INITIALISE_MESSAGE PostMessage(NULL, WM_APP + 0, 0, 0) // --------------------------------------------------------------------------- // includes #include "strconv.h" // --------------------------------------------------------------------------- // from burn extern int bsavedecryptedcs; extern int bsavedecryptedps; extern int bsavedecrypteds1; extern int bsavedecryptedvs; extern int bsavedecryptedm1; extern int bsavedecryptedxor; extern int bsavedecryptedprom; // main.cpp extern HINSTANCE hAppInst; // Application Instance extern HANDLE hMainThread; // Handle to the main thread extern int nAppThreadPriority; extern int nAppShowCmd; extern int nDisableSplash; extern int nLastFilter; extern int nLastRom; extern int nLastFilter; extern int HideChildren; extern int ThreeOrFourPlayerOnly; extern int ArcadeJoystick; extern CBurnApp app; extern IDirect3DDevice9 *pDevice; //extern HACCEL hAccel; #define EXE_NAME_SIZE (32) extern TCHAR szAppExeName[EXE_NAME_SIZE + 1]; extern TCHAR szAppBurnVer[16]; extern bool bCmdOptUsed; extern bool bAlwaysProcessKey; // Used for the load/save dialog in commdlg.h extern TCHAR szChoice[MAX_PATH]; // File chosen by the user int dprintf(TCHAR* pszFormat, ...); // Use instead of printf() in the UI void AppCleanup(); bool AppProcessKeyboardInput(); // popup_win32.cpp enum FBAPopupType { MT_NONE = 0, MT_ERROR, MT_WARNING, MT_INFO }; #define PUF_TYPE_ERROR (1) #define PUF_TYPE_WARNING (2) #define PUF_TYPE_INFO (3) #define PUF_TYPE_LOGONLY (8) #define PUF_TEXT_TRANSLATE (1 << 16) #define PUF_TEXT_NO_TRANSLATE (0) #define PUF_TEXT_DEFAULT (PUF_TEXT_TRANSLATE) int FBAPopupDisplay(int nFlags); int FBAPopupAddText(int nFlags, TCHAR* pszFormat, ...); int FBAPopupDestroyText(); // systeminfo.cpp LONG CALLBACK ExceptionFilter(_EXCEPTION_POINTERS* pExceptionInfo); int SystemInfoCreate(HWND); // splash.cpp extern int nSplashTime; int SplashCreate(); void SplashDestroy(bool bForce); // about.cpp int AboutCreate(HWND); int FirstUsageCreate(HWND); // media.cpp int mediaInit(); int mediaExit(); int mediaChangeFps(int scale); int mediaReInitAudio(); int mediaReInitScrn(); // misc_win32.cpp void createNeedDir(); bool directoryExists(const TCHAR* dirname); void pathCheck(char * path); int directLoadGame(TCHAR* name); bool createToolTip(int toolID, HWND hDlg, TCHAR* pText); int appDirectory(); int getClientScreenRect(HWND hWnd, RECT* pRect); int wndInMid(HWND hMid, HWND hBase); void setWindowAspect(); char* decorateGameName(unsigned int drv); char* decorateKailleraGameName(unsigned int drv); int findRom(int i, struct ArcEntry* list, int count); // drv.cpp extern int bDrvOkay; // 1 if the Driver has been initted okay, and it's okay to use the BurnDrv functions int BurnerDrvInit(int nDrvNum, bool bRestore); int DrvInitCallback(); // Used when Burn library needs to load a game. DrvInit(nBurnSelect, false) int BurnerDrvExit(); // run.cpp extern int nAppVirtualFps; // virtual fps extern int bRunPause; extern int bAltPause; extern int autoFrameSkip; extern bool bShowFPS; extern bool bAppDoFast; extern bool bAppDoStep; extern unsigned int nFastSpeed; extern int nShowEffect; int RunIdle(); int RunMessageLoop(); int RunInit(); int RunExit(); int RunReset(); // scrn.cpp extern HWND hScrnWnd; // Handle to the screen window extern bool bShowOnTop; extern bool bFullscreenOnStart; extern HWND hVideoWnd; // Handle to the video window extern int bAutoPause; extern int nWindowSize; extern RECT SystemWorkArea; // The full screen area extern int nWindowPosX, nWindowPosY; extern int nSavestateSlot; //extern int nScrnVisibleOffset[4]; extern int nXOffset; extern int nYOffset; extern int nXScale; extern int nYScale; int scrnInit(); int scrnExit(); int scrnSize(); int scrnTitle(); int scrnSwitchFull(); int scrnFakeFullscreen(); int scrnSetFull(const bool& full); void __cdecl scrnReinit(); void setPauseMode(bool bPause); void setPauseModeScreen(bool bPause); // sel.cpp extern HWND hSelDlg; extern int nLoadMenuShowX; extern int nLoadDriverShowX; extern int nTabSel; extern TCHAR szUserFilterStr[MAX_PATH]; extern int nSystemSel; int selDialog(HWND); // Choose a Burn driver void clearNodeInfo(); int driverConfigDialog(HWND); // Driver config // translist.cpp extern TCHAR szTransGamelistFile[MAX_PATH]; int loadGamelist(); int createGamelist(); TCHAR* mangleGamename(const TCHAR* pszOldName, bool bRemoveArticle = true); TCHAR* transGameName(const TCHAR* pszOldName, bool bRemoveArticle = true); // favorites.cpp int initFavorites(); int saveFavorites(); void addFavorite(unsigned int index); void removeFavorite(unsigned int index); bool filterFavorite(const unsigned int& index); // config.cpp extern int nIniVersion; int configAppLoadXml(); int configAppSaveXml(); // conc.cpp int configCheatLoad(const TCHAR* filename = NULL); int configCheatReload(const TCHAR* filename = NULL); // wave.cpp extern bool soundLogStart; // wave log start flag int waveLogStart(); int waveLogStop(); void waveLogWrite(); // inpd.cpp int InpdUpdate(); int InpdCreate(); int InpdListMake(int bBuild); int loadDefaultInput(); int SaveDefaultInput(); // inpcheat.cpp int InpCheatCreate(); #ifndef NO_CHEATSEARCH // cheatsearch.cpp int cheatSearchCreate(); void cheatSearchDestroy(); void updateCheatSearch(); #endif // inpdipsw.cpp void InpDIPSWResetDIPs(); int InpDIPSWCreate(); // inpjukebox.cpp extern HANDLE hJukeThread; // Handle to the jukebox window thread extern DWORD dwJukeThreadID; // ID of the jukebox window thread int jukeCreate(); void jukeDestroy(); // inps.cpp extern unsigned int nInpsInput; // The input number we are redefining int InpsCreate(); int InpsUpdate(); // inpc.cpp extern unsigned int nInpcInput; // The input number we are redefining int InpcCreate(); // stated.cpp extern int bDrvSaveAll; int StatedAuto(int bSave); int StatedLoad(int nSlot); int StatedSave(int nSlot); // numdial.cpp void colorAdjustDialog(HWND); void CPUClockDialog(HWND); void aspectSetDialog(HWND); void screenAngleDialog(HWND); // sfactd.cpp int SFactdCreate(); void ToggleLayer(unsigned char thisLayer); void ToggleSprite(unsigned char PriNum); // roms.cpp extern bool avOk; extern bool bRescanRoms; int CreateROMInfo(); // miscpaths.cpp enum ePath { PATH_PREVIEW = 0, PATH_CHEAT, PATH_SCREENSHOT, PATH_SAVESTATE, PATH_RECORDING, PATH_SKIN, PATH_IPS, PATH_TITLE, PATH_FLYER, PATH_SCORE, PATH_SELECT, PATH_GAMEOVER, PATH_BOSS, PATH_ICON, PATH_SUM }; extern TCHAR szMiscPaths[PATH_SUM][MAX_PATH]; int miscDirCreate(HWND); const TCHAR* getMiscPath(unsigned int dirType); const TCHAR* getMiscArchiveName(unsigned int dirType); extern TCHAR szAppRomPaths[DIRS_MAX][MAX_PATH]; int RomsDirCreate(HWND); void pathSheetCreate(HWND); // skin.cpp extern bool bUseGdip; // use GDI+ extern int nRandomSkin; extern bool bVidUsePlaceholder; extern TCHAR szPlaceHolder[MAX_PATH]; HBITMAP loadSkin(HWND hWnd); void randomSelectSkin(); int selectSkin(); void paintSkin(HWND hWnd); // fba_kaillera.cpp int KailleraInitInput(); int KailleraGetInput(); extern int kNetGame; void DoNetGame(); BOOL FBA_KailleraInit(); void FBA_KailleraEnd(); void FBA_KailleraSend(); int ActivateChat(); void DeActivateChat(); bool ChatActivated(); HWND GetChatWindow(); // replay.cpp extern int nReplayStatus; extern bool bReplayReadOnly; extern bool bFrameCounterDisplay; int RecordInput(); int ReplayInput(); int StartRecord(); int StartReplay(const TCHAR* szFileName = NULL); void StopReplay(); int FreezeInput(unsigned char** buf, int* size); int UnfreezeInput(const unsigned char* buf, int size); // memcard.cpp extern int nMemoryCardStatus; // & 1 = file selected, & 2 = inserted int MemCardCreate(); int MemCardSelect(); int MemCardInsert(); int MemCardEject(); int MemCardToggle(); // progress.cpp int ProgressUpdateBurner(double dProgress, const TCHAR* pszText, bool bAbs); int ProgressCreate(); int ProgressDestroy(); // dialogmanager.cpp void dialogAdd(int id, HWND dialog); HWND dialogGet(int id); void dialogDelete(int id); bool dialogIsEmpty(); void dialogClear(); // ---------------------------------------------------------------------------- // Debugger // debugger.cpp int DebugExit(); int DebugCreate(); // ---------------------------------------------------------------------------- // AVI recording extern int nAviStatus; extern int nAviIntAudio; int AviStart(); int AviRecordFrame(int bDraw); int AviStop(); void AviSetBuffer(unsigned char* buffer); // ---------------------------------------------------------------------------- // Audit // State is non-zero if found. 1 = found totally okay enum FIND_STATE { STAT_NOFIND = 0, STAT_OK, STAT_CRC, STAT_SMALL, STAT_LARGE, }; enum AUDIT_STATE { AUDIT_FAIL = 0, AUDIT_PARTPASS = 1, AUDIT_FULLPASS = 3, }; extern char* auditState; int getAllRomsetInfo(); void auditPrepare(); int auditRomset(); void auditCleanup(); void initAuditState(); void resetAuditState(); void freeAuditState(); char getAuditState(const unsigned int& id); void setAuditState(const unsigned int& id, char ret); // xbox utility functions #define DEVICE_MEMORY_UNIT0 1 #define DEVICE_MEMORY_UNIT1 2 #define DEVICE_MEMORY_ONBOARD 3 #define DEVICE_CDROM0 4 #define DEVICE_HARDISK0_PART1 5 #define DEVICE_HARDISK0_SYSPART 6 #define DEVICE_USB0 7 #define DEVICE_USB1 8 #define DEVICE_USB2 9 #define DEVICE_TEST 10 #define DEVICE_CACHE 11 typedef struct _STRING { USHORT Length; USHORT MaximumLength; PCHAR Buffer; } STRING; extern "C" int __stdcall ObCreateSymbolicLink( STRING*, STRING*); void DebugMsg(const char* format, ...); #endif
[ [ [ 1, 455 ] ] ]
02105629cc6d693e97608e534cf038e4c0150ff2
bf4f0fc16bd1218720c3f25143e6e34d6aed1d4e
/Compatibility.h
52d3ad88a6618be6ee143e2eacc855933213e7a4
[]
no_license
shergin/downright
4b0f161700673d7eb49459e4fde2b7d095eb91bb
6cc40cd35878e58f4ae8bae8d5e58256e6df4ce8
refs/heads/master
2020-07-03T13:34:20.697914
2009-09-29T19:15:07
2009-09-29T19:15:07
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
389
h
#pragma once #include "afxtempl.h" class CCompatibility { public: CCompatibility(void); ~CCompatibility(void); void operator = (CString s); operator CString(); CCompatibility& operator = (const CCompatibility &obj); int m_nStrings; CArray<CString,CString&> m_Strings; int m_Type; // 0 - со всеми, 1 - только с этими, 2 - кроме этих };
[ [ [ 1, 16 ] ] ]
6eed9b59cc743cf5ec534ea606aad6b36b423501
b6d1f8a6533bf516a02636dfb0b45fa6adee8efd
/IATModifier.h
b1d0e6af53495a5dd1f6c4bf366599bb084479af
[]
no_license
code4bones/NinjectLib
a6700cf4b18edf4a79e00d0d24cfaa567962d541
a4ef594cfb0c30ba38b7c7b2960a68798bedd3b2
refs/heads/master
2020-12-25T12:07:47.999652
2011-11-15T16:55:37
2011-11-15T16:55:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,434
h
#ifndef IATMODIFIER_H #define IATMODIFIER_H #include <iostream> #include <vector> #include "Process.h" class IATModifier { public: IATModifier(const Process& process); ~IATModifier(); std::vector<IMAGE_IMPORT_DESCRIPTOR> readImportTable(); void setImageBase(uintptr_t address); void writeIAT(const std::vector<std::string>& dlls); void writeIAT(const std::string& dll); IMAGE_NT_HEADERS readNTHeaders() const; private: DWORD pad(DWORD val, DWORD amount) { return (val+amount) & ~amount; }; DWORD padToDword(DWORD val) { return pad(val, 3); }; void* allocateMemAboveBase(void* baseAddress, size_t size); DWORD determineIIDSize(PIMAGE_IMPORT_DESCRIPTOR importDescriptorTableAddress); Process process_; PIMAGE_IMPORT_DESCRIPTOR importDescrTblAddr_; uintptr_t ntHeadersAddr_; unsigned int importDescrTblSize_; }; // general exception for this class class IATModifierException : public std::runtime_error { public: IATModifierException(const std::string& msg) : std::runtime_error(msg) {}; }; // exception while writing image import descriptors class WriteIIDException : public std::runtime_error { public: WriteIIDException(const std::string& msg, const MemoryAccessException& e) : std::runtime_error(msg), innerException_(e) {}; MemoryAccessException innerException() const { return innerException_; }; private: MemoryAccessException innerException_; }; #endif
[ [ [ 1, 50 ] ] ]
e95fc72db61d1de1f742789a30ddff7b702f15f7
ef8e875dbd9e81d84edb53b502b495e25163725c
/classifier/src/classifier_implementation.h
70a6b35019f2d76dc9596416eb37e5e6e7a5ad7a
[]
no_license
panone/litewiz
22b9d549097727754c9a1e6286c50c5ad8e94f2d
e80ed9f9d845b08c55b687117acb1ed9b6e9a444
refs/heads/master
2021-01-10T19:54:31.146153
2010-10-01T13:29:38
2010-10-01T13:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,669
h
/******************************************************************************* *******************************************************************************/ #ifndef CLASSIFIER_IMPLEMENTATION_H #define CLASSIFIER_IMPLEMENTATION_H /******************************************************************************/ #include <QList> #include <QMap> #include <QSet> #include <QStringList> #include "utility.h" /******************************************************************************/ class ClassificationInfo; class StemInfo; /******************************************************************************/ typedef QList< QIntList > QIntList2; typedef QMap< int, int > QIntMap; typedef QMapIterator< int, int > QIntMapIterator; typedef QList< QIntMap > QIntMapList; typedef QMap< int, float > QIntFloatMap; typedef QMapIterator< int, float > QIntFloatMapIterator; typedef QMap< QString, int > QStringIntMap; typedef QMap< QString, QIntList > QStringIntListMap; typedef QMap< QString, QString > QStringMap; typedef QSet< QString > QStringSet; typedef QList< StemInfo > StemInfoList; /******************************************************************************* *******************************************************************************/ class StemInfo { public: int stemLength; int clusters; QIntSet clusterSize; }; /******************************************************************************* *******************************************************************************/ class ClassifierImplementation { public: void classify ( QStringList const & fileNames ); QIntList getPossibleVariance ( void ); int getDefaultVariance ( void ); ClassificationInfo getClassification ( int const variance ); private: void initializeFileDescriptions ( QStringList const & fileNames ); void initializeClusters ( void ); QIntFloatMap getVarianceProbablity ( void ); QIntMap getClusterSizeCount ( void ); QIntSet getUnmatchedClusterSize ( void ); StemInfoList getStemClusterInfo ( void ); void initializeVariance ( QIntFloatMap const & varianceProbability ); void addVarianceProbability ( int const variance, float const probability ); void detectPopularClusterSizes1 ( void ); QIntList getAccumulatedClusterSize ( QIntMap const & clusterSize ); void detectPopularClusterSizes2 ( QIntMap const & clusterSizeCount ); void detectClusterSizeStep ( QIntMap const & clusterSizeCount ); QIntList getRelevantClusterSizes ( QIntList const & clusterSize ); void detectUniqueItemClusterSize ( QIntSet const & clusterSize ); void detectUnmatchedClusterSize ( QIntSet const & clusterSize ); void detectSingleItem1 ( QIntSet const & clusterSize ); void detectItemClusterSize ( StemInfoList const & stemClusterInfo ); void detectSingleItem2 ( StemInfoList const & stemClusterInfo ); void applyVarianceProbability ( QIntFloatMap const & varianceProbability ); void validateVariance ( void ); QIntList getSplitIndices ( int const variance ); QStringMap getItemNames ( QStringList const & stems ); QStringMap getVariantNames ( QStringList const & stems ); float accumulateProbability ( QIntFloatMap const & probability ); private: QStringList fileDescriptions; QIntMapList clusters; QIntFloatMap variance; }; /******************************************************************************/ #endif /* CLASSIFIER_IMPLEMENTATION_H */
[ [ [ 1, 203 ] ] ]
b841996dd754295078bb5fbe934625cad69dc2d2
f64b888affed8c6db2cc56d4618c72c923fe1a7c
/src/platform_unix.cxx
ebb96f676d013fc65a2a8848c0cbd5bcfbad21b4
[ "BSD-2-Clause" ]
permissive
wilx/lockmgr
64ca319f87ccf96214d9c4a3e1095f783fb355d8
9932287c6a49199730abfb4332f85c9ca05d9511
refs/heads/master
2021-01-10T02:19:35.039497
2008-06-09T11:24:32
2008-06-09T11:24:32
36,984,337
0
0
null
null
null
null
UTF-8
C++
false
false
2,867
cxx
// Copyright (c) 2008, Václav Haisman // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "lockmgr/config.hxx" #if defined (LOCKMANAGER_UNIX) #include "lockmgr/internal/platform_unix.hxx" namespace lockmgr { // Definition. ::pthread_key_t thread_id_key; // Definition PthreadMutex thread_id_mutex; // Definition. thread_id_type thread_id_counter; // Definition. thread_id_type get_this_thread_id () { unsigned * thread_id = reinterpret_cast<thread_id_type *> (::pthread_getspecific (thread_id_key)); if (thread_id) return *thread_id; else { thread_id_type new_thread_id; { PthreadMutexGuard mg (thread_id_mutex); new_thread_id = ++thread_id_counter; } std::auto_ptr<thread_id_type> ptid (new thread_id_type (new_thread_id)); int ret = ::pthread_setspecific (thread_id_key, ptid.get ()); if (ret != 0) throw "Using pthread_setspecific() has failed."; else ptid.release (); return new_thread_id; } } namespace { ::pthread_once_t once_control_lockmgr = PTHREAD_ONCE_INIT; void deleter (void * val) { delete reinterpret_cast<thread_id_type *>(val); } void init_lockmgr_pthread_key () { ::pthread_key_create (&thread_id_key, deleter); } struct setup { setup () { ::pthread_once (&once_control_lockmgr, init_lockmgr_pthread_key); } } setup_instance; } // namespace } // namespace lockmgr #endif // defined (LOCKMANAGER_UNIX)
[ [ [ 1, 110 ] ] ]
8a5d0ee81096078825e4e58915d32aac2e0f2f46
fd2b5855f5c8e1d33b3f47017aa0ca8b134b9c6a
/src/text2.cpp
1819d85dd163f884d883ffa0706199089065f8b1
[ "Apache-2.0" ]
permissive
flaithbheartaigh/appuifw2
fc260d998f5d2e209a29dc9c3f08af3967283e58
91ada16e57ac693aa6b2ea17e7bd3649244a1465
refs/heads/master
2021-01-10T11:29:53.717614
2008-09-02T09:41:44
2008-09-02T09:41:44
50,126,456
0
0
null
null
null
null
UTF-8
C++
false
false
41,015
cpp
/* Copyright 2008 Arkadiusz Wahlig ([email protected]) ** ** 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 <e32std.h> #include <e32base.h> #include <s32mem.h> #include <txtfrmat.h> // Text #include <txtfmlyr.h> // Text #include <eikgted.h> // Text #include <eikrted.h> // RText #include <txtrich.h> #include <gdi.h> // RText #include <aknutils.h> #include <aknedsts.h> #include <aknsconstants.h> // for skin IDs #include <aknsbasicbackgroundcontrolcontext.h> #include <aknsutils.h> #include <aknindicatorcontainer.h> #include <akneditstateindicator.h> #include <Python.h> #include <symbian_python_ext_util.h> #include "appuifwutil.h" #include "pycallback.h" #include "fontspec.h" #include "colorspec.h" class CText2RichEditor; class CText2EditObserver; struct Text2_object { // The following fields are required by appuifw.Application. // Note that PyObject_VAR_HEAD is here only to allow using of // this structure as a Python object. However it must always // be present for binary compatibility. PyObject_VAR_HEAD CText2RichEditor *control; CAppuifwEventBindingArray *event_bindings; // The following fields are private. TCharFormatMask char_format_mask; TCharFormat char_format; TInt current_style; CCharFormatLayer *char_format_layer; CParaFormatLayer *para_format_layer; }; const struct _typeobject Text2_type={}; #define KNORMAL 0x00 #define KBOLD 0x01 #define KUNDERLINE 0x02 #define KITALIC 0x04 #define KSTRIKETHROUGH 0x08 #define KHIGHLIGHTNONE 0x00 #define KHIGHLIGHTROUNDED 0x10 #define KHIGHLIGHTSHADOW 0x20 #define KHIGHLIGHTNORMAL 0x40 #define HL_MASK 0x70 class CText2EditObserver : public CBase, public MEditObserver { public: CText2EditObserver(PyObject *aCallBack) { iCallBack = aCallBack; Py_XINCREF(aCallBack); } virtual ~CText2EditObserver() { Py_XDECREF(iCallBack); } virtual void EditObserver(TInt aStart, TInt aExtent) { if (iCallBack) PyAsyncCallBack(iCallBack, Py_BuildValue("ii", aStart, aExtent)); } private: PyObject *iCallBack; }; #ifndef EKA2 class CText2RichEditor : public CEikRichTextEditor, public MEikEdwinObserver #else NONSHARABLE_CLASS(CText2RichEditor) : public CEikRichTextEditor, public MEikEdwinObserver #endif { public: CText2RichEditor() {} virtual void ConstructL(const CCoeControl* aParent, TInt aFlags, TBool aScrollBar, TBool aSkinned, PyObject *aMoveCallBack, PyObject *aEditCallBack); virtual ~CText2RichEditor() { // iCoeEnv->ReleaseScreenFont(aFont); XXX necessary? delete iMyCharFormatLayer; delete iMyParaFormatLayer; if (iBgContext) delete iBgContext; Py_XDECREF(iMoveCallBack); Py_XDECREF(iEditCallBack); if (iEditObserver) delete iEditObserver; } void ReadL(PyObject*& aRval, TInt aPos = 0, TInt aLen = (-1)); TInt WriteL(const TDesC& aText, TInt aPos = -1); void DelL(TInt aPos, TInt aLen); void ApplyFormatL(TInt aPos, TInt aLen); TInt Len() { return RichText()->DocumentLength(); } void ClearL() { RichText()->Reset(); HandleChangeL(0); } TInt SetPos(TInt aPos, TBool aSelect); static TBool CheckRange(TInt& aPos, TInt& aLen, TInt aDocLen); void SetBold(TBool aOpt); void SetUnderline(TBool aOpt); void SetPosture(TBool aOpt); void SetStrikethrough(TBool aOpt); void SetHighlight(TInt mode); void SetStyle(TInt aStyle) { iCurrentStyle = aStyle; }; TInt Style() { return iCurrentStyle; }; void SetTextColor(TRgb color); TRgb TextColor() { return iCharFormat.iFontPresentation.iTextColor; }; void SetHighlightColor(TRgb color); TRgb HighlightColor() { return iCharFormat.iFontPresentation.iHighlightColor; }; void SetFont(TFontSpec&); TFontSpec& Font() { return iCharFormat.iFontSpec; } void SizeChanged() { CEikScrollBarFrame *frame=ScrollBarFrame(); if (iBgContext) { // setup the skinned background TSize size=Size(); TRect rect; #ifdef EKA2 AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EMainPane, rect); #else rect = TRect(0, 44, 176, 188); #endif if (size.iHeight > rect.Height()) { // large, full iBgContext->SetBitmap(KAknsIIDQsnBgScreen); } else { // normal iBgContext->SetBitmap(KAknsIIDQsnBgAreaMain); } iBgContext->SetRect(Rect()); } if (frame) { CEikScrollBar *bar=frame->VerticalScrollBar(); if (bar) { TSize size=Size(); size.iWidth = iParent->Size().iWidth - bar->ScrollBarBreadth(); SetSizeWithoutNotification(size); } } CEikRichTextEditor::HandleSizeChangedL(); TextLayout()->RestrictScrollToTopsOfLines(EFalse); } virtual void MakeVisible(TBool aVisible) { CEikScrollBarFrame *frame=ScrollBarFrame(); if (frame) { TRAPD(error, if (aVisible) frame->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff, CEikScrollBarFrame::EAuto); else frame->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff, CEikScrollBarFrame::EOff); ); } TRAPD(error, if (aVisible) { CAknIndicatorContainer *indi=CAknEnv::Static()-> EditingStateIndicator()->IndicatorContainer(); indi->SetIndicatorValueL(TUid::Uid(EAknNaviPaneEditorIndicatorMessageLength), iIndicatorText); indi->SetIndicatorState(TUid::Uid(EAknNaviPaneEditorIndicatorMessageLength), EAknIndicatorStateOn); } else { CAknIndicatorContainer *indi=CAknEnv::Static()-> EditingStateIndicator()->IndicatorContainer(); indi->SetIndicatorValueL(TUid::Uid(EAknNaviPaneEditorIndicatorMessageLength), _L("")); indi->SetIndicatorState(TUid::Uid(EAknNaviPaneEditorIndicatorMessageLength), EAknIndicatorStateOff); } ); } // needed to draw the scrollbar background virtual TTypeUid::Ptr MopSupplyObject( TTypeUid aId ) { if (aId.iUid == MAknsControlContext::ETypeId && iBgContext) { return MAknsControlContext::SupplyMopObject(aId, iBgContext); } return CEikRichTextEditor::MopSupplyObject( aId ); } virtual void HandleEdwinEventL(CEikEdwin * /*aEdwin*/, TEdwinEvent aEventType) { switch (aEventType) { case EEventNavigation: if (iMoveCallBack) PyCallBack(iMoveCallBack, Py_BuildValue("()")); break; default: break; } } const TDesC &IndicatorText() { return iIndicatorText; } void SetIndicatorTextL(const TDesC &aText) { struct _control_object *o; // copy maximal 32 chars iIndicatorText = aText.Left(32); // refresh the navi indicator if needed // (this is a somewhat hacky test but IsVisible() didn't work, // always returned true) o = AppuifwControl_AsControl(get_app()->ob_body); if (o && o->ob_control == this) { CAknIndicatorContainer *indi=CAknEnv::Static()-> EditingStateIndicator()->IndicatorContainer(); indi->SetIndicatorValueL(TUid::Uid(EAknNaviPaneEditorIndicatorMessageLength), iIndicatorText); indi->SetIndicatorState(TUid::Uid(EAknNaviPaneEditorIndicatorMessageLength), EAknIndicatorStateOn); } } private: void UpdateCharFormatLayerL(); void HandleChangeL(TInt aNewCursorPos) { // TODO: Use SetAmountToFormat to improve performance? HandleTextChangedL(); SetCursorPosL(aNewCursorPos, EFalse); //if (!IsVisible()) { // Otherwise we occasionally pop up unwanted // int in_interpreter=(_PyThreadState_Current == PYTHON_TLS->thread_state); // if (!in_interpreter) // PyEval_RestoreThread(PYTHON_TLS->thread_state); // // The interpreter state must be valid to use the MY_APPUI macro. // CAmarettoAppUi* pyappui = MY_APPUI; // if (!in_interpreter) // PyEval_SaveThread(); // pyappui->RefreshHostedControl(); //} } TCharFormatMask iCharFormatMask; TCharFormat iCharFormat; TInt iCurrentStyle; CCharFormatLayer *iMyCharFormatLayer; CParaFormatLayer *iMyParaFormatLayer; CAknsBasicBackgroundControlContext *iBgContext; PyObject *iMoveCallBack; PyObject *iEditCallBack; CText2EditObserver *iEditObserver; const CCoeControl *iParent; TBuf<32> iIndicatorText; }; void CText2RichEditor::ConstructL(const CCoeControl* aParent, TInt aFlags, TBool aScrollBar, TBool aSkinned, PyObject *aMoveCallBack, PyObject *aEditCallBack) { CEikRichTextEditor::ConstructL(aParent, 0, 0, aFlags, 0, 0); iParent = aParent; ActivateL(); iMyCharFormatLayer = CCharFormatLayer::NewL(); iCurrentStyle = KNORMAL; iCharFormat.iFontPresentation.iTextColor = TRgb(0,128,0); // Default text color: dark green. iCharFormat.iFontPresentation.iHighlightColor = TRgb(180,180,180); // Default highlight color: gray. //iCharFormatMask.SetAll(); iCharFormatMask.SetAttrib(EAttFontHeight); iCharFormatMask.SetAttrib(EAttFontPosture); iCharFormatMask.SetAttrib(EAttFontStrokeWeight); iCharFormatMask.SetAttrib(EAttFontPrintPos); //iCharFormatMask.SetAttrib(EAttFontTypeface); //iCharFormatMask.SetAttrib(EAttFontBitmapStyle); iCharFormatMask.SetAttrib(EAttColor); iCharFormatMask.SetAttrib(EAttFontHighlightColor); iMyCharFormatLayer->SetL(iCharFormat, iCharFormatMask); RichText()->SetGlobalCharFormat(iMyCharFormatLayer); /* Set the global paragraph format. This should be more effective than setting it on every insert. */ iMyParaFormatLayer = CParaFormatLayer::NewL(); CParaFormat paraFormat; TParaFormatMask paraFormatMask; paraFormatMask.SetAttrib(EAttLineSpacing); paraFormatMask.SetAttrib(EAttLineSpacingControl); paraFormat.iLineSpacingControl = CParaFormat::ELineSpacingAtLeastInTwips; paraFormat.iLineSpacingInTwips = 30; iMyParaFormatLayer->SetL(&paraFormat, paraFormatMask); RichText()->SetGlobalParaFormat(iMyParaFormatLayer); if (aSkinned) { iBgContext = CAknsBasicBackgroundControlContext::NewL( KAknsIIDQsnBgScreen, // changed in SizeChanged() TRect(0, 0, 0, 0), // changed in SizeChanged() EFalse); SetSkinBackgroundControlContextL(iBgContext); TInt error; TRgb color; #ifdef EKA2 error = AknsUtils::GetCachedColor( AknsUtils::SkinInstance(), color, KAknsIIDQsnTextColors, EAknsCIQsnTextColorsCG6); #else // Text is always black on 2nd? I see no // text color IDs in 2nd ed includes. error = KErrNone; color = TRgb(0, 0, 0); #endif if (error == KErrNone) SetTextColor(color); } if (aScrollBar) CreateScrollBarFrameL(); if (aMoveCallBack) { iMoveCallBack = aMoveCallBack; Py_INCREF(aMoveCallBack); SetEdwinObserver(this); } if (aEditCallBack) { iEditObserver = new (ELeave) CText2EditObserver(aEditCallBack); RichText()->SetEditObserver(iEditObserver); } } TBool CText2RichEditor::CheckRange(TInt& aPos, TInt& aLen, TInt aDocLen) { if (aPos > aDocLen) return EFalse; if ((aLen < 0) || ((aPos + aLen) > aDocLen)) aLen = aDocLen - aPos; return ETrue; } void CText2RichEditor::ReadL(PyObject*& aRval, TInt aPos, TInt aLen) { if (CheckRange(aPos, aLen, RichText()->DocumentLength()) == EFalse) User::Leave(KErrArgument); if ((aRval = PyUnicode_FromUnicode(NULL, aLen))) { TPtr buf(PyUnicode_AsUnicode(aRval), 0, aLen); RichText()->Extract(buf, aPos, aLen); } } TInt CText2RichEditor::WriteL(const TDesC& aText, TInt aPos) { TInt cpos = CursorPos(); TInt len_written; if (aPos < 0) aPos = cpos; RMemReadStream source(aText.Ptr(), aText.Size()); RichText()->ImportTextL(aPos, source, CPlainText::EOrganiseByParagraph, KMaxTInt, KMaxTInt, &len_written); RichText()->ApplyCharFormatL(iCharFormat, iCharFormatMask, aPos, len_written); /* RichText()->GetParaFormatL(&paraFormat, paraFormatMask, aPos, len_written); paraFormatMask.ClearAll(); RichText()->ApplyParaFormatL(&paraFormat, paraFormatMask, aPos, len_written); */ // BENCHMARKS with N70: // without paraformat, 13s //HandleTextChangedL(); //SetCursorPosL(aPos+len_written, EFalse); // without paraformat, 22s //SetCursorPosL(aPos+len_written, EFalse); //HandleTextChangedL(); // without paraformat, 12s //SetCursorPosL(aPos+len_written, EFalse); // without paraformat, 3.7s //iLayout->SetAmountToFormat(CTextLayout::EFFormatBand); //SetCursorPosL(aPos+len_written, EFalse); // with paraformat, 13.8s //HandleTextChangedL(); //SetCursorPosL(aPos+len_written, EFalse); // with paraformat, 4.6s //iLayout->SetAmountToFormat(CTextLayout::EFFormatBand); //SetCursorPosL(aPos+len_written, EFalse); // with paraformat, 3.9s iTextView->HandleInsertDeleteL(TCursorSelection(aPos,aPos+len_written),0,ETrue); if (cpos > aPos) SetCursorPosL(cpos+len_written,EFalse); return aPos+len_written; } void CText2RichEditor::DelL(TInt aPos, TInt aLen) { TInt cpos = CursorPos(); if (CheckRange(aPos, aLen, RichText()->DocumentLength()) == EFalse) User::Leave(KErrArgument); RichText()->DeleteL(aPos, aLen); iTextView->HandleInsertDeleteL(TCursorSelection(aPos,aPos),aLen,ETrue); if (cpos > aPos) SetCursorPosL(cpos+aLen, EFalse); //HandleTextChangedL(); } void CText2RichEditor::ApplyFormatL(TInt aPos, TInt aLen) { if (CheckRange(aPos, aLen, RichText()->DocumentLength()) == EFalse) User::Leave(KErrArgument); RichText()->ApplyCharFormatL(iCharFormat, iCharFormatMask, aPos, aLen); } TInt CText2RichEditor::SetPos(TInt aPos, TBool aSelect) { if (aPos > RichText()->DocumentLength()) aPos = RichText()->DocumentLength(); TRAPD(error, SetCursorPosL(aPos, aSelect)); return error; } void CText2RichEditor::UpdateCharFormatLayerL(void) { iMyCharFormatLayer->SetL(iCharFormat, iCharFormatMask); } void CText2RichEditor::SetBold(TBool aOpt) { iCharFormatMask.SetAttrib(EAttFontStrokeWeight); if (aOpt) iCharFormat.iFontSpec.iFontStyle.SetStrokeWeight(EStrokeWeightBold); else iCharFormat.iFontSpec.iFontStyle.SetStrokeWeight(EStrokeWeightNormal); UpdateCharFormatLayerL(); } void CText2RichEditor::SetUnderline(TBool aOpt) { iCharFormatMask.SetAttrib(EAttFontUnderline); if (aOpt) iCharFormat.iFontPresentation.iUnderline = EUnderlineOn; else iCharFormat.iFontPresentation.iUnderline = EUnderlineOff; UpdateCharFormatLayerL(); } void CText2RichEditor::SetPosture(TBool aOpt) { iCharFormatMask.SetAttrib(EAttFontPosture); if (aOpt) iCharFormat.iFontSpec.iFontStyle.SetPosture(EPostureItalic); else iCharFormat.iFontSpec.iFontStyle.SetPosture(EPostureUpright); UpdateCharFormatLayerL(); } void CText2RichEditor::SetStrikethrough(TBool aOpt) { iCharFormatMask.SetAttrib(EAttFontStrikethrough); if (aOpt) iCharFormat.iFontPresentation.iStrikethrough = EStrikethroughOn; else iCharFormat.iFontPresentation.iStrikethrough = EStrikethroughOff; UpdateCharFormatLayerL(); } void CText2RichEditor::SetHighlight(TInt mode) { iCharFormatMask.SetAttrib(EAttFontHighlightStyle); switch (mode) { case KHIGHLIGHTNONE: iCharFormat.iFontPresentation.iHighlightStyle = TFontPresentation::EFontHighlightNone; break; case KHIGHLIGHTNORMAL: iCharFormat.iFontPresentation.iHighlightStyle = TFontPresentation::EFontHighlightNormal; break; case KHIGHLIGHTROUNDED: iCharFormat.iFontPresentation.iHighlightStyle = TFontPresentation::EFontHighlightRounded; break; case KHIGHLIGHTSHADOW: iCharFormat.iFontPresentation.iHighlightStyle = TFontPresentation::EFontHighlightShadow; break; } UpdateCharFormatLayerL(); } void CText2RichEditor::SetTextColor(TRgb color) { iCharFormatMask.SetAttrib(EAttColor); iCharFormat.iFontPresentation.iTextColor = color; UpdateCharFormatLayerL(); } void CText2RichEditor::SetHighlightColor(TRgb color) { iCharFormatMask.SetAttrib(EAttFontHighlightColor); iCharFormat.iFontPresentation.iHighlightColor = color; UpdateCharFormatLayerL(); } void CText2RichEditor::SetFont(TFontSpec& aFontSpec) { /* XXX Necessary??? * * iCoeEnv = CEikRichTextEditor::ControlEnv(); TRAPD(error, (aFont = iCoeEnv->CreateScreenFontL(*aFontSpec) )); if (error != KErrNone) { SPyErr_SetFromSymbianOSErr(error); return; } */ iCharFormatMask.SetAttrib(EAttFontHeight); iCharFormatMask.SetAttrib(EAttFontPosture); iCharFormatMask.SetAttrib(EAttFontStrokeWeight); iCharFormatMask.SetAttrib(EAttFontPrintPos); iCharFormatMask.SetAttrib(EAttFontTypeface); //iCharFormatMask.SetAll(); iCharFormat.iFontSpec = aFontSpec; UpdateCharFormatLayerL(); } static Text2_object *PyCObject_AsText2(PyObject *co) { Text2_object *o; if (PyCObject_Check(co)) { o = (Text2_object *) PyCObject_AsVoidPtr(co); if (o->ob_type == &Text2_type) return o; } PyErr_SetString(PyExc_TypeError, "invalid Text2 uicontrolapi object"); return NULL; } static void Text2_destroy(Text2_object *o) { if (o->control) delete o->control; if (o->event_bindings) delete o->event_bindings; delete o; } PyObject* Text2_create(PyObject* /*self*/, PyObject *args) { int flags=EEikEdwinNoAutoSelection| // 0x00000008 EEikEdwinAlwaysShowSelection| // 0x00001000 EEikEdwinInclusiveSizeFixed; // 0x00000100 int scrollbar=1, skinned=0; PyObject *move_callback=NULL, *edit_callback=NULL; Text2_object *o; CCoeControl *container; TInt error; if (!PyArg_ParseTuple(args, "|iiiOO", &flags, &scrollbar, &skinned, &move_callback, &edit_callback)) return NULL; if (move_callback) { if (move_callback == Py_None) move_callback = NULL; else if (!PyCallable_Check(move_callback)) { PyErr_SetString(PyExc_TypeError, "move callback must be a callable"); return NULL; } } if (edit_callback) { if (edit_callback == Py_None) edit_callback = NULL; else if (!PyCallable_Check(edit_callback)) { PyErr_SetString(PyExc_TypeError, "edit callback must be a callable"); return NULL; } } o = new Text2_object; if (!o) return PyErr_NoMemory(); o->control = NULL; o->event_bindings = NULL; o->event_bindings = new CAppuifwEventBindingArray; if (!o->event_bindings) { Text2_destroy(o); return PyErr_NoMemory(); } o->control = new CText2RichEditor; if (!o->control) { Text2_destroy(o); return PyErr_NoMemory(); } container = get_app()->ob_data->appui->iContainer; TRAP(error, o->control->ConstructL(container, flags, scrollbar, skinned, move_callback, edit_callback); ); if (error != KErrNone) { Text2_destroy(o); return SPyErr_SetFromSymbianOSErr(error); } PyObject *pyfontname = Py_BuildValue("s", "dense"); TFontSpec fontspec; TFontSpec_from_python_fontspec(pyfontname, fontspec, *CEikonEnv::Static()->ScreenDevice()); o->control->SetFont(fontspec); Py_DECREF(pyfontname); o->ob_type = (struct _typeobject *) &Text2_type; return PyCObject_FromVoidPtr(o, (void (*)(void *)) Text2_destroy); } PyObject* Text2_clear(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClearL(); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_get_text(PyObject* /*self*/, PyObject *args) { PyObject *co, *r=NULL; int pos=0, count=-1; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O|ii", &co, &pos, &count)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ReadL(r, pos, count) ) if (error != KErrNone) return SPyErr_SetFromSymbianOSErr(error); return r; } PyObject* Text2_set_text(PyObject* /*self*/, PyObject *args) { PyObject *co; Py_UNICODE *ctext; int ctextlen; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Ou#", &co, &ctext, &ctextlen)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClearL(); o->control->WriteL(TPtrC((TUint16 *)ctext, ctextlen)); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_add_text(PyObject* /*self*/, PyObject *args) { PyObject *co; Py_UNICODE *ctext; int ctextlen, pos; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Ou#", &co, &ctext, &ctextlen)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, pos = o->control->WriteL(TPtrC((TUint16 *)ctext, ctextlen)); o->control->SetCursorPosL(pos, EFalse); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_insert_text(PyObject* /*self*/, PyObject *args) { PyObject *co; Py_UNICODE *ctext; int ctextlen, pos; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Oiu#", &co, &pos, &ctext, &ctextlen)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (pos < 0) pos = 0; TRAP(error, o->control->WriteL(TPtrC((TUint16 *)ctext, ctextlen), pos); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_delete_text(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos=0, count=-1; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O|ii", &co, &pos, &count)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->DelL(pos, count); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_apply(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos=0, count=-1; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O|ii", &co, &pos, &count)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ApplyFormatL(pos, count); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_text_length(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->Len()); } PyObject* Text2_set_pos(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos, select=0; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Oi|i", &co, &pos, &select)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; error = o->control->SetPos(pos, select); RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_get_pos(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->CursorPos()); } PyObject* Text2_set_focus(PyObject* /*self*/, PyObject *args) { PyObject *co; int focus; Text2_object *o; if (!PyArg_ParseTuple(args, "Oi", &co, &focus)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetFocus(focus ? ETrue : EFalse); RETURN_PYNONE; } PyObject* Text2_get_focus(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->IsFocused()); } PyObject* Text2_set_style(PyObject* /*self*/, PyObject *args) { PyObject *co; int style; Text2_object *o; // appuifw also allows None as style, this is done in Python here if (!PyArg_ParseTuple(args, "Oi", &co, &style)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetBold(style & KBOLD ? ETrue : EFalse); o->control->SetUnderline(style & KUNDERLINE ? ETrue : EFalse); o->control->SetPosture(style & KITALIC ? ETrue : EFalse); o->control->SetStrikethrough(style & KSTRIKETHROUGH ? ETrue : EFalse); if (style & HL_MASK) { switch (style & HL_MASK) { case KHIGHLIGHTNORMAL: o->control->SetHighlight(KHIGHLIGHTNORMAL); break; case KHIGHLIGHTROUNDED: o->control->SetHighlight(KHIGHLIGHTROUNDED); break; case KHIGHLIGHTSHADOW: o->control->SetHighlight(KHIGHLIGHTSHADOW); break; default: PyErr_SetString(PyExc_TypeError, "Expected a valid combination of flags for highlight style"); return NULL; } } else o->control->SetHighlight(KHIGHLIGHTNONE); if ( (style >= KNORMAL) && (style <= (KBOLD|KUNDERLINE|KITALIC|KSTRIKETHROUGH|HL_MASK)) ) o->control->SetStyle(style); else { PyErr_SetString(PyExc_TypeError, "Expected a valid combination of flags for text and highlight style"); return NULL; } if ( (style >= KNORMAL) && (style <= (KBOLD|KUNDERLINE|KITALIC|KSTRIKETHROUGH|HL_MASK)) ) o->control->SetStyle(style); else { PyErr_SetString(PyExc_TypeError, "Expected a valid combination of flags for text and highlight style"); return NULL; } RETURN_PYNONE; } PyObject* Text2_get_style(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->Style()); } PyObject* Text2_set_color(PyObject* /*self*/, PyObject *args) { PyObject *co, *color; Text2_object *o; TRgb rgb; if (!PyArg_ParseTuple(args, "OO", &co, &color)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (!ColorSpec_AsRgb(color, &rgb)) return NULL; o->control->SetTextColor(rgb); RETURN_PYNONE; } PyObject* Text2_get_color(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return ColorSpec_FromRgb(o->control->TextColor()); } PyObject* Text2_set_highlight_color(PyObject* /*self*/, PyObject *args) { PyObject *co, *color; Text2_object *o; TRgb rgb; if (!PyArg_ParseTuple(args, "OO", &co, &color)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (!ColorSpec_AsRgb(color, &rgb)) return NULL; o->control->SetHighlightColor(rgb); RETURN_PYNONE; } PyObject* Text2_get_highlight_color(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return ColorSpec_FromRgb(o->control->HighlightColor()); } PyObject* Text2_set_font(PyObject* /*self*/, PyObject *args) { PyObject *co, *font; Text2_object *o; TFontSpec fontspec; if (!PyArg_ParseTuple(args, "OO", &co, &font)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (TFontSpec_from_python_fontspec(font, fontspec, *CEikonEnv::Static()->ScreenDevice()) < 0) return NULL; o->control->SetFont(fontspec); RETURN_PYNONE; } PyObject* Text2_get_font(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return python_fontspec_from_TFontSpec(o->control->Font(), *CEikonEnv::Static()->ScreenDevice()); } PyObject* Text2_select_all(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->SelectAllL(); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_set_read_only(PyObject* /*self*/, PyObject *args) { PyObject *co; int read_only=1; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &read_only)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetReadOnly(read_only ? TRUE : FALSE); RETURN_PYNONE; } PyObject* Text2_get_read_only(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->IsReadOnly() ? 1: 0); } PyObject* Text2_get_selection(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("ii", o->control->Selection().iCursorPos, o->control->Selection().iAnchorPos); } PyObject* Text2_set_selection(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos, anchorpos; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Oii", &co, &pos, &anchorpos)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (anchorpos < 0) anchorpos = o->control->Len() - pos; if (pos < 0 || pos >= o->control->Len() || anchorpos < 0 || anchorpos >= o->control->Len()) return SPyErr_SetFromSymbianOSErr(KErrArgument); TRAP(error, o->control->SetSelectionL(pos, anchorpos); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_clear_selection(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClearSelectionL(); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_set_word_wrap(PyObject* /*self*/, PyObject *args) { PyObject *co; int word_wrap=1; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &word_wrap)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetAvkonWrap(word_wrap ? TRUE : FALSE); RETURN_PYNONE; } PyObject* Text2_set_limit(PyObject* /*self*/, PyObject *args) { PyObject *co; int limit=0; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O|i", &co, &limit)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->SetTextLimit(limit); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_undo(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->UndoL(); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_clear_undo(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClearUndo(); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_set_allow_undo(PyObject* /*self*/, PyObject *args) { PyObject *co; int allow=1; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O|i", &co, &allow)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->SetAllowUndo(allow ? TRUE : FALSE); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_get_allow_undo(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->SupportsUndo() ? 1: 0); } PyObject* Text2_can_undo(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->CanUndo() ? 1: 0); } PyObject* Text2_get_word_info(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos=-1, startpos, length; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &pos)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (pos < 0) pos = o->control->CursorPos(); o->control->GetWordInfo(pos, startpos, length); return Py_BuildValue("ii", startpos, length); } PyObject* Text2_set_case(PyObject* /*self*/, PyObject *args) { PyObject *co; int acase=EAknEditorTextCase; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &acase)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetAknEditorCurrentCase(acase); RETURN_PYNONE; } PyObject* Text2_set_allowed_cases(PyObject* /*self*/, PyObject *args) { PyObject *co; int cases=EAknEditorAllCaseModes; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &cases)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetAknEditorPermittedCaseModes(cases); RETURN_PYNONE; } PyObject* Text2_set_input_mode(PyObject* /*self*/, PyObject *args) { PyObject *co; int mode=EAknEditorTextInputMode; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &mode)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetAknEditorCurrentInputMode(mode); RETURN_PYNONE; } PyObject* Text2_set_allowed_input_modes(PyObject* /*self*/, PyObject *args) { PyObject *co; int modes=EAknEditorAllInputModes; Text2_object *o; if (!PyArg_ParseTuple(args, "O|i", &co, &modes)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetAknEditorAllowedInputModes(modes); RETURN_PYNONE; } PyObject* Text2_set_editor_flags(PyObject* /*self*/, PyObject *args) { PyObject *co; int flags; Text2_object *o; if (!PyArg_ParseTuple(args, "Oi", &co, &flags)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; o->control->SetAknEditorFlags(flags); RETURN_PYNONE; } PyObject* Text2_set_undo_buffer(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos=0, anchorpos=-1; Text2_object *o; TInt error; TBool r=EFalse; if (!PyArg_ParseTuple(args, "O|ii", &co, &pos, &anchorpos)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; if (anchorpos < 0) anchorpos = o->control->Len() - pos; if (pos < 0 || pos >= o->control->Len() || anchorpos < 0 || anchorpos >= o->control->Len()) return SPyErr_SetFromSymbianOSErr(KErrArgument); TRAP(error, r = o->control->SetUndoBufferL(TCursorSelection(pos, anchorpos)); ) if (error != KErrNone) return SPyErr_SetFromSymbianOSErr(error); return Py_BuildValue("i", r ? 1 : 0); } PyObject* Text2_can_cut(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->CcpuCanCut() ? 1 : 0); } PyObject* Text2_cut(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClipboardL(CEikEdwin::ECut); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_can_copy(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->CcpuCanCopy() ? 1: 0); } PyObject* Text2_copy(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClipboardL(CEikEdwin::ECopy); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_can_paste(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->CcpuCanPaste() ? 1: 0); } PyObject* Text2_paste(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->ClipboardL(CEikEdwin::EPaste); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_move(PyObject* /*self*/, PyObject *args) { PyObject *co; int movement, select=0; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Oi|i", &co, &movement, &select)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->MoveCursorL(TCursorPosition::TMovementType(movement), TBool(select)); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_move_display(PyObject* /*self*/, PyObject *args) { PyObject *co; int movement; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Oi", &co, &movement)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->MoveDisplayL(TCursorPosition::TMovementType(movement)); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_set_has_changed(PyObject* /*self*/, PyObject *args) { PyObject *co; int changed=1; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "O|i", &co, &changed)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->RichText()->SetHasChanged(TBool(changed)); ) RETURN_ERROR_OR_PYNONE(error); } PyObject* Text2_get_has_changed(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; return Py_BuildValue("i", o->control->RichText()->HasChanged() ? 1: 0); } PyObject* Text2_xy2pos(PyObject* /*self*/, PyObject *args) { PyObject *co; int x, y, pos=0; Text2_object *o; TInt error; TPoint p; if (!PyArg_ParseTuple(args, "O(ii)", &co, &x, &y)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; p = TPoint(x, y); TRAP(error, pos = o->control->TextView()->XyPosToDocPosL(p); ) if (error != KErrNone) return SPyErr_SetFromSymbianOSErr(error); return Py_BuildValue("i", pos); } PyObject* Text2_pos2xy(PyObject* /*self*/, PyObject *args) { PyObject *co; int pos; Text2_object *o; TInt error; TPoint p; TBool form=EFalse; if (!PyArg_ParseTuple(args, "Oi", &co, &pos)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, form = o->control->TextView()->DocPosToXyPosL(pos, p); ) if (error != KErrNone) return SPyErr_SetFromSymbianOSErr(error); if (!form) { PyErr_SetString(PyExc_ValueError, "position not formatted"); return NULL; } return Py_BuildValue("ii", p.iX, p.iY); } PyObject* Text2_get_indicator_text(PyObject* /*self*/, PyObject *args) { PyObject *co; Text2_object *o; if (!PyArg_ParseTuple(args, "O", &co)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; const TDesC &txt = o->control->IndicatorText(); return PyUnicode_FromUnicode(txt.Ptr(), txt.Length()); } PyObject* Text2_set_indicator_text(PyObject* /*self*/, PyObject *args) { PyObject *co; Py_UNICODE *ctext; int ctextlen; Text2_object *o; TInt error; if (!PyArg_ParseTuple(args, "Ou#", &co, &ctext, &ctextlen)) return NULL; if ((o = PyCObject_AsText2(co)) == NULL) return NULL; TRAP(error, o->control->SetIndicatorTextL(TPtrC((TUint16 *)ctext, ctextlen)); ) RETURN_ERROR_OR_PYNONE(error); }
[ "arkadiusz.wahlig@d722e5d8-1a54-0410-81c3-2588f0083ad8" ]
[ [ [ 1, 1736 ] ] ]
221aee6842ee408e09a7866510f246feb8176a88
282057a05d0cbf9a0fe87457229f966a2ecd3550
/EIBServer/include/UsersDB.h
8f4ff265303e9f2bcbb82314a1aabf53f2b0dde8
[]
no_license
radtek/eibsuite
0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd
4504fcf4fa8c7df529177b3460d469b5770abf7a
refs/heads/master
2021-05-29T08:34:08.764000
2011-12-06T20:42:06
2011-12-06T20:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,697
h
#ifndef __USERS_DATA_BASE_HEADER__ #define __USERS_DATA_BASE_HEADER__ #include "CString.h" #include <map> #include <fstream> #include "GenericDB.h" #include "EibNetwork.h" #include "LogFile.h" #include "PacketFilter.h" #define USER_POLICY_NONE 0x0 #define USER_POLICY_READ_ACCESS 0x1 #define USER_POLICY_WRITE_ACCESS 0x2 #define USER_POLICY_CONSOLE_ACCESS 0x4 #define USER_PASSWORD_PARAM_NAME "PASSWORD" #define USER_PRIVILIGES_PARAM_NAME "PRIVILIGES" //Allowed #define USER_ALLOWED_SOURCE_ADDRESS "ALLOWED_SOURCE_ADDRESS" #define USER_ALLOWED_SOURCE_MASK "ALLOWED_SOURCE_MASK" #define USER_ALLOWED_DEST_ADDRESS "ALLOWED_DEST_ADDRESS" #define USER_ALLOWED_DEST_MASK "ALLOWED_DEST_MASK" class CEIBServer; class CUsersDB; class CUser { public: CUser(); CUser(const CUser& user); virtual ~CUser(); bool IsReadPolicyAllowed() const; bool IsWritePolicyAllowed() const; bool IsConsoleAccessAllowed() const { return (_priviliges & USER_POLICY_CONSOLE_ACCESS ) != 0; } const CString& GetName() const; const CString& GetPassword() const; unsigned short GetSrcMask() const { return _filter.GetSrcMask(); } unsigned short GetDstMask() const { return _filter.GetDstMask(); } void Print() const; void SetName(const CString& name) { _name = name; } void SetPassword(const CString& password) { _password = password;} void SetPriviliges(int priviliges) { _priviliges = priviliges;} void SetAllowedSourceAddressMask(unsigned short mask) { _filter.SetAllowedSourceAddressMask(mask);} void SetAllowedDestAddressMask(unsigned short mask) { _filter.SetAllowedDestAddressMask(mask);} const CPacketFilter& GetFilter() const { return _filter;} friend class CUsersDB; private: void Reset(); private: CString _name; CString _password; unsigned int _priviliges; CPacketFilter _filter; }; class CUsersDB : public CGenericDB<CString,CUser> { public: CUsersDB(); virtual ~CUsersDB(); virtual void Init(const CString& file_name); virtual void Print() const; const map<CString,CUser>& GetUsersList() const { return _data;} bool Validate(); void InteractiveConf(); virtual void OnReadParamComplete(CUser& current_record, const CString& param,const CString& value); virtual void OnReadRecordComplete(CUser& current_record); virtual void OnReadRecordNameComplete(CUser& current_record, const CString& record_name); virtual void OnSaveRecordStarted(const CUser& record,CString& record_name, list<pair<CString,CString> >& param_values); private: bool AddOrUpdateUser(CUser& user); bool DeleteUser(const CString& file_name); bool UpdateUser(const CString& file_name); }; #endif
[ [ [ 1, 93 ] ] ]
e84d9f7b61f26b18a3d3913958bb9c78ac1a093b
6c8c4728e608a4badd88de181910a294be56953a
/Foundation/PlatformNix.h
fd2bede389b06e70e4b4f2f0205907ed9a3e875d
[ "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
1,619
h
// For conditions of distribution and use, see copyright notice in license.txt #ifndef incl_FoundationPlatformNix_h #define incl_FoundationPlatformNix_h #if !defined(_WINDOWS) #include <iostream> namespace Foundation { class Framework; //! Low-level *nix specific functionality /*! \ingroup Foundation_group */ class PlatformNix { public: //! default constructor explicit PlatformNix(Framework *framework) : framework_(framework) {} //! destructor virtual ~PlatformNix() {} static void Message(const std::string& title, const std::string& text) { std::cerr << title << " " << text; } static void Message(const std::wstring& title, const std::wstring& text) { std::wcerr << title << " " << text; } //! Returns user specific application data directory. /*! Returns non-unicode path. May throw Expection if folder is not found. */ std::string GetApplicationDataDirectory(); //! Returns user specific application data directory. /*! Returns unicode path. May throw Expection if folder is not found. */ std::wstring GetApplicationDataDirectoryW(); //! \copydoc Foundation::PlatformWin::GetUserDocumentsDirectory() std::string GetUserDocumentsDirectory(); //! \copydoc PlatformWin::GetUserDocumentsDirectoryW() std::wstring GetUserDocumentsDirectoryW(); private: Framework *framework_; }; } #endif #endif
[ "cmayhem@5b2332b8-efa3-11de-8684-7d64432d61a3", "jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3", "cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 6 ], [ 10, 20 ], [ 22, 35 ], [ 37, 40 ], [ 42, 60 ] ], [ [ 7, 9 ], [ 21, 21 ] ], [ [ 36, 36 ], [ 41, 41 ] ] ]
9e997470c2cf2e5183a38410c1cd8efabf4da19a
f177993b13e97f9fecfc0e751602153824dfef7e
/ImProSln/ARTagApp/TestCamera.h
c582d5829ff9837342bb7b36e1b56c4e96fd67c8
[]
no_license
svn2github/imtophooksln
7bd7412947d6368ce394810f479ebab1557ef356
bacd7f29002135806d0f5047ae47cbad4c03f90e
refs/heads/master
2020-05-20T04:00:56.564124
2010-09-24T09:10:51
2010-09-24T09:10:51
11,787,598
1
0
null
null
null
null
UTF-8
C++
false
false
1,132
h
#pragma once #include "camerads.h" #include "..\DXRender\IDXRenderer.h" #include "..\HomoWarpFilter\IHomoWarpFilter.h" #include "..\ArLayoutFilter\MyTestFilter\IARLayoutFilter.h" #include "..\TouchLibFilter\ITouchLibFilter.h" #include "..\AR2WarpController\IAR2WarpController.h" class TestCamera : public CCameraDS { protected: CComPtr<IBaseFilter> m_pDXRenderer; CComPtr<IPin> m_pDXRendererInputPin; CComPtr<IBaseFilter> m_pHomoWarpFilter; CComPtr<IPin> m_pHomoWarpInputPin; CComPtr<IPin> m_pHomoWarpOutD3DPin; CComPtr<IBaseFilter> m_pARLayoutFilter; CComPtr<IPin> m_pARLayoutInputConfigPin; CComPtr<IPin> m_pARLayoutOutputPin; CComPtr<IBaseFilter> m_pTouchLibFilter; CComPtr<IPin> m_pTouchLibInputPin; CComPtr<IPin> m_pTouchLibOutputPin; CComPtr<IPin> m_pTouchLibFGOutPin; CComPtr<IBaseFilter> m_pAR2WarpFilter; CComPtr<IPin> m_pAR2WarpInputTouchPin; CComPtr<IPin> m_pAR2WarpOutputARConfigPin; virtual HRESULT ConnectGraph(); virtual HRESULT CreateFilters(int nCamID, bool bDisplayProperties, int nWidth, int nHeight); public: TestCamera(void); ~TestCamera(void); };
[ "ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a" ]
[ [ [ 1, 37 ] ] ]
e349bc04d500ef8804e27520e8a0941d3ca2be27
067ff5708784b1fd2595957de78518e87073ccb4
/ImageViewer/ImageViewer/FTPSender.cpp
38d1f981ad213f58f45c74d12e9f91aedccbbcdd
[]
no_license
wolfmanu/opencvthesis
637a6a6ead5c839e731faca19ae0dd3e59e33cd3
c4e806d6369b4ed80ebadce1684e32f147eafce4
refs/heads/master
2016-09-05T22:38:07.528951
2010-09-10T12:01:49
2010-09-10T12:01:49
32,142,213
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
#include "StdAfx.h" #include "FTPSender.h" #define FTP_DEBUG string nl="\r\n";//\015\012 FTPSender::FTPSender(string serverName, string serverPort) :net(serverName, serverPort) { } FTPSender::~FTPSender(void) { } int FTPSender::FTPconnect(string user, string pwd) { string sUser= "USER "; string sPwd= "PASS "; string Msg; int iResult; if( net.NWConnect()==-1) { cout<<"FTP connection error"<<endl; return -1; } iResult = FTPrcvData(&Msg); //Receive Welcome Message if(iResult<=0) { cout<<"FTP connection error"<<endl; return -1; } //std::cout<<welcomeMsg; //Inviare nome e pw per la connessione ftp se richiesto /*if(user=="") return 1;*/ sUser.append(user); sUser.append(nl); FTPsendData(sUser); FTPrcvData(&Msg); if(Msg[0]=='4' || Msg[0]=='5') { cout<<"FTP usermane error"<<endl; return -2; } //230, meaning that the client has permission to access files under that username; //or with code 331 or 332, meaning that permission might be granted after a PASS requ if(Msg[0]=='2') return 1; //pw not needed /*if(pwd=="") return 1;*/ sPwd.append(pwd); sPwd.append(nl); FTPsendData(sPwd); FTPrcvData(&Msg); if(Msg[0]=='4' || Msg[0]=='5') { cout<<"FTP password error"<<endl; return -3; } return 1; } int FTPSender::FTPsendData(string data) { int iResult; string sdata(data.begin(),data.end()); sdata.append(nl); iResult = net.NWsendData(sdata.c_str(),sdata.length()); if (iResult == SOCKET_ERROR) { printf("[FTPSender]sendData - send failed: %d\n", WSAGetLastError()); net.~Network(); return 0; } return iResult; } int FTPSender::FTPrcvData(string* data) //bloccante { int iResult; char recvbuf[BUFLEN]; ZeroMemory( &recvbuf, sizeof(recvbuf) ); iResult = net.NWrcvData(recvbuf, BUFLEN); data->assign(recvbuf); return iResult; }
[ "thewolfmanu@8d742ff4-5afa-cc76-88a1-f39302f5df42" ]
[ [ [ 1, 97 ] ] ]
ab44d815cfc5388c034c250e0869dc7a9c8feed0
0c5fd443401312fafae18ea6a9d17bac9ee61474
/code/engine/EventSystem/Core/network/ClientChannel.h
ae05d584fc9bc3c0c061e3791bc016e9dc61eede
[]
no_license
nurF/Brute-Force-Game-Engine
fcfebc997d6ab487508a5706b849e9d7bc66792d
b930472429ec6d6f691230e36076cd2c868d853d
refs/heads/master
2021-01-18T09:29:44.038036
2011-12-02T17:31:59
2011-12-02T17:31:59
2,877,061
1
0
null
null
null
null
UTF-8
C++
false
false
2,052
h
/* ___ _________ ____ __ / _ )/ __/ ___/____/ __/___ ___ _/_/___ ___ / _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_) /____/_/ \___/ /___//_//_|_, /_//_//_|__/ /___/ This file is part of the Brute-Force Game Engine, BFG-Engine For the latest info, see http://www.brute-force-games.com Copyright (c) 2011 Brute-Force Games GbR The BFG-Engine 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. The BFG-Engine 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 the BFG-Engine. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __EVENT_CLIENT_CHANNEL_H_ #define __EVENT_CLIENT_CHANNEL_H_ #include <EventSystem/Core/network/NetworkChannel.h> #include <boost/enable_shared_from_this.hpp> namespace EventSystem { class ClientChannel : public NetworkChannel, public boost::enable_shared_from_this<ClientChannel> { public: typedef boost::shared_ptr<ClientChannel> Pointer; static Pointer create(boost::asio::io_service& io_service) { return Pointer(new ClientChannel(io_service)); } virtual ~ClientChannel(); void connect(boost::asio::ip::tcp::endpoint& ep); virtual void startHandShake(); private: ClientChannel(boost::asio::io_service& io_service); virtual void handleHandShakeResponse(const boost::system::error_code& error); virtual void handleReadHeader(const boost::system::error_code& error); virtual void handleReadData(const boost::system::error_code& error); }; } #endif //__EVENT_CLIENT_CHANNEL_H_
[ [ [ 1, 64 ] ] ]
15d35a94cacd6b4360ec21c2a2d3fcba4719798c
28e80ec171dfe5c73c93a98045a8d370d059f8c2
/src/RGBfixture.h
1cd6d01b09a86a58af96f75de7757971a9b18576
[]
no_license
GunioRobot/movieToeSign
db83909fdf8c750944be52a35ba1fdc9445f11a9
7dfc105f940445dc84f7f0c5015e046669b7f665
refs/heads/master
2020-12-24T14:09:54.648624
2011-12-13T16:38:35
2011-12-13T16:38:35
2,996,486
0
0
null
null
null
null
UTF-8
C++
false
false
537
h
#pragma once #include "ofMain.h" class RGBfixture { public: RGBfixture(); virtual ~RGBfixture(); //adding mouse events to a class http://www.slideshare.net/roxlu/openframeworks-007-events //void mousePressed(ofMouseEventArgs& args); void setRGB(unsigned char R, unsigned char G, unsigned char B); //void draw(float x, float y, float width, float height); protected: private: ofColor c; ofRectangle fixtureRect; bool bFixtureSet; };
[ [ [ 1, 26 ] ] ]
5b38e5754e589c43e167181d680feb8c5a5774af
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/numeric/ublas/bench4/bench4.cpp
24d752391d153b9aaa46859b71d159a1be287c70
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
8,834
cpp
// // 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. // #include <iostream> #include <string> #include <boost/numeric/interval.hpp> #include <boost/numeric/interval/io.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/timer.hpp> #include "bench4.hpp" void header (std::string text) { std::cout << text << std::endl; std::cerr << text << std::endl; } template<class T> struct peak_c_plus { typedef T value_type; void operator () (int runs) const { try { static T s (0); boost::timer t; for (int i = 0; i < runs; ++ i) { s += T (0); // sink_scalar (s); } footer<value_type> () (0, 1, runs, t.elapsed ()); } catch (std::exception &e) { std::cout << e.what () << std::endl; } catch (...) { std::cout << "unknown exception" << std::endl; } } }; template<class T> struct peak_c_multiplies { typedef T value_type; void operator () (int runs) const { try { static T s (1); boost::timer t; for (int i = 0; i < runs; ++ i) { s *= T (1); // sink_scalar (s); } footer<value_type> () (0, 1, runs, t.elapsed ()); } catch (std::exception &e) { std::cout << e.what () << std::endl; } catch (...) { std::cout << "unknown exception" << std::endl; } } }; template<class T> void peak<T>::operator () (int runs) { header ("peak"); header ("plus"); peak_c_plus<T> () (runs); header ("multiplies"); peak_c_multiplies<T> () (runs); } template struct peak<boost::numeric::interval<float> >; template struct peak<boost::numeric::interval<double> >; #ifdef USE_BOOST_COMPLEX template struct peak<boost::complex<boost::numeric::interval<float> > >; template struct peak<boost::complex<boost::numeric::interval<double> > >; #endif #ifdef BOOST_MSVC // Standard new handler is not standard compliant. #include <new.h> int __cdecl std_new_handler (unsigned) { throw std::bad_alloc (); } #endif int main (int argc, char *argv []) { #ifdef BOOST_MSVC _set_new_handler (std_new_handler); #endif #ifdef USE_FLOAT header ("boost::numeric::interval<float>"); peak<boost::numeric::interval<float> > () (100000000); #endif #ifdef USE_DOUBLE header ("boost::numeric::interval<double>"); peak<boost::numeric::interval<double> > () (100000000); #endif #ifdef USE_STD_COMPLEX #ifdef USE_FLOAT header ("std:complex<boost::numeric::interval<float> >"); peak<boost::complex<boost::numeric::interval<float> > > () (100000000); #endif #ifdef USE_DOUBLE header ("std:complex<boost::numeric::interval<double> >"); peak<boost::complex<boost::numeric::interval<double> > > () (100000000); #endif #endif int scale = 1; if (argc > 1) #ifndef BOOST_NO_STDC_NAMESPACE scale = std::atoi (argv [1]); #else scale = ::atoi (argv [1]); #endif #ifdef USE_FLOAT header ("boost::numeric::interval<float>, 3"); bench_1<boost::numeric::interval<float>, 3> () (1000000 * scale); bench_2<boost::numeric::interval<float>, 3> () (300000 * scale); bench_3<boost::numeric::interval<float>, 3> () (100000 * scale); header ("boost::numeric::interval<float>, 10"); bench_1<boost::numeric::interval<float>, 10> () (300000 * scale); bench_2<boost::numeric::interval<float>, 10> () (30000 * scale); bench_3<boost::numeric::interval<float>, 10> () (3000 * scale); header ("boost::numeric::interval<float>, 30"); bench_1<boost::numeric::interval<float>, 30> () (100000 * scale); bench_2<boost::numeric::interval<float>, 30> () (3000 * scale); bench_3<boost::numeric::interval<float>, 30> () (100 * scale); header ("boost::numeric::interval<float>, 100"); bench_1<boost::numeric::interval<float>, 100> () (30000 * scale); bench_2<boost::numeric::interval<float>, 100> () (300 * scale); bench_3<boost::numeric::interval<float>, 100> () (3 * scale); #endif #ifdef USE_DOUBLE header ("boost::numeric::interval<double>, 3"); bench_1<boost::numeric::interval<double>, 3> () (1000000 * scale); bench_2<boost::numeric::interval<double>, 3> () (300000 * scale); bench_3<boost::numeric::interval<double>, 3> () (100000 * scale); header ("boost::numeric::interval<double>, 10"); bench_1<boost::numeric::interval<double>, 10> () (300000 * scale); bench_2<boost::numeric::interval<double>, 10> () (30000 * scale); bench_3<boost::numeric::interval<double>, 10> () (3000 * scale); header ("boost::numeric::interval<double>, 30"); bench_1<boost::numeric::interval<double>, 30> () (100000 * scale); bench_2<boost::numeric::interval<double>, 30> () (3000 * scale); bench_3<boost::numeric::interval<double>, 30> () (100 * scale); header ("boost::numeric::interval<double>, 100"); bench_1<boost::numeric::interval<double>, 100> () (30000 * scale); bench_2<boost::numeric::interval<double>, 100> () (300 * scale); bench_3<boost::numeric::interval<double>, 100> () (3 * scale); #endif #ifdef USE_BOOST_COMPLEX #ifdef USE_FLOAT header ("boost::complex<boost::numeric::interval<float> >, 3"); bench_1<boost::complex<boost::numeric::interval<float> >, 3> () (1000000 * scale); bench_2<boost::complex<boost::numeric::interval<float> >, 3> () (300000 * scale); bench_3<boost::complex<boost::numeric::interval<float> >, 3> () (100000 * scale); header ("boost::complex<boost::numeric::interval<float> >, 10"); bench_1<boost::complex<boost::numeric::interval<float> >, 10> () (300000 * scale); bench_2<boost::complex<boost::numeric::interval<float> >, 10> () (30000 * scale); bench_3<boost::complex<boost::numeric::interval<float> >, 10> () (3000 * scale); header ("boost::complex<boost::numeric::interval<float> >, 30"); bench_1<boost::complex<boost::numeric::interval<float> >, 30> () (100000 * scale); bench_2<boost::complex<boost::numeric::interval<float> >, 30> () (3000 * scale); bench_3<boost::complex<boost::numeric::interval<float> >, 30> () (100 * scale); header ("boost::complex<boost::numeric::interval<float> >, 100"); bench_1<boost::complex<boost::numeric::interval<float> >, 100> () (30000 * scale); bench_2<boost::complex<boost::numeric::interval<float> >, 100> () (300 * scale); bench_3<boost::complex<boost::numeric::interval<float> >, 100> () (3 * scale); #endif #ifdef USE_DOUBLE header ("boost::complex<boost::numeric::interval<double> >, 3"); bench_1<boost::complex<boost::numeric::interval<double> >, 3> () (1000000 * scale); bench_2<boost::complex<boost::numeric::interval<double> >, 3> () (300000 * scale); bench_3<boost::complex<boost::numeric::interval<double> >, 3> () (100000 * scale); header ("boost::complex<boost::numeric::interval<double> >, 10"); bench_1<boost::complex<boost::numeric::interval<double> >, 10> () (300000 * scale); bench_2<boost::complex<boost::numeric::interval<double> >, 10> () (30000 * scale); bench_3<boost::complex<boost::numeric::interval<double> >, 10> () (3000 * scale); header ("boost::complex<boost::numeric::interval<double> >, 30"); bench_1<boost::complex<boost::numeric::interval<double> >, 30> () (100000 * scale); bench_2<boost::complex<boost::numeric::interval<double> >, 30> () (3000 * scale); bench_3<boost::complex<boost::numeric::interval<double> >, 30> () (100 * scale); header ("boost::complex<boost::numeric::interval<double> >, 100"); bench_1<boost::complex<boost::numeric::interval<double> >, 100> () (30000 * scale); bench_2<boost::complex<boost::numeric::interval<double> >, 100> () (300 * scale); bench_3<boost::complex<boost::numeric::interval<double> >, 100> () (3 * scale); #endif #endif return 0; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 252 ] ] ]
ee9907eaec614f19503354ceba6fc150dceea92d
1d5c2ff3350d099bf57049a3a66915d7ba91c39f
/CurrencyMainDialog.h
c3f063872190ab8feaef257bafc90585b3ff7069
[]
no_license
kjk/moriarty-sm
f73f9a4f5e1ac9bfa923fdcfd1fc7a308d5db057
75cfa46e60e75c6054549800270601448ab5b3b9
refs/heads/master
2021-01-20T06:20:11.762112
2005-10-17T15:39:11
2005-10-17T15:39:11
18,798
2
0
null
null
null
null
UTF-8
C++
false
false
1,176
h
#ifndef CURRENCY_MAIN_DIALOG_H__ #define CURRENCY_MAIN_DIALOG_H__ #include "ModuleDialog.h" #include <WindowsCE/Controls.hpp> class CurrencyMainDialog: public ModuleDialog { Widget label_; EditBox edit_; ListView list_; double amount_; double baseRate_; CurrencyMainDialog(); ~CurrencyMainDialog(); void createListColumns(); void createListItems(bool update = false); bool handleListItemChanged(NMLISTVIEW& lv); void updateAmountField(); void amountFieldChanged(); protected: bool handleInitDialog(HWND fw, long ip); long handleResize(UINT st, ushort w, ushort h); long handleCommand(ushort nc, ushort id, HWND sender); bool handleLookupFinished(Event& event, const LookupFinishedEventData* data); long handleNotify(int controlId, const NMHDR& header); bool handleContextMenu(WPARAM wParam, LPARAM lParam); LRESULT callback(UINT msg, WPARAM wParam, LPARAM lParam); long handleDestroy(); public: MODULE_DIALOG_CREATE_DECLARE(CurrencyMainDialog); }; #endif // CURRENCY_MAIN_DIALOG_H__
[ "andrzejc@9579cb1a-affb-0310-8771-bc50cd49e4fc" ]
[ [ [ 1, 49 ] ] ]
ddaf374d64e8831e4853d2230630b50d178687f7
fc4946d917dc2ea50798a03981b0274e403eb9b7
/gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10InfoQueue.h
f2d62abcd01d462998252148ddc45da42847a63d
[]
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
9,587
h
//Copyright (c) Microsoft Corporation. All rights reserved. #pragma once #include "DirectUnknown.h" namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace Direct3D10 { using namespace System; using namespace Microsoft::WindowsAPICodePack::DirectX; /// <summary> /// An information-queue interface stores, retrieves, and filters debug messages. The queue consists of a message queue, an optional storage filter stack, and a optional retrieval filter stack. /// <para>(Also see DirectX SDK: ID3D10InfoQueue)</para> /// </summary> public ref class InfoQueue : public DirectUnknown { public: /// <summary> /// Add a user-defined message to the message queue and send that message to debug output. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::AddApplicationMessage)</para> /// </summary> /// <param name="severity">Severity of a message (see <see cref="MessageSeverity"/>)<seealso cref="MessageSeverity"/>.</param> /// <param name="description">Message string.</param> void AddApplicationMessage(MessageSeverity severity, String^ description); /// <summary> /// Add a Direct3D 10 debug message to the message queue and send that message to debug output. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::AddMessage)</para> /// </summary> /// <param name="category">Category of a message (see <see cref="MessageCategory"/>)<seealso cref="MessageCategory"/>.</param> /// <param name="severity">Severity of a message (see <see cref="MessageSeverity"/>)<seealso cref="MessageSeverity"/>.</param> /// <param name="id">Unique identifier of a message (see <see cref="MessageId"/>)<seealso cref="MessageId"/>.</param> /// <param name="description">User-defined message.</param> void AddMessage(MessageCategory category, MessageSeverity severity, MessageId id, String^ description); /// <summary> /// Clear all messages from the message queue. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::ClearStoredMessages)</para> /// </summary> void ClearStoredMessages(); /// <summary> /// Get a message category to break on when a message with that category passes through the storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetBreakOnCategory)</para> /// </summary> /// <param name="category">Message category to break on (see <see cref="MessageCategory"/>)<seealso cref="MessageCategory"/>.</param> Boolean GetBreakOnCategory(MessageCategory category); /// <summary> /// Get a message identifier to break on when a message with that identifier passes through the storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetBreakOnID)</para> /// </summary> /// <param name="id">Message identifier to break on (see <see cref="MessageId"/>)<seealso cref="MessageId"/>.</param> Boolean GetBreakOnId(MessageId id); /// <summary> /// Get a message severity level to break on when a message with that severity level passes through the storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetBreakOnSeverity)</para> /// </summary> /// <param name="severity">Message severity level to break on (see <see cref="MessageSeverity"/>)<seealso cref="MessageSeverity"/>.</param> Boolean GetBreakOnSeverity(MessageSeverity severity); /// <summary> /// Get a message from the message queue. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetMessage)</para> /// </summary> /// <param name="messageIndex">Index into message queue after an optional retrieval filter has been applied. /// This can be between 0 and the number of messages in the message queue that pass through the retrieval filter (which can be obtained with GetNumStoredMessagesAllowedByRetrievalFilter(). /// 0 is the message at the front of the message queue.</param> /// <returns>Returned message (see <see cref="Message"/>)<seealso cref="Message"/>.</returns> Message GetMessage(UInt64 messageIndex); /// <summary> /// Try to get a message from the message queue. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetMessage)</para> /// </summary> /// <param name="messageIndex">Index into message queue after an optional retrieval filter has been applied. /// This can be between 0 and the number of messages in the message queue that pass through the retrieval filter /// (which can be obtained with NumStoredMessagesAllowedByRetrievalFilter property. /// Index 0 is the message at the front of the message queue. </param> /// <param name="message">Returned message (see <see cref="Message"/>)<seealso cref="Message"/>.</param> /// <returns>True if successful; false otherwise.</returns> Boolean TryGetMessage(UInt64 messageIndex, [System::Runtime::InteropServices::Out] Message % message); /// <summary> /// Get or set the maximum number of messages that can be added to the message queue. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetMessageCountLimit)</para> /// </summary> property UInt64 MessageCountLimit { UInt64 get(); void set(UInt64); } /// <summary> /// Get or set a boolean that turns the debug output on or off. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetMuteDebugOutput)</para> /// </summary> property Boolean MuteDebugOutput { Boolean get(); void set(Boolean); } /// <summary> /// Get the number of messages that were allowed to pass through a storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetNumMessagesAllowedByStorageFilter)</para> /// </summary> property UInt64 NumMessagesAllowedByStorageFilter { UInt64 get(); } /// <summary> /// Get the number of messages that were denied passage through a storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetNumMessagesDeniedByStorageFilter)</para> /// </summary> property UInt64 NumMessagesDeniedByStorageFilter { UInt64 get(); } /// <summary> /// Get the number of messages that were discarded due to the message count limit. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetNumMessagesDiscardedByMessageCountLimit)</para> /// </summary> property UInt64 NumMessagesDiscardedByMessageCountLimit { UInt64 get(); } /// <summary> /// Get the number of messages currently stored in the message queue. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetNumStoredMessages)</para> /// </summary> property UInt64 NumStoredMessages { UInt64 get(); } /// <summary> /// Get the number of messages that are able to pass through a retrieval filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::GetNumStoredMessagesAllowedByRetrievalFilter)</para> /// </summary> property UInt64 NumStoredMessagesAllowedByRetrievalFilter { UInt64 get(); } /// <summary> /// Set a message category to break on when a message with that category passes through the storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::SetBreakOnCategory)</para> /// </summary> /// <param name="category">Message category to break on (see <see cref="MessageCategory"/>)<seealso cref="MessageCategory"/>.</param> /// <param name="enable">Turns this breaking condition on or off (true for on, false for off).</param> void SetBreakOnCategory(MessageCategory category, Boolean enable); /// <summary> /// Set a message identifier to break on when a message with that identifier passes through the storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::SetBreakOnID)</para> /// </summary> /// <param name="id">Message identifier to break on (see <see cref="MessageId"/>)<seealso cref="MessageId"/>.</param> /// <param name="enable">Turns this breaking condition on or off (true for on, false for off).</param> void SetBreakOnId(MessageId id, Boolean enable); /// <summary> /// Set a message severity level to break on when a message with that severity level passes through the storage filter. /// <para>(Also see DirectX SDK: ID3D10InfoQueue::SetBreakOnSeverity)</para> /// </summary> /// <param name="severity">Message severity level to break on (see <see cref="MessageSeverity"/>)<seealso cref="MessageSeverity"/>.</param> /// <param name="enable">Turns this breaking condition on or off (true for on, false for off).</param> void SetBreakOnSeverity(MessageSeverity severity, Boolean enable); internal: InfoQueue() { } InfoQueue(ID3D10InfoQueue* pNativeID3D10InfoQueue) : DirectUnknown(pNativeID3D10InfoQueue) { } }; } } } }
[ "lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5" ]
[ [ [ 1, 184 ] ] ]
01bd1b970384b246bfe5a5e4136b8bd8ea0956a0
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/drm/drm_helper_api/src/BCTestDRMHelperLibBlocks.cpp
a13aa0b8f316068f767cb7a9362dc551339e961b
[]
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
46,695
cpp
/* * Copyright (c) 2002 - 2007 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: ?Description * */ // [INCLUDE FILES] - do not remove #include <e32svr.h> #include <StifParser.h> #include <Stiftestinterface.h> #include "BCTestDRMHelperLib.h" #include <DRMHelper.h> #include <COEMAIN.H> _LIT(KAppName, "BCAppDRMHelperLib"); _LIT( KVideoInterval, "c:\\data\\others\\video_interval1h.dcf" ); _LIT( KValidFile, "c:\\data\\others\\sd_S60FBT_005.dcf" ); _LIT( KImageInterval, "c:\\data\\others\\sd_water003.dcf" ); _LIT( KImageStartEnd, "c:\\data\\others\\sd_S60FBT_015.dcf" ); _LIT( KSilentFile, "c:\\data\\others\\129-allthatshewants.odf" ); const TInt KROsInDB = 3; const TInt KDRMHelperTestLibraryContentUriMaxLen = 256; // EXTERNAL DATA STRUCTURES //extern ?external_data; // EXTERNAL FUNCTION PROTOTYPES //extern ?external_function( ?arg_type,?arg_type ); // CONSTANTS //const ?type ?constant_var = ?constant; // MACROS //#define ?macro ?macro_def // LOCAL CONSTANTS AND MACROS //const ?type ?constant_var = ?constant; //#define ?macro_name ?macro_def // MODULE DATA STRUCTURES //enum ?declaration //typedef ?declaration // LOCAL FUNCTION PROTOTYPES //?type ?function_name( ?arg_type, ?arg_type ); // FORWARD DECLARATIONS //class ?FORWARD_CLASSNAME; // ============================= LOCAL FUNCTIONS =============================== // ----------------------------------------------------------------------------- // ?function_name ?description. // ?description // Returns: ?value_1: ?description // ?value_n: ?description_line1 // ?description_line2 // ----------------------------------------------------------------------------- // /* ?type ?function_name( ?arg_type arg, // ?description ?arg_type arg) // ?description { ?code // ?comment // ?comment ?code } */ // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CBCTestDRMHelperLib::Delete // Delete here all resources allocated and opened from test methods. // Called from destructor. // ----------------------------------------------------------------------------- // void CBCTestDRMHelperLib::Delete() { } // ----------------------------------------------------------------------------- // CBCTestDRMHelperLib::RunMethodL // Run specified method. Contains also table of test mothods and their names. // ----------------------------------------------------------------------------- // TInt CBCTestDRMHelperLib::RunMethodL( CStifItemParser& aItem ) { TStifFunctionInfo const KFunctions[] = { // Copy this line for every implemented function. // First string is the function name used in TestScripter script file. // Second is the actual implementation member function. ENTRY( "LaunchRightsManagerUI", CBCTestDRMHelperLib::LaunchRightsManagerUIL ), ENTRY( "LaunchRightsManagerUIContentUri", CBCTestDRMHelperLib::LaunchRightsManagerUIContentUriL ), ENTRY( "LaunchRightsManagerUIFileHandle", CBCTestDRMHelperLib::LaunchRightsManagerUIFileHandleL ), ENTRY( "HandleErrorExpiredFile", CBCTestDRMHelperLib::HandleErrorExpiredFileL), ENTRY( "HandleErrorNoRightsUri", CBCTestDRMHelperLib::HandleErrorNoRightsUriL), ENTRY( "HandleErrorNoRightsFileHandle", CBCTestDRMHelperLib::HandleErrorNoRightsFileHandleL), ENTRY( "CheckRightsAmountFile", CBCTestDRMHelperLib::CheckRightsAmountFileL), ENTRY( "CheckRightsAmountFileHandle", CBCTestDRMHelperLib::CheckRightsAmountFileHandleL), ENTRY( "CheckRightsAmountUri", CBCTestDRMHelperLib::CheckRightsAmountUriL), ENTRY( "CheckRightsPercentFile", CBCTestDRMHelperLib::CheckRightsPercentFileL), ENTRY( "CheckRightsPercentFileHandle", CBCTestDRMHelperLib::CheckRightsPercentFileHandleL), ENTRY( "GetRightsDetailsFile", CBCTestDRMHelperLib::GetRightsDetailsFileL), ENTRY( "GetRightsDetailsFileHandle", CBCTestDRMHelperLib::GetRightsDetailsFileHandleL), ENTRY( "SetAutomatedFile", CBCTestDRMHelperLib::SetAutomatedFileL), ENTRY( "SetAutomatedUri", CBCTestDRMHelperLib::SetAutomatedUriL), ENTRY( "SetAutomatedFileHandle", CBCTestDRMHelperLib::SetAutomatedFileHandleL), ENTRY( "ShowAutomatedNoteFile", CBCTestDRMHelperLib::ShowAutomatedNoteFileL), ENTRY( "ShowAutomatedNoteUri", CBCTestDRMHelperLib::ShowAutomatedNoteUriL), ENTRY( "ShowAutomatedNoteFileHandle", CBCTestDRMHelperLib::ShowAutomatedNoteFileHandleL), ENTRY( "SetAutomatedPassiveFile", CBCTestDRMHelperLib::SetAutomatedPassiveFileL), ENTRY( "SetAutomatedPassiveUri", CBCTestDRMHelperLib::SetAutomatedPassiveUriL), ENTRY( "SetAutomatedPassiveFileHandle", CBCTestDRMHelperLib::SetAutomatedPassiveFileHandleL), ENTRY( "SetAutomatedSilentFile", CBCTestDRMHelperLib::SetAutomatedSilentFileL), ENTRY( "SetAutomatedSilentUri", CBCTestDRMHelperLib::SetAutomatedSilentUriL), ENTRY( "SetAutomatedSilentFileHandle", CBCTestDRMHelperLib::SetAutomatedSilentFileHandleL), ENTRY( "RemoveAutomatedFile", CBCTestDRMHelperLib::RemoveAutomatedFileL), ENTRY( "RemoveAutomatedUri", CBCTestDRMHelperLib::RemoveAutomatedUriL), ENTRY( "RemoveAutomatedFileHandle", CBCTestDRMHelperLib::RemoveAutomatedFileHandleL), ENTRY( "RemoveAutomatedPassiveFile", CBCTestDRMHelperLib::RemoveAutomatedPassiveFileL), ENTRY( "RemoveAutomatedPassiveUri", CBCTestDRMHelperLib::RemoveAutomatedPassiveUriL), ENTRY( "RemoveAutomatedPassiveFileHandle", CBCTestDRMHelperLib::RemoveAutomatedPassiveFileHandleL), ENTRY( "CanSetAutomatedFile", CBCTestDRMHelperLib::CanSetAutomatedFileL), ENTRY( "CanSetAutomatedUri", CBCTestDRMHelperLib::CanSetAutomatedUriL), ENTRY( "CanSetAutomatedFileHandle", CBCTestDRMHelperLib::CanSetAutomatedFileHandleL), ENTRY( "IndicateIdle", CBCTestDRMHelperLib::IndicateIdleL), ENTRY( "SetCountLimit", CBCTestDRMHelperLib::SetCountLimit1L), ENTRY( "SetTimeLimit", CBCTestDRMHelperLib::SetTimeLimit1L), ENTRY( "SetPercentageLimit", CBCTestDRMHelperLib::SetPercentageLimit1L), ENTRY( "GetContentUriList", CBCTestDRMHelperLib::GetContentUriListL), ENTRY( "DataTypesCount", CBCTestDRMHelperLib::DataTypesCountL), ENTRY( "SupportedDataType", CBCTestDRMHelperLib::SupportedDataTypeL), ENTRY( "RegisterDataType", CBCTestDRMHelperLib::RegisterDataTypeL), ENTRY( "UnregisterDataType", CBCTestDRMHelperLib::UnregisterDataTypeL), ENTRY( "SupportedDrmMethods", CBCTestDRMHelperLib::SupportedDrmMethodsL), ENTRY( "ConsumeUri", CBCTestDRMHelperLib::ConsumeUriL), ENTRY( "ConsumeFile", CBCTestDRMHelperLib::ConsumeFileL), ENTRY( "ConsumeFileHandle", CBCTestDRMHelperLib::ConsumeFileHandleL), ENTRY( "ActivateContentFile", CBCTestDRMHelperLib::ActivateContentFileL), ENTRY( "ActivateContentData", CBCTestDRMHelperLib::ActivateContentDataL), ENTRY( "HasPreviewFile", CBCTestDRMHelperLib::HasPreviewFileL), ENTRY( "HasPreviewData", CBCTestDRMHelperLib::HasPreviewDataL), ENTRY( "GetPreviewRightsFile", CBCTestDRMHelperLib::GetPreviewRightsFileL), ENTRY( "GetPreviewRightsData", CBCTestDRMHelperLib::GetPreviewRightsDataL), ENTRY( "EmbeddedPreviewCompletedFile", CBCTestDRMHelperLib::EmbeddedPreviewCompletedFileL), ENTRY( "EmbeddedPreviewCompletedData", CBCTestDRMHelperLib::EmbeddedPreviewCompletedDataL), ENTRY( "HasInfoUrlFile", CBCTestDRMHelperLib::HasInfoUrlFileL), ENTRY( "HasInfoUrlData", CBCTestDRMHelperLib::HasInfoUrlDataL), ENTRY( "OpenInfoUrlFile", CBCTestDRMHelperLib::OpenInfoUrlFileL), ENTRY( "OpenInfoUrlData", CBCTestDRMHelperLib::OpenInfoUrlDataL), ENTRY( "SetPreviewMediaType", CBCTestDRMHelperLib::SetPreviewMediaTypeL), ENTRY( "HandleErrorOrPreviewFile", CBCTestDRMHelperLib::HandleErrorOrPreviewFileL), ENTRY( "HandleErrorOrPreviewFileHandle", CBCTestDRMHelperLib::HandleErrorOrPreviewFileHandleL), ENTRY( "HandleErrorOrPreviewSilentFile", CBCTestDRMHelperLib::HandleErrorOrPreviewSilentFileL), ENTRY( "HandleErrorOrPreviewSilentFileHandle", CBCTestDRMHelperLib::HandleErrorOrPreviewSilentFileHandleL), // [test cases entries] - Do not remove }; const TInt count = sizeof( KFunctions ) / sizeof( TStifFunctionInfo ); return RunInternalL( KFunctions, count, aItem ); } // ----------------------------------------------------------------------------- // CBCTestDRMHelperLib::ExampleL // Example test method function. // (other items were commented in a header). // ----------------------------------------------------------------------------- // TInt CBCTestDRMHelperLib::ExampleL( CStifItemParser& aItem ) { // Print to UI _LIT( KBCTestDRMHelperLib, "BCTestDRMHelperLib" ); _LIT( KExample, "In Example" ); TestModuleIf().Printf( 0, KBCTestDRMHelperLib, KExample ); // Print to log file iLog->Log( KExample ); TInt i = 0; TPtrC string; _LIT( KParam, "Param[%i]: %S" ); while ( aItem.GetNextString ( string ) == KErrNone ) { TestModuleIf().Printf( i, KBCTestDRMHelperLib, KParam, i, &string ); i++; } return KErrNone; } //member functions // --------------------------------------------------------- // CBCTestDRMHelperLib::ContentUriLC // // (other items were commented in a header). // --------------------------------------------------------- // HBufC* CBCTestDRMHelperLib::ContentUriLC( const TDesC& aFileName ) { HBufC* contentUri = HBufC::NewLC( KDRMHelperTestLibraryContentUriMaxLen ); TVirtualPathPtr virtualPath( aFileName, KDefaultContentObject ); ContentAccess::CData* data = ContentAccess::CData::NewLC( virtualPath, EPeek, EContentShareReadWrite ); TPtr ptr = contentUri->Des(); User::LeaveIfError( data->GetStringAttribute( EContentID, ptr ) ); CleanupStack::PopAndDestroy( data ); return contentUri; } // --------------------------------------------------------- // CBCTestDRMHelperLib::ConvertTo8BitLC // // (other items were commented in a header). // --------------------------------------------------------- // HBufC8* CBCTestDRMHelperLib::ConvertTo8BitLC( HBufC* aBuffer ) { HBufC8* buffer8 = HBufC8::NewLC( aBuffer->Length() ); buffer8->Des().Copy( *aBuffer ); return buffer8; } // --------------------------------------------------------- // CBCTestDRMHelperLib::OpenFileL // // (other items were commented in a header). // --------------------------------------------------------- // void CBCTestDRMHelperLib::OpenFileL( const TDesC& aFileName, RFile& aFile ) { TInt r = KErrNone; r = aFile.Open(iFs, aFileName, EFileRead | EFileShareReadersOrWriters); if (r == KErrInUse) { r = aFile.Open(iFs, aFileName, EFileRead | EFileShareAny); if (r == KErrInUse) { r = aFile.Open(iFs, aFileName, EFileRead | EFileShareReadersOnly); } } User::LeaveIfError( r ); } // --------------------------------------------------------- // CBCTestDRMHelperLib::CreateContentObjectLC // // (other items were commented in a header). // --------------------------------------------------------- // ContentAccess::CData* CBCTestDRMHelperLib::CreateContentObjectLC( const TDesC& aFileName ) { TVirtualPathPtr virtualPath( aFileName ); ContentAccess::CData* content = NULL; TRAPD( r, content = ContentAccess::CData::NewL( virtualPath, EPeek, EContentShareReadWrite ) ); if ( r == KErrInUse ) { content = ContentAccess::CData::NewL( virtualPath, EPeek, EContentShareReadOnly ); } else { User::LeaveIfError( r ); } CleanupStack::PushL( content ); return content; } // --------------------------------------------------------- // CBCTestDRMHelperLib::CheckPermissionL // // (other items were commented in a header). // --------------------------------------------------------- // void CBCTestDRMHelperLib::CheckPermissionL( CDRMHelperRightsConstraints* aConstraint ) { TInt err( KErrNone ); TUint32 counter(0); TUint32 originalCounter(0); TTime time; TTimeIntervalSeconds interval; TTimeIntervalSeconds timer; if ( aConstraint->FullRights() ) { iLog->Log( _L( "Full rights!")); } if ( aConstraint->IsPreview() ) { iLog->Log( _L( "Preview rights!!")); } TRAP( err, aConstraint->GetCountersL( counter, originalCounter ) ); if ( err != KErrNotFound ) { iLog->Log( _L( "GetCountersL leaved with: %d "),err); } err = KErrNone; TRAP( err, aConstraint->GetStartTimeL( time ) ); if ( err != KErrNotFound ) { iLog->Log( _L( "GetStartTimeL leaved with: %d "),err); } err = KErrNone; TRAP( err, aConstraint->GetEndTimeL( time ) ); if ( err != KErrNotFound ) { iLog->Log( _L( "GetEndTimeL leaved with: %d "),err); } err = KErrNone; TRAP( err, aConstraint->GetIntervalL( interval ) ); if ( err ) { iLog->Log( _L( "GetIntervalL leaved with: %d "),err); } err = KErrNone; TRAP( err, aConstraint->GetIntervalStartL( time ) ); if ( err != KErrNotFound ) { iLog->Log( _L( "GetIntervalStartL leaved with: %d "),err); } err = KErrNone; TRAP( err, aConstraint->GetTimedCountL( counter, originalCounter, timer ) ); if ( err != KErrNotFound ) { iLog->Log( _L( "GetTimedCountL leaved with: %d "),err); } err = KErrNone; TRAP( err, aConstraint->GetAccumulatedTimeL( interval ) ); if ( err != KErrNotFound ) { iLog->Log( _L( "GetAccumulatedTimeL leaved with: %d "),err); } err = KErrNone; } //test cases TInt CBCTestDRMHelperLib::LaunchRightsManagerUIL() { SetupL(); TRAPD(res,iHelper->LaunchDetailsViewEmbeddedL( KVideoInterval )); Teardown(); return res; } TInt CBCTestDRMHelperLib::LaunchRightsManagerUIContentUriL() { SetupL(); contentUri = ContentUriLC( KVideoInterval ); contentUri8 = ConvertTo8BitLC( contentUri ); iHelper->LaunchDetailsViewEmbeddedL( contentUri8 ); CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::LaunchRightsManagerUIFileHandleL() { SetupL(); OpenFileL( KVideoInterval, file ); CleanupClosePushL( file ); iHelper->LaunchDetailsViewEmbeddedL( file ); CleanupStack::PopAndDestroy(); // close file Teardown(); return retval; } TInt CBCTestDRMHelperLib::HandleErrorExpiredFileL() { SetupL(); TInt retval = iHelper->HandleErrorL( KErrCANoPermission, KValidFile ); if ( retval ) { iLog->Log( _L( "HandleErrorL returned: &d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::HandleErrorNoRightsUriL() { SetupL(); contentUri = ContentUriLC( KValidFile ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->HandleErrorL( KErrCANoRights, *contentUri8 ); CleanupStack::PopAndDestroy( 2, contentUri ); if ( retval ) { iLog->Log( _L( "HandleErrorL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::HandleErrorNoRightsFileHandleL() { SetupL(); OpenFileL( KValidFile, file ); CleanupClosePushL( file ); TInt retval = iHelper->HandleErrorL( KErrCANoRights, file ); CleanupStack::PopAndDestroy(); // close file if ( retval ) { iLog->Log( _L( "HandleErrorL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::CheckRightsAmountFileL () { SetupL(); TInt retval = iHelper->CheckRightsAmountL( KVideoInterval, 0, 0 ); if ( retval ) { iLog->Log( _L( "CheckRightsAmountL returned: %d" ), retval ); User::Leave( retval ); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::CheckRightsAmountFileHandleL() { SetupL(); OpenFileL( KVideoInterval, file ); CleanupClosePushL( file ); TInt retval = iHelper->CheckRightsAmountL( file, 0, 0 ); CleanupStack::PopAndDestroy(); // close file if ( retval ) { iLog->Log( _L( "CheckRightsAmountL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::CheckRightsAmountUriL() { SetupL(); contentUri = ContentUriLC( KVideoInterval ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->CheckRightsAmountL( *contentUri8, 0, 0 ); CleanupStack::PopAndDestroy( 2, contentUri ); if ( retval ) { iLog->Log( _L( "CheckRightsAmountL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::CheckRightsPercentFileL() { SetupL(); TInt retval = iHelper->CheckRightsPercentL( KVideoInterval, 100 ); if ( retval ) { iLog->Log( _L( "CheckRightsPercentL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::CheckRightsPercentFileHandleL() { SetupL(); OpenFileL( KVideoInterval, file ); CleanupClosePushL( file ); TInt retval = iHelper->CheckRightsPercentL( file, 100 ); CleanupStack::PopAndDestroy(); // close file if ( retval ) { iLog->Log( _L( "CheckRightsPercentL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::GetRightsDetailsFileL() { SetupL(); iHelper->GetRightsDetailsL( KImageInterval, 0, expired, sendingAllowed, play, display, execute, print ); if ( expired ) { iLog->Log( _L8( "GetRightsDetailsFileL : Expired!" ) ); User::Leave(KErrGeneral); } if ( !sendingAllowed ) { iLog->Log( _L8( "GetRightsDetailsFileL : Sending not allowed!" ) ); User::Leave(KErrGeneral); } if ( play ) { iLog->Log( _L8( "GetRightsDetailsFileL : play permission found!" ) ); User::Leave(KErrGeneral); } if ( execute ) { iLog->Log( _L8( "GetRightsDetailsFileL : execute permission found!" ) ); User::Leave(KErrGeneral); } if ( display ) { CheckPermissionL( display ); delete display; } else { iLog->Log( _L8( "GetRightsDetailsFileL : display permission not found!" ) ); User::Leave(KErrGeneral); } if ( print ) { CheckPermissionL( print ); delete print; } else { iLog->Log( _L8( "GetRightsDetailsFileL : print permission not found!" ) ); User::Leave(KErrGeneral); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::GetRightsDetailsFileHandleL() { SetupL(); OpenFileL( KImageInterval, file ); CleanupClosePushL( file ); iHelper->GetRightsDetailsL( file, 0, expired, sendingAllowed, play, display, execute, print ); CleanupStack::PopAndDestroy(); // close file if ( expired ) { iLog->Log( _L8( "GetRightsDetailsFileHandleL : Expired!" ) ); User::Leave(KErrGeneral); } if ( !sendingAllowed ) { iLog->Log( _L8( "GetRightsDetailsFileHandleL : Sending not allowed!" ) ); User::Leave(KErrGeneral); } if ( play ) { iLog->Log( _L8( "GetRightsDetailsFileHandleL : play permission found!" ) ); User::Leave(KErrGeneral); } if ( execute ) { iLog->Log( _L8( "GetRightsDetailsFileHandleL : execute permission found!" ) ); User::Leave(KErrGeneral); } if ( display ) { CheckPermissionL( display ); delete display; } else { iLog->Log( _L8( "GetRightsDetailsFileHandleL : display permission not found!" ) ); User::Leave(KErrGeneral); } if ( print ) { CheckPermissionL( print ); delete print; } else { iLog->Log( _L8( "GetRightsDetailsFileHandleL : print permission not found!" ) ); User::Leave(KErrGeneral); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::SetAutomatedFileL() { SetupL(); TInt retval = iHelper->SetAutomated( KImageStartEnd ); if ( retval ) { iLog->Log( _L( "SetAutomated returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->SetAutomated( *contentUri8 ); if ( retval ) { iLog->Log( _L( "SetAutomated returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->SetAutomated( file ); if ( retval ) { iLog->Log( _L( "SetAutomated returned: %d" ), retval ); User::Leave(retval); } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::ShowAutomatedNoteFileL() { SetupL(); TInt retval = iHelper->ShowAutomatedNote( KImageStartEnd ); if ( retval != KErrCancel ) { iLog->Log( _L( "ShowAutomatedNote returned: %d" ), retval ); User::Leave(retval); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::ShowAutomatedNoteUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->ShowAutomatedNote( *contentUri8 ); if ( retval != KErrCancel ) { iLog->Log( _L( "ShowAutomatedNote returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::ShowAutomatedNoteFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->ShowAutomatedNote( file ); if ( retval != KErrCancel ) { iLog->Log( _L( "ShowAutomatedNote returned: %d" ), retval ); User::Leave(retval); } file.Close(); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::SetAutomatedPassiveFileL() { SetupL(); TInt retval = iHelper->SetAutomatedPassive( KImageStartEnd ); if ( retval ) { iLog->Log( _L( "SetAutomatedPassive returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedPassiveUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->SetAutomatedPassive( *contentUri8 ); if ( retval ) { iLog->Log( _L( "SetAutomatedPassive returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedPassiveFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->SetAutomatedPassive( file ); if ( retval ) { iLog->Log( _L( "SetAutomatedPassive returned: %d" ), retval ); User::Leave(retval); } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedSilentFileL() { SetupL(); TInt retval = iHelper->SetAutomatedSilent( KImageStartEnd, ETrue ); if ( retval ) { iLog->Log( _L( "SetAutomatedSilent returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedSilentUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->SetAutomatedSilent( *contentUri8, ETrue ); if ( retval ) { iLog->Log( _L( "SetAutomatedSilent returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetAutomatedSilentFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->SetAutomatedSilent( file, ETrue ); if ( retval ) { iLog->Log( _L( "SetAutomatedSilent returned: %d" ), retval ); User::Leave(retval); } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::RemoveAutomatedFileL() { SetupL(); TInt retval = iHelper->RemoveAutomated( KImageStartEnd ); if ( retval ) { iLog->Log( _L( "RemoveAutomated returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::RemoveAutomatedUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->RemoveAutomated( *contentUri8 ); if ( retval ) { iLog->Log( _L( "RemoveAutomated returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::RemoveAutomatedFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->RemoveAutomated( file ); if ( retval ) { iLog->Log( _L( "RemoveAutomated returned: %d" ), retval ); User::Leave(retval); } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::RemoveAutomatedPassiveFileL() { SetupL(); TInt retval = iHelper->RemoveAutomatedPassive( KImageStartEnd ); if ( retval ) { iLog->Log( _L( "RemoveAutomatedpassive returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::RemoveAutomatedPassiveUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->RemoveAutomatedPassive( *contentUri8 ); if ( retval ) { iLog->Log( _L( "RemoveAutomatedpassive returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::RemoveAutomatedPassiveFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->RemoveAutomatedPassive( file ); if ( retval ) { iLog->Log( _L( "RemoveAutomatedpassive returned: %d" ), retval ); User::Leave(retval); } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::CanSetAutomatedFileL() { SetupL(); TInt retval = iHelper->CanSetAutomated( KImageStartEnd, automatedUseAllowed ); if ( retval ) { iLog->Log( _L( "CanSetAutomated returned: %d" ), retval ); User::Leave(retval); } if ( !automatedUseAllowed ) { iLog->Log( _L( "CanSetAutomated returned: !automatedUseAllowed %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::CanSetAutomatedUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->CanSetAutomated( *contentUri8, automatedUseAllowed ); if ( retval ) { iLog->Log( _L( "CanSetAutomated returned: %d" ), retval ); User::Leave(retval); } if ( !automatedUseAllowed ) { iLog->Log( _L8( "CanSetAutomatedUriL : Automated use not allowed!" ) ); User::Leave(retval); } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::CanSetAutomatedFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->CanSetAutomated( file, automatedUseAllowed ); if ( retval ) { iLog->Log( _L( "CanSetAutomated returned: " ), retval ); User::Leave(retval); } if ( !automatedUseAllowed ) { iLog->Log(_L("CanSetAutomated : automated use allowed failed")); User::Leave( retval ); } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::IndicateIdleL() { SetupL(); TRAPD(retval,iHelper->IndicateIdle()); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetCountLimit1L () { SetupL(); TRAPD(retval,iHelper->SetCountLimitL( 3 )); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetTimeLimit1L() { SetupL(); TRAPD(retval,iHelper->SetTimeLimitL( 7 )); Teardown(); return retval; } TInt CBCTestDRMHelperLib::SetPercentageLimit1L() { SetupL(); TRAPD(retval,iHelper->SetPercentageLimitL( 10 )); Teardown(); return retval; } TInt CBCTestDRMHelperLib::GetContentUriListL() { SetupL(); TInt retval = iHelper->GetContentURIList( uriList ); if ( retval ) { iLog->Log( _L( "GetContentURIList returned: %d" ), retval ); User::Leave(retval); } if ( uriList ) { if ( uriList->Count() != KROsInDB ) { iLog->Log( _L( "GetContentURIList returned number of ROs in DB: %d" ), uriList->Count() ); User::Leave(KErrGeneral); } uriList->ResetAndDestroy(); delete uriList; } Teardown(); return retval; } TInt CBCTestDRMHelperLib::DataTypesCountL() { SetupL(); TInt retval = iHelper->DataTypesCount( supportedDataTypes ); if ( retval ) { iLog->Log( _L8( "DataTypesCount returned: " ), retval ); User::Leave(KErrGeneral); } else if ( !supportedDataTypes ) { iLog->Log( _L8( "DataTypesCount: No data types found" ) ); User::Leave(KErrGeneral); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::SupportedDataTypeL() { SetupL(); TInt retval = iHelper->DataTypesCount( supportedDataTypes ); if ( !retval && supportedDataTypes ) { retval = iHelper->SupportedDataType( supportedDataTypes - 1, dataType ); if ( retval ) { iLog->Log( _L( "SupportedDataType returned: %d" ), retval ); User::Leave(retval); } } else { iLog->Log( _L( "SupportedDataType: getting amount of datatypes failed" ) ); User::Leave(KErrGeneral); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::RegisterDataTypeL() { SetupL(); TInt retval = iHelper->RegisterDataType( dataType ); if ( retval == KErrNone ) { iLog->Log( _L( "RegisterDataType returned: %d" ), retval ); User::Leave( retval ); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::UnregisterDataTypeL() { SetupL(); TInt retval = iHelper->UnRegisterDataType( 0 ); if ( retval == KErrNone ) { iLog->Log( _L( "UnRegisterDataType returned: %d" ), retval ); User::Leave( retval ); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::SupportedDrmMethodsL() { SetupL(); CDRMHelper::TDRMHelperOMALevel omaLevel; omaLevel = CDRMHelper::EOMA_None ; TInt retval = iHelper->SupportedDRMMethods2( drmMethod, omaLevel ); if ( retval ) { iLog->Log( _L( "SupportedDRMMethods returned: %d" ), retval ); User::Leave(retval); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::ConsumeUriL() { SetupL(); contentUri = ContentUriLC( KImageStartEnd ); contentUri8 = ConvertTo8BitLC( contentUri ); TInt retval = iHelper->Consume2( *contentUri8, ContentAccess::EView, CDRMHelper::EStart ); if ( retval ) { iLog->Log( _L( "Consume2 start returned: %d" ), retval ); User::Leave(retval); } else { retval = iHelper->Consume2( *contentUri8, ContentAccess::EView, CDRMHelper::EFinish ); if ( retval ) { iLog->Log( _L( "Consume2 finish returned: %d" ), retval ); User::Leave(retval); } } CleanupStack::PopAndDestroy( 2, contentUri ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::ConsumeFileL() { SetupL(); TInt retval = iHelper->ConsumeFile2( KImageStartEnd, ContentAccess::EView, CDRMHelper::EStart ); if ( retval ) { iLog->Log( _L( "ConsumeFile2 start returned: %d" ), retval ); User::Leave(retval); } else { retval = iHelper->ConsumeFile2( KImageStartEnd, ContentAccess::EView, CDRMHelper::EFinish ); if ( retval ) { iLog->Log( _L( "ConsumeFile2 finish returned: %d" ), retval ); User::Leave(retval); } } Teardown(); return retval; } TInt CBCTestDRMHelperLib::ConsumeFileHandleL() { SetupL(); OpenFileL( KImageStartEnd, file ); TInt retval = iHelper->ConsumeFile2( file, ContentAccess::EView, CDRMHelper::EStart ); if ( retval ) { iLog->Log( _L( "ConsumeFile2 start returned: %d" ), retval ); User::Leave(retval); } else { retval = iHelper->ConsumeFile2( KImageStartEnd, ContentAccess::EView, CDRMHelper::EFinish ); if ( retval ) { iLog->Log( _L( "ConsumeFile2 finish returned: %d" ), retval ); User::Leave(retval); } } file.Close(); Teardown(); return retval; } TInt CBCTestDRMHelperLib::ActivateContentFileL() { SetupL(); fileName = KValidFile; TInt retval; TRAP( retval, iHelper->ActivateContentL( fileName ) ); if ( retval != KErrCancel ) { iLog->Log( _L( "ActivateContentL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::ActivateContentDataL() { SetupL(); ContentAccess::CData* content; content = NULL; content = CreateContentObjectLC( KValidFile ); TInt retval; TRAP( retval, iHelper->ActivateContentL( *content ) ); if ( retval != KErrCancel ) { iLog->Log( _L( "ActivateContentL returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( content ); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HasPreviewFileL() { SetupL(); CDRMHelper::TDRMHelperPreviewType previewType; fileName = KImageStartEnd; previewType = iHelper->HasPreviewL( fileName, previewUrl ); if ( previewType != CDRMHelper::ENoPreview ) { iLog->Log( _L8( "HasPreviewL: preview found" ) ); delete previewUrl; User::Leave(KErrGeneral); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HasPreviewDataL() { SetupL(); CDRMHelper::TDRMHelperPreviewType previewType; ContentAccess::CData* content; content = NULL; content = CreateContentObjectLC( KImageStartEnd ); previewType = iHelper->HasPreviewL( *content, previewUrl ); if ( previewType != CDRMHelper::ENoPreview ) { iLog->Log( _L8( "HasPreviewL: preview found" ) ); delete previewUrl; User::Leave(KErrGeneral); } CleanupStack::PopAndDestroy( content ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::GetPreviewRightsFileL() { SetupL(); fileName = KImageStartEnd; TRAP( retval, iHelper->GetPreviewRightsL( fileName ) ); if ( retval != KErrArgument ) { iLog->Log( _L( "GetPreviewRightsL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::GetPreviewRightsDataL() { SetupL(); ContentAccess::CData* content; content = NULL; content = CreateContentObjectLC( KImageStartEnd ); TRAP( retval, iHelper->GetPreviewRightsL( *content ) ); if ( retval != KErrArgument ) { iLog->Log( _L( "GetPreviewRightsL returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( content ); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::EmbeddedPreviewCompletedFileL() { SetupL(); fileName = KImageStartEnd; TRAP( retval, buyRights = iHelper->EmbeddedPreviewCompletedL( fileName ) ); if ( retval && retval != KErrArgument ) { iLog->Log( _L( "EmbeddedPreviewCompletedFileL returned: %d" ), retval ); User::Leave(retval); } if ( buyRights ) { iLog->Log( _L8( "EmbeddedPreviewCompletedL: wrong value" ) ); User::Leave(KErrGeneral); } Teardown(); return retval; } TInt CBCTestDRMHelperLib::EmbeddedPreviewCompletedDataL() { SetupL(); ContentAccess::CData* content; content = NULL; content = CreateContentObjectLC( KImageStartEnd ); TRAP( retval, buyRights = iHelper->EmbeddedPreviewCompletedL( *content ) ); if ( retval && retval != KErrArgument ) { iLog->Log( _L( "EmbeddedPreviewCompletedDataL returned: %d" ), retval ); User::Leave(retval); } if ( buyRights ) { iLog->Log( _L8( "EmbeddedPreviewCompletedDataL: wrong value" ) ); User::Leave(KErrGeneral); } CleanupStack::PopAndDestroy( content ); Teardown(); return retval; } TInt CBCTestDRMHelperLib::HasInfoUrlFileL() { SetupL(); fileName = KImageStartEnd; infoUrlExists = iHelper->HasInfoUrlL( fileName, infoUrl ); if ( infoUrlExists ) { iLog->Log( _L8( "EmbeddedPreviewCompletedL: wrong value" ) ); delete infoUrl; User::Leave(KErrGeneral); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HasInfoUrlDataL() { SetupL(); ContentAccess::CData* content; content = NULL; content = CreateContentObjectLC( KImageStartEnd ); infoUrlExists = iHelper->HasInfoUrlL( *content, infoUrl ); if ( infoUrlExists ) { iLog->Log( _L8( "EmbeddedPreviewCompletedL: wrong value" ) ); delete infoUrl; User::Leave(KErrGeneral); } CleanupStack::PopAndDestroy( content ); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::OpenInfoUrlFileL() { SetupL(); fileName = KImageStartEnd; TRAP( retval, iHelper->OpenInfoUrlL( fileName ) ); if ( retval != KErrArgument ) { iLog->Log( _L( "OpenInfoUrlL returned: %d" ), retval ); User::Leave(retval); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::OpenInfoUrlDataL() { SetupL(); ContentAccess::CData* content; content = NULL; content = CreateContentObjectLC( KImageStartEnd ); TRAP( retval, iHelper->OpenInfoUrlL( *content ) ); if ( retval != KErrArgument ) { iLog->Log( _L( "OpenInfoUrlL returned: %d" ), retval ); User::Leave(retval); } CleanupStack::PopAndDestroy( content ); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::SetPreviewMediaTypeL() { SetupL(); retval = iHelper->SetPreviewMediaType( EPreviewTypeAudio ); if ( retval ) { iLog->Log( _L( "SetPreviewMediaType returned %d"),retval); User::Leave( retval ); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HandleErrorOrPreviewFileL() { SetupL(); retval = iHelper->HandleErrorOrPreviewL( KErrCANoPermission, KValidFile, previewUrl ); if ( previewUrl ) { iLog->Log( _L( "HandleErrorOrPreviewL: preview URI returned: %d"), retval); delete previewUrl; previewUrl = NULL; User::Leave( retval ); } else if ( retval != KErrCANoPermission && retval != KErrCANoRights && retval != KErrCancel ) { iLog->Log( _L( "HandleErrorOrPreviewL returned: %d"),retval); User::Leave( retval ); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HandleErrorOrPreviewFileHandleL() { SetupL(); OpenFileL( KValidFile, file ); retval = iHelper->HandleErrorOrPreviewL( KErrCANoRights, file, previewUrl ); if ( previewUrl ) { iLog->Log( _L( "HandleErrorOrPreviewL: preview URI returned: %d"), retval); delete previewUrl; previewUrl = NULL; User::Leave( retval ); } else if ( retval != KErrCANoPermission && retval != KErrCANoRights && retval != KErrCancel ) { iLog->Log( _L( "HandleErrorOrPreviewL returned: %d"),retval ); User::Leave( retval ); } file.Close(); Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HandleErrorOrPreviewSilentFileL() { SetupL(); retval = iHelper->HandleErrorOrPreviewL( KErrCANoPermission, KSilentFile, previewUrl ); if ( previewUrl ) { iLog->Log( _L( "HandleErrorOrPreviewL: preview URI returned: %d"), retval); delete previewUrl; previewUrl = NULL; User::Leave( retval ); } else if ( retval != KErrCANoPermission && retval != KErrCANoRights && retval != KErrCancel ) { iLog->Log( _L( "HandleErrorOrPreviewL returned: %d"),retval); User::Leave( retval ); } Teardown(); return KErrNone; } TInt CBCTestDRMHelperLib::HandleErrorOrPreviewSilentFileHandleL() { SetupL(); OpenFileL( KSilentFile, file ); retval = iHelper->HandleErrorOrPreviewL( KErrCANoRights, file, previewUrl ); if ( previewUrl ) { iLog->Log( _L( "HandleErrorOrPreviewL: preview URI returned")); delete previewUrl; previewUrl = NULL; User::Leave( KErrGeneral ); } else if ( retval != KErrCANoPermission && retval != KErrCANoRights && retval != KErrCancel ) { iLog->Log( _L( "HandleErrorOrPreviewL returned: %d"),retval); User::Leave( retval ); } file.Close(); Teardown(); return KErrNone; } void CBCTestDRMHelperLib::SetupL() { contentUri = NULL; contentUri8 = NULL; expired = EFalse ; sendingAllowed = EFalse; play = NULL; display = NULL; print = NULL; execute = NULL; automatedUseAllowed = EFalse ; uriList = NULL; supportedDataTypes = 0 ; drmMethod = 0 ; // omaLevel = CDRMHelper::EOMA_None ; //content = NULL; previewUrl = NULL; buyRights = EFalse ; infoUrlExists = EFalse ; infoUrl = NULL; // Create CDRMHelper object User::LeaveIfError( iFs.Connect() ); iHelper = CDRMHelper::NewL( *CCoeEnv::Static(), iFs ); // BringToForeground(); } void CBCTestDRMHelperLib::Teardown() { // SendToBackground(); delete iHelper; iHelper = NULL; iFs.Close(); }
[ "none@none" ]
[ [ [ 1, 1499 ] ] ]
9b88eaa9661973224bc6dfda394a6569edeb009c
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/entity/componentnode.h
73f150e65e60520dc3758a98ff0f7a192524c516
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
870
h
/* * componentnode.h * * Created on: 22.10.2011 * Author: akin */ #ifndef ICE_COMPONENTNODE_H_ #define ICE_COMPONENTNODE_H_ #include <deque> #include <threadpool/tque> #define NODE_NULL 0 namespace ice { class Component; class ComponentNode { protected: Component& current; TQue<ComponentNode*> *finishQueu; unsigned int endTime; bool running; public: ComponentNode( Component *component ); ComponentNode( ComponentNode& other ); virtual ~ComponentNode(); std::deque<ComponentNode *> dependencies; std::deque<ComponentNode *> childs; unsigned int time; Component& getComponent(); bool isRunning(); void componentStart( TQue<ComponentNode*>& target , unsigned int start , unsigned int end ); void componentFinished(); }; } /* namespace ice */ #endif /* COMPONENTNODE_H_ */
[ "akin@lich", "akin@localhost" ]
[ [ [ 1, 7 ], [ 10, 12 ], [ 14, 17 ], [ 43, 44 ] ], [ [ 8, 9 ], [ 13, 13 ], [ 18, 42 ] ] ]
d2088a703a0b6c2489e984ef335d34c3c7bba7e8
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/internal/WFXMLScanner.cpp
8ce802e4ffa000def7824945e101a86545703143
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
78,358
cpp
/* * Copyright 2002,2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: WFXMLScanner.cpp,v 1.25 2004/09/28 21:27:38 peiyongz Exp $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/WFXMLScanner.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/RuntimeException.hpp> #include <xercesc/util/UnexpectedEOFException.hpp> #include <xercesc/sax/InputSource.hpp> #include <xercesc/framework/XMLDocumentHandler.hpp> #include <xercesc/framework/XMLEntityHandler.hpp> #include <xercesc/framework/XMLPScanToken.hpp> #include <xercesc/framework/XMLValidityCodes.hpp> #include <xercesc/internal/EndOfEntityException.hpp> #include <xercesc/util/OutOfMemoryException.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // WFXMLScanner: Constructors and Destructor // --------------------------------------------------------------------------- WFXMLScanner::WFXMLScanner( XMLValidator* const valToAdopt , GrammarResolver* const grammarResolver , MemoryManager* const manager) : XMLScanner(valToAdopt, grammarResolver, manager) , fElementIndex(0) , fElements(0) , fEntityTable(0) , fAttrNameHashList(0) , fAttrNSList(0) , fElementLookup(0) { try { commonInit(); } catch(const OutOfMemoryException&) { throw; } catch(...) { cleanUp(); throw; } } WFXMLScanner::WFXMLScanner( XMLDocumentHandler* const docHandler , DocTypeHandler* const docTypeHandler , XMLEntityHandler* const entityHandler , XMLErrorReporter* const errHandler , XMLValidator* const valToAdopt , GrammarResolver* const grammarResolver , MemoryManager* const manager) : XMLScanner(docHandler, docTypeHandler, entityHandler, errHandler, valToAdopt, grammarResolver, manager) , fElementIndex(0) , fElements(0) , fEntityTable(0) , fAttrNameHashList(0) , fAttrNSList(0) , fElementLookup(0) { try { commonInit(); } catch(const OutOfMemoryException&) { throw; } catch(...) { cleanUp(); throw; } } WFXMLScanner::~WFXMLScanner() { cleanUp(); } // --------------------------------------------------------------------------- // XMLScanner: Getter methods // --------------------------------------------------------------------------- NameIdPool<DTDEntityDecl>* WFXMLScanner::getEntityDeclPool() { return 0; } const NameIdPool<DTDEntityDecl>* WFXMLScanner::getEntityDeclPool() const { return 0; } // --------------------------------------------------------------------------- // WFXMLScanner: Main entry point to scan a document // --------------------------------------------------------------------------- void WFXMLScanner::scanDocument(const InputSource& src) { // Bump up the sequence id for this parser instance. This will invalidate // any previous progressive scan tokens. fSequenceId++; try { // Reset the scanner and its plugged in stuff for a new run. This // resets all the data structures, creates the initial reader and // pushes it on the stack, and sets up the base document path. scanReset(src); // If we have a document handler, then call the start document if (fDocHandler) fDocHandler->startDocument(); // Scan the prolog part, which is everything before the root element // including the DTD subsets. scanProlog(); // If we got to the end of input, then its not a valid XML file. // Else, go on to scan the content. if (fReaderMgr.atEOF()) { emitError(XMLErrs::EmptyMainEntity); } else { // Scan content, and tell it its not an external entity if (scanContent()) { // That went ok, so scan for any miscellaneous stuff if (!fReaderMgr.atEOF()) scanMiscellaneous(); } } // If we have a document handler, then call the end document if (fDocHandler) fDocHandler->endDocument(); // Reset the reader manager to close all files, sockets, etc... fReaderMgr.reset(); } // NOTE: // // In all of the error processing below, the emitError() call MUST come // before the flush of the reader mgr, or it will fail because it tries // to find out the position in the XML source of the error. catch(const XMLErrs::Codes) { // This is a 'first fatal error' type exit, so reset and fall through fReaderMgr.reset(); } catch(const XMLValid::Codes) { // This is a 'first fatal error' type exit, so reset and fall through fReaderMgr.reset(); } catch(const XMLException& excToCatch) { // Emit the error and catch any user exception thrown from here. Make // sure in all cases we flush the reader manager. fInException = true; try { if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); } catch(const OutOfMemoryException&) { throw; } catch(...) { // Flush the reader manager and rethrow user's error fReaderMgr.reset(); throw; } // If it returned, then reset the reader manager and fall through fReaderMgr.reset(); } catch(const OutOfMemoryException&) { throw; } catch(...) { // Reset and rethrow fReaderMgr.reset(); throw; } } bool WFXMLScanner::scanNext(XMLPScanToken& token) { // Make sure this token is still legal if (!isLegalToken(token)) ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_BadPScanToken, fMemoryManager); // Find the next token and remember the reader id unsigned int orgReader; XMLTokens curToken; bool retVal = true; try { while (true) { // We have to handle any end of entity exceptions that happen here. // We could be at the end of X nested entities, each of which will // generate an end of entity exception as we try to move forward. try { curToken = senseNextToken(orgReader); break; } catch(const EndOfEntityException& toCatch) { // Send an end of entity reference event if (fDocHandler) fDocHandler->endEntityReference(toCatch.getEntity()); } } if (curToken == Token_CharData) { scanCharData(fCDataBuf); } else if (curToken == Token_EOF) { if (!fElemStack.isEmpty()) { const ElemStack::StackElem* topElem = fElemStack.popTop(); emitError ( XMLErrs::EndedWithTagsOnStack , topElem->fThisElement->getFullName() ); } retVal = false; } else { // Its some sort of markup bool gotData = true; switch(curToken) { case Token_CData : // Make sure we are within content if (fElemStack.isEmpty()) emitError(XMLErrs::CDATAOutsideOfContent); scanCDSection(); break; case Token_Comment : scanComment(); break; case Token_EndTag : scanEndTag(gotData); break; case Token_PI : scanPI(); break; case Token_StartTag : if (fDoNamespaces) scanStartTagNS(gotData); else scanStartTag(gotData); break; default : fReaderMgr.skipToChar(chOpenAngle); break; } if (orgReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); // If we hit the end, then do the miscellaneous part if (!gotData) { // That went ok, so scan for any miscellaneous stuff scanMiscellaneous(); if (fDocHandler) fDocHandler->endDocument(); } } } // NOTE: // // In all of the error processing below, the emitError() call MUST come // before the flush of the reader mgr, or it will fail because it tries // to find out the position in the XML source of the error. catch(const XMLErrs::Codes) { // This is a 'first failure' exception, so reset and return failure fReaderMgr.reset(); return false; } catch(const XMLValid::Codes) { // This is a 'first fatal error' type exit, so reset and reuturn failure fReaderMgr.reset(); return false; } catch(const XMLException& excToCatch) { // Emit the error and catch any user exception thrown from here. Make // sure in all cases we flush the reader manager. fInException = true; try { if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); } catch(const OutOfMemoryException&) { throw; } catch(...) { // Reset and rethrow user error fReaderMgr.reset(); throw; } // Reset and return failure fReaderMgr.reset(); return false; } catch(const OutOfMemoryException&) { throw; } catch(...) { // Reset and rethrow original error fReaderMgr.reset(); throw; } // If we hit the end, then flush the reader manager if (!retVal) fReaderMgr.reset(); return retVal; } // --------------------------------------------------------------------------- // WFXMLScanner: Private helper methods. // --------------------------------------------------------------------------- // This method handles the common initialization, to avoid having to do // it redundantly in multiple constructors. void WFXMLScanner::commonInit() { fEntityTable = new (fMemoryManager) ValueHashTableOf<XMLCh>(11, fMemoryManager); fAttrNameHashList = new (fMemoryManager)ValueVectorOf<unsigned int>(16, fMemoryManager); fAttrNSList = new (fMemoryManager) ValueVectorOf<XMLAttr*>(8, fMemoryManager); fElements = new (fMemoryManager) RefVectorOf<XMLElementDecl>(32, true, fMemoryManager); fElementLookup = new (fMemoryManager) RefHashTableOf<XMLElementDecl>(109, false, fMemoryManager); // Add the default entity entries for the character refs that must always // be present. fEntityTable->put((void*) XMLUni::fgAmp, chAmpersand); fEntityTable->put((void*) XMLUni::fgLT, chOpenAngle); fEntityTable->put((void*) XMLUni::fgGT, chCloseAngle); fEntityTable->put((void*) XMLUni::fgQuot, chDoubleQuote); fEntityTable->put((void*) XMLUni::fgApos, chSingleQuote); } void WFXMLScanner::cleanUp() { delete fEntityTable; delete fAttrNameHashList; delete fAttrNSList; delete fElementLookup; delete fElements; } unsigned int WFXMLScanner::resolvePrefix(const XMLCh* const prefix , const ElemStack::MapModes mode) { // Watch for the special namespace prefixes. We always map these to // special URIs. 'xml' gets mapped to the official URI that its defined // to map to by the NS spec. xmlns gets mapped to a special place holder // URI that we define (so that it maps to something checkable.) if (XMLString::equals(prefix, XMLUni::fgXMLNSString)) return fXMLNSNamespaceId; else if (XMLString::equals(prefix, XMLUni::fgXMLString)) return fXMLNamespaceId; // Ask the element stack to search up itself for a mapping for the // passed prefix. bool unknown; unsigned int uriId = fElemStack.mapPrefixToURI(prefix, mode, unknown); // If it was unknown, then the URI was faked in but we have to issue an error if (unknown) emitError(XMLErrs::UnknownPrefix, prefix); return uriId; } // This method will reset the scanner data structures, and related plugged // in stuff, for a new scan session. We get the input source for the primary // XML entity, create the reader for it, and push it on the stack so that // upon successful return from here we are ready to go. void WFXMLScanner::scanReset(const InputSource& src) { // For all installed handlers, send reset events. This gives them // a chance to flush any cached data. if (fDocHandler) fDocHandler->resetDocument(); if (fEntityHandler) fEntityHandler->resetEntities(); if (fErrorReporter) fErrorReporter->resetErrors(); // Reset the element stack, and give it the latest ids for the special // URIs it has to know about. fElemStack.reset ( fEmptyNamespaceId , fUnknownNamespaceId , fXMLNamespaceId , fXMLNSNamespaceId ); // Reset some status flags fInException = false; fStandalone = false; fErrorCount = 0; fHasNoDTD = true; fElementIndex = 0; // Reset elements lookup table fElementLookup->removeAll(); // Handle the creation of the XML reader object for this input source. // This will provide us with transcoding and basic lexing services. XMLReader* newReader = fReaderMgr.createReader ( src , true , XMLReader::RefFrom_NonLiteral , XMLReader::Type_General , XMLReader::Source_External , fCalculateSrcOfs ); if (!newReader) { if (src.getIssueFatalErrorIfNotFound()) ThrowXMLwithMemMgr1(RuntimeException, XMLExcepts::Scan_CouldNotOpenSource, src.getSystemId(), fMemoryManager); else ThrowXMLwithMemMgr1(RuntimeException, XMLExcepts::Scan_CouldNotOpenSource_Warning, src.getSystemId(), fMemoryManager); } // Push this read onto the reader manager fReaderMgr.pushReader(newReader, 0); // and reset security-related things if necessary: if(fSecurityManager != 0) { fEntityExpansionLimit = fSecurityManager->getEntityExpansionLimit(); fEntityExpansionCount = 0; } } // This method is called between markup in content. It scans for character // data that is sent to the document handler. It watches for any markup // characters that would indicate that the character data has ended. It also // handles expansion of general and character entities. // // sendData() is a local static helper for this method which handles some // code that must be done in three different places here. void WFXMLScanner::sendCharData(XMLBuffer& toSend) { // If no data in the buffer, then nothing to do if (toSend.isEmpty()) return; // Always assume its just char data if not validating if (fDocHandler) fDocHandler->docCharacters(toSend.getRawBuffer(), toSend.getLen(), false); // Reset buffer toSend.reset(); } // --------------------------------------------------------------------------- // WFXMLScanner: Private scanning methods // --------------------------------------------------------------------------- // This method will kick off the scanning of the primary content of the // document, i.e. the elements. bool WFXMLScanner::scanContent() { // Go into a loop until we hit the end of the root element, or we fall // out because there is no root element. // // We have to do kind of a deeply nested double loop here in order to // avoid doing the setup/teardown of the exception handler on each // round. Doing it this way we only do it when an exception actually // occurs. bool gotData = true; bool inMarkup = false; while (gotData) { try { while (gotData) { // Sense what the next top level token is. According to what // this tells us, we will call something to handle that kind // of thing. unsigned int orgReader; const XMLTokens curToken = senseNextToken(orgReader); // Handle character data and end of file specially. Char data // is not markup so we don't want to handle it in the loop // below. if (curToken == Token_CharData) { // Scan the character data and call appropriate events. Let // him use our local character data buffer for efficiency. scanCharData(fCDataBuf); continue; } else if (curToken == Token_EOF) { // The element stack better be empty at this point or we // ended prematurely before all elements were closed. if (!fElemStack.isEmpty()) { const ElemStack::StackElem* topElem = fElemStack.popTop(); emitError ( XMLErrs::EndedWithTagsOnStack , topElem->fThisElement->getFullName() ); } // Its the end of file, so clear the got data flag gotData = false; continue; } // We are in some sort of markup now inMarkup = true; // According to the token we got, call the appropriate // scanning method. switch(curToken) { case Token_CData : // Make sure we are within content if (fElemStack.isEmpty()) emitError(XMLErrs::CDATAOutsideOfContent); scanCDSection(); break; case Token_Comment : scanComment(); break; case Token_EndTag : scanEndTag(gotData); break; case Token_PI : scanPI(); break; case Token_StartTag : if (fDoNamespaces) scanStartTagNS(gotData); else scanStartTag(gotData); break; default : fReaderMgr.skipToChar(chOpenAngle); break; } if (orgReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); // And we are back out of markup again inMarkup = false; } } catch(const EndOfEntityException& toCatch) { // If we were in some markup when this happened, then its a // partial markup error. if (inMarkup) emitError(XMLErrs::PartialMarkupInEntity); // Send an end of entity reference event if (fDocHandler) fDocHandler->endEntityReference(toCatch.getEntity()); inMarkup = false; } } // It went ok, so return success return true; } void WFXMLScanner::scanEndTag(bool& gotData) { // Assume we will still have data until proven otherwise. It will only // ever be false if this is the end of the root element. gotData = true; // Check if the element stack is empty. If so, then this is an unbalanced // element (i.e. more ends than starts, perhaps because of bad text // causing one to be skipped.) if (fElemStack.isEmpty()) { emitError(XMLErrs::MoreEndThanStartTags); fReaderMgr.skipPastChar(chCloseAngle); ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_UnbalancedStartEnd, fMemoryManager); } // Pop the stack of the element we are supposed to be ending. Remember // that we don't own this. The stack just keeps them and reuses them. unsigned int uriId = (fDoNamespaces) ? fElemStack.getCurrentURI() : fEmptyNamespaceId; const ElemStack::StackElem* topElem = fElemStack.popTop(); // See if it was the root element, to avoid multiple calls below const bool isRoot = fElemStack.isEmpty(); // Make sure that its the end of the element that we expect if (!fReaderMgr.skippedString(topElem->fThisElement->getFullName())) { emitError ( XMLErrs::ExpectedEndOfTagX , topElem->fThisElement->getFullName() ); fReaderMgr.skipPastChar(chCloseAngle); return; } // Make sure we are back on the same reader as where we started if (topElem->fReaderNum != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialTagMarkupError); // Skip optional whitespace fReaderMgr.skipPastSpaces(); // Make sure we find the closing bracket if (!fReaderMgr.skippedChar(chCloseAngle)) { emitError ( XMLErrs::UnterminatedEndTag , topElem->fThisElement->getFullName() ); } // If we have a doc handler, tell it about the end tag if (fDocHandler) { fDocHandler->endElement ( *topElem->fThisElement , uriId , isRoot , topElem->fThisElement->getElementName()->getPrefix() ); } // If this was the root, then done with content gotData = !isRoot; } void WFXMLScanner::scanDocTypeDecl() { // Just skips over it // REVISIT: Should we issue a warning static const XMLCh doctypeIE[] = { chOpenSquare, chCloseAngle, chNull }; XMLCh nextCh = fReaderMgr.skipUntilIn(doctypeIE); if (nextCh == chOpenSquare) fReaderMgr.skipPastChar(chCloseSquare); fReaderMgr.skipPastChar(chCloseAngle); } bool WFXMLScanner::scanStartTag(bool& gotData) { // Assume we will still have data until proven otherwise. It will only // ever be false if this is the root and its empty. gotData = true; // Get the QName. In this case, we are not doing namespaces, so we just // use it as is and don't have to break it into parts. if (!fReaderMgr.getName(fQNameBuf)) { emitError(XMLErrs::ExpectedElementName); fReaderMgr.skipToChar(chOpenAngle); return false; } // Assume it won't be an empty tag bool isEmpty = false; // See if its the root element const bool isRoot = fElemStack.isEmpty(); // Lets try to look up the element const XMLCh* qnameRawBuf = fQNameBuf.getRawBuffer(); XMLElementDecl* elemDecl = fElementLookup->get(qnameRawBuf); if (!elemDecl) { if (fElementIndex < fElements->size()) { elemDecl = fElements->elementAt(fElementIndex); } else { elemDecl = new (fGrammarPoolMemoryManager) DTDElementDecl ( fGrammarPoolMemoryManager ); fElements->addElement(elemDecl); } elemDecl->setElementName(XMLUni::fgZeroLenString, qnameRawBuf, fEmptyNamespaceId); fElementLookup->put((void*)elemDecl->getFullName(), elemDecl); fElementIndex++; } // Expand the element stack and add the new element fElemStack.addLevel(elemDecl, fReaderMgr.getCurrentReaderNum()); // Skip any whitespace after the name fReaderMgr.skipPastSpaces(); // We loop until we either see a /> or >, handling attribute/value // pairs until we get there. unsigned int attCount = 0; unsigned int curAttListSize = fAttrList->size(); while (true) { // And get the next non-space character XMLCh nextCh = fReaderMgr.peekNextChar(); // If the next character is not a slash or closed angle bracket, // then it must be whitespace, since whitespace is required // between the end of the last attribute and the name of the next // one. if (attCount) { if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle)) { if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) { // Ok, skip by them and peek another char fReaderMgr.skipPastSpaces(); nextCh = fReaderMgr.peekNextChar(); } else { // Emit the error but keep on going emitError(XMLErrs::ExpectedWhitespace); } } } // Ok, here we first check for any of the special case characters. // If its not one, then we do the normal case processing, which // assumes that we've hit an attribute value, Otherwise, we do all // the special case checks. if (!fReaderMgr.getCurrentReader()->isSpecialStartTagChar(nextCh)) { // Assume its going to be an attribute, so get a name from // the input. if (!fReaderMgr.getName(fAttNameBuf)) { emitError(XMLErrs::ExpectedAttrName); fReaderMgr.skipPastChar(chCloseAngle); return false; } // And next must be an equal sign if (!scanEq()) { static const XMLCh tmpList[] = { chSingleQuote, chDoubleQuote, chCloseAngle , chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedEqSign); // Try to sync back up by skipping forward until we either // hit something meaningful. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash)) { // Jump back to top for normal processing of these continue; } else if ((chFound == chSingleQuote) || (chFound == chDoubleQuote) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through assuming that the value is to follow } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // See if this attribute is declared more than one for this element. const XMLCh* attNameRawBuf = fAttNameBuf.getRawBuffer(); unsigned int attNameHash = XMLString::hash(attNameRawBuf, 109, fMemoryManager); if (attCount) { for (unsigned int k=0; k < attCount; k++) { if (fAttrNameHashList->elementAt(k) == attNameHash) { if ( XMLString::equals ( fAttrList->elementAt(k)->getName() , attNameRawBuf ) ) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , attNameRawBuf , qnameRawBuf ); break; } } } } // Skip any whitespace before the value and then scan the att // value. This will come back normalized with entity refs and // char refs expanded. fReaderMgr.skipPastSpaces(); if (!scanAttValue(attNameRawBuf, fAttValueBuf)) { static const XMLCh tmpList[] = { chCloseAngle, chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedAttrValue); // It failed, so lets try to get synced back up. We skip // forward until we find some whitespace or one of the // chars in our list. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through and process this attribute, though // the value will be "". } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // Add this attribute to the attribute list that we use to // pass them to the handler. We reuse its existing elements // but expand it as required. XMLAttr* curAtt; if (attCount >= curAttListSize) { curAtt = new (fMemoryManager) XMLAttr ( -1 , attNameRawBuf , XMLUni::fgZeroLenString , fAttValueBuf.getRawBuffer() , XMLAttDef::CData , true , fMemoryManager ); fAttrList->addElement(curAtt); fAttrNameHashList->addElement(attNameHash); } else { curAtt = fAttrList->elementAt(attCount); curAtt->set ( -1 , attNameRawBuf , XMLUni::fgZeroLenString , fAttValueBuf.getRawBuffer() ); curAtt->setSpecified(true); fAttrNameHashList->setElementAt(attNameHash, attCount); } attCount++; // And jump back to the top of the loop continue; } // It was some special case character so do all of the checks and // deal with it. if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == chForwardSlash) { fReaderMgr.getNextChar(); isEmpty = true; if (!fReaderMgr.skippedChar(chCloseAngle)) emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); break; } else if (nextCh == chCloseAngle) { fReaderMgr.getNextChar(); break; } else if (nextCh == chOpenAngle) { // Check for this one specially, since its going to be common // and it is kind of auto-recovering since we've already hit the // next open bracket, which is what we would have seeked to (and // skipped this whole tag.) emitError(XMLErrs::UnterminatedStartTag, elemDecl->getFullName()); break; } else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote)) { // Check for this one specially, which is probably a missing // attribute name, e.g. ="value". Just issue expected name // error and eat the quoted string, then jump back to the // top again. emitError(XMLErrs::ExpectedAttrName); fReaderMgr.getNextChar(); fReaderMgr.skipQuotedString(nextCh); fReaderMgr.skipPastSpaces(); continue; } } // If empty, validate content right now if we are validating and then // pop the element stack top. Else, we have to update the current stack // top's namespace mapping elements. if (isEmpty) { // Pop the element stack back off since it'll never be used now fElemStack.popTop(); // If the elem stack is empty, then it was an empty root if (isRoot) gotData = false; } // If we have a document handler, then tell it about this start tag. We // don't have any URI id to send along, so send fEmptyNamespaceId. We also do not send // any prefix since its just one big name if we are not doing namespaces. if (fDocHandler) { fDocHandler->startElement ( *elemDecl , fEmptyNamespaceId , 0 , *fAttrList , attCount , isEmpty , isRoot ); } return true; } // This method is called to scan a start tag when we are processing // namespaces. There are two different versions of this method, one for // namespace aware processing an done for non-namespace aware processing. // // This method is called after we've scanned the < of a start tag. So we // have to get the element name, then scan the attributes, after which // we are either going to see >, />, or attributes followed by one of those // sequences. bool WFXMLScanner::scanStartTagNS(bool& gotData) { // Assume we will still have data until proven otherwise. It will only // ever be false if this is the root and its empty. gotData = true; // The current position is after the open bracket, so we need to read in // in the element name. if (!fReaderMgr.getName(fQNameBuf)) { emitError(XMLErrs::ExpectedElementName); fReaderMgr.skipToChar(chOpenAngle); return false; } // See if its the root element const bool isRoot = fElemStack.isEmpty(); // Assume it won't be an empty tag bool isEmpty = false; // Skip any whitespace after the name fReaderMgr.skipPastSpaces(); // Lets try to look up the element const XMLCh* qnameRawBuf = fQNameBuf.getRawBuffer(); XMLElementDecl* elemDecl = fElementLookup->get(qnameRawBuf); if (!elemDecl) { if (!XMLString::compareNString(qnameRawBuf, XMLUni::fgXMLNSColonString, 6)) emitError(XMLErrs::NoXMLNSAsElementPrefix, qnameRawBuf); if (fElementIndex < fElements->size()) { elemDecl = fElements->elementAt(fElementIndex); } else { elemDecl = new (fGrammarPoolMemoryManager) DTDElementDecl ( fGrammarPoolMemoryManager ); fElements->addElement(elemDecl); } elemDecl->setElementName(qnameRawBuf, fEmptyNamespaceId); fElementLookup->put((void*)elemDecl->getFullName(), elemDecl); fElementIndex++; } // Expand the element stack and add the new element fElemStack.addLevel(elemDecl, fReaderMgr.getCurrentReaderNum()); // reset NS attribute list fAttrNSList->removeAllElements(); // We loop until we either see a /> or >, handling attribute/value // pairs until we get there. unsigned int attCount = 0; unsigned int curAttListSize = fAttrList->size(); while (true) { // And get the next non-space character XMLCh nextCh = fReaderMgr.peekNextChar(); // If the next character is not a slash or closed angle bracket, // then it must be whitespace, since whitespace is required // between the end of the last attribute and the name of the next // one. if (attCount) { if ((nextCh != chForwardSlash) && (nextCh != chCloseAngle)) { if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) { // Ok, skip by them and peek another char fReaderMgr.skipPastSpaces(); nextCh = fReaderMgr.peekNextChar(); } else { // Emit the error but keep on going emitError(XMLErrs::ExpectedWhitespace); } } } // Ok, here we first check for any of the special case characters. // If its not one, then we do the normal case processing, which // assumes that we've hit an attribute value, Otherwise, we do all // the special case checks. if (!fReaderMgr.getCurrentReader()->isSpecialStartTagChar(nextCh)) { // Assume its going to be an attribute, so get a name from // the input. if (!fReaderMgr.getName(fAttNameBuf)) { emitError(XMLErrs::ExpectedAttrName); fReaderMgr.skipPastChar(chCloseAngle); return false; } // And next must be an equal sign if (!scanEq()) { static const XMLCh tmpList[] = { chSingleQuote, chDoubleQuote, chCloseAngle , chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedEqSign); // Try to sync back up by skipping forward until we either // hit something meaningful. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash)) { // Jump back to top for normal processing of these continue; } else if ((chFound == chSingleQuote) || (chFound == chDoubleQuote) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through assuming that the value is to follow } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // See if this attribute is declared more than one for this element. const XMLCh* attNameRawBuf = fAttNameBuf.getRawBuffer(); unsigned int attNameHash = XMLString::hash(attNameRawBuf, 109, fMemoryManager); if (attCount) { for (unsigned int k=0; k < attCount; k++) { if (fAttrNameHashList->elementAt(k) == attNameHash) { if (XMLString::equals( fAttrList->elementAt(k)->getQName() , attNameRawBuf)) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , attNameRawBuf , qnameRawBuf ); break; } } } } // Skip any whitespace before the value and then scan the att // value. This will come back normalized with entity refs and // char refs expanded. fReaderMgr.skipPastSpaces(); if (!scanAttValue(attNameRawBuf, fAttValueBuf)) { static const XMLCh tmpList[] = { chCloseAngle, chOpenAngle, chForwardSlash, chNull }; emitError(XMLErrs::ExpectedAttrValue); // It failed, so lets try to get synced back up. We skip // forward until we find some whitespace or one of the // chars in our list. const XMLCh chFound = fReaderMgr.skipUntilInOrWS(tmpList); if ((chFound == chCloseAngle) || (chFound == chForwardSlash) || fReaderMgr.getCurrentReader()->isWhitespace(chFound)) { // Just fall through and process this attribute, though // the value will be "". } else if (chFound == chOpenAngle) { // Assume a malformed tag and that new one is starting emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); return false; } else { // Something went really wrong return false; } } // Add this attribute to the attribute list that we use to // pass them to the handler. We reuse its existing elements // but expand it as required. const XMLCh* attValueRawBuf = fAttValueBuf.getRawBuffer(); XMLAttr* curAtt = 0; if (attCount >= curAttListSize) { curAtt = new (fMemoryManager) XMLAttr ( fEmptyNamespaceId , attNameRawBuf , attValueRawBuf , XMLAttDef::CData , true , fMemoryManager ); fAttrList->addElement(curAtt); fAttrNameHashList->addElement(attNameHash); } else { curAtt = fAttrList->elementAt(attCount); curAtt->set ( fEmptyNamespaceId , attNameRawBuf , attValueRawBuf ); curAtt->setSpecified(true); fAttrNameHashList->setElementAt(attNameHash, attCount); } // Make sure that the name is basically well formed for namespace // enabled rules. It either has no colons, or it has one which // is neither the first or last char. const int colonFirst = XMLString::indexOf(attNameRawBuf, chColon); if (colonFirst != -1) { const int colonLast = XMLString::lastIndexOf(attNameRawBuf, chColon); if (colonFirst != colonLast) { emitError(XMLErrs::TooManyColonsInName); continue; } else if ((colonFirst == 0) || (colonLast == (int)fAttNameBuf.getLen() - 1)) { emitError(XMLErrs::InvalidColonPos); continue; } } // Map prefix to namespace const XMLCh* attPrefix = curAtt->getPrefix(); const XMLCh* attLocalName = curAtt->getName(); const XMLCh* namespaceURI = fAttValueBuf.getRawBuffer(); if (attPrefix && *attPrefix) { if (XMLString::equals(attPrefix, XMLUni::fgXMLString)) { curAtt->setURIId(fXMLNamespaceId); } else if (XMLString::equals(attPrefix, XMLUni::fgXMLNSString)) { if (XMLString::equals(attLocalName, XMLUni::fgXMLNSString)) emitError(XMLErrs::NoUseOfxmlnsAsPrefix); else if (XMLString::equals(attLocalName, XMLUni::fgXMLString)) { if (!XMLString::equals(namespaceURI, XMLUni::fgXMLURIName)) emitError(XMLErrs::PrefixXMLNotMatchXMLURI); } if (!namespaceURI) emitError(XMLErrs::NoEmptyStrNamespace, attNameRawBuf); else if(!*namespaceURI && fXMLVersion == XMLReader::XMLV1_0) emitError(XMLErrs::NoEmptyStrNamespace, attNameRawBuf); fElemStack.addPrefix ( attLocalName , fURIStringPool->addOrFind(namespaceURI) ); curAtt->setURIId(fXMLNSNamespaceId); } else { fAttrNSList->addElement(curAtt); } } else { if (XMLString::equals(XMLUni::fgXMLNSString, attLocalName)) { if (XMLString::equals(namespaceURI, XMLUni::fgXMLNSURIName)) emitError(XMLErrs::NoUseOfxmlnsURI); else if (XMLString::equals(namespaceURI, XMLUni::fgXMLURIName)) emitError(XMLErrs::XMLURINotMatchXMLPrefix); fElemStack.addPrefix ( XMLUni::fgZeroLenString , fURIStringPool->addOrFind(namespaceURI) ); } } // increment attribute count attCount++; // And jump back to the top of the loop continue; } // It was some special case character so do all of the checks and // deal with it. if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); if (nextCh == chForwardSlash) { fReaderMgr.getNextChar(); isEmpty = true; if (!fReaderMgr.skippedChar(chCloseAngle)) emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); break; } else if (nextCh == chCloseAngle) { fReaderMgr.getNextChar(); break; } else if (nextCh == chOpenAngle) { // Check for this one specially, since its going to be common // and it is kind of auto-recovering since we've already hit the // next open bracket, which is what we would have seeked to (and // skipped this whole tag.) emitError(XMLErrs::UnterminatedStartTag, qnameRawBuf); break; } else if ((nextCh == chSingleQuote) || (nextCh == chDoubleQuote)) { // Check for this one specially, which is probably a missing // attribute name, e.g. ="value". Just issue expected name // error and eat the quoted string, then jump back to the // top again. emitError(XMLErrs::ExpectedAttrName); fReaderMgr.getNextChar(); fReaderMgr.skipQuotedString(nextCh); fReaderMgr.skipPastSpaces(); continue; } } // Handle provided attributes that we did not map their prefixes for (unsigned int i=0; i < fAttrNSList->size(); i++) { XMLAttr* providedAttr = fAttrNSList->elementAt(i); providedAttr->setURIId ( resolvePrefix ( providedAttr->getPrefix(), ElemStack::Mode_Attribute ) ); } if(attCount) { // // Decide if to use hash table to do duplicate checking // bool toUseHashTable = false; setAttrDupChkRegistry(attCount, toUseHashTable); // check for duplicate namespace attributes: // by checking for qualified names with the same local part and with prefixes // which have been bound to namespace names that are identical. XMLAttr* loopAttr; XMLAttr* curAtt; for (unsigned int attrIndex=0; attrIndex < attCount-1; attrIndex++) { loopAttr = fAttrList->elementAt(attrIndex); if (!toUseHashTable) { for (unsigned int curAttrIndex = attrIndex+1; curAttrIndex < attCount; curAttrIndex++) { curAtt = fAttrList->elementAt(curAttrIndex); if (curAtt->getURIId() == loopAttr->getURIId() && XMLString::equals(curAtt->getName(), loopAttr->getName())) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , curAtt->getName() , elemDecl->getFullName() ); } } } else { if (fAttrDupChkRegistry->containsKey((void*)loopAttr->getName(), loopAttr->getURIId())) { emitError ( XMLErrs::AttrAlreadyUsedInSTag , loopAttr->getName() , elemDecl->getFullName() ); } fAttrDupChkRegistry->put((void*)loopAttr->getName(), loopAttr->getURIId(), loopAttr); } } } // Resolve the qualified name to a URI. unsigned int uriId = resolvePrefix ( elemDecl->getElementName()->getPrefix() , ElemStack::Mode_Element ); // Now we can update the element stack fElemStack.setCurrentURI(uriId); // Tell the document handler about this start tag if (fDocHandler) { fDocHandler->startElement ( *elemDecl , uriId , elemDecl->getElementName()->getPrefix() , *fAttrList , attCount , false , isRoot ); } // If empty, validate content right now if we are validating and then // pop the element stack top. Else, we have to update the current stack // top's namespace mapping elements. if (isEmpty) { // Pop the element stack back off since it'll never be used now fElemStack.popTop(); // If we have a doc handler, tell it about the end tag if (fDocHandler) { fDocHandler->endElement ( *elemDecl , uriId , isRoot , elemDecl->getElementName()->getPrefix() ); } // If the elem stack is empty, then it was an empty root if (isRoot) gotData = false; } return true; } unsigned int WFXMLScanner::resolveQName(const XMLCh* const qName , XMLBuffer& prefixBuf , const short mode , int& prefixColonPos) { // Lets split out the qName into a URI and name buffer first. The URI // can be empty. prefixColonPos = XMLString::indexOf(qName, chColon); if (prefixColonPos == -1) { // Its all name with no prefix, so put the whole thing into the name // buffer. Then map the empty string to a URI, since the empty string // represents the default namespace. This will either return some // explicit URI which the default namespace is mapped to, or the // the default global namespace. bool unknown = false; prefixBuf.reset(); return fElemStack.mapPrefixToURI(XMLUni::fgZeroLenString, (ElemStack::MapModes) mode, unknown); } else { // Copy the chars up to but not including the colon into the prefix // buffer. prefixBuf.set(qName, prefixColonPos); // Watch for the special namespace prefixes. We always map these to // special URIs. 'xml' gets mapped to the official URI that its defined // to map to by the NS spec. xmlns gets mapped to a special place holder // URI that we define (so that it maps to something checkable.) const XMLCh* prefixRawBuf = prefixBuf.getRawBuffer(); if (XMLString::equals(prefixRawBuf, XMLUni::fgXMLNSString)) { // if this is an element, it is an error to have xmlns as prefix if (mode == ElemStack::Mode_Element) emitError(XMLErrs::NoXMLNSAsElementPrefix, qName); return fXMLNSNamespaceId; } else if (XMLString::equals(prefixRawBuf, XMLUni::fgXMLString)) { return fXMLNamespaceId; } else { bool unknown = false; unsigned int uriId = fElemStack.mapPrefixToURI(prefixRawBuf, (ElemStack::MapModes) mode, unknown); if (unknown) emitError(XMLErrs::UnknownPrefix, prefixRawBuf); return uriId; } } } // --------------------------------------------------------------------------- // XMLScanner: Private parsing methods // --------------------------------------------------------------------------- bool WFXMLScanner::scanAttValue(const XMLCh* const attrName , XMLBuffer& toFill) { // Reset the target buffer toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr.skipIfQuote(quoteCh)) return false; // We have to get the current reader because we have to ignore closing // quotes until we hit the same reader again. const unsigned int curReader = fReaderMgr.getCurrentReaderNum(); // Loop until we get the attribute value. Note that we use a double // loop here to avoid the setup/teardown overhead of the exception // handler on every round. XMLCh nextCh; XMLCh secondCh = 0; bool gotLeadingSurrogate = false; bool escaped; while (true) { try { while(true) { nextCh = fReaderMgr.getNextChar(); if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); // Check for our ending quote in the same entity if (nextCh == quoteCh) { if (curReader == fReaderMgr.getCurrentReaderNum()) return true; // Watch for spillover into a previous entity if (curReader > fReaderMgr.getCurrentReaderNum()) { emitError(XMLErrs::PartialMarkupInEntity); return false; } } // Check for an entity ref now, before we let it affect our // whitespace normalization logic below. We ignore the empty flag // in this one. escaped = false; if (nextCh == chAmpersand) { if (scanEntityRef(true, nextCh, secondCh, escaped) != EntityExp_Returned) { gotLeadingSurrogate = false; continue; } } else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Deal with surrogate pairs // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacterInAttrValue, attrName, tmpBuf); } } gotLeadingSurrogate = false; } // If its not escaped, then make sure its not a < character, which // is not allowed in attribute values. if (!escaped) { if (nextCh == chOpenAngle) emitError(XMLErrs::BracketInAttrValue, attrName); else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) nextCh = chSpace; } // Else add it to the buffer toFill.append(nextCh); if (secondCh) { toFill.append(secondCh); secondCh=0; } } } catch(const EndOfEntityException&) { // Just eat it and continue. gotLeadingSurrogate = false; escaped = false; } } return true; } // This method scans a CDATA section. It collects the character into one // of the temp buffers and calls the document handler, if any, with the // characters. It assumes that the <![CDATA string has been scanned before // this call. void WFXMLScanner::scanCDSection() { static const XMLCh CDataClose[] = { chCloseSquare, chCloseAngle, chNull }; // The next character should be the opening square bracket. If not // issue an error, but then try to recover by skipping any whitespace // and checking again. if (!fReaderMgr.skippedChar(chOpenSquare)) { emitError(XMLErrs::ExpectedOpenSquareBracket); fReaderMgr.skipPastSpaces(); // If we still don't find it, then give up, else keep going if (!fReaderMgr.skippedChar(chOpenSquare)) return; } // Get a buffer for this XMLBufBid bbCData(&fBufMgr); // We just scan forward until we hit the end of CDATA section sequence. // CDATA is effectively a big escape mechanism so we don't treat markup // characters specially here. bool emittedError = false; bool gotLeadingSurrogate = false; while (true) { const XMLCh nextCh = fReaderMgr.getNextChar(); // Watch for unexpected end of file if (!nextCh) { emitError(XMLErrs::UnterminatedCDATASection); ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); } // If this is a close square bracket it could be our closing // sequence. if (nextCh == chCloseSquare && fReaderMgr.skippedString(CDataClose)) { // make sure we were not expecting a trailing surrogate. if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); // If we have a doc handler, call it if (fDocHandler) { fDocHandler->docCharacters ( bbCData.getRawBuffer() , bbCData.getLen() , true ); } // And we are done break; } // Make sure its a valid character. But if we've emitted an error // already, don't bother with the overhead since we've already told // them about it. if (!emittedError) { // Deal with surrogate pairs if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacter, tmpBuf); emittedError = true; } } gotLeadingSurrogate = false; } } // Add it to the buffer bbCData.append(nextCh); } } void WFXMLScanner::scanCharData(XMLBuffer& toUse) { // We have to watch for the stupid ]]> sequence, which is illegal in // character data. So this is a little state machine that handles that. enum States { State_Waiting , State_GotOne , State_GotTwo }; // Reset the buffer before we start toUse.reset(); // Turn on the 'throw at end' flag of the reader manager ThrowEOEJanitor jan(&fReaderMgr, true); // In order to be more efficient we have to use kind of a deeply nested // set of blocks here. The outer block puts on a try and catches end of // entity exceptions. The inner loop is the per-character loop. If we // put the try inside the inner loop, it would work but would require // the exception handling code setup/teardown code to be invoked for // each character. XMLCh nextCh; XMLCh secondCh = 0; States curState = State_Waiting; bool escaped = false; bool gotLeadingSurrogate = false; bool notDone = true; while (notDone) { try { while (true) { // Eat through as many plain content characters as possible without // needing special handling. Moving most content characters here, // in this one call, rather than running the overall loop once // per content character, is a speed optimization. if (curState == State_Waiting && !gotLeadingSurrogate) { fReaderMgr.movePlainContentChars(toUse); } // Try to get another char from the source // The code from here on down covers all contengencies, if (!fReaderMgr.getNextCharIfNot(chOpenAngle, nextCh)) { // If we were waiting for a trailing surrogate, its an error if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); notDone = false; break; } // Watch for a reference. Note that the escapement mechanism // is ignored in this content. escaped = false; if (nextCh == chAmpersand) { sendCharData(toUse); // Turn off the throwing at the end of entity during this ThrowEOEJanitor jan(&fReaderMgr, false); if (scanEntityRef(false, nextCh, secondCh, escaped) != EntityExp_Returned) { gotLeadingSurrogate = false; continue; } } else if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { // Deal with surrogate pairs // Its a leading surrogate. If we already got one, then // issue an error, else set leading flag to make sure that // we look for a trailing next time. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } else gotLeadingSurrogate = true; } else { // If its a trailing surrogate, make sure that we are // prepared for that. Else, its just a regular char so make // sure that we were not expected a trailing surrogate. if ((nextCh >= 0xDC00) && (nextCh <= 0xDFFF)) { // Its trailing, so make sure we were expecting it if (!gotLeadingSurrogate) emitError(XMLErrs::Unexpected2ndSurrogateChar); } else { // Its just a char, so make sure we were not expecting a // trailing surrogate. if (gotLeadingSurrogate) { emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacter, tmpBuf); } } gotLeadingSurrogate = false; } // Keep the state machine up to date if (!escaped) { if (nextCh == chCloseSquare) { if (curState == State_Waiting) curState = State_GotOne; else if (curState == State_GotOne) curState = State_GotTwo; } else if (nextCh == chCloseAngle) { if (curState == State_GotTwo) emitError(XMLErrs::BadSequenceInCharData); curState = State_Waiting; } else { curState = State_Waiting; } } else { curState = State_Waiting; } // Add this char to the buffer toUse.append(nextCh); if (secondCh) { toUse.append(secondCh); secondCh=0; } } } catch(const EndOfEntityException& toCatch) { // Some entity ended, so we have to send any accumulated // chars and send an end of entity event. sendCharData(toUse); gotLeadingSurrogate = false; if (fDocHandler) fDocHandler->endEntityReference(toCatch.getEntity()); } } // Send any char data that we accumulated into the buffer sendCharData(toUse); } InputSource* WFXMLScanner::resolveSystemId(const XMLCh* const) { return 0; } // This method will scan a general/character entity ref. It will either // expand a char ref and return it directly, or push a reader for a general // entity. // // The return value indicates whether the char parameters hold the value // or whether the value was pushed as a reader, or that it failed. // // The escaped flag tells the caller whether the returned parameter resulted // from a character reference, which escapes the character in some cases. It // only makes any difference if the return value indicates the value was // returned directly. XMLScanner::EntityExpRes WFXMLScanner::scanEntityRef(const bool , XMLCh& firstCh , XMLCh& secondCh , bool& escaped) { // Assume no escape secondCh = 0; escaped = false; // We have to insure that its all in one entity const unsigned int curReader = fReaderMgr.getCurrentReaderNum(); // If the next char is a pound, then its a character reference and we // need to expand it always. if (fReaderMgr.skippedChar(chPound)) { // Its a character reference, so scan it and get back the numeric // value it represents. if (!scanCharRef(firstCh, secondCh)) return EntityExp_Failed; escaped = true; if (curReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); return EntityExp_Returned; } // Expand it since its a normal entity ref XMLBufBid bbName(&fBufMgr); if (!fReaderMgr.getName(bbName.getBuffer())) { emitError(XMLErrs::ExpectedEntityRefName); return EntityExp_Failed; } // Next char must be a semi-colon. But if its not, just emit // an error and try to continue. if (!fReaderMgr.skippedChar(chSemiColon)) emitError(XMLErrs::UnterminatedEntityRef, bbName.getRawBuffer()); // Make sure we ended up on the same entity reader as the & char if (curReader != fReaderMgr.getCurrentReaderNum()) emitError(XMLErrs::PartialMarkupInEntity); // Look up the name in the general entity pool // If it does not exist, then obviously an error if (!fEntityTable->containsKey(bbName.getRawBuffer())) { // XML 1.0 Section 4.1 // Well-formedness Constraint for entity not found: // In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, // or a document with "standalone='yes'", for an entity reference that does not occur within the external subset // or a parameter entity if (fStandalone || fHasNoDTD) emitError(XMLErrs::EntityNotFound, bbName.getRawBuffer()); return EntityExp_Failed; } // here's where we need to check if there's a SecurityManager, // how many entity references we've had if(fSecurityManager != 0 && ++fEntityExpansionCount > fEntityExpansionLimit) { XMLCh expLimStr[16]; XMLString::binToText(fEntityExpansionLimit, expLimStr, 15, 10, fMemoryManager); emitError ( XMLErrs::EntityExpansionLimitExceeded , expLimStr ); // there seems nothing better to be done than to reset the entity expansion counter fEntityExpansionCount = 0; } firstCh = fEntityTable->get(bbName.getRawBuffer()); escaped = true; return EntityExp_Returned; } // --------------------------------------------------------------------------- // WFXMLScanner: Grammar preparsing // --------------------------------------------------------------------------- Grammar* WFXMLScanner::loadGrammar(const InputSource& , const short , const bool) { // REVISIT: emit a warning or throw an exception return 0; } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 2165 ] ] ]
81f4eaf9b08f800ec35ad9b533fb5905aeb8a3b5
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/rules/src/Kampftechnik.cpp
e13b0706fd13646fcf692fe931b5a8210360bfd2
[ "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,818
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 "Kampftechnik.h" #include "DsaManager.h" namespace rl { Kampftechnik::Kampftechnik(const CeGuiString name, const CeGuiString description, int ebe) : mName(name), mDescription(description), mEbe(ebe) { } bool Kampftechnik::operator==(const Kampftechnik& rhs) const { return mName == rhs.mName; } bool Kampftechnik::operator<(const Kampftechnik& rhs) const { return mName < rhs.mName; } CeGuiString Kampftechnik::getName() const { return mName; } CeGuiString Kampftechnik::getDescription() const { return mDescription; } int Kampftechnik::getEbe() const { return mEbe; } int Kampftechnik::calculateEbe(int be) const { if (mEbe == EBE_KEINE_BE) return 0; if (mEbe == EBE_BEx2) return be*2; return std::max(be + mEbe, 0); } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 67 ] ] ]
58d8b2ab7161e9536564778d6f8d0b6f2673b9cd
205069c97095da8f15e45cede1525f384ba6efd2
/Casino/Code/Server/Tool/DataBaseTool/stdafx.cpp
5fb561d70cba0ec3f0a831c699d35f650028372d
[]
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
170
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // DataBaseTool.pch 将是预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ [ [ 1, 7 ] ] ]
b1b5daa9f2d36712dec7833abecc69a1ff973306
4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8
/Trunk/Battle Cars/Battle Cars/Source/CAttackState.h
45f2a44e0eba6b6a18a67ea0ca2893b31be75e14
[]
no_license
FiveFourFive/battle-cars
5f2046e7afe5ac50eeeb9129b87fcb4b2893386c
1809cce27a975376b0b087a96835347069fe2d4c
refs/heads/master
2021-05-29T19:52:25.782568
2011-07-28T17:48:39
2011-07-28T17:48:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,114
h
///////////////////////////////////////////////// // File : "CAttackState.h" // // Author : John Rostick // // Purpose : Enemy Attack State declarations // // ///////////////////////////////////////////////// #ifndef _CATTACKSTATE_H_ #define _CATTACKSTATE_H_ //#include <Windows.h> #include "IAIBaseState.h" #include "SGD_Math.h" class CEnemy; class CCar; class CAttackState : public IAIBaseState { private: // member variables CEnemy* m_Owner; CCar* m_Target; float m_fAggroRadius; float m_fFireRate; float m_fFireTimer; void Chase(float fElapsedTime); bool StillThreat(void); bool Damaged(void); CAttackState(const CAttackState&); CAttackState& operator = (const CAttackState&); public: CAttackState(void){}; ~CAttackState(void){}; void Update (float fElapsedTime); void Render (); void Enter (); void Exit (); //Accessors CEnemy* GetOwner() {return m_Owner;} CCar* GetTarget() {return m_Target;} //Mutators void SetOwner(CEnemy* pOwner) {m_Owner = pOwner;} void SetTarget(CCar* pTarget) {m_Target = pTarget;} }; #endif
[ "[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330", "[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330", "[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330" ]
[ [ [ 1, 17 ], [ 19, 24 ], [ 26, 36 ], [ 40, 47 ], [ 49, 50 ], [ 52, 54 ] ], [ [ 18, 18 ], [ 25, 25 ], [ 48, 48 ], [ 51, 51 ] ], [ [ 37, 39 ] ] ]
1ccccafe0a70ac91c884829acb47d290ccc115af
c66499a43b01dc474b85e1b74f871870f0e8d5ed
/MSADataProtector/src/MSADataProtector.cpp
a2a6606c1ed1179ff6ed56ae0190ae301414ba46
[]
no_license
joshuajnoble/msalibs
c50e58530514dc750eb21c3ddb37289959a58d42
d6da5bd33e90f22dec002a439540baa144bd5ee0
refs/heads/master
2021-01-16T23:02:09.205880
2011-08-06T09:42:21
2011-08-06T09:42:21
1,996,246
1
1
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
/*********************************************************************** Copyright (c) 2008, 2009, 2010, Memo Akten, www.memo.tv *** The Mega Super Awesome Visuals Company *** * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of MSA Visuals nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * ***********************************************************************/ #include "MSADataProtector.h" #include "hashlibpp.h" #include "MSAUtils.h" namespace MSA { using namespace std; bool checkFileMD5(string filename, string checkAgainstHash, bool bExitOnFalse) { // printf("Checking file %s\n", filename.c_str()); md5wrapper md5; string path = dataPath(filename); string currentHash = md5.getHashFromFile(path); bool isCorrect = checkAgainstHash.compare(currentHash) == 0; if(bExitOnFalse == false) { printf("%s: %s\n", filename.c_str(), currentHash.c_str()); // use this to see what correct hash should be } else if(!isCorrect) { showDialog("**** DATA CORRUPT ****", "The data files have been tampered with, please contact [email protected] for help.", 2); printf(" **** DATA CORRUPT **** "); std:exit(0); } return isCorrect; } }
[ [ [ 1, 34 ], [ 36, 41 ], [ 43, 49 ], [ 51, 51 ], [ 53, 60 ] ], [ [ 35, 35 ], [ 42, 42 ], [ 50, 50 ], [ 52, 52 ] ] ]
f2e24df3087f625cf14e58666016b8d640a1be41
8020ee737f9d88efac93bba3b9ff4e03bb96ff2a
/src/breakout.h
fc810999704a271579a0d22d423324906dfe2b97
[ "WTFPL" ]
permissive
osgcc/osgcc2-OMGWTFADD
f4169c06436ae0357e9143015ccf671041925154
2ec7d0de5deea28980c5d4e66501406e71f36205
refs/heads/master
2020-08-23T16:28:06.086903
2010-03-11T22:14:47
2010-03-11T22:14:47
823,620
2
0
null
null
null
null
UTF-8
C++
false
false
979
h
#ifndef BREAKOUT_INCLUDED #define BREAKOUT_INCLUDED #include "game.h" class BreakOut : public Game { public: // conventions: void InitGame(game_info* gi); void Update(game_info* gi, float deltatime); void Draw(game_info* gi); void DrawOrtho(game_info* gi); void KeyDown(game_info* gi, Uint32 key); void KeyUp(game_info* gi, Uint32 key); void KeyRepeat(game_info* gi); void MouseMovement(game_info* gi, Uint32 x, Uint32 y); void MouseDown(game_info* gi); void Attack(game_info* gi, int severity); // --- float GetLeftBounds(game_info* gi); float GetRightBounds(game_info* gi); void DrawBall(game_info* gi); void MoveBall(game_info* gi, float t, int last_type); float CheckBallAgainst(game_info* gi, float t, float x1, float y1, float x2, float y2); bool CheckBallAgainstBlock(game_info* gi, float t, float &cur_t, int &type_t, int last_type, float x, float y, int isPaddle); }; #endif //BREAKOUT_INCLUDED
[ [ [ 1, 41 ] ] ]
393f1ff91c6ab2f26afc0e84286333dcae8035aa
fb4cf44e2c146b26ddde6350180cc420611fe17a
/SDK/CvPlayer.cpp
ab6cf6622285588280de33c7d4865f1e299bb4b4
[]
no_license
dharkness/civ4bullai
93e0685ef53e404ac4ffa5c1aecf4edaf61acd61
e56c8a4f1172e2d2b15eb87eaa78adb9d357fae6
refs/heads/master
2022-09-15T23:31:55.030351
2010-11-13T07:23:13
2010-11-13T07:23:13
267,723,017
0
0
null
null
null
null
UTF-8
C++
false
false
638,815
cpp
// player.cpp #include "CvGameCoreDLL.h" #include "CvGlobals.h" #include "CvArea.h" #include "CvGameAI.h" #include "CvMap.h" #include "CvPlot.h" #include "CvRandom.h" #include "CvTeamAI.h" #include "CvGameCoreUtils.h" #include "CvPlayerAI.h" #include "CvPlayer.h" #include "CvGameCoreUtils.h" #include "CvArtFileMgr.h" #include "CvDiploParameters.h" #include "CvInitCore.h" #include "CyArgsList.h" #include "CvInfos.h" #include "CvPopupInfo.h" #include "CvDiploParameters.h" #include "FProfiler.h" #include "CvGameTextMgr.h" #include "CyCity.h" #include "CyPlot.h" #include "CyUnit.h" #include "CvEventReporter.h" #include "CvDLLInterfaceIFaceBase.h" #include "CvDLLEntityIFaceBase.h" #include "CvDLLEngineIFaceBase.h" #include "CvDLLFAStarIFaceBase.h" #include "CvDLLPythonIFaceBase.h" /************************************************************************************************/ /* BETTER_BTS_AI_MOD 05/09/09 jdog5000 */ /* */ /* General AI */ /************************************************************************************************/ #include "CvDLLFlagEntityIFaceBase.h" /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ #include "BetterBTSAI.h" /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ // BUG - Ignore Harmless Barbarians - start #include "CvBugOptions.h" // BUG - Ignore Harmless Barbarians - end // Public Functions... CvPlayer::CvPlayer() { m_aiSeaPlotYield = new int[NUM_YIELD_TYPES]; m_aiYieldRateModifier = new int[NUM_YIELD_TYPES]; m_aiCapitalYieldRateModifier = new int[NUM_YIELD_TYPES]; m_aiExtraYieldThreshold = new int[NUM_YIELD_TYPES]; m_aiTradeYieldModifier = new int[NUM_YIELD_TYPES]; m_aiFreeCityCommerce = new int[NUM_COMMERCE_TYPES]; m_aiCommercePercent = new int[NUM_COMMERCE_TYPES]; m_aiCommerceRate = new int[NUM_COMMERCE_TYPES]; m_aiCommerceRateModifier = new int[NUM_COMMERCE_TYPES]; m_aiCapitalCommerceRateModifier = new int[NUM_COMMERCE_TYPES]; m_aiStateReligionBuildingCommerce = new int[NUM_COMMERCE_TYPES]; m_aiSpecialistExtraCommerce = new int[NUM_COMMERCE_TYPES]; m_aiCommerceFlexibleCount = new int[NUM_COMMERCE_TYPES]; m_aiGoldPerTurnByPlayer = new int[MAX_PLAYERS]; m_aiEspionageSpendingWeightAgainstTeam = new int[MAX_TEAMS]; m_abFeatAccomplished = new bool[NUM_FEAT_TYPES]; m_abOptions = new bool[NUM_PLAYEROPTION_TYPES]; m_paiBonusExport = NULL; m_paiBonusImport = NULL; m_paiImprovementCount = NULL; m_paiFreeBuildingCount = NULL; m_paiExtraBuildingHappiness = NULL; m_paiExtraBuildingHealth = NULL; m_paiFeatureHappiness = NULL; m_paiUnitClassCount = NULL; m_paiUnitClassMaking = NULL; m_paiBuildingClassCount = NULL; m_paiBuildingClassMaking = NULL; m_paiHurryCount = NULL; m_paiSpecialBuildingNotRequiredCount = NULL; m_paiHasCivicOptionCount = NULL; m_paiNoCivicUpkeepCount = NULL; m_paiHasReligionCount = NULL; m_paiHasCorporationCount = NULL; m_paiUpkeepCount = NULL; m_paiSpecialistValidCount = NULL; m_pabResearchingTech = NULL; m_pabLoyalMember = NULL; m_paeCivics = NULL; m_ppaaiSpecialistExtraYield = NULL; m_ppaaiImprovementYieldChange = NULL; /************************************************************************************************/ /* AI_AUTO_PLAY_MOD 09/01/07 MRGENIE */ /* */ /* */ /************************************************************************************************/ m_bDisableHuman = false; /************************************************************************************************/ /* AI_AUTO_PLAY_MOD END */ /************************************************************************************************/ /************************************************************************************************/ /* UNOFFICIAL_PATCH 12/07/09 EmperorFool */ /* */ /* Bugfix */ /************************************************************************************************/ // Free Tech Popup Fix m_bChoosingFreeTech = false; /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ reset(NO_PLAYER, true); } CvPlayer::~CvPlayer() { uninit(); SAFE_DELETE_ARRAY(m_aiSeaPlotYield); SAFE_DELETE_ARRAY(m_aiYieldRateModifier); SAFE_DELETE_ARRAY(m_aiCapitalYieldRateModifier); SAFE_DELETE_ARRAY(m_aiExtraYieldThreshold); SAFE_DELETE_ARRAY(m_aiTradeYieldModifier); SAFE_DELETE_ARRAY(m_aiFreeCityCommerce); SAFE_DELETE_ARRAY(m_aiCommercePercent); SAFE_DELETE_ARRAY(m_aiCommerceRate); SAFE_DELETE_ARRAY(m_aiCommerceRateModifier); SAFE_DELETE_ARRAY(m_aiCapitalCommerceRateModifier); SAFE_DELETE_ARRAY(m_aiStateReligionBuildingCommerce); SAFE_DELETE_ARRAY(m_aiSpecialistExtraCommerce); SAFE_DELETE_ARRAY(m_aiCommerceFlexibleCount); SAFE_DELETE_ARRAY(m_aiGoldPerTurnByPlayer); SAFE_DELETE_ARRAY(m_aiEspionageSpendingWeightAgainstTeam); SAFE_DELETE_ARRAY(m_abFeatAccomplished); SAFE_DELETE_ARRAY(m_abOptions); } void CvPlayer::init(PlayerTypes eID) { LeaderHeadTypes eBestPersonality; int iValue; int iBestValue; int iI, iJ; //-------------------------------- // Init saved data reset(eID); //-------------------------------- // Init containers m_plotGroups.init(); m_cities.init(); m_units.init(); m_selectionGroups.init(); m_eventsTriggered.init(); //-------------------------------- // Init non-saved data setupGraphical(); //-------------------------------- // Init other game data FAssert(getTeam() != NO_TEAM); GET_TEAM(getTeam()).changeNumMembers(1); if ((GC.getInitCore().getSlotStatus(getID()) == SS_TAKEN) || (GC.getInitCore().getSlotStatus(getID()) == SS_COMPUTER)) { setAlive(true); if (GC.getGameINLINE().isOption(GAMEOPTION_RANDOM_PERSONALITIES)) { if (!isBarbarian() && !isMinorCiv()) { iBestValue = 0; eBestPersonality = NO_LEADER; for (iI = 0; iI < GC.getNumLeaderHeadInfos(); iI++) { if (iI != GC.getDefineINT("BARBARIAN_LEADER")) // XXX minor civ??? { iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "Choosing Personality")); for (iJ = 0; iJ < MAX_CIV_PLAYERS; iJ++) { if (GET_PLAYER((PlayerTypes)iJ).isAlive()) { if (GET_PLAYER((PlayerTypes)iJ).getPersonalityType() == ((LeaderHeadTypes)iI)) { iValue /= 2; } } } if (iValue > iBestValue) { iBestValue = iValue; eBestPersonality = ((LeaderHeadTypes)iI); } } } if (eBestPersonality != NO_LEADER) { setPersonalityType(eBestPersonality); } } } changeBaseFreeUnits(GC.getDefineINT("INITIAL_BASE_FREE_UNITS")); changeBaseFreeMilitaryUnits(GC.getDefineINT("INITIAL_BASE_FREE_MILITARY_UNITS")); changeFreeUnitsPopulationPercent(GC.getDefineINT("INITIAL_FREE_UNITS_POPULATION_PERCENT")); changeFreeMilitaryUnitsPopulationPercent(GC.getDefineINT("INITIAL_FREE_MILITARY_UNITS_POPULATION_PERCENT")); changeGoldPerUnit(GC.getDefineINT("INITIAL_GOLD_PER_UNIT")); changeTradeRoutes(GC.getDefineINT("INITIAL_TRADE_ROUTES")); changeStateReligionHappiness(GC.getDefineINT("INITIAL_STATE_RELIGION_HAPPINESS")); changeNonStateReligionHappiness(GC.getDefineINT("INITIAL_NON_STATE_RELIGION_HAPPINESS")); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { changeTradeYieldModifier(((YieldTypes)iI), GC.getYieldInfo((YieldTypes)iI).getTradeModifier()); } for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { setCommercePercent(((CommerceTypes)iI), GC.getCommerceInfo((CommerceTypes)iI).getInitialPercent()); } FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvPlayer::init"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { changeExtraHealth(GC.getTraitInfo((TraitTypes)iI).getHealth()); changeExtraHappiness(GC.getTraitInfo((TraitTypes)iI).getHappiness()); for (iJ = 0; iJ < GC.getNumBuildingInfos(); iJ++) { changeExtraBuildingHappiness((BuildingTypes)iJ, GC.getBuildingInfo((BuildingTypes)iJ).getHappinessTraits(iI)); } changeUpkeepModifier(GC.getTraitInfo((TraitTypes)iI).getUpkeepModifier()); changeLevelExperienceModifier(GC.getTraitInfo((TraitTypes)iI).getLevelExperienceModifier()); changeGreatPeopleRateModifier(GC.getTraitInfo((TraitTypes)iI).getGreatPeopleRateModifier()); changeGreatGeneralRateModifier(GC.getTraitInfo((TraitTypes)iI).getGreatGeneralRateModifier()); changeDomesticGreatGeneralRateModifier(GC.getTraitInfo((TraitTypes)iI).getDomesticGreatGeneralRateModifier()); changeMaxGlobalBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxGlobalBuildingProductionModifier()); changeMaxTeamBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxTeamBuildingProductionModifier()); changeMaxPlayerBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxPlayerBuildingProductionModifier()); for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { changeTradeYieldModifier(((YieldTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getTradeYieldModifier(iJ)); } for (iJ = 0; iJ < NUM_COMMERCE_TYPES; iJ++) { changeFreeCityCommerce(((CommerceTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getCommerceChange(iJ)); changeCommerceRateModifier(((CommerceTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getCommerceModifier(iJ)); } for (iJ = 0; iJ < GC.getNumCivicOptionInfos(); iJ++) { if (GC.getCivicOptionInfo((CivicOptionTypes) iJ).getTraitNoUpkeep(iI)) { changeNoCivicUpkeepCount(((CivicOptionTypes)iJ), 1); } } } } updateMaxAnarchyTurns(); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { updateExtraYieldThreshold((YieldTypes)iI); } for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { setCivics(((CivicOptionTypes)iI), ((CivicTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationInitialCivics(iI)))); } for (iI = 0; iI < GC.getNumEventInfos(); iI++) { resetEventOccured((EventTypes)iI, false); } for (iI = 0; iI < GC.getNumEventTriggerInfos(); iI++) { resetTriggerFired((EventTriggerTypes)iI); } for (iI = 0; iI < GC.getNumUnitClassInfos(); ++iI) { UnitTypes eUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(iI))); if (NO_UNIT != eUnit) { if (GC.getUnitInfo(eUnit).isFound()) { setUnitExtraCost((UnitClassTypes)iI, getNewCityProductionValue()); } } } } AI_init(); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD 12/30/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // Copy of CvPlayer::init but with modifications for use in the middle of a game // void CvPlayer::initInGame(PlayerTypes eID) { LeaderHeadTypes eBestPersonality; int iValue; int iBestValue; int iI, iJ; //-------------------------------- // Init saved data reset(eID); //-------------------------------- // Init containers m_plotGroups.init(); m_cities.init(); m_units.init(); m_selectionGroups.init(); m_eventsTriggered.init(); //-------------------------------- // Init non-saved data setupGraphical(); //-------------------------------- // Init other game data FAssert(getTeam() != NO_TEAM); // Some effects on team necessary if this is the only member of the team int iOtherTeamMembers = 0; for (iI = 0; iI < MAX_CIV_PLAYERS; iI++) { if( iI != getID() ) { if( GET_PLAYER((PlayerTypes)iI).getTeam() == getTeam() ) { iOtherTeamMembers++; } } } bool bTeamInit = false; if( (iOtherTeamMembers == 0) || GET_TEAM(getTeam()).getNumMembers() == 0 ) { bTeamInit = true; GET_TEAM(getTeam()).init(getTeam()); GET_TEAM(getTeam()).resetPlotAndCityData(); } if( bTeamInit || (GET_TEAM(getTeam()).getNumMembers() == iOtherTeamMembers) ) { GET_TEAM(getTeam()).changeNumMembers(1); } if ((GC.getInitCore().getSlotStatus(getID()) == SS_TAKEN) || (GC.getInitCore().getSlotStatus(getID()) == SS_COMPUTER)) { setAlive(true); if (GC.getGameINLINE().isOption(GAMEOPTION_RANDOM_PERSONALITIES)) { if (!isBarbarian() && !isMinorCiv()) { iBestValue = 0; eBestPersonality = NO_LEADER; for (iI = 0; iI < GC.getNumLeaderHeadInfos(); iI++) { if (iI != GC.getDefineINT("BARBARIAN_LEADER")) // XXX minor civ??? { iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "Choosing Personality")); for (iJ = 0; iJ < MAX_CIV_PLAYERS; iJ++) { if (GET_PLAYER((PlayerTypes)iJ).isAlive()) { if (GET_PLAYER((PlayerTypes)iJ).getPersonalityType() == ((LeaderHeadTypes)iI)) { iValue /= 2; } } } if (iValue > iBestValue) { iBestValue = iValue; eBestPersonality = ((LeaderHeadTypes)iI); } } } if (eBestPersonality != NO_LEADER) { setPersonalityType(eBestPersonality); } } } changeBaseFreeUnits(GC.getDefineINT("INITIAL_BASE_FREE_UNITS")); changeBaseFreeMilitaryUnits(GC.getDefineINT("INITIAL_BASE_FREE_MILITARY_UNITS")); changeFreeUnitsPopulationPercent(GC.getDefineINT("INITIAL_FREE_UNITS_POPULATION_PERCENT")); changeFreeMilitaryUnitsPopulationPercent(GC.getDefineINT("INITIAL_FREE_MILITARY_UNITS_POPULATION_PERCENT")); changeGoldPerUnit(GC.getDefineINT("INITIAL_GOLD_PER_UNIT")); changeTradeRoutes(GC.getDefineINT("INITIAL_TRADE_ROUTES")); changeStateReligionHappiness(GC.getDefineINT("INITIAL_STATE_RELIGION_HAPPINESS")); changeNonStateReligionHappiness(GC.getDefineINT("INITIAL_NON_STATE_RELIGION_HAPPINESS")); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { changeTradeYieldModifier(((YieldTypes)iI), GC.getYieldInfo((YieldTypes)iI).getTradeModifier()); } for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { setCommercePercent(((CommerceTypes)iI), GC.getCommerceInfo((CommerceTypes)iI).getInitialPercent()); } FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvPlayer::init"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { changeExtraHealth(GC.getTraitInfo((TraitTypes)iI).getHealth()); changeExtraHappiness(GC.getTraitInfo((TraitTypes)iI).getHappiness()); for (iJ = 0; iJ < GC.getNumBuildingInfos(); iJ++) { changeExtraBuildingHappiness((BuildingTypes)iJ, GC.getBuildingInfo((BuildingTypes)iJ).getHappinessTraits(iI)); } changeUpkeepModifier(GC.getTraitInfo((TraitTypes)iI).getUpkeepModifier()); changeLevelExperienceModifier(GC.getTraitInfo((TraitTypes)iI).getLevelExperienceModifier()); changeGreatPeopleRateModifier(GC.getTraitInfo((TraitTypes)iI).getGreatPeopleRateModifier()); changeGreatGeneralRateModifier(GC.getTraitInfo((TraitTypes)iI).getGreatGeneralRateModifier()); changeDomesticGreatGeneralRateModifier(GC.getTraitInfo((TraitTypes)iI).getDomesticGreatGeneralRateModifier()); changeMaxGlobalBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxGlobalBuildingProductionModifier()); changeMaxTeamBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxTeamBuildingProductionModifier()); changeMaxPlayerBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxPlayerBuildingProductionModifier()); for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { changeTradeYieldModifier(((YieldTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getTradeYieldModifier(iJ)); } for (iJ = 0; iJ < NUM_COMMERCE_TYPES; iJ++) { changeFreeCityCommerce(((CommerceTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getCommerceChange(iJ)); changeCommerceRateModifier(((CommerceTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getCommerceModifier(iJ)); } for (iJ = 0; iJ < GC.getNumCivicOptionInfos(); iJ++) { if (GC.getCivicOptionInfo((CivicOptionTypes) iJ).getTraitNoUpkeep(iI)) { changeNoCivicUpkeepCount(((CivicOptionTypes)iJ), 1); } } } } updateMaxAnarchyTurns(); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { updateExtraYieldThreshold((YieldTypes)iI); } for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { setCivics(((CivicOptionTypes)iI), ((CivicTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationInitialCivics(iI)))); } // Reset all triggers at first, set those whose events have fired in next block for (iI = 0; iI < GC.getNumEventTriggerInfos(); iI++) { resetTriggerFired((EventTriggerTypes)iI); } for (iI = 0; iI < GC.getNumEventInfos(); iI++) { /* original bts code resetEventOccured((EventTypes)iI, false); */ // Has global trigger fired already? const EventTriggeredData* pEvent = NULL; for (iJ = 0; iJ < MAX_CIV_PLAYERS; iJ++) { if( iJ != getID() ) { pEvent = GET_PLAYER((PlayerTypes)iJ).getEventOccured((EventTypes)iI); if ( pEvent != NULL ) { CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(pEvent->m_eTrigger); if( kTrigger.isGlobal() ) { setTriggerFired( *pEvent, false, false ); break; } else if( kTrigger.isTeam() && GET_PLAYER((PlayerTypes)iJ).getTeam() == getTeam() ) { setTriggerFired( *pEvent, false, false ); break; } } } } resetEventOccured((EventTypes)iI, false); } for (iI = 0; iI < GC.getNumUnitClassInfos(); ++iI) { UnitTypes eUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(iI))); if (NO_UNIT != eUnit) { if (GC.getUnitInfo(eUnit).isFound()) { setUnitExtraCost((UnitClassTypes)iI, getNewCityProductionValue()); } } } } resetPlotAndCityData(); AI_init(); } // // Reset all data for this player stored in plot and city objects // void CvPlayer::resetPlotAndCityData( ) { CvPlot* pLoopPlot; CvCity* pLoopCity; for (int iPlot = 0; iPlot < GC.getMapINLINE().numPlotsINLINE(); ++iPlot) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iPlot); pLoopPlot->setCulture(getID(), 0, false, false); pLoopPlot->setFoundValue(getID(), 0); pLoopCity = pLoopPlot->getPlotCity(); if( pLoopCity != NULL ) { pLoopCity->setCulture(getID(), 0, false, false); pLoopCity->changeNumRevolts(getID(), -pLoopCity->getNumRevolts(getID())); pLoopCity->setEverOwned(getID(), false); pLoopCity->setTradeRoute(getID(), false); } } } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ void CvPlayer::uninit() { SAFE_DELETE_ARRAY(m_paiBonusExport); SAFE_DELETE_ARRAY(m_paiBonusImport); SAFE_DELETE_ARRAY(m_paiImprovementCount); SAFE_DELETE_ARRAY(m_paiFreeBuildingCount); SAFE_DELETE_ARRAY(m_paiExtraBuildingHappiness); SAFE_DELETE_ARRAY(m_paiExtraBuildingHealth); SAFE_DELETE_ARRAY(m_paiFeatureHappiness); SAFE_DELETE_ARRAY(m_paiUnitClassCount); SAFE_DELETE_ARRAY(m_paiUnitClassMaking); SAFE_DELETE_ARRAY(m_paiBuildingClassCount); SAFE_DELETE_ARRAY(m_paiBuildingClassMaking); SAFE_DELETE_ARRAY(m_paiHurryCount); SAFE_DELETE_ARRAY(m_paiSpecialBuildingNotRequiredCount); SAFE_DELETE_ARRAY(m_paiHasCivicOptionCount); SAFE_DELETE_ARRAY(m_paiNoCivicUpkeepCount); SAFE_DELETE_ARRAY(m_paiHasReligionCount); SAFE_DELETE_ARRAY(m_paiHasCorporationCount); SAFE_DELETE_ARRAY(m_paiUpkeepCount); SAFE_DELETE_ARRAY(m_paiSpecialistValidCount); SAFE_DELETE_ARRAY(m_pabResearchingTech); SAFE_DELETE_ARRAY(m_pabLoyalMember); SAFE_DELETE_ARRAY(m_paeCivics); m_triggersFired.clear(); if (m_ppaaiSpecialistExtraYield != NULL) { for (int iI = 0; iI < GC.getNumSpecialistInfos(); iI++) { SAFE_DELETE_ARRAY(m_ppaaiSpecialistExtraYield[iI]); } SAFE_DELETE_ARRAY(m_ppaaiSpecialistExtraYield); } if (m_ppaaiImprovementYieldChange != NULL) { for (int iI = 0; iI < GC.getNumImprovementInfos(); iI++) { SAFE_DELETE_ARRAY(m_ppaaiImprovementYieldChange[iI]); } SAFE_DELETE_ARRAY(m_ppaaiImprovementYieldChange); } m_groupCycle.clear(); m_researchQueue.clear(); m_cityNames.clear(); m_plotGroups.uninit(); m_cities.uninit(); m_units.uninit(); m_selectionGroups.uninit(); m_eventsTriggered.uninit(); clearMessages(); clearPopups(); clearDiplomacy(); } // FUNCTION: reset() // Initializes data members that are serialized. void CvPlayer::reset(PlayerTypes eID, bool bConstructorCall) { int iI, iJ; //-------------------------------- // Uninit class uninit(); m_iStartingX = INVALID_PLOT_COORD; m_iStartingY = INVALID_PLOT_COORD; m_iTotalPopulation = 0; m_iTotalLand = 0; m_iTotalLandScored = 0; m_iGold = 0; m_iGoldPerTurn = 0; m_iAdvancedStartPoints = -1; m_iGoldenAgeTurns = 0; m_iNumUnitGoldenAges = 0; m_iStrikeTurns = 0; m_iAnarchyTurns = 0; m_iMaxAnarchyTurns = 0; m_iAnarchyModifier = 0; m_iGoldenAgeModifier = 0; m_iGlobalHurryModifier = 0; m_iGreatPeopleCreated = 0; m_iGreatGeneralsCreated = 0; m_iGreatPeopleThresholdModifier = 0; m_iGreatGeneralsThresholdModifier = 0; m_iGreatPeopleRateModifier = 0; m_iGreatGeneralRateModifier = 0; m_iDomesticGreatGeneralRateModifier = 0; m_iStateReligionGreatPeopleRateModifier = 0; m_iMaxGlobalBuildingProductionModifier = 0; m_iMaxTeamBuildingProductionModifier = 0; m_iMaxPlayerBuildingProductionModifier = 0; m_iFreeExperience = 0; m_iFeatureProductionModifier = 0; m_iWorkerSpeedModifier = 0; m_iImprovementUpgradeRateModifier = 0; m_iMilitaryProductionModifier = 0; m_iSpaceProductionModifier = 0; m_iCityDefenseModifier = 0; m_iNumNukeUnits = 0; m_iNumOutsideUnits = 0; m_iBaseFreeUnits = 0; m_iBaseFreeMilitaryUnits = 0; m_iFreeUnitsPopulationPercent = 0; m_iFreeMilitaryUnitsPopulationPercent = 0; m_iGoldPerUnit = 0; m_iGoldPerMilitaryUnit = 0; m_iExtraUnitCost = 0; m_iNumMilitaryUnits = 0; m_iHappyPerMilitaryUnit = 0; m_iMilitaryFoodProductionCount = 0; m_iConscriptCount = 0; m_iMaxConscript = 0; m_iHighestUnitLevel = 1; m_iOverflowResearch = 0; m_iNoUnhealthyPopulationCount = 0; m_iExpInBorderModifier = 0; m_iBuildingOnlyHealthyCount = 0; m_iDistanceMaintenanceModifier = 0; m_iNumCitiesMaintenanceModifier = 0; m_iCorporationMaintenanceModifier = 0; m_iTotalMaintenance = 0; m_iUpkeepModifier = 0; m_iLevelExperienceModifier = 0; m_iExtraHealth = 0; m_iBuildingGoodHealth = 0; m_iBuildingBadHealth = 0; m_iExtraHappiness = 0; m_iBuildingHappiness = 0; m_iLargestCityHappiness = 0; m_iWarWearinessPercentAnger = 0; m_iWarWearinessModifier = 0; m_iFreeSpecialist = 0; m_iNoForeignTradeCount = 0; m_iNoCorporationsCount = 0; m_iNoForeignCorporationsCount = 0; m_iCoastalTradeRoutes = 0; m_iTradeRoutes = 0; m_iRevolutionTimer = 0; m_iConversionTimer = 0; m_iStateReligionCount = 0; m_iNoNonStateReligionSpreadCount = 0; m_iStateReligionHappiness = 0; m_iNonStateReligionHappiness = 0; m_iStateReligionUnitProductionModifier = 0; m_iStateReligionBuildingProductionModifier = 0; m_iStateReligionFreeExperience = 0; m_iCapitalCityID = FFreeList::INVALID_INDEX; m_iCitiesLost = 0; m_iWinsVsBarbs = 0; m_iAssets = 0; m_iPower = 0; m_iPopulationScore = 0; m_iLandScore = 0; m_iTechScore = 0; m_iWondersScore = 0; m_iCombatExperience = 0; m_iPopRushHurryCount = 0; m_iInflationModifier = 0; m_uiStartTime = 0; m_bAlive = false; m_bEverAlive = false; m_bTurnActive = false; m_bAutoMoves = false; m_bEndTurn = false; m_bPbemNewTurn = false; m_bExtendedGame = false; m_bFoundedFirstCity = false; m_bStrike = false; /************************************************************************************************/ /* UNOFFICIAL_PATCH 12/07/09 EmperorFool */ /* */ /* Bugfix */ /************************************************************************************************/ // Free Tech Popup Fix m_bChoosingFreeTech = false; /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ /************************************************************************************************/ /* AI_AUTO_PLAY_MOD 09/01/07 MRGENIE */ /* */ /* */ /************************************************************************************************/ m_bDisableHuman = false; /************************************************************************************************/ /* AI_AUTO_PLAY_MOD END */ /************************************************************************************************/ m_eID = eID; updateTeamType(); updateHuman(); if (m_eID != NO_PLAYER) { m_ePersonalityType = GC.getInitCore().getLeader(m_eID); //??? Is this repeated data??? } else { m_ePersonalityType = NO_LEADER; } m_eCurrentEra = ((EraTypes)0); //??? Is this repeated data??? m_eLastStateReligion = NO_RELIGION; m_eParent = NO_PLAYER; for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { m_aiSeaPlotYield[iI] = 0; m_aiYieldRateModifier[iI] = 0; m_aiCapitalYieldRateModifier[iI] = 0; m_aiExtraYieldThreshold[iI] = 0; m_aiTradeYieldModifier[iI] = 0; } for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { m_aiFreeCityCommerce[iI] = 0; m_aiCommercePercent[iI] = 0; m_aiCommerceRate[iI] = 0; m_aiCommerceRateModifier[iI] = 0; m_aiCapitalCommerceRateModifier[iI] = 0; m_aiStateReligionBuildingCommerce[iI] = 0; m_aiSpecialistExtraCommerce[iI] = 0; m_aiCommerceFlexibleCount[iI] = 0; } for (iI = 0; iI < MAX_PLAYERS; iI++) { m_aiGoldPerTurnByPlayer[iI] = 0; if (!bConstructorCall && getID() != NO_PLAYER) { GET_PLAYER((PlayerTypes) iI).m_aiGoldPerTurnByPlayer[getID()] = 0; } } for (iI = 0; iI < MAX_TEAMS; iI++) { m_aiEspionageSpendingWeightAgainstTeam[iI] = 0; if (!bConstructorCall && getTeam() != NO_TEAM) { for (iJ = 0; iJ < MAX_PLAYERS; iJ++) { if (GET_PLAYER((PlayerTypes) iJ).getTeam() == iI) { GET_PLAYER((PlayerTypes) iJ).setEspionageSpendingWeightAgainstTeam(getTeam(), 0); } } } } for (iI = 0; iI < NUM_FEAT_TYPES; iI++) { m_abFeatAccomplished[iI] = false; } for (iI = 0; iI < NUM_PLAYEROPTION_TYPES; iI++) { m_abOptions[iI] = false; } m_szScriptData = ""; if (!bConstructorCall) { FAssertMsg(0 < GC.getNumBonusInfos(), "GC.getNumBonusInfos() is not greater than zero but it is used to allocate memory in CvPlayer::reset"); FAssertMsg(m_paiBonusExport==NULL, "about to leak memory, CvPlayer::m_paiBonusExport"); m_paiBonusExport = new int [GC.getNumBonusInfos()]; FAssertMsg(m_paiBonusImport==NULL, "about to leak memory, CvPlayer::m_paiBonusImport"); m_paiBonusImport = new int [GC.getNumBonusInfos()]; for (iI = 0; iI < GC.getNumBonusInfos(); iI++) { m_paiBonusExport[iI] = 0; m_paiBonusImport[iI] = 0; } FAssertMsg(0 < GC.getNumImprovementInfos(), "GC.getNumImprovementInfos() is not greater than zero but it is used to allocate memory in CvPlayer::reset"); FAssertMsg(m_paiImprovementCount==NULL, "about to leak memory, CvPlayer::m_paiImprovementCount"); m_paiImprovementCount = new int [GC.getNumImprovementInfos()]; for (iI = 0; iI < GC.getNumImprovementInfos(); iI++) { m_paiImprovementCount[iI] = 0; } FAssertMsg(m_paiFreeBuildingCount==NULL, "about to leak memory, CvPlayer::m_paiFreeBuildingCount"); m_paiFreeBuildingCount = new int [GC.getNumBuildingInfos()]; FAssertMsg(m_paiExtraBuildingHappiness==NULL, "about to leak memory, CvPlayer::m_paiExtraBuildingHappiness"); m_paiExtraBuildingHappiness = new int [GC.getNumBuildingInfos()]; FAssertMsg(m_paiExtraBuildingHealth==NULL, "about to leak memory, CvPlayer::m_paiExtraBuildingHealth"); m_paiExtraBuildingHealth = new int [GC.getNumBuildingInfos()]; for (iI = 0; iI < GC.getNumBuildingInfos(); iI++) { m_paiFreeBuildingCount[iI] = 0; m_paiExtraBuildingHappiness[iI] = 0; m_paiExtraBuildingHealth[iI] = 0; } FAssertMsg(m_paiFeatureHappiness==NULL, "about to leak memory, CvPlayer::m_paiFeatureHappiness"); m_paiFeatureHappiness = new int [GC.getNumFeatureInfos()]; for (iI = 0; iI < GC.getNumFeatureInfos(); iI++) { m_paiFeatureHappiness[iI] = 0; } FAssertMsg(m_paiUnitClassCount==NULL, "about to leak memory, CvPlayer::m_paiUnitClassCount"); m_paiUnitClassCount = new int [GC.getNumUnitClassInfos()]; FAssertMsg(m_paiUnitClassMaking==NULL, "about to leak memory, CvPlayer::m_paiUnitClassMaking"); m_paiUnitClassMaking = new int [GC.getNumUnitClassInfos()]; for (iI = 0; iI < GC.getNumUnitClassInfos(); iI++) { m_paiUnitClassCount[iI] = 0; m_paiUnitClassMaking[iI] = 0; } FAssertMsg(m_paiBuildingClassCount==NULL, "about to leak memory, CvPlayer::m_paiBuildingClassCount"); m_paiBuildingClassCount = new int [GC.getNumBuildingClassInfos()]; FAssertMsg(m_paiBuildingClassMaking==NULL, "about to leak memory, CvPlayer::m_paiBuildingClassMaking"); m_paiBuildingClassMaking = new int [GC.getNumBuildingClassInfos()]; for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++) { m_paiBuildingClassCount[iI] = 0; m_paiBuildingClassMaking[iI] = 0; } FAssertMsg(m_paiHurryCount==NULL, "about to leak memory, CvPlayer::m_paiHurryCount"); m_paiHurryCount = new int [GC.getNumHurryInfos()]; for (iI = 0; iI < GC.getNumHurryInfos(); iI++) { m_paiHurryCount[iI] = 0; } FAssertMsg(m_paiSpecialBuildingNotRequiredCount==NULL, "about to leak memory, CvPlayer::m_paiSpecialBuildingNotRequiredCount"); m_paiSpecialBuildingNotRequiredCount = new int [GC.getNumSpecialBuildingInfos()]; for (iI = 0; iI < GC.getNumSpecialBuildingInfos(); iI++) { m_paiSpecialBuildingNotRequiredCount[iI] = 0; } FAssertMsg(m_paiHasCivicOptionCount==NULL, "about to leak memory, CvPlayer::m_paiHasCivicOptionCount"); m_paiHasCivicOptionCount = new int[GC.getNumCivicOptionInfos()]; FAssertMsg(m_paiNoCivicUpkeepCount==NULL, "about to leak memory, CvPlayer::m_paiNoCivicUpkeepCount"); m_paiNoCivicUpkeepCount = new int[GC.getNumCivicOptionInfos()]; FAssertMsg(m_paeCivics==NULL, "about to leak memory, CvPlayer::m_paeCivics"); m_paeCivics = new CivicTypes [GC.getNumCivicOptionInfos()]; for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { m_paiHasCivicOptionCount[iI] = 0; m_paiNoCivicUpkeepCount[iI] = 0; m_paeCivics[iI] = NO_CIVIC; } FAssertMsg(m_paiHasReligionCount==NULL, "about to leak memory, CvPlayer::m_paiHasReligionCount"); m_paiHasReligionCount = new int[GC.getNumReligionInfos()]; for (iI = 0;iI < GC.getNumReligionInfos();iI++) { m_paiHasReligionCount[iI] = 0; } FAssertMsg(m_paiHasCorporationCount==NULL, "about to leak memory, CvPlayer::m_paiHasReligionCount"); m_paiHasCorporationCount = new int[GC.getNumCorporationInfos()]; for (iI = 0;iI < GC.getNumCorporationInfos();iI++) { m_paiHasCorporationCount[iI] = 0; } FAssertMsg(m_pabResearchingTech==NULL, "about to leak memory, CvPlayer::m_pabResearchingTech"); m_pabResearchingTech = new bool[GC.getNumTechInfos()]; for (iI = 0; iI < GC.getNumTechInfos(); iI++) { m_pabResearchingTech[iI] = false; } FAssertMsg(m_pabLoyalMember==NULL, "about to leak memory, CvPlayer::m_pabLoyalMember"); m_pabLoyalMember = new bool[GC.getNumVoteSourceInfos()]; for (iI = 0; iI < GC.getNumVoteSourceInfos(); iI++) { m_pabLoyalMember[iI] = true; } FAssertMsg(0 < GC.getNumUpkeepInfos(), "GC.getNumUpkeepInfos() is not greater than zero but it is used to allocate memory in CvPlayer::reset"); FAssertMsg(m_paiUpkeepCount==NULL, "about to leak memory, CvPlayer::m_paiUpkeepCount"); m_paiUpkeepCount = new int[GC.getNumUpkeepInfos()]; for (iI = 0; iI < GC.getNumUpkeepInfos(); iI++) { m_paiUpkeepCount[iI] = 0; } FAssertMsg(0 < GC.getNumSpecialistInfos(), "GC.getNumSpecialistInfos() is not greater than zero but it is used to allocate memory in CvPlayer::reset"); FAssertMsg(m_paiSpecialistValidCount==NULL, "about to leak memory, CvPlayer::m_paiSpecialistValidCount"); m_paiSpecialistValidCount = new int[GC.getNumSpecialistInfos()]; for (iI = 0; iI < GC.getNumSpecialistInfos(); iI++) { m_paiSpecialistValidCount[iI] = 0; } FAssertMsg(0 < GC.getNumSpecialistInfos(), "GC.getNumSpecialistInfos() is not greater than zero but it is used to allocate memory in CvPlayer::reset"); FAssertMsg(m_ppaaiSpecialistExtraYield==NULL, "about to leak memory, CvPlayer::m_ppaaiSpecialistExtraYield"); m_ppaaiSpecialistExtraYield = new int*[GC.getNumSpecialistInfos()]; for (iI = 0; iI < GC.getNumSpecialistInfos(); iI++) { m_ppaaiSpecialistExtraYield[iI] = new int[NUM_YIELD_TYPES]; for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { m_ppaaiSpecialistExtraYield[iI][iJ] = 0; } } FAssertMsg(m_ppaaiImprovementYieldChange==NULL, "about to leak memory, CvPlayer::m_ppaaiImprovementYieldChange"); m_ppaaiImprovementYieldChange = new int*[GC.getNumImprovementInfos()]; for (iI = 0; iI < GC.getNumImprovementInfos(); iI++) { m_ppaaiImprovementYieldChange[iI] = new int[NUM_YIELD_TYPES]; for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { m_ppaaiImprovementYieldChange[iI][iJ] = 0; } } m_mapEventsOccured.clear(); m_mapEventCountdown.clear(); m_aFreeUnitCombatPromotions.clear(); m_aFreeUnitClassPromotions.clear(); m_aVote.clear(); m_aUnitExtraCosts.clear(); m_triggersFired.clear(); } m_plotGroups.removeAll(); m_cities.removeAll(); m_units.removeAll(); m_selectionGroups.removeAll(); m_eventsTriggered.removeAll(); if (!bConstructorCall) { AI_reset(false); } } /************************************************************************************************/ /* CHANGE_PLAYER 08/17/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // for logging // void CvPlayer::logMsg(char* format, ... ) { static char buf[2048]; _vsnprintf( buf, 2048-4, format, (char*)(&format+1) ); gDLL->logMsg("sdkDbg.log", buf); } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ /************************************************************************************************/ /* CHANGE_PLAYER 08/17/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // for stripping obsolete trait bonuses // for complete reset, use in conjunction with addTraitBonuses // void CvPlayer::clearTraitBonuses( ) { int iI, iJ; FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvPlayer::init"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { changeExtraHealth(-GC.getTraitInfo((TraitTypes)iI).getHealth()); changeExtraHappiness(-GC.getTraitInfo((TraitTypes)iI).getHappiness()); for (iJ = 0; iJ < GC.getNumBuildingInfos(); iJ++) { changeExtraBuildingHappiness((BuildingTypes)iJ, -GC.getBuildingInfo((BuildingTypes)iJ).getHappinessTraits(iI)); } changeUpkeepModifier(-GC.getTraitInfo((TraitTypes)iI).getUpkeepModifier()); changeLevelExperienceModifier(-GC.getTraitInfo((TraitTypes)iI).getLevelExperienceModifier()); changeGreatPeopleRateModifier(-GC.getTraitInfo((TraitTypes)iI).getGreatPeopleRateModifier()); changeGreatGeneralRateModifier(-GC.getTraitInfo((TraitTypes)iI).getGreatGeneralRateModifier()); changeDomesticGreatGeneralRateModifier(-GC.getTraitInfo((TraitTypes)iI).getDomesticGreatGeneralRateModifier()); changeMaxGlobalBuildingProductionModifier(-GC.getTraitInfo((TraitTypes)iI).getMaxGlobalBuildingProductionModifier()); changeMaxTeamBuildingProductionModifier(-GC.getTraitInfo((TraitTypes)iI).getMaxTeamBuildingProductionModifier()); changeMaxPlayerBuildingProductionModifier(-GC.getTraitInfo((TraitTypes)iI).getMaxPlayerBuildingProductionModifier()); for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { changeTradeYieldModifier(((YieldTypes)iJ), -GC.getTraitInfo((TraitTypes)iI).getTradeYieldModifier(iJ)); } for (iJ = 0; iJ < NUM_COMMERCE_TYPES; iJ++) { changeFreeCityCommerce(((CommerceTypes)iJ), -GC.getTraitInfo((TraitTypes)iI).getCommerceChange(iJ)); changeCommerceRateModifier(((CommerceTypes)iJ), -GC.getTraitInfo((TraitTypes)iI).getCommerceModifier(iJ)); } for (iJ = 0; iJ < GC.getNumCivicOptionInfos(); iJ++) { if (GC.getCivicOptionInfo((CivicOptionTypes) iJ).getTraitNoUpkeep(iI)) { changeNoCivicUpkeepCount(((CivicOptionTypes)iJ), -1); } } } } } // // for adding new trait bonuses // void CvPlayer::addTraitBonuses( ) { int iI, iJ; FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvPlayer::init"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { changeExtraHealth(GC.getTraitInfo((TraitTypes)iI).getHealth()); changeExtraHappiness(GC.getTraitInfo((TraitTypes)iI).getHappiness()); for (iJ = 0; iJ < GC.getNumBuildingInfos(); iJ++) { changeExtraBuildingHappiness((BuildingTypes)iJ, GC.getBuildingInfo((BuildingTypes)iJ).getHappinessTraits(iI)); } changeUpkeepModifier(GC.getTraitInfo((TraitTypes)iI).getUpkeepModifier()); changeLevelExperienceModifier(GC.getTraitInfo((TraitTypes)iI).getLevelExperienceModifier()); changeGreatPeopleRateModifier(GC.getTraitInfo((TraitTypes)iI).getGreatPeopleRateModifier()); changeGreatGeneralRateModifier(GC.getTraitInfo((TraitTypes)iI).getGreatGeneralRateModifier()); changeDomesticGreatGeneralRateModifier(GC.getTraitInfo((TraitTypes)iI).getDomesticGreatGeneralRateModifier()); changeMaxGlobalBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxGlobalBuildingProductionModifier()); changeMaxTeamBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxTeamBuildingProductionModifier()); changeMaxPlayerBuildingProductionModifier(GC.getTraitInfo((TraitTypes)iI).getMaxPlayerBuildingProductionModifier()); for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { changeTradeYieldModifier(((YieldTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getTradeYieldModifier(iJ)); } for (iJ = 0; iJ < NUM_COMMERCE_TYPES; iJ++) { changeFreeCityCommerce(((CommerceTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getCommerceChange(iJ)); changeCommerceRateModifier(((CommerceTypes)iJ), GC.getTraitInfo((TraitTypes)iI).getCommerceModifier(iJ)); } for (iJ = 0; iJ < GC.getNumCivicOptionInfos(); iJ++) { if (GC.getCivicOptionInfo((CivicOptionTypes) iJ).getTraitNoUpkeep(iI)) { changeNoCivicUpkeepCount(((CivicOptionTypes)iJ), 1); } } } } updateMaxAnarchyTurns(); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { updateExtraYieldThreshold((YieldTypes)iI); } } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ /************************************************************************************************/ /* CHANGE_PLAYER 08/17/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // for changing the personality of the player // void CvPlayer::changePersonalityType( ) { LeaderHeadTypes eBestPersonality; int iValue; int iBestValue; int iI, iJ; if (GC.getGameINLINE().isOption(GAMEOPTION_RANDOM_PERSONALITIES)) { if (!isBarbarian()) { iBestValue = 0; eBestPersonality = NO_LEADER; for (iI = 0; iI < GC.getNumLeaderHeadInfos(); iI++) { if (iI != GC.getDefineINT("BARBARIAN_LEADER")) // XXX minor civ??? { iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "Choosing Personality")); for (iJ = 0; iJ < MAX_CIV_PLAYERS; iJ++) { if (GET_PLAYER((PlayerTypes)iJ).isAlive()) { if (GET_PLAYER((PlayerTypes)iJ).getPersonalityType() == ((LeaderHeadTypes)iI)) { iValue /= 2; } } } if (iValue > iBestValue) { iBestValue = iValue; eBestPersonality = ((LeaderHeadTypes)iI); } } } if (eBestPersonality != NO_LEADER) { setPersonalityType(eBestPersonality); } } } else { setPersonalityType( getLeaderType() ); } } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ /************************************************************************************************/ /* CHANGE_PLAYER 08/17/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // reset state of event logic, unit prices // void CvPlayer::resetCivTypeEffects( ) { int iI; if( !isAlive() ) { for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { setCivics(((CivicOptionTypes)iI), ((CivicTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationInitialCivics(iI)))); } for (iI = 0; iI < GC.getNumEventInfos(); iI++) { resetEventOccured((EventTypes)iI, false); } for (iI = 0; iI < GC.getNumEventTriggerInfos(); iI++) { if( (!GC.getEventTriggerInfo((EventTriggerTypes)iI).isGlobal()) && (!GC.getEventTriggerInfo((EventTriggerTypes)iI).isTeam() || GET_TEAM(getTeam()).getNumMembers() == 1) ) { resetTriggerFired((EventTriggerTypes)iI); } } } for (iI = 0; iI < GC.getNumUnitClassInfos(); ++iI) { UnitTypes eUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(iI))); if (NO_UNIT != eUnit) { if (GC.getUnitInfo(eUnit).isFound()) { setUnitExtraCost((UnitClassTypes)iI, getNewCityProductionValue()); } } } } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ /************************************************************************************************/ /* CHANGE_PLAYER 08/17/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // for switching the leaderhead of this player // void CvPlayer::changeLeader( LeaderHeadTypes eNewLeader ) { LeaderHeadTypes eOldLeader = getLeaderType(); if( eOldLeader == eNewLeader ) return; // Clear old traits clearTraitBonuses(); GC.getInitCore().setLeader( getID(), eNewLeader ); // Add new traits addTraitBonuses(); // Set new personality changePersonalityType(); if( isAlive() || isEverAlive() ) { gDLL->getInterfaceIFace()->setDirty(HighlightPlot_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(UnitInfo_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Flag_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(MinimapSection_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Foreign_Screen_DIRTY_BIT, true); } AI_init(); } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ /************************************************************************************************/ /* CHANGE_PLAYER 05/09/09 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // for changing the civilization of this player // void CvPlayer::changeCiv( CivilizationTypes eNewCiv ) { CivilizationTypes eOldCiv = getCivilizationType(); PlayerColorTypes eColor = (PlayerColorTypes)GC.getCivilizationInfo(eNewCiv).getDefaultPlayerColor(); if( eOldCiv == eNewCiv ) return; for (int iI = 0; iI < MAX_CIV_PLAYERS; iI++) { if (eColor == NO_PLAYERCOLOR || (GET_PLAYER((PlayerTypes)iI).getPlayerColor() == eColor && iI != getID()) ) { for (int iK = 0; iK < GC.getNumPlayerColorInfos(); iK++) { if (iK != GC.getCivilizationInfo((CivilizationTypes)GC.getDefineINT("BARBARIAN_CIVILIZATION")).getDefaultPlayerColor()) { bool bValid = true; for (int iL = 0; iL < MAX_CIV_PLAYERS; iL++) { if (GET_PLAYER((PlayerTypes)iL).getPlayerColor() == iK) { bValid = false; break; } } if (bValid) { eColor = (PlayerColorTypes)iK; iI = MAX_CIV_PLAYERS; break; } } } } } GC.getInitCore().setCiv( getID(), eNewCiv ); GC.getInitCore().setColor( getID(), eColor ); resetCivTypeEffects(); if( isAlive() ) { // if the player is alive and showing on scoreboard, etc // change colors, graphics, flags, units GC.getInitCore().setFlagDecal( getID(), (CvWString)GC.getCivilizationInfo(eNewCiv).getFlagTexture() ); GC.getInitCore().setArtStyle( getID(), (ArtStyleTypes)GC.getCivilizationInfo(eNewCiv).getArtStyleType() ); // Forces update of units flags EraTypes eEra = getCurrentEra(); bool bAuto = m_bDisableHuman; m_bDisableHuman = true; //setCurrentEra((EraTypes)((eEra + 1)%GC.getNumEraInfos())); setCurrentEra((EraTypes)0); setCurrentEra((EraTypes)(GC.getNumEraInfos() - 1)); setCurrentEra(eEra); m_bDisableHuman = bAuto; gDLL->getInterfaceIFace()->makeInterfaceDirty(); int iLoop; CvCity* pLoopCity; // dirty all of this player's cities... for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getOwnerINLINE() == getID()) { pLoopCity->setLayoutDirty(true); } } //update unit eras CvUnit* pLoopUnit; CvPlot* pLoopPlot; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { pLoopUnit->reloadEntity(); pLoopPlot = pLoopUnit->plot(); /* if( pLoopPlot != NULL ) { CvFlagEntity* pFlag = pLoopPlot->getFlagSymbol(); if( pFlag != NULL ) { if( gDLL->getFlagEntityIFace()->getPlayer(pFlag) == getID() ) { gDLL->getFlagEntityIFace()->destroy(pFlag); CvFlagEntity* pNewFlag = gDLL->getFlagEntityIFace()->create(getID()); if (pFlag != NULL) { gDLL->getFlagEntityIFace()->setPlot(pNewFlag, pLoopPlot, false); } gDLL->getFlagEntityIFace()->updateGraphicEra(pNewFlag); } } pLoopPlot->setFlagDirty(true); //pLoopPlot->updateGraphicEra(); } */ } //update flag eras gDLL->getInterfaceIFace()->setDirty(Flag_DIRTY_BIT, true); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Soundtrack_DIRTY_BIT, true); } gDLL->getInterfaceIFace()->makeInterfaceDirty(); // Need to force redraw gDLL->getEngineIFace()->SetDirty(CultureBorders_DIRTY_BIT, true); gDLL->getEngineIFace()->SetDirty(MinimapTexture_DIRTY_BIT, true); gDLL->getEngineIFace()->SetDirty(GlobeTexture_DIRTY_BIT, true); gDLL->getEngineIFace()->SetDirty(GlobePartialTexture_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(ColoredPlots_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(HighlightPlot_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(UnitInfo_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GlobeLayer_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(MinimapSection_DIRTY_BIT, true); gDLL->getEngineIFace()->SetDirty(MinimapTexture_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Foreign_Screen_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionSound_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GlobeInfo_DIRTY_BIT, true); } else if( isEverAlive() ) { // Not currently alive, but may show on some people's scoreboard // or graphs // change colors gDLL->getInterfaceIFace()->setDirty(InfoPane_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); } setupGraphical(); } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ /************************************************************************************************/ /* CHANGE_PLAYER 08/17/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // // for changing whether this player is human or not // void CvPlayer::setIsHuman( bool bNewValue ) { if( bNewValue == isHuman() ) return; if( bNewValue ) GC.getInitCore().setSlotStatus( getID(), SS_TAKEN ); else GC.getInitCore().setSlotStatus( getID(), SS_COMPUTER ); // or SS_OPEN for multiplayer? } /************************************************************************************************/ /* CHANGE_PLAYER END */ /************************************************************************************************/ ////////////////////////////////////// // graphical only setup ////////////////////////////////////// void CvPlayer::setupGraphical() { if (!GC.IsGraphicsInitialized()) return; CvCity* pLoopCity; CvUnit* pLoopUnit; // Setup m_cities int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->setupGraphical(); } // Setup m_units for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { pLoopUnit->setupGraphical(); } } void CvPlayer::initFreeState() { setGold(0); changeGold(GC.getHandicapInfo(getHandicapType()).getStartingGold()); changeGold(GC.getEraInfo(GC.getGameINLINE().getStartEra()).getStartingGold()); clearResearchQueue(); } void CvPlayer::initFreeUnits() { UnitTypes eLoopUnit; int iFreeCount; int iI, iJ; if (GC.getGameINLINE().isOption(GAMEOPTION_ADVANCED_START) && !isBarbarian()) { int iPoints = GC.getGameINLINE().getNumAdvancedStartPoints(); iPoints *= GC.getHandicapInfo(getHandicapType()).getAdvancedStartPointsMod(); iPoints /= 100; if (!isHuman()) { iPoints *= GC.getHandicapInfo(getHandicapType()).getAIAdvancedStartPercent(); iPoints /= 100; } setAdvancedStartPoints(iPoints); // Starting visibility CvPlot* pStartingPlot = getStartingPlot(); if (NULL != pStartingPlot) { for (int iPlotLoop = 0; iPlotLoop < GC.getMapINLINE().numPlots(); ++iPlotLoop) { CvPlot* pPlot = GC.getMapINLINE().plotByIndex(iPlotLoop); if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pStartingPlot->getX_INLINE(), pStartingPlot->getY_INLINE()) <= GC.getDefineINT("ADVANCED_START_SIGHT_RANGE")) { pPlot->setRevealed(getTeam(), true, false, NO_TEAM, false); } } } } else { for (iI = 0; iI < GC.getNumUnitClassInfos(); iI++) { eLoopUnit = (UnitTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(iI); if (eLoopUnit != NO_UNIT) { iFreeCount = GC.getCivilizationInfo(getCivilizationType()).getCivilizationFreeUnitsClass(iI); iFreeCount *= (GC.getEraInfo(GC.getGameINLINE().getStartEra()).getStartingUnitMultiplier() + ((!isHuman()) ? GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIStartingUnitMultiplier() : 0)); for (iJ = 0; iJ < iFreeCount; iJ++) { addFreeUnit(eLoopUnit); } } } iFreeCount = GC.getEraInfo(GC.getGameINLINE().getStartEra()).getStartingDefenseUnits(); iFreeCount += GC.getHandicapInfo(getHandicapType()).getStartingDefenseUnits(); if (!isHuman()) { iFreeCount += GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIStartingDefenseUnits(); } if (iFreeCount > 0) { addFreeUnitAI(UNITAI_CITY_DEFENSE, iFreeCount); } iFreeCount = GC.getEraInfo(GC.getGameINLINE().getStartEra()).getStartingWorkerUnits(); iFreeCount += GC.getHandicapInfo(getHandicapType()).getStartingWorkerUnits(); if (!isHuman()) { iFreeCount += GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIStartingWorkerUnits(); } if (iFreeCount > 0) { addFreeUnitAI(UNITAI_WORKER, iFreeCount); } iFreeCount = GC.getEraInfo(GC.getGameINLINE().getStartEra()).getStartingExploreUnits(); iFreeCount += GC.getHandicapInfo(getHandicapType()).getStartingExploreUnits(); if (!isHuman()) { iFreeCount += GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIStartingExploreUnits(); } if (iFreeCount > 0) { addFreeUnitAI(UNITAI_EXPLORE, iFreeCount); } } } void CvPlayer::addFreeUnitAI(UnitAITypes eUnitAI, int iCount) { UnitTypes eLoopUnit; UnitTypes eBestUnit; bool bValid; int iValue; int iBestValue; int iI, iJ; eBestUnit = NO_UNIT; iBestValue = 0; for (iI = 0; iI < GC.getNumUnitClassInfos(); iI++) { eLoopUnit = (UnitTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(iI); if (eLoopUnit != NO_UNIT) { if (canTrain(eLoopUnit)) { bValid = true; if (GC.getUnitInfo(eLoopUnit).getPrereqAndBonus() != NO_BONUS) { bValid = false; } for (iJ = 0; iJ < GC.getNUM_UNIT_PREREQ_OR_BONUSES(); iJ++) { if (GC.getUnitInfo(eLoopUnit).getPrereqOrBonuses(iJ) != NO_BONUS) { bValid = false; } } if (bValid) { iValue = AI_unitValue(eLoopUnit, eUnitAI, NULL); if (iValue > iBestValue) { eBestUnit = eLoopUnit; iBestValue = iValue; } } } } } if (eBestUnit != NO_UNIT) { for (iI = 0; iI < iCount; iI++) { addFreeUnit(eBestUnit, eUnitAI); } } } void CvPlayer::addFreeUnit(UnitTypes eUnit, UnitAITypes eUnitAI) { CvPlot* pStartingPlot; CvPlot* pBestPlot; CvPlot* pLoopPlot; int iRandOffset; int iI; if (GC.getGameINLINE().isOption(GAMEOPTION_ONE_CITY_CHALLENGE) && isHuman()) { if ((eUnitAI == UNITAI_SETTLE) || (GC.getUnitInfo(eUnit).getDefaultUnitAIType() == UNITAI_SETTLE)) { if (AI_getNumAIUnits(UNITAI_SETTLE) >= 1) { return; } } } pStartingPlot = getStartingPlot(); if (pStartingPlot != NULL) { pBestPlot = NULL; if (isHuman()) { long lResult=0; gDLL->getPythonIFace()->callFunction(gDLL->getPythonIFace()->getMapScriptModule(), "startHumansOnSameTile", NULL, &lResult); if (lResult == 0) { if (!(GC.getUnitInfo(eUnit).isFound())) { iRandOffset = GC.getGameINLINE().getSorenRandNum(NUM_CITY_PLOTS, "Place Units (Player)"); for (iI = 0; iI < NUM_CITY_PLOTS; iI++) { pLoopPlot = plotCity(pStartingPlot->getX_INLINE(), pStartingPlot->getY_INLINE(), ((iI + iRandOffset) % NUM_CITY_PLOTS)); if (pLoopPlot != NULL) { if (pLoopPlot->getArea() == pStartingPlot->getArea()) { if (!(pLoopPlot->isImpassable())) { if (!(pLoopPlot->isUnit())) { if (!(pLoopPlot->isGoody())) { pBestPlot = pLoopPlot; break; } } } } } } } } } if (pBestPlot == NULL) { pBestPlot = pStartingPlot; } initUnit(eUnit, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), eUnitAI); } } int CvPlayer::startingPlotRange() const { int iRange; iRange = (GC.getMapINLINE().maxStepDistance() + 10); iRange *= GC.getDefineINT("STARTING_DISTANCE_PERCENT"); iRange /= 100; iRange *= (GC.getMapINLINE().getLandPlots() / (GC.getWorldInfo(GC.getMapINLINE().getWorldSize()).getTargetNumCities() * GC.getGameINLINE().countCivPlayersAlive())); iRange /= NUM_CITY_PLOTS; iRange += std::min(((GC.getMapINLINE().getNumAreas() + 1) / 2), GC.getGameINLINE().countCivPlayersAlive()); long lResult=0; if (gDLL->getPythonIFace()->callFunction(gDLL->getPythonIFace()->getMapScriptModule(), "minStartingDistanceModifier", NULL, &lResult)) { iRange *= std::max<int>(0, (lResult + 100)); iRange /= 100; } return std::max(iRange, GC.getDefineINT("MIN_CIV_STARTING_DISTANCE")); } bool CvPlayer::startingPlotWithinRange(CvPlot* pPlot, PlayerTypes ePlayer, int iRange, int iPass) const { //PROFILE_FUNC(); //XXX changes to AI_foundValue (which are far more flexible) make this function // redundant but it is still called from Python. return false; } int CvPlayer::startingPlotDistanceFactor(CvPlot* pPlot, PlayerTypes ePlayer, int iRange) const { PROFILE_FUNC(); FAssert(ePlayer != getID()); CvPlot* pStartingPlot; int iValue = 1000; pStartingPlot = getStartingPlot(); if (pStartingPlot != NULL) { if (GC.getGameINLINE().isTeamGame()) { if (GET_PLAYER(ePlayer).getTeam() == getTeam()) { iRange *= GC.getDefineINT("OWN_TEAM_STARTING_MODIFIER"); iRange /= 100; } else { iRange *= GC.getDefineINT("RIVAL_TEAM_STARTING_MODIFIER"); iRange /= 100; } } int iDistance = stepDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pStartingPlot->getX_INLINE(), pStartingPlot->getY_INLINE()); if (pStartingPlot->getArea() != pPlot->getArea()) { iDistance *= 4; iDistance /= 3; } iValue *= iDistance; iValue /= iRange ; } return std::max(1, iValue); } // Returns the id of the best area, or -1 if it doesn't matter: int CvPlayer::findStartingArea() const { PROFILE_FUNC(); long result = -1; CyArgsList argsList; argsList.add(getID()); // pass in this players ID if (gDLL->getPythonIFace()->callFunction(gDLL->getPythonIFace()->getMapScriptModule(), "findStartingArea", argsList.makeFunctionArgs(), &result)) { if (!gDLL->getPythonIFace()->pythonUsingDefaultImpl()) // Python override { if (result == -1 || GC.getMapINLINE().getArea(result) != NULL) { return result; } else { FAssertMsg(false, "python findStartingArea() must return -1 or the ID of a valid area"); } } } int iBestValue = 0; int iBestArea = -1; int iValue; int iLoop = 0; CvArea *pLoopArea = NULL; // find best land area for(pLoopArea = GC.getMapINLINE().firstArea(&iLoop); pLoopArea != NULL; pLoopArea = GC.getMapINLINE().nextArea(&iLoop)) { if (!(pLoopArea->isWater())) { // iNumPlayersOnArea is the number of players starting on the area, plus this player int iNumPlayersOnArea = (pLoopArea->getNumStartingPlots() + 1); int iTileValue = ((pLoopArea->calculateTotalBestNatureYield() + (pLoopArea->countCoastalLand() * 2) + pLoopArea->getNumRiverEdges() + (pLoopArea->getNumTiles())) + 1); iValue = iTileValue / iNumPlayersOnArea; iValue *= std::min(NUM_CITY_PLOTS + 1, pLoopArea->getNumTiles() + 1); iValue /= (NUM_CITY_PLOTS + 1); if (iNumPlayersOnArea <= 2) { iValue *= 4; iValue /= 3; } if (iValue > iBestValue) { iBestValue = iValue; iBestArea = pLoopArea->getID(); } } } return iBestArea; } CvPlot* CvPlayer::findStartingPlot(bool bRandomize) { PROFILE_FUNC(); long result = -1; CyArgsList argsList; argsList.add(getID()); // pass in this players ID if (gDLL->getPythonIFace()->callFunction(gDLL->getPythonIFace()->getMapScriptModule(), "findStartingPlot", argsList.makeFunctionArgs(), &result)) { if (!gDLL->getPythonIFace()->pythonUsingDefaultImpl()) // Python override { CvPlot *pPlot = GC.getMapINLINE().plotByIndexINLINE(result); if (pPlot != NULL) { return pPlot; } else { FAssertMsg(false, "python findStartingPlot() returned an invalid plot index!"); } } } CvPlot* pLoopPlot; bool bValid; int iBestArea = -1; int iValue; int iRange; int iI; bool bNew = false; if (getStartingPlot() != NULL) { iBestArea = getStartingPlot()->getArea(); setStartingPlot(NULL, true); bNew = true; } AI_updateFoundValues(true);//this sets all plots found values to -1 if (!bNew) { iBestArea = findStartingArea(); } iRange = startingPlotRange(); for(int iPass = 0; iPass < GC.getMapINLINE().maxPlotDistance(); iPass++) { CvPlot *pBestPlot = NULL; int iBestValue = 0; for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if ((iBestArea == -1) || (pLoopPlot->getArea() == iBestArea)) { //the distance factor is now done inside foundValue iValue = pLoopPlot->getFoundValue(getID()); if (bRandomize && iValue > 0) { iValue += GC.getGameINLINE().getSorenRandNum(10000, "Randomize Starting Location"); } if (iValue > iBestValue) { bValid = true; if (bValid) { iBestValue = iValue; pBestPlot = pLoopPlot; } } } } if (pBestPlot != NULL) { return pBestPlot; } FAssertMsg(iPass != 0, "CvPlayer::findStartingPlot - could not find starting plot in first pass."); } FAssertMsg(false, "Could not find starting plot."); return NULL; } CvPlotGroup* CvPlayer::initPlotGroup(CvPlot* pPlot) { CvPlotGroup* pPlotGroup; pPlotGroup = addPlotGroup(); FAssertMsg(pPlotGroup != NULL, "PlotGroup is not assigned a valid value"); pPlotGroup->init(pPlotGroup->getID(), getID(), pPlot); return pPlotGroup; } CvCity* CvPlayer::initCity(int iX, int iY, bool bBumpUnits, bool bUpdatePlotGroups) { PROFILE_FUNC(); CvCity* pCity; pCity = addCity(); FAssertMsg(pCity != NULL, "City is not assigned a valid value"); FAssertMsg(!(GC.getMapINLINE().plotINLINE(iX, iY)->isCity()), "No city is expected at this plot when initializing new city"); pCity->init(pCity->getID(), getID(), iX, iY, bBumpUnits, bUpdatePlotGroups); return pCity; } void CvPlayer::acquireCity(CvCity* pOldCity, bool bConquest, bool bTrade, bool bUpdatePlotGroups) { CLLNode<IDInfo>* pUnitNode; CvCity* pNewCity; CvUnit* pLoopUnit; CvPlot* pCityPlot; CvPlot* pLoopPlot; bool* pabHasReligion; bool* pabHolyCity; bool* pabHasCorporation; bool* pabHeadquarters; int* paiNumRealBuilding; int* paiBuildingOriginalOwner; int* paiBuildingOriginalTime; CvWString szBuffer; CvWString szName; bool abEverOwned[MAX_PLAYERS]; int aiCulture[MAX_PLAYERS]; PlayerTypes eOldOwner; PlayerTypes eOriginalOwner; PlayerTypes eHighestCulturePlayer; BuildingTypes eBuilding; bool bRecapture; bool bRaze; bool bGift; int iRange; int iCaptureGold; int iGameTurnFounded; int iPopulation; int iHighestPopulation; int iHurryAngerTimer; int iConscriptAngerTimer; int iDefyResolutionAngerTimer; int iOccupationTimer; int iTeamCulturePercent; int iDamage; int iDX, iDY; int iI; CLinkList<IDInfo> oldUnits; std::vector<int> aeFreeSpecialists; pCityPlot = pOldCity->plot(); pUnitNode = pCityPlot->headUnitNode(); while (pUnitNode != NULL) { oldUnits.insertAtEnd(pUnitNode->m_data); pUnitNode = pCityPlot->nextUnitNode(pUnitNode); } pUnitNode = oldUnits.head(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = oldUnits.next(pUnitNode); if (pLoopUnit && pLoopUnit->getTeam() != getTeam()) { if (pLoopUnit->getDomainType() == DOMAIN_IMMOBILE) { pLoopUnit->kill(false, getID()); } } } if (bConquest) { iRange = pOldCity->getCultureLevel(); for (iDX = -(iRange); iDX <= iRange; iDX++) { for (iDY = -(iRange); iDY <= iRange; iDY++) { if (pOldCity->cultureDistance(iDX, iDY) <= iRange) { pLoopPlot = plotXY(pOldCity->getX_INLINE(),pOldCity-> getY_INLINE(), iDX, iDY); if (pLoopPlot != NULL) { if (pLoopPlot->getOwnerINLINE() == pOldCity->getOwnerINLINE()) { if (pLoopPlot->getNumCultureRangeCities(pOldCity->getOwnerINLINE()) == 1) { bool bForceUnowned = false; for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if ((GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam()) && (GET_PLAYER((PlayerTypes)iI).getTeam() != pOldCity->getTeam())) { if (pLoopPlot->getNumCultureRangeCities((PlayerTypes)iI) > 0) { bForceUnowned = true; break; } } } } if (bForceUnowned) { pLoopPlot->setForceUnownedTimer(GC.getDefineINT("FORCE_UNOWNED_CITY_TIMER")); } } } } } } } } if (pOldCity->getOriginalOwner() == pOldCity->getOwnerINLINE()) { GET_PLAYER(pOldCity->getOriginalOwner()).changeCitiesLost(1); } else if (pOldCity->getOriginalOwner() == getID()) { GET_PLAYER(pOldCity->getOriginalOwner()).changeCitiesLost(-1); } if (bConquest) { szBuffer = gDLL->getText("TXT_KEY_MISC_CAPTURED_CITY", pOldCity->getNameKey()).GetCString(); gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CITYCAPTURE", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getInterfaceArtInfo("WORLDBUILDER_CITY_EDIT")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pOldCity->getX_INLINE(), pOldCity->getY_INLINE(), true, true); szName.Format(L"%s (%s)", pOldCity->getName().GetCString(), GET_PLAYER(pOldCity->getOwnerINLINE()).getName()); for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (iI != getID()) { if (pOldCity->isRevealed(GET_PLAYER((PlayerTypes)iI).getTeam(), false)) { szBuffer = gDLL->getText("TXT_KEY_MISC_CITY_CAPTURED_BY", szName.GetCString(), getCivilizationDescriptionKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CITYCAPTURED", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getInterfaceArtInfo("WORLDBUILDER_CITY_EDIT")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pOldCity->getX_INLINE(), pOldCity->getY_INLINE(), true, true); } } } } szBuffer = gDLL->getText("TXT_KEY_MISC_CITY_WAS_CAPTURED_BY", szName.GetCString(), getCivilizationDescriptionKey()); GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szBuffer, pOldCity->getX_INLINE(), pOldCity->getY_INLINE(), (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); } iCaptureGold = 0; if (bConquest) { long lCaptureGold; // Use python to determine city capture gold amounts... lCaptureGold = 0; CyCity* pyOldCity = new CyCity(pOldCity); CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pyOldCity)); // pass in plot class gDLL->getPythonIFace()->callFunction(PYGameModule, "doCityCaptureGold", argsList.makeFunctionArgs(),&lCaptureGold); delete pyOldCity; // python fxn must not hold on to this pointer iCaptureGold = (int)lCaptureGold; } changeGold(iCaptureGold); pabHasReligion = new bool[GC.getNumReligionInfos()]; pabHolyCity = new bool[GC.getNumReligionInfos()]; pabHasCorporation = new bool[GC.getNumCorporationInfos()]; pabHeadquarters = new bool[GC.getNumCorporationInfos()]; paiNumRealBuilding = new int[GC.getNumBuildingInfos()]; paiBuildingOriginalOwner = new int[GC.getNumBuildingInfos()]; paiBuildingOriginalTime = new int[GC.getNumBuildingInfos()]; for (iI = 0; iI < GC.getNumVoteSourceInfos(); ++iI) { pOldCity->processVoteSourceBonus((VoteSourceTypes)iI, false); } eOldOwner = pOldCity->getOwnerINLINE(); eOriginalOwner = pOldCity->getOriginalOwner(); eHighestCulturePlayer = pOldCity->findHighestCulture(); iGameTurnFounded = pOldCity->getGameTurnFounded(); iPopulation = pOldCity->getPopulation(); iHighestPopulation = pOldCity->getHighestPopulation(); iHurryAngerTimer = pOldCity->getHurryAngerTimer(); iConscriptAngerTimer = pOldCity->getConscriptAngerTimer(); iDefyResolutionAngerTimer = pOldCity->getDefyResolutionAngerTimer(); iOccupationTimer = pOldCity->getOccupationTimer(); szName = pOldCity->getNameKey(); iDamage = pOldCity->getDefenseDamage(); int iOldCityId = pOldCity->getID(); for (iI = 0; iI < GC.getNumSpecialistInfos(); ++iI) { aeFreeSpecialists.push_back(pOldCity->getAddedFreeSpecialistCount((SpecialistTypes)iI)); } for (iI = 0; iI < MAX_PLAYERS; iI++) { abEverOwned[iI] = pOldCity->isEverOwned((PlayerTypes)iI); aiCulture[iI] = pOldCity->getCultureTimes100((PlayerTypes)iI); } abEverOwned[getID()] = true; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { pabHasReligion[iI] = pOldCity->isHasReligion((ReligionTypes)iI); pabHolyCity[iI] = pOldCity->isHolyCity((ReligionTypes)iI); } for (iI = 0; iI < GC.getNumCorporationInfos(); iI++) { pabHasCorporation[iI] = pOldCity->isHasCorporation((CorporationTypes)iI); pabHeadquarters[iI] = pOldCity->isHeadquarters((CorporationTypes)iI); } for (iI = 0; iI < GC.getNumBuildingInfos(); iI++) { paiNumRealBuilding[iI] = pOldCity->getNumRealBuilding((BuildingTypes)iI); paiBuildingOriginalOwner[iI] = pOldCity->getBuildingOriginalOwner((BuildingTypes)iI); paiBuildingOriginalTime[iI] = pOldCity->getBuildingOriginalTime((BuildingTypes)iI); } std::vector<BuildingYieldChange> aBuildingYieldChange; std::vector<BuildingCommerceChange> aBuildingCommerceChange; BuildingChangeArray aBuildingHappyChange; BuildingChangeArray aBuildingHealthChange; for (iI = 0; iI < GC.getNumBuildingClassInfos(); ++iI) { for (int iYield = 0; iYield < NUM_YIELD_TYPES; ++iYield) { BuildingYieldChange kChange; kChange.eBuildingClass = (BuildingClassTypes)iI; kChange.eYield = (YieldTypes)iYield; kChange.iChange = pOldCity->getBuildingYieldChange((BuildingClassTypes)iI, (YieldTypes)iYield); if (0 != kChange.iChange) { aBuildingYieldChange.push_back(kChange); } } for (int iCommerce = 0; iCommerce < NUM_COMMERCE_TYPES; ++iCommerce) { BuildingCommerceChange kChange; kChange.eBuildingClass = (BuildingClassTypes)iI; kChange.eCommerce = (CommerceTypes)iCommerce; kChange.iChange = pOldCity->getBuildingCommerceChange((BuildingClassTypes)iI, (CommerceTypes)iCommerce); if (0 != kChange.iChange) { aBuildingCommerceChange.push_back(kChange); } } int iChange = pOldCity->getBuildingHappyChange((BuildingClassTypes)iI); if (0 != iChange) { aBuildingHappyChange.push_back(std::make_pair((BuildingClassTypes)iI, iChange)); } iChange = pOldCity->getBuildingHealthChange((BuildingClassTypes)iI); if (0 != iChange) { aBuildingHealthChange.push_back(std::make_pair((BuildingClassTypes)iI, iChange)); } } bRecapture = ((eHighestCulturePlayer != NO_PLAYER) ? (GET_PLAYER(eHighestCulturePlayer).getTeam() == getTeam()) : false); pOldCity->kill(false); if (bTrade) { for (iDX = -1; iDX <= 1; iDX++) { for (iDY = -1; iDY <= 1; iDY++) { pLoopPlot = plotXY(pCityPlot->getX_INLINE(), pCityPlot->getY_INLINE(), iDX, iDY); if (pLoopPlot != NULL) { pLoopPlot->setCulture(eOldOwner, 0, false, false); } } } } pNewCity = initCity(pCityPlot->getX_INLINE(), pCityPlot->getY_INLINE(), !bConquest, false); FAssertMsg(pNewCity != NULL, "NewCity is not assigned a valid value"); pNewCity->setPreviousOwner(eOldOwner); pNewCity->setOriginalOwner(eOriginalOwner); pNewCity->setGameTurnFounded(iGameTurnFounded); pNewCity->setPopulation((bConquest && !bRecapture) ? std::max(1, (iPopulation - 1)) : iPopulation); pNewCity->setHighestPopulation(iHighestPopulation); pNewCity->setName(szName); pNewCity->setNeverLost(false); pNewCity->changeDefenseDamage(iDamage); for (iI = 0; iI < MAX_PLAYERS; iI++) { pNewCity->setEverOwned(((PlayerTypes)iI), abEverOwned[iI]); pNewCity->setCultureTimes100(((PlayerTypes)iI), aiCulture[iI], false, false); } for (iI = 0; iI < GC.getNumBuildingInfos(); iI++) { int iNum = 0; if (paiNumRealBuilding[iI] > 0) { BuildingClassTypes eBuildingClass = (BuildingClassTypes)GC.getBuildingInfo((BuildingTypes)iI).getBuildingClassType(); if (::isWorldWonderClass(eBuildingClass)) { eBuilding = (BuildingTypes)iI; } else { eBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(eBuildingClass); } if (eBuilding != NO_BUILDING) { if (bTrade || !(GC.getBuildingInfo((BuildingTypes)iI).isNeverCapture())) { if (!isProductionMaxedBuildingClass(((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType())), true)) { if (pNewCity->isValidBuildingLocation(eBuilding)) { if (!bConquest || bRecapture || GC.getGameINLINE().getSorenRandNum(100, "Capture Probability") < GC.getBuildingInfo((BuildingTypes)iI).getConquestProbability()) { iNum += paiNumRealBuilding[iI]; } } } } pNewCity->setNumRealBuildingTimed(eBuilding, std::min(pNewCity->getNumRealBuilding(eBuilding) + iNum, GC.getCITY_MAX_NUM_BUILDINGS()), false, ((PlayerTypes)(paiBuildingOriginalOwner[iI])), paiBuildingOriginalTime[iI]); } } } for (std::vector<BuildingYieldChange>::iterator it = aBuildingYieldChange.begin(); it != aBuildingYieldChange.end(); ++it) { pNewCity->setBuildingYieldChange((*it).eBuildingClass, (*it).eYield, (*it).iChange); } for (std::vector<BuildingCommerceChange>::iterator it = aBuildingCommerceChange.begin(); it != aBuildingCommerceChange.end(); ++it) { pNewCity->setBuildingCommerceChange((*it).eBuildingClass, (*it).eCommerce, (*it).iChange); } for (BuildingChangeArray::iterator it = aBuildingHappyChange.begin(); it != aBuildingHappyChange.end(); ++it) { pNewCity->setBuildingHappyChange((*it).first, (*it).second); } for (BuildingChangeArray::iterator it = aBuildingHealthChange.begin(); it != aBuildingHealthChange.end(); ++it) { pNewCity->setBuildingHealthChange((*it).first, (*it).second); } for (iI = 0; iI < GC.getNumSpecialistInfos(); ++iI) { pNewCity->changeFreeSpecialistCount((SpecialistTypes)iI, aeFreeSpecialists[iI]); } for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { if (pabHasReligion[iI]) { pNewCity->setHasReligion(((ReligionTypes)iI), true, false, true); } if (pabHolyCity[iI]) { GC.getGameINLINE().setHolyCity(((ReligionTypes)iI), pNewCity, false); } } for (iI = 0; iI < GC.getNumCorporationInfos(); iI++) { if (pabHasCorporation[iI]) { pNewCity->setHasCorporation(((CorporationTypes)iI), true, false); } if (pabHeadquarters[iI]) { GC.getGameINLINE().setHeadquarters(((CorporationTypes)iI), pNewCity, false); } } if (bTrade) { if (isHuman() || (getTeam() == GET_PLAYER(eOldOwner).getTeam())) { pNewCity->changeHurryAngerTimer(iHurryAngerTimer); pNewCity->changeConscriptAngerTimer(iConscriptAngerTimer); pNewCity->changeDefyResolutionAngerTimer(iDefyResolutionAngerTimer); } if (!bRecapture) { pNewCity->changeOccupationTimer(iOccupationTimer); } } if (bConquest) { iTeamCulturePercent = pNewCity->calculateTeamCulturePercent(getTeam()); if (iTeamCulturePercent < GC.getDefineINT("OCCUPATION_CULTURE_PERCENT_THRESHOLD")) { pNewCity->changeOccupationTimer(((GC.getDefineINT("BASE_OCCUPATION_TURNS") + ((pNewCity->getPopulation() * GC.getDefineINT("OCCUPATION_TURNS_POPULATION_PERCENT")) / 100)) * (100 - iTeamCulturePercent)) / 100); } GC.getMapINLINE().verifyUnitValidPlot(); } pCityPlot->setRevealed(GET_PLAYER(eOldOwner).getTeam(), true, false, NO_TEAM, false); pNewCity->updateEspionageVisibility(false); if (bUpdatePlotGroups) { GC.getGameINLINE().updatePlotGroups(); } CvEventReporter::getInstance().cityAcquired(eOldOwner, getID(), pNewCity, bConquest, bTrade); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gPlayerLogLevel >= 1 ) { logBBAI(" Player %d (%S) acquires city %S bConq %d bTrade %d", getID(), getCivilizationDescription(0), pNewCity->getName(0).GetCString(), bConquest, bTrade ); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ SAFE_DELETE_ARRAY(pabHasReligion); SAFE_DELETE_ARRAY(pabHolyCity); SAFE_DELETE_ARRAY(pabHasCorporation); SAFE_DELETE_ARRAY(pabHeadquarters); SAFE_DELETE_ARRAY(paiNumRealBuilding); SAFE_DELETE_ARRAY(paiBuildingOriginalOwner); SAFE_DELETE_ARRAY(paiBuildingOriginalTime); if (bConquest) { CyCity* pyCity = new CyCity(pNewCity); CyArgsList argsList; argsList.add(getID()); // Player ID argsList.add(gDLL->getPythonIFace()->makePythonObject(pyCity)); // pass in city class long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "canRazeCity", argsList.makeFunctionArgs(), &lResult); delete pyCity; // python fxn must not hold on to this pointer if (lResult == 1) { //auto raze based on game rules if (pNewCity->isAutoRaze()) { if (iCaptureGold > 0) { szBuffer = gDLL->getText("TXT_KEY_MISC_PILLAGED_CITY", iCaptureGold, pNewCity->getNameKey()); gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CITYRAZE", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getInterfaceArtInfo("WORLDBUILDER_CITY_EDIT")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pNewCity->getX_INLINE(), pNewCity->getY_INLINE(), true, true); } pNewCity->doTask(TASK_RAZE); } else if (!isHuman()) { AI_conquerCity(pNewCity); // could delete the pointer... } else { //popup raze option eHighestCulturePlayer = pNewCity->getLiberationPlayer(true); bRaze = canRaze(pNewCity); bGift = ((eHighestCulturePlayer != NO_PLAYER) && (eHighestCulturePlayer != getID()) && ((getTeam() == GET_PLAYER(eHighestCulturePlayer).getTeam()) || GET_TEAM(getTeam()).isOpenBorders(GET_PLAYER(eHighestCulturePlayer).getTeam()) || GET_TEAM(GET_PLAYER(eHighestCulturePlayer).getTeam()).isVassal(getTeam()))); if (bRaze || bGift) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_RAZECITY); pInfo->setData1(pNewCity->getID()); pInfo->setData2(eHighestCulturePlayer); pInfo->setData3(iCaptureGold); gDLL->getInterfaceIFace()->addPopup(pInfo, getID()); } else { pNewCity->chooseProduction(); CvEventReporter::getInstance().cityAcquiredAndKept(getID(), pNewCity); } } } } else if (!bTrade) { if (isHuman()) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_DISBANDCITY); pInfo->setData1(pNewCity->getID()); gDLL->getInterfaceIFace()->addPopup(pInfo, getID()); } else { CvEventReporter::getInstance().cityAcquiredAndKept(getID(), pNewCity); } } // Forcing events that deal with the old city not to expire just because we conquered that city for (CvEventMap::iterator it = m_mapEventsOccured.begin(); it != m_mapEventsOccured.end(); ++it) { EventTriggeredData &triggerData = it->second; if((triggerData.m_eOtherPlayer == eOldOwner) && (triggerData.m_iOtherPlayerCityId == iOldCityId)) { triggerData.m_iOtherPlayerCityId = -1; } } } void CvPlayer::killCities() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->kill(false); } GC.getGameINLINE().updatePlotGroups(); } CvWString CvPlayer::getNewCityName() const { CLLNode<CvWString>* pNode; CvWString szName; int iI; for (pNode = headCityNameNode(); (pNode != NULL); pNode = nextCityNameNode(pNode)) { szName = gDLL->getText(pNode->m_data); if (isCityNameValid(szName, true)) { szName = pNode->m_data; break; } } if (szName.empty()) { getCivilizationCityName(szName, getCivilizationType()); } if (szName.empty()) { // Pick a name from another random civ int iRandOffset = GC.getGameINLINE().getSorenRandNum(GC.getNumCivilizationInfos(), "Place Units (Player)"); for (iI = 0; iI < GC.getNumCivilizationInfos(); iI++) { int iLoopName = ((iI + iRandOffset) % GC.getNumCivilizationInfos()); getCivilizationCityName(szName, ((CivilizationTypes)iLoopName)); if (!szName.empty()) { break; } } } if (szName.empty()) { szName = "TXT_KEY_CITY"; } return szName; } void CvPlayer::getCivilizationCityName(CvWString& szBuffer, CivilizationTypes eCivilization) const { int iRandOffset; int iLoopName; int iI; if (isBarbarian() || isMinorCiv()) { iRandOffset = GC.getGameINLINE().getSorenRandNum(GC.getCivilizationInfo(eCivilization).getNumCityNames(), "Place Units (Player)"); } else { iRandOffset = 0; } for (iI = 0; iI < GC.getCivilizationInfo(eCivilization).getNumCityNames(); iI++) { iLoopName = ((iI + iRandOffset) % GC.getCivilizationInfo(eCivilization).getNumCityNames()); CvWString szName = gDLL->getText(GC.getCivilizationInfo(eCivilization).getCityNames(iLoopName)); if (isCityNameValid(szName, true)) { szBuffer = GC.getCivilizationInfo(eCivilization).getCityNames(iLoopName); break; } } } bool CvPlayer::isCityNameValid(CvWString& szName, bool bTestDestroyed) const { CvCity* pLoopCity; int iLoop; if (bTestDestroyed) { if (GC.getGameINLINE().isDestroyedCityName(szName)) { return false; } for (int iPlayer = 0; iPlayer < MAX_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); for (pLoopCity = kLoopPlayer.firstCity(&iLoop); pLoopCity != NULL; pLoopCity = kLoopPlayer.nextCity(&iLoop)) { if (pLoopCity->getName() == szName) { return false; } } } } else { for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getName() == szName) { return false; } } } return true; } CvUnit* CvPlayer::initUnit(UnitTypes eUnit, int iX, int iY, UnitAITypes eUnitAI, DirectionTypes eFacingDirection) { PROFILE_FUNC(); FAssertMsg(eUnit != NO_UNIT, "Unit is not assigned a valid value"); CvUnit* pUnit = addUnit(); FAssertMsg(pUnit != NULL, "Unit is not assigned a valid value"); if (NULL != pUnit) { pUnit->init(pUnit->getID(), eUnit, ((eUnitAI == NO_UNITAI) ? ((UnitAITypes)(GC.getUnitInfo(eUnit).getDefaultUnitAIType())) : eUnitAI), getID(), iX, iY, eFacingDirection); } return pUnit; } void CvPlayer::disbandUnit(bool bAnnounce) { CvUnit* pLoopUnit; CvUnit* pBestUnit; wchar szBuffer[1024]; int iValue; int iBestValue; int iLoop; iBestValue = MAX_INT; pBestUnit = NULL; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (!(pLoopUnit->hasCargo())) { if (!(pLoopUnit->isGoldenAge())) { if (pLoopUnit->getUnitInfo().getProductionCost() > 0) { if (!(pLoopUnit->isMilitaryHappiness()) || !(pLoopUnit->plot()->isCity()) || (pLoopUnit->plot()->plotCount(PUF_isMilitaryHappiness, -1, -1, getID()) > 1)) { iValue = (10000 + GC.getGameINLINE().getSorenRandNum(1000, "Disband Unit")); iValue += (pLoopUnit->getUnitInfo().getProductionCost() * 5); iValue += (pLoopUnit->getExperience() * 20); iValue += (pLoopUnit->getLevel() * 100); if (pLoopUnit->canDefend() && pLoopUnit->plot()->isCity()) { iValue *= 2; } if (pLoopUnit->plot()->getTeam() == pLoopUnit->getTeam()) { iValue *= 3; } switch (pLoopUnit->AI_getUnitAIType()) { case UNITAI_UNKNOWN: case UNITAI_ANIMAL: break; case UNITAI_SETTLE: iValue *= 20; break; case UNITAI_WORKER: iValue *= 10; break; case UNITAI_ATTACK: case UNITAI_ATTACK_CITY: case UNITAI_COLLATERAL: case UNITAI_PILLAGE: case UNITAI_RESERVE: case UNITAI_COUNTER: iValue *= 2; break; case UNITAI_CITY_DEFENSE: case UNITAI_CITY_COUNTER: case UNITAI_CITY_SPECIAL: case UNITAI_PARADROP: iValue *= 6; break; case UNITAI_EXPLORE: iValue *= 15; break; case UNITAI_MISSIONARY: iValue *= 8; break; case UNITAI_PROPHET: case UNITAI_ARTIST: case UNITAI_SCIENTIST: case UNITAI_GENERAL: case UNITAI_MERCHANT: case UNITAI_ENGINEER: break; case UNITAI_SPY: iValue *= 12; break; case UNITAI_ICBM: iValue *= 4; break; case UNITAI_WORKER_SEA: iValue *= 18; break; case UNITAI_ATTACK_SEA: case UNITAI_RESERVE_SEA: case UNITAI_ESCORT_SEA: break; case UNITAI_EXPLORE_SEA: iValue *= 25; break; case UNITAI_ASSAULT_SEA: case UNITAI_SETTLER_SEA: case UNITAI_MISSIONARY_SEA: case UNITAI_SPY_SEA: case UNITAI_CARRIER_SEA: case UNITAI_MISSILE_CARRIER_SEA: iValue *= 5; break; case UNITAI_PIRATE_SEA: case UNITAI_ATTACK_AIR: break; case UNITAI_DEFENSE_AIR: case UNITAI_CARRIER_AIR: case UNITAI_MISSILE_AIR: iValue *= 3; break; default: FAssert(false); break; } if (pLoopUnit->getUnitInfo().getExtraCost() > 0) { iValue /= (pLoopUnit->getUnitInfo().getExtraCost() + 1); } if (iValue < iBestValue) { iBestValue = iValue; pBestUnit = pLoopUnit; } } } } } } if (pBestUnit != NULL) { swprintf(szBuffer, gDLL->getText("TXT_KEY_MISC_UNIT_DISBANDED_NO_MONEY", pBestUnit->getNameKey()).GetCString()); gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_UNITDISBANDED", MESSAGE_TYPE_MINOR_EVENT, pBestUnit->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pBestUnit->getX_INLINE(), pBestUnit->getY_INLINE(), true, true); FAssert(!(pBestUnit->isGoldenAge())); pBestUnit->kill(false); } } void CvPlayer::killUnits() { CvUnit* pLoopUnit; int iLoop; for (pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { pLoopUnit->kill(false); } } // XXX should pUnit be a CvSelectionGroup??? // Returns the next unit in the cycle... CvSelectionGroup* CvPlayer::cycleSelectionGroups(CvUnit* pUnit, bool bForward, bool bWorkers, bool* pbWrap) { CLLNode<int>* pSelectionGroupNode; CLLNode<int>* pFirstSelectionGroupNode; CvSelectionGroup* pLoopSelectionGroup; if (pbWrap != NULL) { *pbWrap = false; } pSelectionGroupNode = headGroupCycleNode(); if (pUnit != NULL) { while (pSelectionGroupNode != NULL) { if (getSelectionGroup(pSelectionGroupNode->m_data) == pUnit->getGroup()) { if (bForward) { pSelectionGroupNode = nextGroupCycleNode(pSelectionGroupNode); } else { pSelectionGroupNode = previousGroupCycleNode(pSelectionGroupNode); } break; } pSelectionGroupNode = nextGroupCycleNode(pSelectionGroupNode); } } if (pSelectionGroupNode == NULL) { if (bForward) { pSelectionGroupNode = headGroupCycleNode(); } else { pSelectionGroupNode = tailGroupCycleNode(); } if (pbWrap != NULL) { *pbWrap = true; } } if (pSelectionGroupNode != NULL) { pFirstSelectionGroupNode = pSelectionGroupNode; while (true) { pLoopSelectionGroup = getSelectionGroup(pSelectionGroupNode->m_data); FAssertMsg(pLoopSelectionGroup != NULL, "LoopSelectionGroup is not assigned a valid value"); if (pLoopSelectionGroup->readyToSelect()) { if (!bWorkers || pLoopSelectionGroup->hasWorker()) { if (pUnit && pLoopSelectionGroup == pUnit->getGroup()) { if (pbWrap != NULL) { *pbWrap = true; } } return pLoopSelectionGroup; } } if (bForward) { pSelectionGroupNode = nextGroupCycleNode(pSelectionGroupNode); if (pSelectionGroupNode == NULL) { pSelectionGroupNode = headGroupCycleNode(); if (pbWrap != NULL) { *pbWrap = true; } } } else { pSelectionGroupNode = previousGroupCycleNode(pSelectionGroupNode); if (pSelectionGroupNode == NULL) { pSelectionGroupNode = tailGroupCycleNode(); if (pbWrap != NULL) { *pbWrap = true; } } } if (pSelectionGroupNode == pFirstSelectionGroupNode) { break; } } } return NULL; } bool CvPlayer::hasTrait(TraitTypes eTrait) const { FAssertMsg((getLeaderType() >= 0), "getLeaderType() is less than zero"); FAssertMsg((eTrait >= 0), "eTrait is less than zero"); return GC.getLeaderHeadInfo(getLeaderType()).hasTrait(eTrait); } /************************************************************************************************/ /* AI_AUTO_PLAY_MOD 07/09/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ void CvPlayer::setHumanDisabled( bool newVal ) { m_bDisableHuman = newVal; updateHuman(); } bool CvPlayer::isHumanDisabled( ) { return m_bDisableHuman; } /************************************************************************************************/ /* AI_AUTO_PLAY_MOD END */ /************************************************************************************************/ bool CvPlayer::isHuman() const { return m_bHuman; } void CvPlayer::updateHuman() { if (getID() == NO_PLAYER) { m_bHuman = false; } else { /************************************************************************************************/ /* AI_AUTO_PLAY_MOD 09/01/07 MRGENIE */ /* */ /* */ /************************************************************************************************/ /* m_bHuman = GC.getInitCore().getHuman(getID()); */ if( m_bDisableHuman ) { m_bHuman = false; } else { m_bHuman = GC.getInitCore().getHuman(getID()); } /************************************************************************************************/ /* AI_AUTO_PLAY_MOD END */ /************************************************************************************************/ } } bool CvPlayer::isBarbarian() const { return (getID() == BARBARIAN_PLAYER); } const wchar* CvPlayer::getName(uint uiForm) const { if (GC.getInitCore().getLeaderName(getID(), uiForm).empty() || (GC.getGameINLINE().isMPOption(MPOPTION_ANONYMOUS) && isAlive() && GC.getGameINLINE().getGameState() == GAMESTATE_ON)) { return GC.getLeaderHeadInfo(getLeaderType()).getDescription(uiForm); } else { return GC.getInitCore().getLeaderName(getID(), uiForm); } } const wchar* CvPlayer::getNameKey() const { if (GC.getInitCore().getLeaderNameKey(getID()).empty() || (GC.getGameINLINE().isMPOption(MPOPTION_ANONYMOUS) && isAlive())) { return GC.getLeaderHeadInfo(getLeaderType()).getTextKeyWide(); } else { return GC.getInitCore().getLeaderNameKey(getID()); } } const wchar* CvPlayer::getCivilizationDescription(uint uiForm) const { if (GC.getInitCore().getCivDescription(getID(), uiForm).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getDescription(uiForm); } else { return GC.getInitCore().getCivDescription(getID(), uiForm); } } const wchar* CvPlayer::getCivilizationDescriptionKey() const { if (GC.getInitCore().getCivDescriptionKey(getID()).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getTextKeyWide(); } else { return GC.getInitCore().getCivDescriptionKey(getID()); } } const wchar* CvPlayer::getCivilizationShortDescription(uint uiForm) const { if (GC.getInitCore().getCivShortDesc(getID(), uiForm).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getShortDescription(uiForm); } else { return GC.getInitCore().getCivShortDesc(getID(), uiForm); } } const wchar* CvPlayer::getCivilizationShortDescriptionKey() const { if (GC.getInitCore().getCivShortDescKey(getID()).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getShortDescriptionKey(); } else { return GC.getInitCore().getCivShortDescKey(getID()); } } const wchar* CvPlayer::getCivilizationAdjective(uint uiForm) const { if (GC.getInitCore().getCivAdjective(getID(), uiForm).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getAdjective(uiForm); } else { return GC.getInitCore().getCivAdjective(getID(), uiForm); } } const wchar* CvPlayer::getCivilizationAdjectiveKey() const { if (GC.getInitCore().getCivAdjectiveKey(getID()).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getAdjectiveKey(); } else { return GC.getInitCore().getCivAdjectiveKey(getID()); } } CvWString CvPlayer::getFlagDecal() const { if (GC.getInitCore().getFlagDecal(getID()).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getFlagTexture(); } else { return GC.getInitCore().getFlagDecal(getID()); } } bool CvPlayer::isWhiteFlag() const { if (GC.getInitCore().getFlagDecal(getID()).empty()) { return GC.getCivilizationInfo(getCivilizationType()).getArtInfo()->isWhiteFlag(); } else { return GC.getInitCore().getWhiteFlag(getID()); } } const wchar* CvPlayer::getStateReligionName(uint uiForm) const { return GC.getReligionInfo(getStateReligion()).getDescription(uiForm); } const wchar* CvPlayer::getStateReligionKey() const { if (getStateReligion() != NO_RELIGION) { return GC.getReligionInfo(getStateReligion()).getTextKeyWide(); } return L"TXT_KEY_MISC_NO_STATE_RELIGION"; } const CvWString CvPlayer::getBestAttackUnitName(uint uiForm) const { return gDLL->getObjectText((CvString)getBestAttackUnitKey(), uiForm, true); } const CvWString CvPlayer::getWorstEnemyName() const { TeamTypes eWorstEnemy; eWorstEnemy = GET_TEAM(getTeam()).AI_getWorstEnemy(); if (eWorstEnemy != NO_TEAM) { return GET_TEAM(eWorstEnemy).getName(); } return ""; } const wchar* CvPlayer::getBestAttackUnitKey() const { CvCity* pCapitalCity; CvCity* pLoopCity; UnitTypes eBestUnit; int iLoop; eBestUnit = NO_UNIT; pCapitalCity = getCapitalCity(); if (pCapitalCity != NULL) { eBestUnit = pCapitalCity->AI_bestUnitAI(UNITAI_ATTACK, true); } if (eBestUnit == NO_UNIT) { for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { eBestUnit = pLoopCity->AI_bestUnitAI(UNITAI_ATTACK, true); if (eBestUnit != NO_UNIT) { break; } } } if (eBestUnit != NO_UNIT) { return GC.getUnitInfo(eBestUnit).getTextKeyWide(); } return L"TXT_KEY_MISC_NO_UNIT"; } ArtStyleTypes CvPlayer::getArtStyleType() const { if (GC.getInitCore().getArtStyle(getID()) == NO_ARTSTYLE) { return ((ArtStyleTypes)(GC.getCivilizationInfo(getCivilizationType()).getArtStyleType())); } else { return GC.getInitCore().getArtStyle(getID()); } } const TCHAR* CvPlayer::getUnitButton(UnitTypes eUnit) const { return GC.getUnitInfo(eUnit).getArtInfo(0, getCurrentEra(), (UnitArtStyleTypes) GC.getCivilizationInfo(getCivilizationType()).getUnitArtStyleType())->getButton(); } void CvPlayer::doTurn() { PROFILE_FUNC(); CvCity* pLoopCity; int iLoop; FAssertMsg(isAlive(), "isAlive is expected to be true"); FAssertMsg(!hasBusyUnit() || GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS) || GC.getGameINLINE().isSimultaneousTeamTurns(), "End of turn with busy units in a sequential-turn game"); CvEventReporter::getInstance().beginPlayerTurn( GC.getGameINLINE().getGameTurn(), getID()); doUpdateCacheOnTurn(); GC.getGameINLINE().verifyDeals(); AI_doTurnPre(); if (getRevolutionTimer() > 0) { changeRevolutionTimer(-1); } if (getConversionTimer() > 0) { changeConversionTimer(-1); } setConscriptCount(0); AI_assignWorkingPlots(); if (0 == GET_TEAM(getTeam()).getHasMetCivCount(true) || GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { setCommercePercent(COMMERCE_ESPIONAGE, 0); } verifyGoldCommercePercent(); doGold(); doResearch(); doEspionagePoints(); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 05/08/09 jdog5000 */ /* */ /* City AI */ /************************************************************************************************/ // New function to handle wonder construction in a centralized manner GET_PLAYER(getID()).AI_doCentralizedProduction(); /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->doTurn(); } /********************************************************************************/ /* Worker Counting 04.08.2010 Fuyu */ /********************************************************************************/ //Fuyu WorkersHave check #ifdef _DEBUG int iTotalWorkersHave = 0; int iTotalWorkersFinishedSoon = 0; int iNumWorkerAIUnits = AI_getNumAIUnits(UNITAI_WORKER); for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalWorkersHave += pLoopCity->AI_getWorkersHave(); //From AI_updateWorkersNeededHere if (pLoopCity->getProductionUnit() != NO_UNIT) { if (pLoopCity->getProductionUnitAI() == UNITAI_WORKER) { //if (pLoopCity->getProductionTurnsLeft() <= 2) // doProduction has already happened if (pLoopCity->getProductionTurnsLeft() <= 1) { iTotalWorkersFinishedSoon++; } } } } if (iTotalWorkersHave != (iNumWorkerAIUnits + iTotalWorkersFinishedSoon)) { if( gPlayerLogLevel >= 1 ) logBBAI(" Player %d (%S) thinks he has %d workers but actually has %d (%d)", getID(), getCivilizationDescription(0), iTotalWorkersHave, (iNumWorkerAIUnits + iTotalWorkersFinishedSoon), iTotalWorkersFinishedSoon); FAssertMsg(iTotalWorkersHave <= (iNumWorkerAIUnits + iTotalWorkersFinishedSoon), "Player has less workers than he thinks he has"); } #endif /********************************************************************************/ /* Worker Counting END */ /********************************************************************************/ if (getGoldenAgeTurns() > 0) { changeGoldenAgeTurns(-1); } if (getAnarchyTurns() > 0) { changeAnarchyTurns(-1); } verifyCivics(); updateTradeRoutes(); updateWarWearinessPercentAnger(); doEvents(); updateEconomyHistory(GC.getGameINLINE().getGameTurn(), calculateTotalCommerce()); updateIndustryHistory(GC.getGameINLINE().getGameTurn(), calculateTotalYield(YIELD_PRODUCTION)); updateAgricultureHistory(GC.getGameINLINE().getGameTurn(), calculateTotalYield(YIELD_FOOD)); updatePowerHistory(GC.getGameINLINE().getGameTurn(), getPower()); updateCultureHistory(GC.getGameINLINE().getGameTurn(), countTotalCulture()); updateEspionageHistory(GC.getGameINLINE().getGameTurn(), GET_TEAM(getTeam()).getEspionagePointsEver()); expireMessages(); // turn log gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); AI_doTurnPost(); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 07/08/09 jdog5000 */ /* */ /* Debug */ /************************************************************************************************/ if( GC.getGameINLINE().isDebugMode() ) { GC.getGameINLINE().updateColoredPlots(); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ CvEventReporter::getInstance().endPlayerTurn( GC.getGameINLINE().getGameTurn(), getID()); } void CvPlayer::doTurnUnits() { PROFILE_FUNC(); CvSelectionGroup* pLoopSelectionGroup; int iLoop; AI_doTurnUnitsPre(); for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup != NULL; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { pLoopSelectionGroup->doDelayedDeath(); } for (int iPass = 0; iPass < 4; iPass++) { for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup != NULL; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { switch (pLoopSelectionGroup->getDomainType()) { case DOMAIN_AIR: if (iPass == 1) { pLoopSelectionGroup->doTurn(); } break; case DOMAIN_SEA: if (iPass == 2) { pLoopSelectionGroup->doTurn(); } break; case DOMAIN_LAND: if (iPass == 3) { pLoopSelectionGroup->doTurn(); } break; case DOMAIN_IMMOBILE: if (iPass == 0) { pLoopSelectionGroup->doTurn(); } break; case NO_DOMAIN: FAssertMsg(NULL == pLoopSelectionGroup->getHeadUnit(), "Unit with no Domain"); default: if (iPass == 3) { pLoopSelectionGroup->doTurn(); } break; } } } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getFAStarIFace()->ForceReset(&GC.getInterfacePathFinder()); gDLL->getInterfaceIFace()->setDirty(Waypoints_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); } gDLL->getInterfaceIFace()->setDirty(UnitInfo_DIRTY_BIT, true); AI_doTurnUnitsPost(); } void CvPlayer::verifyCivics() { int iI, iJ; if (!isAnarchy()) { for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { if (!canDoCivics(getCivics((CivicOptionTypes)iI))) { for (iJ = 0; iJ < GC.getNumCivicInfos(); iJ++) { if (GC.getCivicInfo((CivicTypes)iJ).getCivicOptionType() == iI) { if (canDoCivics((CivicTypes)iJ)) { setCivics(((CivicOptionTypes)iI), ((CivicTypes)iJ)); break; } } } } } } } void CvPlayer::updatePlotGroups() { PROFILE_FUNC(); CvPlotGroup* pLoopPlotGroup; int iLoop; int iI; if (!(GC.getGameINLINE().isFinalInitialized())) { return; } for(pLoopPlotGroup = firstPlotGroup(&iLoop); pLoopPlotGroup != NULL; pLoopPlotGroup = nextPlotGroup(&iLoop)) { pLoopPlotGroup->recalculatePlots(); } for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { GC.getMapINLINE().plotByIndexINLINE(iI)->updatePlotGroup(getID(), false); } updateTradeRoutes(); } void CvPlayer::updateYield() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateYield(); } } void CvPlayer::updateMaintenance() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateMaintenance(); } } void CvPlayer::updatePowerHealth() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updatePowerHealth(); } } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::updateExtraBuildingHappiness(bool bLimited) { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateExtraBuildingHappiness(bLimited); } } //Fuyu bLimited void CvPlayer::updateExtraBuildingHealth(bool bLimited) { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateExtraBuildingHealth(bLimited); } } //Fuyu bLimited void CvPlayer::updateFeatureHappiness(bool bLimited) { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateFeatureHappiness(bLimited); } } //Fuyu bLimited void CvPlayer::updateReligionHappiness(bool bLimited) { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateReligionHappiness(bLimited); } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ void CvPlayer::updateExtraSpecialistYield() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateExtraSpecialistYield(); } } void CvPlayer::updateCommerce(CommerceTypes eCommerce) { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateCommerce(eCommerce); } } void CvPlayer::updateCommerce() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateCommerce(); } } void CvPlayer::updateBuildingCommerce() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateBuildingCommerce(); } } void CvPlayer::updateReligionCommerce() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateReligionCommerce(); } } void CvPlayer::updateCorporation() { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->updateCorporation(); } } void CvPlayer::updateCityPlotYield() { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->plot()->updateYield(); } } void CvPlayer::updateCitySight(bool bIncrement, bool bUpdatePlotGroups) { CvCity* pLoopCity; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->plot()->updateSight(bIncrement, bUpdatePlotGroups); } } void CvPlayer::updateTradeRoutes() { CLLNode<int>* pCityNode; CvCity* pLoopCity; CvCity* pListCity; CLinkList<int> cityList; int iTotalTradeModifier; int iLoop; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->clearTradeRoutes(); } cityList.clear(); for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalTradeModifier = pLoopCity->totalTradeModifier(); pCityNode = cityList.head(); while (pCityNode != NULL) { pListCity = getCity(pCityNode->m_data); if (iTotalTradeModifier > pListCity->totalTradeModifier()) { cityList.insertBefore(pLoopCity->getID(), pCityNode); break; } else { pCityNode = cityList.next(pCityNode); } } if (pCityNode == NULL) { cityList.insertAtEnd(pLoopCity->getID()); } } pCityNode = cityList.head(); while (pCityNode != NULL) { getCity(pCityNode->m_data)->updateTradeRoutes(); pCityNode = cityList.next(pCityNode); } } void CvPlayer::updatePlunder(int iChange, bool bUpdatePlotGroups) { int iLoop; for (CvUnit* pLoopUnit = firstUnit(&iLoop); NULL != pLoopUnit; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->isBlockading()) { pLoopUnit->updatePlunder(iChange, bUpdatePlotGroups); } } } void CvPlayer::updateTimers() { CvSelectionGroup* pLoopSelectionGroup; int iLoop; for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { pLoopSelectionGroup->updateTimers(); // could destroy the selection group... } // if a unit was busy, perhaps it was not quite deleted yet, give it one more try if (getNumSelectionGroups() > getNumUnits()) { for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { pLoopSelectionGroup->doDelayedDeath(); // could destroy the selection group... } } FAssertMsg(getNumSelectionGroups() <= getNumUnits(), "The number of Units is expected not to exceed the number of Selection Groups"); } bool CvPlayer::hasReadyUnit(bool bAny) const { PROFILE_FUNC(); CvSelectionGroup* pLoopSelectionGroup; int iLoop; for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { if (pLoopSelectionGroup->readyToMove(bAny)) { return true; } } return false; } bool CvPlayer::hasAutoUnit() const { PROFILE_FUNC(); CvSelectionGroup* pLoopSelectionGroup; int iLoop; for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { if (pLoopSelectionGroup->readyToAuto()) { return true; } } return false; } bool CvPlayer::hasBusyUnit() const { PROFILE_FUNC(); CvSelectionGroup* pLoopSelectionGroup; int iLoop; for(pLoopSelectionGroup = firstSelectionGroup(&iLoop); pLoopSelectionGroup; pLoopSelectionGroup = nextSelectionGroup(&iLoop)) { if (pLoopSelectionGroup->isBusy()) { if (pLoopSelectionGroup->getNumUnits() == 0) { pLoopSelectionGroup->kill(); return false; } return true; } } return false; } /************************************************************************************************/ /* UNOFFICIAL_PATCH 12/07/09 EmperorFool */ /* */ /* Bugfix */ /************************************************************************************************/ // Free Tech Popup Fix bool CvPlayer::isChoosingFreeTech() const { return m_bChoosingFreeTech; } void CvPlayer::setChoosingFreeTech(bool bValue) { m_bChoosingFreeTech = bValue; } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ void CvPlayer::chooseTech(int iDiscover, CvWString szText, bool bFront) { /************************************************************************************************/ /* UNOFFICIAL_PATCH 12/07/09 EmperorFool */ /* */ /* Bugfix */ /************************************************************************************************/ // Free Tech Popup Fix if (iDiscover > 0) { setChoosingFreeTech(true); } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_CHOOSETECH); if (NULL != pInfo) { pInfo->setData1(iDiscover); pInfo->setText(szText); gDLL->getInterfaceIFace()->addPopup(pInfo, getID(), false, bFront); } } int CvPlayer::calculateScore(bool bFinal, bool bVictory) { PROFILE_FUNC(); if (!isAlive()) { return 0; } if (GET_TEAM(getTeam()).getNumMembers() == 0) { return 0; } long lScore = 0; CyArgsList argsList; argsList.add((int) getID()); argsList.add(bFinal); argsList.add(bVictory); gDLL->getPythonIFace()->callFunction(PYGameModule, "calculateScore", argsList.makeFunctionArgs(), &lScore); return ((int)lScore); } int CvPlayer::findBestFoundValue() const { CvArea* pLoopArea; int iValue; int iBestValue; int iLoop; iBestValue = 0; for(pLoopArea = GC.getMapINLINE().firstArea(&iLoop); pLoopArea != NULL; pLoopArea = GC.getMapINLINE().nextArea(&iLoop)) { iValue = pLoopArea->getBestFoundValue(getID()); if (iValue > iBestValue) { iBestValue = iValue; } } return iBestValue; } int CvPlayer::upgradeAllPrice(UnitTypes eUpgradeUnit, UnitTypes eFromUnit) { CvUnit* pLoopUnit; int iPrice; int iLoop; iPrice = 0; // Loop through units and determine the total power of this player's military for (pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->getUnitType() == eFromUnit) { if (pLoopUnit->canUpgrade(eUpgradeUnit, true)) { iPrice += pLoopUnit->upgradePrice(eUpgradeUnit); } } } return iPrice; } /************************************************************************************************/ /* BETTER_BTS_AI_MOD 11/14/09 jdog5000 */ /* */ /* General AI */ /************************************************************************************************/ int CvPlayer::countReligionSpreadUnits(CvArea* pArea, ReligionTypes eReligion, bool bIncludeTraining) const { PROFILE_FUNC(); CvUnit* pLoopUnit; int iCount; int iLoop; iCount = 0; for (pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->getArea() == pArea->getID()) { if (pLoopUnit->getUnitInfo().getReligionSpreads(eReligion) > 0) { iCount++; } } } if( bIncludeTraining ) { CvCity* pLoopCity; for( pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop) ) { UnitTypes eUnit = pLoopCity->getProductionUnit(); if( eUnit != NO_UNIT ) { if(GC.getUnitInfo(eUnit).getReligionSpreads(eReligion) > 0) { iCount++; } } } } return iCount; } int CvPlayer::countCorporationSpreadUnits(CvArea* pArea, CorporationTypes eCorporation, bool bIncludeTraining) const { PROFILE_FUNC(); int iCount = 0; int iLoop; for (CvUnit* pLoopUnit = firstUnit(&iLoop); NULL != pLoopUnit; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->area() == pArea) { if (pLoopUnit->getUnitInfo().getCorporationSpreads(eCorporation) > 0) { ++iCount; } } } if( bIncludeTraining ) { CvCity* pLoopCity; for( pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop) ) { UnitTypes eUnit = pLoopCity->getProductionUnit(); if( eUnit != NO_UNIT ) { if(GC.getUnitInfo(eUnit).getCorporationSpreads(eCorporation) > 0) { iCount++; } } } } return iCount; } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ int CvPlayer::countNumCoastalCities() const { CvCity* pLoopCity; int iCount; int iLoop; iCount = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->isCoastal(GC.getMIN_WATER_SIZE_FOR_OCEAN())) { iCount++; } } return iCount; } int CvPlayer::countNumCoastalCitiesByArea(CvArea* pArea) const { CvCity* pLoopCity; int iCount; int iLoop; iCount = 0; int iAreaID = pArea->getID(); for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->isCoastal(GC.getMIN_WATER_SIZE_FOR_OCEAN())) { if ((pLoopCity->getArea() == iAreaID) || pLoopCity->plot()->isAdjacentToArea(iAreaID)) { iCount++; } } } return iCount; } int CvPlayer::countTotalCulture() const { CvCity* pLoopCity; int iCount; int iLoop; iCount = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iCount += pLoopCity->getCultureTimes100(getID()); } return iCount/100; } int CvPlayer::countOwnedBonuses(BonusTypes eBonus) const { PROFILE("CvPlayer::countOwnedBonuses"); CvCity* pLoopCity; CvPlot* pLoopPlot; int iCount; int iI; int iLoop; bool bAdvancedStart = (getAdvancedStartPoints() >= 0) && (getCurrentEra() < 3); iCount = 0; //count bonuses outside city radius for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if ((pLoopPlot->getOwnerINLINE() == getID()) && !pLoopPlot->isCityRadius()) { if (pLoopPlot->getBonusType(getTeam()) == eBonus) { iCount++; } } else if (bAdvancedStart && pLoopPlot->isRevealed(getTeam(), false)) { if (pLoopPlot->getBonusType(getTeam()) == eBonus) { iCount++; } } } //count bonuses inside city radius or easily claimed for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iCount += pLoopCity->AI_countNumBonuses(eBonus, true, pLoopCity->getCommerceRate(COMMERCE_CULTURE) > 0, -1); } return iCount; } int CvPlayer::countUnimprovedBonuses(CvArea* pArea, CvPlot* pFromPlot) const { PROFILE_FUNC(); CvPlot* pLoopPlot; ImprovementTypes eImprovement; BuildTypes eBuild; BonusTypes eNonObsoleteBonus; int iCount; int iI, iJ; gDLL->getFAStarIFace()->ForceReset(&GC.getBorderFinder()); iCount = 0; for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if (pLoopPlot->area() == pArea) { if (pLoopPlot->getOwnerINLINE() == getID()) { if (!(pLoopPlot->isCity())) { eNonObsoleteBonus = pLoopPlot->getNonObsoleteBonusType(getTeam()); if (eNonObsoleteBonus != NO_BONUS) { eImprovement = pLoopPlot->getImprovementType(); if ((eImprovement == NO_IMPROVEMENT) || !(GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus))) { if ((pFromPlot == NULL) || gDLL->getFAStarIFace()->GeneratePath(&GC.getBorderFinder(), pFromPlot->getX_INLINE(), pFromPlot->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), false, getID(), true)) { for (iJ = 0; iJ < GC.getNumBuildInfos(); iJ++) { eBuild = ((BuildTypes)iJ); if (GC.getBuildInfo(eBuild).getImprovement() != NO_IMPROVEMENT) { if (GC.getImprovementInfo((ImprovementTypes)(GC.getBuildInfo(eBuild).getImprovement())).isImprovementBonusTrade(eNonObsoleteBonus)) { if (canBuild(pLoopPlot, eBuild)) { iCount++; } } } } } } } } } } } return iCount; } int CvPlayer::countCityFeatures(FeatureTypes eFeature) const { PROFILE_FUNC(); CvCity* pLoopCity; CvPlot* pLoopPlot; int iCount; int iLoop; int iI; iCount = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { for (iI = 0; iI < NUM_CITY_PLOTS; iI++) { pLoopPlot = plotCity(pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE(), iI); if (pLoopPlot != NULL) { if (pLoopPlot->getFeatureType() == eFeature) { iCount++; } } } } return iCount; } int CvPlayer::countNumBuildings(BuildingTypes eBuilding) const { PROFILE_FUNC(); CvCity* pLoopCity; int iCount; int iLoop; iCount = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getNumBuilding(eBuilding) > 0) { iCount += pLoopCity->getNumBuilding(eBuilding); } } return iCount; } int CvPlayer::countNumCitiesConnectedToCapital() const { CvCity* pLoopCity; int iCount; int iLoop; iCount = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->isConnectedToCapital()) { iCount++; } } return iCount; } int CvPlayer::countPotentialForeignTradeCities(CvArea* pIgnoreArea) const { int iTempValue; int iCount; int iI; iCount = 0; for (iI = 0; iI < MAX_CIV_TEAMS; iI++) { if (GET_TEAM((TeamTypes)iI).isAlive()) { if (iI != getTeam()) { if (GET_TEAM(getTeam()).isFreeTrade((TeamTypes)iI)) { iTempValue = GET_TEAM((TeamTypes)iI).getNumCities(); if (pIgnoreArea != NULL) { iTempValue -= GET_TEAM((TeamTypes)iI).countNumCitiesByArea(pIgnoreArea); } iCount += iTempValue; } } } } return iCount; } int CvPlayer::countPotentialForeignTradeCitiesConnected() const { CvCity* pCapitalCity; CvCity* pLoopCity; int iCount; int iLoop; int iI; iCount = 0; pCapitalCity = getCapitalCity(); if (pCapitalCity != NULL) { for (iI = 0; iI < MAX_CIV_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam()) { if (GET_TEAM(getTeam()).isFreeTrade(GET_PLAYER((PlayerTypes)iI).getTeam())) { for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop)) { FAssert(pLoopCity->getOwnerINLINE() != getID()); FAssert(pLoopCity->getTeam() != getTeam()); if (pLoopCity->plotGroup(getID()) == pCapitalCity->plotGroup(getID())) { iCount++; } } } } } } } return iCount; } bool CvPlayer::canContact(PlayerTypes ePlayer) const { if (ePlayer == getID()) { return false; } if (!isAlive() || !(GET_PLAYER(ePlayer).isAlive())) { return false; } if (isBarbarian() || GET_PLAYER(ePlayer).isBarbarian()) { return false; } if (isMinorCiv() || GET_PLAYER(ePlayer).isMinorCiv()) { return false; } if (getTeam() != GET_PLAYER(ePlayer).getTeam()) { if (!(GET_TEAM(getTeam()).isHasMet(GET_PLAYER(ePlayer).getTeam()))) { return false; } if (atWar(getTeam(), GET_PLAYER(ePlayer).getTeam())) { if (!(GET_TEAM(getTeam()).canChangeWarPeace(GET_PLAYER(ePlayer).getTeam()))) { return false; } } if (isHuman() || GET_PLAYER(ePlayer).isHuman()) { if (GC.getGameINLINE().isOption(GAMEOPTION_ALWAYS_WAR)) { return false; } } } return true; } void CvPlayer::contact(PlayerTypes ePlayer) { CvDiploParameters* pDiplo; if (!canContact(ePlayer) || isTurnDone()) { return; } if (GET_PLAYER(ePlayer).isHuman()) { if (GC.getGameINLINE().isPbem() || GC.getGameINLINE().isHotSeat() || (GC.getGameINLINE().isPitboss() && !gDLL->isConnected(GET_PLAYER(ePlayer).getNetID()))) { if (gDLL->isMPDiplomacy()) { gDLL->beginMPDiplomacy(ePlayer, false, false); } } else { if (gDLL->getInterfaceIFace()->isFlashing(ePlayer)) { if (!gDLL->getInterfaceIFace()->isDiplomacyLocked()) { gDLL->getInterfaceIFace()->setDiplomacyLocked(true); gDLL->sendContactCiv(NETCONTACT_RESPONSE, ePlayer); } } else { gDLL->sendContactCiv(NETCONTACT_INITIAL, ePlayer); } } } else { pDiplo = new CvDiploParameters(ePlayer); FAssert(pDiplo != NULL); if (gDLL->ctrlKey()) { pDiplo->setDiploComment((DiploCommentTypes)GC.getInfoTypeForString("AI_DIPLOCOMMENT_TRADING")); } gDLL->getInterfaceIFace()->setDiploQueue(pDiplo, GC.getGameINLINE().getActivePlayer()); } } void CvPlayer::handleDiploEvent(DiploEventTypes eDiploEvent, PlayerTypes ePlayer, int iData1, int iData2) { CivicTypes* paeNewCivics; CvCity* pCity; int iI; FAssertMsg(ePlayer != getID(), "shouldn't call this function on ourselves"); switch (eDiploEvent) { case DIPLOEVENT_CONTACT: AI_setFirstContact(ePlayer, true); GET_PLAYER(ePlayer).AI_setFirstContact(getID(), true); break; case DIPLOEVENT_AI_CONTACT: break; case DIPLOEVENT_FAILED_CONTACT: AI_setFirstContact(ePlayer, true); GET_PLAYER(ePlayer).AI_setFirstContact(getID(), true); break; case DIPLOEVENT_GIVE_HELP: AI_changeMemoryCount(ePlayer, MEMORY_GIVE_HELP, 1); forcePeace(ePlayer); break; case DIPLOEVENT_REFUSED_HELP: AI_changeMemoryCount(ePlayer, MEMORY_REFUSED_HELP, 1); break; case DIPLOEVENT_ACCEPT_DEMAND: AI_changeMemoryCount(ePlayer, MEMORY_ACCEPT_DEMAND, 1); forcePeace(ePlayer); break; case DIPLOEVENT_REJECTED_DEMAND: FAssertMsg(GET_PLAYER(ePlayer).getTeam() != getTeam(), "shouldn't call this function on our own team"); AI_changeMemoryCount(ePlayer, MEMORY_REJECTED_DEMAND, 1); if (AI_demandRebukedSneak(ePlayer)) { GET_TEAM(getTeam()).AI_setWarPlan(GET_PLAYER(ePlayer).getTeam(), WARPLAN_PREPARING_LIMITED); } break; case DIPLOEVENT_DEMAND_WAR: FAssertMsg(GET_PLAYER(ePlayer).getTeam() != getTeam(), "shouldn't call this function on our own team"); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gTeamLogLevel >= 2 ) { logBBAI(" Team %d (%S) declares war on team %d due to DIPLOEVENT", getTeam(), getCivilizationDescription(0), ePlayer ); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ GET_TEAM(getTeam()).declareWar(GET_PLAYER(ePlayer).getTeam(), false, WARPLAN_LIMITED); break; case DIPLOEVENT_CONVERT: AI_changeMemoryCount(ePlayer, MEMORY_ACCEPTED_RELIGION, 1); GET_PLAYER(ePlayer).convert(getStateReligion()); break; case DIPLOEVENT_NO_CONVERT: AI_changeMemoryCount(ePlayer, MEMORY_DENIED_RELIGION, 1); break; case DIPLOEVENT_REVOLUTION: AI_changeMemoryCount(ePlayer, MEMORY_ACCEPTED_CIVIC, 1); paeNewCivics = new CivicTypes[GC.getNumCivicOptionInfos()]; for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { paeNewCivics[iI] = GET_PLAYER(ePlayer).getCivics((CivicOptionTypes)iI); } FAssertMsg(GC.getLeaderHeadInfo(getPersonalityType()).getFavoriteCivic() != NO_CIVIC, "getFavoriteCivic() must be valid"); paeNewCivics[GC.getCivicInfo((CivicTypes)(GC.getLeaderHeadInfo(getPersonalityType())).getFavoriteCivic()).getCivicOptionType()] = ((CivicTypes)(GC.getLeaderHeadInfo(getPersonalityType()).getFavoriteCivic())); GET_PLAYER(ePlayer).revolution(paeNewCivics, true); SAFE_DELETE_ARRAY(paeNewCivics); break; case DIPLOEVENT_NO_REVOLUTION: AI_changeMemoryCount(ePlayer, MEMORY_DENIED_CIVIC, 1); break; case DIPLOEVENT_JOIN_WAR: AI_changeMemoryCount(ePlayer, MEMORY_ACCEPTED_JOIN_WAR, 1); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gTeamLogLevel >= 2 ) { logBBAI(" Team %d (%S) declares war on team %d due to DIPLOEVENT", getTeam(), getCivilizationDescription(0), ePlayer ); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ GET_TEAM(GET_PLAYER(ePlayer).getTeam()).declareWar(((TeamTypes)iData1), false, WARPLAN_DOGPILE); for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == ((TeamTypes)iData1)) { GET_PLAYER((PlayerTypes)iI).AI_changeMemoryCount(getID(), MEMORY_HIRED_WAR_ALLY, 1); } } } break; case DIPLOEVENT_NO_JOIN_WAR: AI_changeMemoryCount(ePlayer, MEMORY_DENIED_JOIN_WAR, 1); break; case DIPLOEVENT_STOP_TRADING: AI_changeMemoryCount(ePlayer, MEMORY_ACCEPTED_STOP_TRADING, 1); GET_PLAYER(ePlayer).stopTradingWithTeam((TeamTypes)iData1); for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == ((TeamTypes)iData1)) { GET_PLAYER((PlayerTypes)iI).AI_changeMemoryCount(getID(), MEMORY_HIRED_TRADE_EMBARGO, 1); } } } break; case DIPLOEVENT_NO_STOP_TRADING: AI_changeMemoryCount(ePlayer, MEMORY_DENIED_STOP_TRADING, 1); break; case DIPLOEVENT_ASK_HELP: AI_changeMemoryCount(ePlayer, MEMORY_MADE_DEMAND_RECENT, 1); break; case DIPLOEVENT_MADE_DEMAND: if (AI_getMemoryCount(ePlayer, MEMORY_MADE_DEMAND) < 10) { AI_changeMemoryCount(ePlayer, MEMORY_MADE_DEMAND, 1); } AI_changeMemoryCount(ePlayer, MEMORY_MADE_DEMAND_RECENT, 1); break; case DIPLOEVENT_MADE_DEMAND_VASSAL: break; case DIPLOEVENT_RESEARCH_TECH: pushResearch(((TechTypes)iData1), true); break; case DIPLOEVENT_TARGET_CITY: pCity = GET_PLAYER((PlayerTypes)iData1).getCity(iData2); if (pCity != NULL) { pCity->area()->setTargetCity(getID(), pCity); } break; default: FAssert(false); break; } } bool CvPlayer::canTradeWith(PlayerTypes eWhoTo) const { if (atWar(getTeam(), GET_PLAYER(eWhoTo).getTeam())) { return true; } if (GET_TEAM(getTeam()).isTechTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isTechTrading()) { return true; } if (GET_TEAM(getTeam()).isGoldTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isGoldTrading()) { return true; } if (GET_TEAM(getTeam()).isMapTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isMapTrading()) { return true; } if (canTradeNetworkWith(eWhoTo)) { return true; } if (GET_TEAM(getTeam()).isOpenBordersTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isOpenBordersTrading()) { return true; } if (GET_TEAM(getTeam()).isDefensivePactTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isDefensivePactTrading()) { return true; } if (GET_TEAM(getTeam()).isPermanentAllianceTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isPermanentAllianceTrading()) { return true; } if (GET_TEAM(getTeam()).isVassalStateTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isVassalStateTrading()) { return true; } return false; } bool CvPlayer::canReceiveTradeCity() const { if (GC.getGameINLINE().isOption(GAMEOPTION_ONE_CITY_CHALLENGE) && isHuman()) { return false; } return true; } bool CvPlayer::canTradeItem(PlayerTypes eWhoTo, TradeData item, bool bTestDenial) const { CvCity *pOurCapitalCity; if (bTestDenial) { if (getTradeDenial(eWhoTo, item) != NO_DENIAL) { return false; } } switch (item.m_eItemType) { case TRADE_TECHNOLOGIES: if (!(GC.getGameINLINE().isOption(GAMEOPTION_NO_TECH_TRADING))) { if (GC.getTechInfo((TechTypes)(item.m_iData)).isTrade()) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)(item.m_iData)) && !(GET_TEAM(getTeam()).isNoTradeTech((TechTypes)(item.m_iData)))) { if (!GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isHasTech((TechTypes)(item.m_iData))) { //if (GET_PLAYER(eWhoTo).isHuman() || (GET_PLAYER(eWhoTo).getCurrentResearch() != item.m_iData)) { if (GET_TEAM(getTeam()).isTechTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isTechTrading()) { FAssertMsg(item.m_iData >= 0, "item.m_iData is expected to be non-negative (invalid Index)"); if (GET_PLAYER(eWhoTo).canResearch(((TechTypes)item.m_iData), true)) { return true; } } } } } } } break; case TRADE_RESOURCES: FAssertMsg(item.m_iData > -1, "iData is expected to be non-negative"); if (canTradeNetworkWith(eWhoTo)) { if (!GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isBonusObsolete((BonusTypes) item.m_iData) && !GET_TEAM(getTeam()).isBonusObsolete((BonusTypes) item.m_iData)) { bool bCanTradeAll = (isHuman() || getTeam() == GET_PLAYER(eWhoTo).getTeam() || GET_TEAM(getTeam()).isVassal(GET_PLAYER(eWhoTo).getTeam())); if (getNumTradeableBonuses((BonusTypes) item.m_iData) > (bCanTradeAll ? 0 : 1)) { // if (GET_PLAYER(eWhoTo).getNumAvailableBonuses(eBonus) == 0) { return true; } } } } break; case TRADE_CITIES: { CvCity* pCityTraded = getCity(item.m_iData); if (NULL != pCityTraded && pCityTraded->getLiberationPlayer(false) == eWhoTo) { return true; } if (GET_PLAYER(eWhoTo).canReceiveTradeCity()) { if (0 == GC.getGameINLINE().getMaxCityElimination()) { if (!GET_TEAM(getTeam()).isAVassal() && !GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isVassal(getTeam())) { pOurCapitalCity = getCapitalCity(); if (pOurCapitalCity != NULL) { if (pOurCapitalCity->getID() != item.m_iData) { return true; } } } } } } break; case TRADE_GOLD: if (GET_TEAM(getTeam()).isGoldTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isGoldTrading()) { if (getGold() >= item.m_iData) { return true; } } break; case TRADE_GOLD_PER_TURN: if (GET_TEAM(getTeam()).isGoldTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isGoldTrading()) { return true; } break; case TRADE_MAPS: if (getTeam() != GET_PLAYER(eWhoTo).getTeam()) { if (GET_TEAM(getTeam()).isMapTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isMapTrading()) { return true; } } break; case TRADE_VASSAL: case TRADE_SURRENDER: /************************************************************************************************/ /* BETTER_BTS_AI_MOD 12/06/09 jdog5000 */ /* */ /* Customization */ /************************************************************************************************/ if (!isHuman() || GET_PLAYER(eWhoTo).isHuman() || (GC.getBBAI_HUMAN_AS_VASSAL_OPTION())) /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ { CvTeam& kVassalTeam = GET_TEAM(getTeam()); CvTeam& kMasterTeam = GET_TEAM(GET_PLAYER(eWhoTo).getTeam()); if (kMasterTeam.isVassalStateTrading()) // the master must possess the tech { if (!kVassalTeam.isAVassal() && !kMasterTeam.isAVassal() && getTeam() != GET_PLAYER(eWhoTo).getTeam()) { if ((kMasterTeam.isAtWar(getTeam()) || item.m_iData == 1) && item.m_eItemType == TRADE_SURRENDER) { return true; } if (!kMasterTeam.isAtWar(getTeam()) && item.m_eItemType == TRADE_VASSAL) { return true; } } } } break; case TRADE_PEACE: if (!(GET_TEAM(getTeam()).isHuman())) { if (!(GET_TEAM(getTeam()).isAVassal())) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)(item.m_iData)) && GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isHasMet((TeamTypes)(item.m_iData))) { if (atWar(getTeam(), ((TeamTypes)(item.m_iData)))) { return true; } } } } break; case TRADE_WAR: if (!(GET_TEAM(getTeam()).isHuman())) { if (!(GET_TEAM(getTeam()).isAVassal())) { if (!GET_TEAM((TeamTypes)item.m_iData).isAVassal()) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)(item.m_iData)) && GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isHasMet((TeamTypes)(item.m_iData))) { if (GET_TEAM(getTeam()).canDeclareWar((TeamTypes)(item.m_iData))) { return true; } } } } } break; case TRADE_EMBARGO: if (!(GET_TEAM(getTeam()).isHuman())) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)(item.m_iData)) && GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isHasMet((TeamTypes)(item.m_iData))) { if (canStopTradingWithTeam((TeamTypes)(item.m_iData))) { return true; } } } break; case TRADE_CIVIC: /************************************************************************************************/ /* UNOFFICIAL_PATCH 10/22/09 denev & jdog5000 */ /* */ /* Diplomacy */ /************************************************************************************************/ /* original bts code if (!(GET_TEAM(getTeam()).isHuman())) */ if (!(GET_TEAM(getTeam()).isHuman()) || (getTeam() == GET_PLAYER(eWhoTo).getTeam())) /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ { if (GET_PLAYER(eWhoTo).isCivic((CivicTypes)(item.m_iData))) { if (canDoCivics((CivicTypes)(item.m_iData)) && !isCivic((CivicTypes)(item.m_iData))) { if (canRevolution(NULL)) { return true; } } } } break; case TRADE_RELIGION: /************************************************************************************************/ /* UNOFFICIAL_PATCH 10/22/09 denev & jdog5000 */ /* */ /* Diplomacy */ /************************************************************************************************/ /* original bts code if (!(GET_TEAM(getTeam()).isHuman())) */ if (!(GET_TEAM(getTeam()).isHuman()) || (getTeam() == GET_PLAYER(eWhoTo).getTeam())) /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ { if (GET_PLAYER(eWhoTo).getStateReligion() == ((ReligionTypes)(item.m_iData))) { if (canConvert((ReligionTypes)(item.m_iData))) { return true; } } } break; case TRADE_OPEN_BORDERS: if (getTeam() != GET_PLAYER(eWhoTo).getTeam()) { if (!atWar(getTeam(), GET_PLAYER(eWhoTo).getTeam())) { if (!(GET_TEAM(getTeam()).isOpenBorders(GET_PLAYER(eWhoTo).getTeam()))) { if (GET_TEAM(getTeam()).isOpenBordersTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isOpenBordersTrading()) { return true; } } } } break; case TRADE_DEFENSIVE_PACT: if (!(GET_TEAM(getTeam()).isAVassal()) && !(GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isAVassal())) { if (getTeam() != GET_PLAYER(eWhoTo).getTeam() && !GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isVassal(getTeam())) { if (!atWar(getTeam(), GET_PLAYER(eWhoTo).getTeam())) { if (!(GET_TEAM(getTeam()).isDefensivePact(GET_PLAYER(eWhoTo).getTeam()))) { if (GET_TEAM(getTeam()).isDefensivePactTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isDefensivePactTrading()) { if ((GET_TEAM(getTeam()).getAtWarCount(true) == 0) && (GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).getAtWarCount(true) == 0)) { if (GET_TEAM(getTeam()).canSignDefensivePact(GET_PLAYER(eWhoTo).getTeam())) { return true; } } } } } } } break; case TRADE_PERMANENT_ALLIANCE: if (!(GET_TEAM(getTeam()).isAVassal()) && !(GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isAVassal())) { if (getTeam() != GET_PLAYER(eWhoTo).getTeam() && !GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isVassal(getTeam())) { if (!atWar(getTeam(), GET_PLAYER(eWhoTo).getTeam())) { if (GET_TEAM(getTeam()).isPermanentAllianceTrading() || GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).isPermanentAllianceTrading()) { if ((GET_TEAM(getTeam()).getNumMembers() == 1) && (GET_TEAM(GET_PLAYER(eWhoTo).getTeam()).getNumMembers() == 1)) { return true; } } } } } break; case TRADE_PEACE_TREATY: return true; break; } return false; } DenialTypes CvPlayer::getTradeDenial(PlayerTypes eWhoTo, TradeData item) const { CvCity* pCity; switch (item.m_eItemType) { case TRADE_TECHNOLOGIES: return GET_TEAM(getTeam()).AI_techTrade(((TechTypes)(item.m_iData)), GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_RESOURCES: return AI_bonusTrade(((BonusTypes)(item.m_iData)), eWhoTo); break; case TRADE_CITIES: pCity = getCity(item.m_iData); if (pCity != NULL) { return AI_cityTrade(pCity, eWhoTo); } break; case TRADE_GOLD: case TRADE_GOLD_PER_TURN: break; case TRADE_MAPS: return GET_TEAM(getTeam()).AI_mapTrade(GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_SURRENDER: return GET_TEAM(getTeam()).AI_surrenderTrade(GET_PLAYER(eWhoTo).getTeam(), 140); break; case TRADE_VASSAL: return GET_TEAM(getTeam()).AI_vassalTrade(GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_PEACE: return GET_TEAM(getTeam()).AI_makePeaceTrade(((TeamTypes)(item.m_iData)), GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_WAR: return GET_TEAM(getTeam()).AI_declareWarTrade(((TeamTypes)(item.m_iData)), GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_EMBARGO: return AI_stopTradingTrade(((TeamTypes)(item.m_iData)), eWhoTo); break; case TRADE_CIVIC: return AI_civicTrade(((CivicTypes)(item.m_iData)), eWhoTo); break; case TRADE_RELIGION: return AI_religionTrade(((ReligionTypes)(item.m_iData)), eWhoTo); break; case TRADE_OPEN_BORDERS: return GET_TEAM(getTeam()).AI_openBordersTrade(GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_DEFENSIVE_PACT: return GET_TEAM(getTeam()).AI_defensivePactTrade(GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_PERMANENT_ALLIANCE: return GET_TEAM(getTeam()).AI_permanentAllianceTrade(GET_PLAYER(eWhoTo).getTeam()); break; case TRADE_PEACE_TREATY: break; } return NO_DENIAL; } bool CvPlayer::canTradeNetworkWith(PlayerTypes ePlayer) const { CvCity* pOurCapitalCity; pOurCapitalCity = getCapitalCity(); if (pOurCapitalCity != NULL) { if (pOurCapitalCity->isConnectedToCapital(ePlayer)) { return true; } } return false; } int CvPlayer::getNumAvailableBonuses(BonusTypes eBonus) const { CvPlotGroup* pPlotGroup; pPlotGroup = ((getCapitalCity() != NULL) ? getCapitalCity()->plot()->getOwnerPlotGroup() : NULL); if (pPlotGroup != NULL) { return pPlotGroup->getNumBonuses(eBonus); } return 0; } int CvPlayer::getNumTradeableBonuses(BonusTypes eBonus) const { return (getNumAvailableBonuses(eBonus) - getBonusImport(eBonus)); } bool CvPlayer::hasBonus(BonusTypes eBonus) const { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->hasBonus(eBonus)) { return true; } } return false; } int CvPlayer::getNumTradeBonusImports(PlayerTypes ePlayer) const { CLLNode<TradeData>* pNode; CvDeal* pLoopDeal; int iCount; int iLoop; FAssert(ePlayer != getID()); iCount = 0; for(pLoopDeal = GC.getGameINLINE().firstDeal(&iLoop); pLoopDeal != NULL; pLoopDeal = GC.getGameINLINE().nextDeal(&iLoop)) { if ((pLoopDeal->getFirstPlayer() == getID()) && (pLoopDeal->getSecondPlayer() == ePlayer)) { for (pNode = pLoopDeal->headSecondTradesNode(); (pNode != NULL); pNode = pLoopDeal->nextSecondTradesNode(pNode)) { if (pNode->m_data.m_eItemType == TRADE_RESOURCES) { iCount++; } } } if ((pLoopDeal->getFirstPlayer() == ePlayer) && (pLoopDeal->getSecondPlayer() == getID())) { for (pNode = pLoopDeal->headFirstTradesNode(); (pNode != NULL); pNode = pLoopDeal->nextFirstTradesNode(pNode)) { if (pNode->m_data.m_eItemType == TRADE_RESOURCES) { iCount++; } } } } return iCount; } bool CvPlayer::isTradingWithTeam(TeamTypes eTeam, bool bIncludeCancelable) const { int iLoop; if (eTeam == getTeam()) { return false; } for (CvDeal* pLoopDeal = GC.getGameINLINE().firstDeal(&iLoop); pLoopDeal != NULL; pLoopDeal = GC.getGameINLINE().nextDeal(&iLoop)) { if (bIncludeCancelable || pLoopDeal->isCancelable(getID())) { if (!pLoopDeal->isPeaceDeal()) { if ((pLoopDeal->getFirstPlayer() == getID()) && (GET_PLAYER(pLoopDeal->getSecondPlayer()).getTeam() == eTeam)) { if (pLoopDeal->getLengthFirstTrades() > 0) { return true; } } if ((pLoopDeal->getSecondPlayer() == getID()) && (GET_PLAYER(pLoopDeal->getFirstPlayer()).getTeam() == eTeam)) { if (pLoopDeal->getLengthSecondTrades() > 0) { return true; } } } } } return false; } bool CvPlayer::canStopTradingWithTeam(TeamTypes eTeam, bool bContinueNotTrading) const { if (eTeam == getTeam()) { return false; } if (GET_TEAM(getTeam()).isVassal(eTeam)) { return false; } if (!isTradingWithTeam(eTeam, false)) { if (bContinueNotTrading && !isTradingWithTeam(eTeam, true)) { return true; } return false; } return true; } void CvPlayer::stopTradingWithTeam(TeamTypes eTeam) { CvDeal* pLoopDeal; int iLoop; int iI; FAssert(eTeam != getTeam()); for(pLoopDeal = GC.getGameINLINE().firstDeal(&iLoop); pLoopDeal != NULL; pLoopDeal = GC.getGameINLINE().nextDeal(&iLoop)) { if (pLoopDeal->isCancelable(getID()) && !(pLoopDeal->isPeaceDeal())) { if (((pLoopDeal->getFirstPlayer() == getID()) && (GET_PLAYER(pLoopDeal->getSecondPlayer()).getTeam() == eTeam)) || ((pLoopDeal->getSecondPlayer() == getID()) && (GET_PLAYER(pLoopDeal->getFirstPlayer()).getTeam() == eTeam))) { pLoopDeal->kill(); } } } for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == eTeam) { GET_PLAYER((PlayerTypes)iI).AI_changeMemoryCount(getID(), MEMORY_STOPPED_TRADING, 1); GET_PLAYER((PlayerTypes)iI).AI_changeMemoryCount(getID(), MEMORY_STOPPED_TRADING_RECENT, 1); } } } } void CvPlayer::killAllDeals() { CvDeal* pLoopDeal; int iLoop; for(pLoopDeal = GC.getGameINLINE().firstDeal(&iLoop); pLoopDeal != NULL; pLoopDeal = GC.getGameINLINE().nextDeal(&iLoop)) { if ((pLoopDeal->getFirstPlayer() == getID()) || (pLoopDeal->getSecondPlayer() == getID())) { pLoopDeal->kill(); } } } void CvPlayer::findNewCapital() { CvCity* pOldCapital; CvCity* pLoopCity; CvCity* pBestCity; BuildingTypes eCapitalBuilding; int iValue; int iBestValue; int iLoop; eCapitalBuilding = ((BuildingTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(GC.getDefineINT("CAPITAL_BUILDINGCLASS")))); if (eCapitalBuilding == NO_BUILDING) { return; } pOldCapital = getCapitalCity(); iBestValue = 0; pBestCity = NULL; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity != pOldCapital) { if (0 == pLoopCity->getNumRealBuilding(eCapitalBuilding)) { iValue = (pLoopCity->getPopulation() * 4); iValue += pLoopCity->getYieldRate(YIELD_FOOD); iValue += (pLoopCity->getYieldRate(YIELD_PRODUCTION) * 3); iValue += (pLoopCity->getYieldRate(YIELD_COMMERCE) * 2); iValue += pLoopCity->getCultureLevel(); iValue += pLoopCity->getReligionCount(); iValue += pLoopCity->getCorporationCount(); iValue += (pLoopCity->getNumGreatPeople() * 2); iValue *= (pLoopCity->calculateCulturePercent(getID()) + 100); iValue /= 100; if (iValue > iBestValue) { iBestValue = iValue; pBestCity = pLoopCity; } } } } if (pBestCity != NULL) { if (pOldCapital != NULL) { pOldCapital->setNumRealBuilding(eCapitalBuilding, 0); } FAssertMsg(!(pBestCity->getNumRealBuilding(eCapitalBuilding)), "(pBestCity->getNumRealBuilding(eCapitalBuilding)) did not return false as expected"); pBestCity->setNumRealBuilding(eCapitalBuilding, 1); } } int CvPlayer::getNumGovernmentCenters() const { CvCity* pLoopCity; int iCount; int iLoop; iCount = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->isGovernmentCenter()) { iCount++; } } return iCount; } bool CvPlayer::canRaze(CvCity* pCity) const { if (!pCity->isAutoRaze()) { if (GC.getGameINLINE().isOption(GAMEOPTION_NO_CITY_RAZING)) { return false; } if (pCity->getOwnerINLINE() != getID()) { return false; } if (pCity->calculateTeamCulturePercent(getTeam()) >= GC.getDefineINT("RAZING_CULTURAL_PERCENT_THRESHOLD")) { return false; } } CyCity* pyCity = new CyCity(pCity); CyArgsList argsList; argsList.add(getID()); // Player ID argsList.add(gDLL->getPythonIFace()->makePythonObject(pyCity)); // pass in city class long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "canRazeCity", argsList.makeFunctionArgs(), &lResult); delete pyCity; // python fxn must not hold on to this pointer if (lResult == 0) { return (false); } return true; } void CvPlayer::raze(CvCity* pCity) { wchar szBuffer[1024]; PlayerTypes eHighestCulturePlayer; int iI, iJ; if (!canRaze(pCity)) { return; } FAssert(pCity->getOwnerINLINE() == getID()); eHighestCulturePlayer = pCity->findHighestCulture(); if (eHighestCulturePlayer != NO_PLAYER) { if (GET_PLAYER(eHighestCulturePlayer).getTeam() != getTeam()) { GET_PLAYER(eHighestCulturePlayer).AI_changeMemoryCount(getID(), MEMORY_RAZED_CITY, 1); } } for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { if (pCity->isHolyCity((ReligionTypes)iI)) { for (iJ = 0; iJ < MAX_PLAYERS; iJ++) { if (GET_PLAYER((PlayerTypes)iJ).isAlive()) { if (iJ != getID()) { if (GET_PLAYER((PlayerTypes)iJ).getStateReligion() == ((ReligionTypes)iI)) { GET_PLAYER((PlayerTypes)iJ).AI_changeMemoryCount(getID(), MEMORY_RAZED_HOLY_CITY, 1); } } } } } } swprintf(szBuffer, gDLL->getText("TXT_KEY_MISC_DESTROYED_CITY", pCity->getNameKey()).GetCString()); gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CITYRAZE", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getInterfaceArtInfo("WORLDBUILDER_CITY_EDIT")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pCity->getX_INLINE(), pCity->getY_INLINE(), true, true); for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (iI != getID()) { if (pCity->isRevealed(GET_PLAYER((PlayerTypes)iI).getTeam(), false)) { swprintf(szBuffer, gDLL->getText("TXT_KEY_MISC_CITY_HAS_BEEN_RAZED_BY", pCity->getNameKey(), getCivilizationDescriptionKey()).GetCString()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CITYRAZED", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getInterfaceArtInfo("WORLDBUILDER_CITY_EDIT")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCity->getX_INLINE(), pCity->getY_INLINE(), true, true); } } } } swprintf(szBuffer, gDLL->getText("TXT_KEY_MISC_CITY_RAZED_BY", pCity->getNameKey(), getCivilizationDescriptionKey()).GetCString()); GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szBuffer, pCity->getX_INLINE(), pCity->getY_INLINE(), (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); // Report this event CvEventReporter::getInstance().cityRazed(pCity, getID()); disband(pCity); } void CvPlayer::disband(CvCity* pCity) { if (getNumCities() == 1) { setFoundedFirstCity(false); } GC.getGameINLINE().addDestroyedCityName(pCity->getName()); pCity->kill(true); } bool CvPlayer::canReceiveGoody(CvPlot* pPlot, GoodyTypes eGoody, CvUnit* pUnit) const { CvCity* pCity; UnitTypes eUnit; bool bTechFound; int iI; if (GC.getGoodyInfo(eGoody).getExperience() > 0) { if ((pUnit == NULL) || !(pUnit->canAcquirePromotionAny()) || (GC.getGameINLINE().getElapsedGameTurns() < 10)) { return false; } } if (GC.getGoodyInfo(eGoody).getDamagePrereq() > 0) { if ((pUnit == NULL) || (pUnit->getDamage() < ((pUnit->maxHitPoints() * GC.getGoodyInfo(eGoody).getDamagePrereq()) / 100))) { return false; } } if (GC.getGoodyInfo(eGoody).isTech()) { bTechFound = false; for (iI = 0; iI < GC.getNumTechInfos(); iI++) { if (GC.getTechInfo((TechTypes) iI).isGoodyTech()) { if (canResearch((TechTypes)iI)) { bTechFound = true; break; } } } if (!bTechFound) { return false; } } if (GC.getGoodyInfo(eGoody).isBad()) { if ((pUnit == NULL) || pUnit->isNoBadGoodies()) { return false; } } if (GC.getGoodyInfo(eGoody).getUnitClassType() != NO_UNITCLASS) { eUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(GC.getGoodyInfo(eGoody).getUnitClassType()))); if (eUnit == NO_UNIT) { return false; } if ((GC.getUnitInfo(eUnit).getCombat() > 0) && !(GC.getUnitInfo(eUnit).isOnlyDefensive())) { if (GC.getGameINLINE().isGameMultiPlayer() || (GC.getGameINLINE().getElapsedGameTurns() < 20)) { return false; } } if (GC.getGameINLINE().isOption(GAMEOPTION_ONE_CITY_CHALLENGE) && isHuman()) { if (GC.getUnitInfo(eUnit).isFound()) { return false; } } } if (GC.getGoodyInfo(eGoody).getBarbarianUnitClass() != NO_UNITCLASS) { if (GC.getGameINLINE().isOption(GAMEOPTION_NO_BARBARIANS)) { return false; } if (getNumCities() == 0) { return false; } if (getNumCities() == 1) { pCity = GC.getMapINLINE().findCity(pPlot->getX_INLINE(), pPlot->getY_INLINE(), NO_PLAYER, getTeam()); if (pCity != NULL) { if (plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pCity->getX_INLINE(), pCity->getY_INLINE()) <= (8 - getNumCities())) { return false; } } } } return true; } void CvPlayer::receiveGoody(CvPlot* pPlot, GoodyTypes eGoody, CvUnit* pUnit) { CvPlot* pLoopPlot; CvPlot* pBestPlot = NULL; CvWString szBuffer; CvWString szTempBuffer; TechTypes eBestTech; UnitTypes eUnit; int iGold; int iOffset; int iRange; int iBarbCount; int iValue; int iBestValue; int iPass; int iDX, iDY; int iI; FAssertMsg(canReceiveGoody(pPlot, eGoody, pUnit), "Instance is expected to be able to recieve goody"); szBuffer = GC.getGoodyInfo(eGoody).getDescription(); iGold = GC.getGoodyInfo(eGoody).getGold() + GC.getGameINLINE().getSorenRandNum(GC.getGoodyInfo(eGoody).getGoldRand1(), "Goody Gold 1") + GC.getGameINLINE().getSorenRandNum(GC.getGoodyInfo(eGoody).getGoldRand2(), "Goody Gold 2"); iGold = (iGold * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getGrowthPercent()) / 100; if (iGold != 0) { changeGold(iGold); szBuffer += gDLL->getText("TXT_KEY_MISC_RECEIVED_GOLD", iGold); } if (!szBuffer.empty()) { // BUG - Goody Hut Log - start // keep messages in event log forever gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, GC.getGoodyInfo(eGoody).getSound(), MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getImprovementArtInfo("ART_DEF_IMPROVEMENT_GOODY_HUT")->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pPlot->getX_INLINE(), pPlot->getY_INLINE()); // BUG - Goody Hut Log - end } iRange = GC.getGoodyInfo(eGoody).getMapRange(); if (iRange > 0) { iOffset = GC.getGoodyInfo(eGoody).getMapOffset(); if (iOffset > 0) { iBestValue = 0; pBestPlot = NULL; for (iDX = -(iOffset); iDX <= iOffset; iDX++) { for (iDY = -(iOffset); iDY <= iOffset; iDY++) { pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY); if (pLoopPlot != NULL) { if (!(pLoopPlot->isRevealed(getTeam(), false))) { iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "Goody Map")); iValue *= plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()); if (iValue > iBestValue) { iBestValue = iValue; pBestPlot = pLoopPlot; } } } } } } if (pBestPlot == NULL) { pBestPlot = pPlot; } for (iDX = -(iRange); iDX <= iRange; iDX++) { for (iDY = -(iRange); iDY <= iRange; iDY++) { pLoopPlot = plotXY(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), iDX, iDY); if (pLoopPlot != NULL) { if (plotDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()) <= iRange) { if (GC.getGameINLINE().getSorenRandNum(100, "Goody Map") < GC.getGoodyInfo(eGoody).getMapProb()) { pLoopPlot->setRevealed(getTeam(), true, false, NO_TEAM, true); } } } } } } if (pUnit != NULL) { pUnit->changeExperience(GC.getGoodyInfo(eGoody).getExperience()); } if (pUnit != NULL) { pUnit->changeDamage(-(GC.getGoodyInfo(eGoody).getHealing())); } if (GC.getGoodyInfo(eGoody).isTech()) { iBestValue = 0; eBestTech = NO_TECH; for (iI = 0; iI < GC.getNumTechInfos(); iI++) { if (GC.getTechInfo((TechTypes) iI).isGoodyTech()) { if (canResearch((TechTypes)iI)) { iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "Goody Tech")); if (iValue > iBestValue) { iBestValue = iValue; eBestTech = ((TechTypes)iI); } } } } FAssertMsg(eBestTech != NO_TECH, "BestTech is not assigned a valid value"); GET_TEAM(getTeam()).setHasTech(eBestTech, true, getID(), true, true); GET_TEAM(getTeam()).setNoTradeTech(eBestTech, true); } if (GC.getGoodyInfo(eGoody).getUnitClassType() != NO_UNITCLASS) { eUnit = (UnitTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(GC.getGoodyInfo(eGoody).getUnitClassType()); if (eUnit != NO_UNIT) { initUnit(eUnit, pPlot->getX_INLINE(), pPlot->getY_INLINE()); } } if (GC.getGoodyInfo(eGoody).getBarbarianUnitClass() != NO_UNITCLASS) { iBarbCount = 0; eUnit = (UnitTypes)GC.getCivilizationInfo(GET_PLAYER(BARBARIAN_PLAYER).getCivilizationType()).getCivilizationUnits(GC.getGoodyInfo(eGoody).getBarbarianUnitClass()); if (eUnit != NO_UNIT) { for (iPass = 0; iPass < 2; iPass++) { if (iBarbCount < GC.getGoodyInfo(eGoody).getMinBarbarians()) { for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++) { pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), ((DirectionTypes)iI)); if (pLoopPlot != NULL) { if (pLoopPlot->getArea() == pPlot->getArea()) { if (!(pLoopPlot->isImpassable())) { if (pLoopPlot->getNumUnits() == 0) { if ((iPass > 0) || (GC.getGameINLINE().getSorenRandNum(100, "Goody Barbs") < GC.getGoodyInfo(eGoody).getBarbarianUnitProb())) { GET_PLAYER(BARBARIAN_PLAYER).initUnit(eUnit, pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((pLoopPlot->isWater()) ? UNITAI_ATTACK_SEA : UNITAI_ATTACK)); iBarbCount++; if ((iPass > 0) && (iBarbCount == GC.getGoodyInfo(eGoody).getMinBarbarians())) { break; } } } } } } } } } } } } void CvPlayer::doGoody(CvPlot* pPlot, CvUnit* pUnit) { CyPlot kGoodyPlot(pPlot); CyUnit kGoodyUnit(pUnit); CyArgsList argsList; argsList.add(getID()); // pass in this players ID argsList.add(gDLL->getPythonIFace()->makePythonObject(&kGoodyPlot)); argsList.add(gDLL->getPythonIFace()->makePythonObject(&kGoodyUnit)); long result=0; bool ok = gDLL->getPythonIFace()->callFunction(PYGameModule, "doGoody", argsList.makeFunctionArgs(), &result); if (ok && result) { return; } FAssertMsg(pPlot->isGoody(), "pPlot->isGoody is expected to be true"); pPlot->removeGoody(); if (!isBarbarian()) { for (int iI = 0; iI < GC.getDefineINT("NUM_DO_GOODY_ATTEMPTS"); iI++) { if (GC.getHandicapInfo(getHandicapType()).getNumGoodies() > 0) { GoodyTypes eGoody = (GoodyTypes)GC.getHandicapInfo(getHandicapType()).getGoodies(GC.getGameINLINE().getSorenRandNum(GC.getHandicapInfo(getHandicapType()).getNumGoodies(), "Goodies")); FAssert(eGoody >= 0); FAssert(eGoody < GC.getNumGoodyInfos()); if (canReceiveGoody(pPlot, eGoody, pUnit)) { receiveGoody(pPlot, eGoody, pUnit); // Python Event CvEventReporter::getInstance().goodyReceived(getID(), pPlot, pUnit, eGoody); break; } } } } } bool CvPlayer::canFound(int iX, int iY, bool bTestVisible) const { CvPlot* pPlot; CvPlot* pLoopPlot; bool bValid; int iRange; int iDX, iDY; pPlot = GC.getMapINLINE().plotINLINE(iX, iY); long lResult=0; if(GC.getUSE_CANNOT_FOUND_CITY_CALLBACK()) { CyArgsList argsList; argsList.add((int)getID()); argsList.add(iX); argsList.add(iY); gDLL->getPythonIFace()->callFunction(PYGameModule, "cannotFoundCity", argsList.makeFunctionArgs(), &lResult); if (lResult == 1) { return false; } } if (GC.getGameINLINE().isFinalInitialized()) { if (GC.getGameINLINE().isOption(GAMEOPTION_ONE_CITY_CHALLENGE) && isHuman()) { if (getNumCities() > 0) { return false; } } } if (pPlot->isImpassable()) { return false; } if (pPlot->getFeatureType() != NO_FEATURE) { if (GC.getFeatureInfo(pPlot->getFeatureType()).isNoCity()) { return false; } } if (pPlot->isOwned() && (pPlot->getOwnerINLINE() != getID())) { return false; } bValid = false; if (!bValid) { if (GC.getTerrainInfo(pPlot->getTerrainType()).isFound()) { bValid = true; } } if (!bValid) { if (GC.getTerrainInfo(pPlot->getTerrainType()).isFoundCoast()) { if (pPlot->isCoastalLand()) { bValid = true; } } } if (!bValid) { if (GC.getTerrainInfo(pPlot->getTerrainType()).isFoundFreshWater()) { if (pPlot->isFreshWater()) { bValid = true; } } } /************************************************************************************************/ /* UNOFFICIAL_PATCH 02/16/10 EmperorFool & jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ // EF: canFoundCitiesOnWater callback handling was incorrect and ignored isWater() if it returned true if (pPlot->isWater()) { if(GC.getUSE_CAN_FOUND_CITIES_ON_WATER_CALLBACK()) { bValid = false; CyArgsList argsList2; argsList2.add(iX); argsList2.add(iY); lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "canFoundCitiesOnWater", argsList2.makeFunctionArgs(), &lResult); if (lResult == 1) { bValid = true; } } } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ if (!bValid) { return false; } if (!bTestVisible) { iRange = GC.getMIN_CITY_RANGE(); for (iDX = -(iRange); iDX <= iRange; iDX++) { for (iDY = -(iRange); iDY <= iRange; iDY++) { pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY); if (pLoopPlot != NULL) { if (pLoopPlot->isCity()) { if (pLoopPlot->area() == pPlot->area()) { return false; } } } } } } return true; } void CvPlayer::found(int iX, int iY) { CvCity* pCity; BuildingTypes eLoopBuilding; UnitTypes eDefenderUnit; int iI; if (!canFound(iX, iY)) { return; } pCity = initCity(iX, iY, true, true); FAssertMsg(pCity != NULL, "City is not assigned a valid value"); if (isBarbarian()) { eDefenderUnit = pCity->AI_bestUnitAI(UNITAI_CITY_DEFENSE); if (eDefenderUnit == NO_UNIT) { eDefenderUnit = pCity->AI_bestUnitAI(UNITAI_ATTACK); } if (eDefenderUnit != NO_UNIT) { for (iI = 0; iI < GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getBarbarianInitialDefenders(); iI++) { initUnit(eDefenderUnit, iX, iY, UNITAI_CITY_DEFENSE); } } } for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++) { eLoopBuilding = ((BuildingTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iI))); if (eLoopBuilding != NO_BUILDING) { if (GC.getBuildingInfo(eLoopBuilding).getFreeStartEra() != NO_ERA) { if (GC.getGameINLINE().getStartEra() >= GC.getBuildingInfo(eLoopBuilding).getFreeStartEra()) { if (pCity->canConstruct(eLoopBuilding)) { pCity->setNumRealBuilding(eLoopBuilding, 1); } } } } } if (getAdvancedStartPoints() >= 0) { // Free border expansion for Creative bool bCreative = false; for (iI = 0; iI < GC.getNumTraitInfos(); ++iI) { if (hasTrait((TraitTypes)iI)) { if (GC.getTraitInfo((TraitTypes)iI).getCommerceChange(COMMERCE_CULTURE) > 0) { bCreative = true; break; } } } if (bCreative) { for (iI = 0; iI < GC.getNumCultureLevelInfos(); ++iI) { int iCulture = GC.getGameINLINE().getCultureThreshold((CultureLevelTypes)iI); if (iCulture > 0) { pCity->setCulture(getID(), iCulture, true, true); break; } } } } if (isHuman() && getAdvancedStartPoints() < 0) { pCity->chooseProduction(); } else { pCity->doFoundMessage(); } CvEventReporter::getInstance().cityBuilt(pCity); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gPlayerLogLevel >= 1 ) { logBBAI(" Player %d (%S) founds new city %S at %d, %d", getID(), getCivilizationDescription(0), pCity->getName(0).GetCString(), iX, iY ); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } bool CvPlayer::canTrain(UnitTypes eUnit, bool bContinue, bool bTestVisible, bool bIgnoreCost) const { PROFILE_FUNC(); UnitClassTypes eUnitClass; int iI; eUnitClass = ((UnitClassTypes)(GC.getUnitInfo(eUnit).getUnitClassType())); FAssert(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(eUnitClass) == eUnit); if (GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(eUnitClass) != eUnit) { return false; } if (!bIgnoreCost) { if (GC.getUnitInfo(eUnit).getProductionCost() == -1) { return false; } } if (GC.getGameINLINE().isOption(GAMEOPTION_ONE_CITY_CHALLENGE) && isHuman()) { if (GC.getUnitInfo(eUnit).isFound()) { return false; } } if (GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { if (GC.getUnitInfo(eUnit).isSpy() || GC.getUnitInfo(eUnit).getEspionagePoints() > 0) { return false; } } if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getUnitInfo(eUnit).getPrereqAndTech())))) { return false; } for (iI = 0; iI < GC.getNUM_UNIT_AND_TECH_PREREQS(); iI++) { if (GC.getUnitInfo(eUnit).getPrereqAndTechs(iI) != NO_TECH) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getUnitInfo(eUnit).getPrereqAndTechs(iI))))) { return false; } } } if (GC.getUnitInfo(eUnit).getStateReligion() != NO_RELIGION) { if (getStateReligion() != GC.getUnitInfo(eUnit).getStateReligion()) { return false; } } if (GC.getGameINLINE().isUnitClassMaxedOut(eUnitClass)) { return false; } if (GET_TEAM(getTeam()).isUnitClassMaxedOut(eUnitClass)) { return false; } if (isUnitClassMaxedOut(eUnitClass)) { return false; } if (!bTestVisible) { if (GC.getGameINLINE().isUnitClassMaxedOut(eUnitClass, (GET_TEAM(getTeam()).getUnitClassMaking(eUnitClass) + ((bContinue) ? -1 : 0)))) { return false; } if (GET_TEAM(getTeam()).isUnitClassMaxedOut(eUnitClass, (GET_TEAM(getTeam()).getUnitClassMaking(eUnitClass) + ((bContinue) ? -1 : 0)))) { return false; } if (isUnitClassMaxedOut(eUnitClass, (getUnitClassMaking(eUnitClass) + ((bContinue) ? -1 : 0)))) { return false; } if (GC.getGameINLINE().isNoNukes() || !GC.getGameINLINE().isNukesValid()) { if (GC.getUnitInfo(eUnit).getNukeRange() != -1) { return false; } } if (GC.getUnitInfo(eUnit).getSpecialUnitType() != NO_SPECIALUNIT) { if (!(GC.getGameINLINE().isSpecialUnitValid((SpecialUnitTypes)(GC.getUnitInfo(eUnit).getSpecialUnitType())))) { return false; } } } return true; } bool CvPlayer::canConstruct(BuildingTypes eBuilding, bool bContinue, bool bTestVisible, bool bIgnoreCost) const { BuildingClassTypes eBuildingClass; int iI; CvTeamAI& currentTeam = GET_TEAM(getTeam()); eBuildingClass = ((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType())); FAssert(GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(eBuildingClass) == eBuilding); if (GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(eBuildingClass) != eBuilding) { return false; } if (!bIgnoreCost) { if (GC.getBuildingInfo(eBuilding).getProductionCost() == -1) { return false; } } if (!(currentTeam.isHasTech((TechTypes)(GC.getBuildingInfo(eBuilding).getPrereqAndTech())))) { return false; } for (iI = 0; iI < GC.getNUM_BUILDING_AND_TECH_PREREQS(); iI++) { if (GC.getBuildingInfo(eBuilding).getPrereqAndTechs(iI) != NO_TECH) { if (!(currentTeam.isHasTech((TechTypes)(GC.getBuildingInfo(eBuilding).getPrereqAndTechs(iI))))) { return false; } } } if (currentTeam.isObsoleteBuilding(eBuilding)) { return false; } if (GC.getBuildingInfo(eBuilding).getSpecialBuildingType() != NO_SPECIALBUILDING) { if (!(currentTeam.isHasTech((TechTypes)(GC.getSpecialBuildingInfo((SpecialBuildingTypes) GC.getBuildingInfo(eBuilding).getSpecialBuildingType()).getTechPrereq())))) { return false; } } if (GC.getBuildingInfo(eBuilding).getStateReligion() != NO_RELIGION) { if (getStateReligion() != GC.getBuildingInfo(eBuilding).getStateReligion()) { return false; } } if (GC.getGameINLINE().countCivTeamsEverAlive() < GC.getBuildingInfo(eBuilding).getNumTeamsPrereq()) { return false; } if (GC.getBuildingInfo(eBuilding).getVictoryPrereq() != NO_VICTORY) { if (!(GC.getGameINLINE().isVictoryValid((VictoryTypes)(GC.getBuildingInfo(eBuilding).getVictoryPrereq())))) { return false; } if (isMinorCiv()) { return false; } if (currentTeam.getVictoryCountdown((VictoryTypes)GC.getBuildingInfo(eBuilding).getVictoryPrereq()) >= 0) { return false; } } if (GC.getBuildingInfo(eBuilding).getMaxStartEra() != NO_ERA) { if (GC.getGameINLINE().getStartEra() > GC.getBuildingInfo(eBuilding).getMaxStartEra()) { return false; } } if (GC.getGameINLINE().isBuildingClassMaxedOut(eBuildingClass)) { return false; } if (currentTeam.isBuildingClassMaxedOut(eBuildingClass)) { return false; } if (isBuildingClassMaxedOut(eBuildingClass)) { return false; } CvCivilizationInfo &civilizationInfo = GC.getCivilizationInfo(getCivilizationType()); int numBuildingClassInfos = GC.getNumBuildingClassInfos(); for (iI = 0; iI < numBuildingClassInfos; iI++) { BuildingTypes ePrereqBuilding = (BuildingTypes)civilizationInfo.getCivilizationBuildings(iI); if (NO_BUILDING != ePrereqBuilding && currentTeam.isObsoleteBuilding(ePrereqBuilding)) { if (getBuildingClassCount((BuildingClassTypes)iI) < getBuildingClassPrereqBuilding(eBuilding, (BuildingClassTypes)iI, 0)) { return false; } } } if (!bTestVisible) { if (GC.getGameINLINE().isBuildingClassMaxedOut(eBuildingClass, (currentTeam.getBuildingClassMaking(eBuildingClass) + ((bContinue) ? -1 : 0)))) { return false; } if (currentTeam.isBuildingClassMaxedOut(eBuildingClass, (currentTeam.getBuildingClassMaking(eBuildingClass) + ((bContinue) ? -1 : 0)))) { return false; } if (isBuildingClassMaxedOut(eBuildingClass, (getBuildingClassMaking(eBuildingClass) + ((bContinue) ? -1 : 0)))) { return false; } if (GC.getGameINLINE().isNoNukes()) { if (GC.getBuildingInfo(eBuilding).isAllowsNukes()) { for (iI = 0; iI < GC.getNumUnitInfos(); iI++) { if (GC.getUnitInfo((UnitTypes)iI).getNukeRange() != -1) { return false; } } } } if (GC.getBuildingInfo(eBuilding).getSpecialBuildingType() != NO_SPECIALBUILDING) { if (!(GC.getGameINLINE().isSpecialBuildingValid((SpecialBuildingTypes)(GC.getBuildingInfo(eBuilding).getSpecialBuildingType())))) { return false; } } if (getNumCities() < GC.getBuildingInfo(eBuilding).getNumCitiesPrereq()) { return false; } if (getHighestUnitLevel() < GC.getBuildingInfo(eBuilding).getUnitLevelPrereq()) { return false; } for (iI = 0; iI < numBuildingClassInfos; iI++) { if (getBuildingClassCount((BuildingClassTypes)iI) < getBuildingClassPrereqBuilding(eBuilding, ((BuildingClassTypes)iI), ((bContinue) ? 0 : getBuildingClassMaking(eBuildingClass)))) { return false; } } } return true; } bool CvPlayer::canCreate(ProjectTypes eProject, bool bContinue, bool bTestVisible) const { int iI; if (isBarbarian()) { return false; } if (GC.getProjectInfo(eProject).getProductionCost() == -1) { return false; } if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getProjectInfo(eProject).getTechPrereq())))) { return false; } if (GC.getProjectInfo(eProject).getVictoryPrereq() != NO_VICTORY) { if (!(GC.getGameINLINE().isVictoryValid((VictoryTypes)(GC.getProjectInfo(eProject).getVictoryPrereq())))) { return false; } if (isMinorCiv()) { return false; } if (GET_TEAM(getTeam()).getVictoryCountdown((VictoryTypes)GC.getProjectInfo(eProject).getVictoryPrereq()) >= 0) { return false; } } if (GC.getGameINLINE().isProjectMaxedOut(eProject)) { return false; } if (GET_TEAM(getTeam()).isProjectMaxedOut(eProject)) { return false; } if (!bTestVisible) { if (GC.getGameINLINE().isProjectMaxedOut(eProject, (GET_TEAM(getTeam()).getProjectMaking(eProject) + ((bContinue) ? -1 : 0)))) { return false; } if (GET_TEAM(getTeam()).isProjectMaxedOut(eProject, (GET_TEAM(getTeam()).getProjectMaking(eProject) + ((bContinue) ? -1 : 0)))) { return false; } if (GC.getGameINLINE().isNoNukes()) { if (GC.getProjectInfo(eProject).isAllowsNukes()) { for (iI = 0; iI < GC.getNumUnitInfos(); iI++) { if (GC.getUnitInfo((UnitTypes)iI).getNukeRange() != -1) { return false; } } } } if (GC.getProjectInfo(eProject).getAnyoneProjectPrereq() != NO_PROJECT) { if (GC.getGameINLINE().getProjectCreatedCount((ProjectTypes)(GC.getProjectInfo(eProject).getAnyoneProjectPrereq())) == 0) { return false; } } for (iI = 0; iI < GC.getNumProjectInfos(); iI++) { if (GET_TEAM(getTeam()).getProjectCount((ProjectTypes)iI) < GC.getProjectInfo(eProject).getProjectsNeeded(iI)) { return false; } } } return true; } bool CvPlayer::canMaintain(ProcessTypes eProcess, bool bContinue) const { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getProcessInfo(eProcess).getTechPrereq())))) { return false; } return true; } bool CvPlayer::isProductionMaxedUnitClass(UnitClassTypes eUnitClass) const { if (eUnitClass == NO_UNITCLASS) { return false; } if (GC.getGameINLINE().isUnitClassMaxedOut(eUnitClass)) { return true; } if (GET_TEAM(getTeam()).isUnitClassMaxedOut(eUnitClass)) { return true; } if (isUnitClassMaxedOut(eUnitClass)) { return true; } return false; } bool CvPlayer::isProductionMaxedBuildingClass(BuildingClassTypes eBuildingClass, bool bAcquireCity) const { if (eBuildingClass == NO_BUILDINGCLASS) { return false; } if (!bAcquireCity) { if (GC.getGameINLINE().isBuildingClassMaxedOut(eBuildingClass)) { return true; } } if (GET_TEAM(getTeam()).isBuildingClassMaxedOut(eBuildingClass)) { return true; } if (isBuildingClassMaxedOut(eBuildingClass, ((bAcquireCity) ? GC.getBuildingClassInfo(eBuildingClass).getExtraPlayerInstances() : 0))) { return true; } return false; } bool CvPlayer::isProductionMaxedProject(ProjectTypes eProject) const { if (eProject == NO_PROJECT) { return false; } if (GC.getGameINLINE().isProjectMaxedOut(eProject)) { return true; } if (GET_TEAM(getTeam()).isProjectMaxedOut(eProject)) { return true; } return false; } int CvPlayer::getProductionNeeded(UnitTypes eUnit) const { UnitClassTypes eUnitClass = (UnitClassTypes)GC.getUnitInfo(eUnit).getUnitClassType(); FAssert(NO_UNITCLASS != eUnitClass); int iProductionNeeded = GC.getUnitInfo(eUnit).getProductionCost(); iProductionNeeded *= 100 + getUnitClassCount(eUnitClass) * GC.getUnitClassInfo(eUnitClass).getInstanceCostModifier(); iProductionNeeded /= 100; iProductionNeeded *= GC.getDefineINT("UNIT_PRODUCTION_PERCENT"); iProductionNeeded /= 100; iProductionNeeded *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getTrainPercent(); iProductionNeeded /= 100; iProductionNeeded *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getTrainPercent(); iProductionNeeded /= 100; if (!isHuman() && !isBarbarian()) { if (isWorldUnitClass(eUnitClass)) { iProductionNeeded *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIWorldTrainPercent(); iProductionNeeded /= 100; } else { iProductionNeeded *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAITrainPercent(); iProductionNeeded /= 100; } iProductionNeeded *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iProductionNeeded /= 100; } iProductionNeeded += getUnitExtraCost(eUnitClass); // Python cost modifier if(GC.getUSE_GET_UNIT_COST_MOD_CALLBACK()) { CyArgsList argsList; argsList.add(getID()); // Player ID argsList.add((int)eUnit); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "getUnitCostMod", argsList.makeFunctionArgs(), &lResult); if (lResult > 1) { iProductionNeeded *= lResult; iProductionNeeded /= 100; } } return std::max(1, iProductionNeeded); } int CvPlayer::getProductionNeeded(BuildingTypes eBuilding) const { int iProductionNeeded; iProductionNeeded = GC.getBuildingInfo(eBuilding).getProductionCost(); iProductionNeeded *= GC.getDefineINT("BUILDING_PRODUCTION_PERCENT"); iProductionNeeded /= 100; iProductionNeeded *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getConstructPercent(); iProductionNeeded /= 100; iProductionNeeded *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getConstructPercent(); iProductionNeeded /= 100; if (!isHuman() && !isBarbarian()) { if (isWorldWonderClass((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType()))) { iProductionNeeded *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIWorldConstructPercent(); iProductionNeeded /= 100; } else { iProductionNeeded *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIConstructPercent(); iProductionNeeded /= 100; } iProductionNeeded *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iProductionNeeded /= 100; } return std::max(1, iProductionNeeded); } int CvPlayer::getProductionNeeded(ProjectTypes eProject) const { int iProductionNeeded; iProductionNeeded = GC.getProjectInfo(eProject).getProductionCost(); iProductionNeeded *= GC.getDefineINT("PROJECT_PRODUCTION_PERCENT"); iProductionNeeded /= 100; iProductionNeeded *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getCreatePercent(); iProductionNeeded /= 100; iProductionNeeded *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getCreatePercent(); iProductionNeeded /= 100; if (!isHuman() && !isBarbarian()) { if (isWorldProject(eProject)) { iProductionNeeded *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIWorldCreatePercent(); iProductionNeeded /= 100; } else { iProductionNeeded *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAICreatePercent(); iProductionNeeded /= 100; } iProductionNeeded *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iProductionNeeded /= 100; } return std::max(1, iProductionNeeded); } int CvPlayer::getProductionModifier(UnitTypes eUnit) const { int iMultiplier = 0; if (GC.getUnitInfo(eUnit).isMilitaryProduction()) { iMultiplier += getMilitaryProductionModifier(); } for (int iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { iMultiplier += GC.getUnitInfo(eUnit).getProductionTraits(iI); if (GC.getUnitInfo(eUnit).getSpecialUnitType() != NO_SPECIALUNIT) { iMultiplier += GC.getSpecialUnitInfo((SpecialUnitTypes) GC.getUnitInfo(eUnit).getSpecialUnitType()).getProductionTraits(iI); } } } return iMultiplier; } int CvPlayer::getProductionModifier(BuildingTypes eBuilding) const { int iMultiplier = 0; for (int iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { iMultiplier += GC.getBuildingInfo(eBuilding).getProductionTraits(iI); if (GC.getBuildingInfo(eBuilding).getSpecialBuildingType() != NO_SPECIALBUILDING) { iMultiplier += GC.getSpecialBuildingInfo((SpecialBuildingTypes) GC.getBuildingInfo(eBuilding).getSpecialBuildingType()).getProductionTraits(iI); } } } if (::isWorldWonderClass((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType()))) { iMultiplier += getMaxGlobalBuildingProductionModifier(); } if (::isTeamWonderClass((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType()))) { iMultiplier += getMaxTeamBuildingProductionModifier(); } if (::isNationalWonderClass((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType()))) { iMultiplier += getMaxPlayerBuildingProductionModifier(); } return iMultiplier; } int CvPlayer::getProductionModifier(ProjectTypes eProject) const { int iMultiplier = 0; if (GC.getProjectInfo(eProject).isSpaceship()) { iMultiplier += getSpaceProductionModifier(); } return iMultiplier; } int CvPlayer::getBuildingClassPrereqBuilding(BuildingTypes eBuilding, BuildingClassTypes ePrereqBuildingClass, int iExtra) const { CvBuildingInfo& kBuilding = GC.getBuildingInfo(eBuilding); int iPrereqs = kBuilding.getPrereqNumOfBuildingClass(ePrereqBuildingClass); // dont bother with the rest of the calcs if we have no prereqs if (iPrereqs < 1) { return 0; } BuildingClassTypes eBuildingClass = (BuildingClassTypes)kBuilding.getBuildingClassType(); iPrereqs *= std::max(0, (GC.getWorldInfo(GC.getMapINLINE().getWorldSize()).getBuildingClassPrereqModifier() + 100)); iPrereqs /= 100; if (!isLimitedWonderClass(eBuildingClass)) { iPrereqs *= (getBuildingClassCount((BuildingClassTypes)(GC.getBuildingInfo(eBuilding).getBuildingClassType())) + iExtra + 1); } if (GC.getGameINLINE().isOption(GAMEOPTION_ONE_CITY_CHALLENGE) && isHuman()) { iPrereqs = std::min(1, iPrereqs); } return iPrereqs; } void CvPlayer::removeBuildingClass(BuildingClassTypes eBuildingClass) { CvCity* pLoopCity; BuildingTypes eBuilding; int iLoop; eBuilding = ((BuildingTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(eBuildingClass))); if (eBuilding != NO_BUILDING) { for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getNumRealBuilding(eBuilding) > 0) { /************************************************************************************************/ /* UNOFFICIAL_PATCH 02/16/10 EmperorFool */ /* */ /* Bugfix */ /************************************************************************************************/ /* original bts code pLoopCity->setNumRealBuilding(eBuilding, 0); */ pLoopCity->setNumRealBuilding(eBuilding, pLoopCity->getNumRealBuilding(eBuilding) - 1); /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ break; } } } } // courtesy of the Gourd Bros... void CvPlayer::processBuilding(BuildingTypes eBuilding, int iChange, CvArea* pArea) { int iI, iJ; if (GC.getBuildingInfo(eBuilding).getFreeBuildingClass() != NO_BUILDINGCLASS) { BuildingTypes eFreeBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(GC.getBuildingInfo(eBuilding).getFreeBuildingClass()); changeFreeBuildingCount(eFreeBuilding, iChange); } if (GC.getBuildingInfo(eBuilding).getCivicOption() != NO_CIVICOPTION) { changeHasCivicOptionCount(((CivicOptionTypes)GC.getBuildingInfo(eBuilding).getCivicOption()), iChange); } changeGreatPeopleRateModifier(GC.getBuildingInfo(eBuilding).getGlobalGreatPeopleRateModifier() * iChange); changeGreatGeneralRateModifier(GC.getBuildingInfo(eBuilding).getGreatGeneralRateModifier() * iChange); changeDomesticGreatGeneralRateModifier(GC.getBuildingInfo(eBuilding).getDomesticGreatGeneralRateModifier() * iChange); changeAnarchyModifier(GC.getBuildingInfo(eBuilding).getAnarchyModifier() * iChange); changeGoldenAgeModifier(GC.getBuildingInfo(eBuilding).getGoldenAgeModifier() * iChange); changeHurryModifier(GC.getBuildingInfo(eBuilding).getGlobalHurryModifier() * iChange); changeFreeExperience(GC.getBuildingInfo(eBuilding).getGlobalFreeExperience() * iChange); changeWarWearinessModifier(GC.getBuildingInfo(eBuilding).getGlobalWarWearinessModifier() * iChange); pArea->changeFreeSpecialist(getID(), (GC.getBuildingInfo(eBuilding).getAreaFreeSpecialist() * iChange)); changeFreeSpecialist(GC.getBuildingInfo(eBuilding).getGlobalFreeSpecialist() * iChange); changeCoastalTradeRoutes(GC.getBuildingInfo(eBuilding).getCoastalTradeRoutes() * iChange); changeTradeRoutes(GC.getBuildingInfo(eBuilding).getGlobalTradeRoutes() * iChange); if (GC.getBuildingInfo(eBuilding).getAreaHealth() > 0) { pArea->changeBuildingGoodHealth(getID(), (GC.getBuildingInfo(eBuilding).getAreaHealth() * iChange)); } else { pArea->changeBuildingBadHealth(getID(), (GC.getBuildingInfo(eBuilding).getAreaHealth() * iChange)); } if (GC.getBuildingInfo(eBuilding).getGlobalHealth() > 0) { changeBuildingGoodHealth(GC.getBuildingInfo(eBuilding).getGlobalHealth() * iChange); } else { changeBuildingBadHealth(GC.getBuildingInfo(eBuilding).getGlobalHealth() * iChange); } pArea->changeBuildingHappiness(getID(), (GC.getBuildingInfo(eBuilding).getAreaHappiness() * iChange)); changeBuildingHappiness(GC.getBuildingInfo(eBuilding).getGlobalHappiness() * iChange); changeWorkerSpeedModifier(GC.getBuildingInfo(eBuilding).getWorkerSpeedModifier() * iChange); changeSpaceProductionModifier(GC.getBuildingInfo(eBuilding).getGlobalSpaceProductionModifier() * iChange); changeCityDefenseModifier(GC.getBuildingInfo(eBuilding).getAllCityDefenseModifier() * iChange); pArea->changeCleanPowerCount(getTeam(), ((GC.getBuildingInfo(eBuilding).isAreaCleanPower()) ? iChange : 0)); pArea->changeBorderObstacleCount(getTeam(), ((GC.getBuildingInfo(eBuilding).isAreaBorderObstacle()) ? iChange : 0)); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { changeSeaPlotYield(((YieldTypes)iI), (GC.getBuildingInfo(eBuilding).getGlobalSeaPlotYieldChange(iI) * iChange)); pArea->changeYieldRateModifier(getID(), ((YieldTypes)iI), (GC.getBuildingInfo(eBuilding).getAreaYieldModifier(iI) * iChange)); changeYieldRateModifier(((YieldTypes)iI), (GC.getBuildingInfo(eBuilding).getGlobalYieldModifier(iI) * iChange)); } for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { changeCommerceRateModifier(((CommerceTypes)iI), (GC.getBuildingInfo(eBuilding).getGlobalCommerceModifier(iI) * iChange)); changeSpecialistExtraCommerce(((CommerceTypes)iI), (GC.getBuildingInfo(eBuilding).getSpecialistExtraCommerce(iI) * iChange)); changeStateReligionBuildingCommerce(((CommerceTypes)iI), (GC.getBuildingInfo(eBuilding).getStateReligionCommerce(iI) * iChange)); changeCommerceFlexibleCount(((CommerceTypes)iI), (GC.getBuildingInfo(eBuilding).isCommerceFlexible(iI)) ? iChange : 0); } for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++) { BuildingTypes eOurBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iI); if (NO_BUILDING != eOurBuilding) { changeExtraBuildingHappiness(eOurBuilding, (GC.getBuildingInfo(eBuilding).getBuildingHappinessChanges(iI) * iChange)); } } for (iI = 0; iI < GC.getNumSpecialistInfos(); iI++) { for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { changeSpecialistExtraYield(((SpecialistTypes)iI), ((YieldTypes)iJ), (GC.getBuildingInfo(eBuilding).getSpecialistYieldChange(iI, iJ) * iChange)); } } } bool CvPlayer::canBuild(const CvPlot* pPlot, BuildTypes eBuild, bool bTestEra, bool bTestVisible) const { PROFILE_FUNC(); if (!(pPlot->canBuild(eBuild, getID(), bTestVisible))) { return false; } if (GC.getBuildInfo(eBuild).getTechPrereq() != NO_TECH) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)GC.getBuildInfo(eBuild).getTechPrereq()))) { if ((!bTestEra && !bTestVisible) || ((getCurrentEra() + 1) < GC.getTechInfo((TechTypes) GC.getBuildInfo(eBuild).getTechPrereq()).getEra())) { return false; } } } if (!bTestVisible) { if (pPlot->getFeatureType() != NO_FEATURE) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)GC.getBuildInfo(eBuild).getFeatureTech(pPlot->getFeatureType())))) { return false; } } if (std::max(0, getGold()) < getBuildCost(pPlot, eBuild)) { return false; } } return true; } // Returns the cost int CvPlayer::getBuildCost(const CvPlot* pPlot, BuildTypes eBuild) const { FAssert(eBuild >= 0 && eBuild < GC.getNumBuildInfos()); if (pPlot->getBuildProgress(eBuild) > 0) { return 0; } return std::max(0, GC.getBuildInfo(eBuild).getCost() * (100 + calculateInflationRate())) / 100; } RouteTypes CvPlayer::getBestRoute(CvPlot* pPlot) const { PROFILE_FUNC(); RouteTypes eRoute; RouteTypes eBestRoute; int iValue; int iBestValue; int iI; iBestValue = 0; eBestRoute = NO_ROUTE; // BBAI TODO: Efficiency: Could cache this, decent savings on large maps // Perhaps save best route type per player each turn, then just check that // one first and only check others if can't do best. for (iI = 0; iI < GC.getNumBuildInfos(); iI++) { eRoute = ((RouteTypes)(GC.getBuildInfo((BuildTypes)iI).getRoute())); if (eRoute != NO_ROUTE) { if ((pPlot != NULL) ? ((pPlot->getRouteType() == eRoute) || canBuild(pPlot, ((BuildTypes)iI))) : GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getBuildInfo((BuildTypes)iI).getTechPrereq()))) { iValue = GC.getRouteInfo(eRoute).getValue(); if (iValue > iBestValue) { iBestValue = iValue; eBestRoute = eRoute; } } } } return eBestRoute; } int CvPlayer::getImprovementUpgradeRate() const { int iRate; iRate = 1; // XXX iRate *= std::max(0, (getImprovementUpgradeRateModifier() + 100)); iRate /= 100; return iRate; } int CvPlayer::calculateTotalYield(YieldTypes eYield) const { CvCity* pLoopCity; int iTotalCommerce = 0; int iLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalCommerce += pLoopCity->getYieldRate(eYield); } return iTotalCommerce; } int CvPlayer::calculateTotalCityHappiness() const { CvCity* pLoopCity; int iTotalHappiness = 0; int iLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalHappiness += pLoopCity->happyLevel(); } return iTotalHappiness; } int CvPlayer::calculateTotalExports(YieldTypes eYield) const { CvCity* pLoopCity; CvCity* pTradeCity; int iTotalExports = 0; int iLoop = 0, iTradeLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { // BUG - Fractional Trade Routes - start #ifdef _MOD_FRACTRADE int iCityExports = 0; #endif for (iTradeLoop = 0; iTradeLoop < pLoopCity->getTradeRoutes(); iTradeLoop++) { pTradeCity = pLoopCity->getTradeCity(iTradeLoop); if (pTradeCity != NULL) { if (pTradeCity->getOwnerINLINE() != getID()) { #ifdef _MOD_FRACTRADE iCityExports += pLoopCity->calculateTradeYield(eYield, pLoopCity->calculateTradeProfitTimes100(pTradeCity)); #else iTotalExports += pLoopCity->calculateTradeYield(eYield, pLoopCity->calculateTradeProfit(pTradeCity)); #endif } } } #ifdef _MOD_FRACTRADE iTotalExports += iCityExports / 100; #endif // BUG - Fractional Trade Routes - end } return iTotalExports; } int CvPlayer::calculateTotalImports(YieldTypes eYield) const { CvCity* pLoopCity; CvCity* pTradeCity; int iTotalImports = 0; int iPlayerLoop = 0, iLoop = 0, iTradeLoop = 0; // Loop through players for (iPlayerLoop = 0; iPlayerLoop < MAX_CIV_PLAYERS; iPlayerLoop++) { if (iPlayerLoop != getID()) { // BUG - Fractional Trade Routes - start #ifdef _MOD_FRACTRADE int iCityImports = 0; #endif for (pLoopCity = GET_PLAYER((PlayerTypes) iPlayerLoop).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes) iPlayerLoop).nextCity(&iLoop)) { for (iTradeLoop = 0; iTradeLoop < pLoopCity->getTradeRoutes(); iTradeLoop++) { pTradeCity = pLoopCity->getTradeCity(iTradeLoop); if (pTradeCity != NULL) { if (pTradeCity->getOwnerINLINE() == getID()) { #ifdef _MOD_FRACTRADE iCityImports += pLoopCity->calculateTradeYield(eYield, pLoopCity->calculateTradeProfitTimes100(pTradeCity)); #else iTotalImports += pLoopCity->calculateTradeYield(eYield, pLoopCity->calculateTradeProfit(pTradeCity)); #endif } } } } #ifdef _MOD_FRACTRADE iTotalImports += iCityImports / 100; #endif // BUG - Fractional Trade Routes - end } } return iTotalImports; } int CvPlayer::calculateTotalCityUnhappiness() const { CvCity* pLoopCity; int iTotalUnhappiness = 0; int iLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalUnhappiness += pLoopCity->unhappyLevel(); } return iTotalUnhappiness; } int CvPlayer::calculateTotalCityHealthiness() const { CvCity* pLoopCity; int iTotalHealthiness = 0; int iLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalHealthiness += pLoopCity->goodHealth(); } return iTotalHealthiness; } int CvPlayer::calculateTotalCityUnhealthiness() const { CvCity* pLoopCity; int iTotalUnhealthiness = 0; int iLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalUnhealthiness += pLoopCity->badHealth(); } return iTotalUnhealthiness; } int CvPlayer::calculateUnitCost(int& iFreeUnits, int& iFreeMilitaryUnits, int& iPaidUnits, int& iPaidMilitaryUnits, int& iBaseUnitCost, int& iMilitaryCost, int& iExtraCost) const { int iSupport; iFreeUnits = GC.getHandicapInfo(getHandicapType()).getFreeUnits(); iFreeUnits += getBaseFreeUnits(); iFreeUnits += ((getTotalPopulation() * getFreeUnitsPopulationPercent()) / 100); iFreeMilitaryUnits = getBaseFreeMilitaryUnits(); iFreeMilitaryUnits += ((getTotalPopulation() * getFreeMilitaryUnitsPopulationPercent()) / 100); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 09/17/09 jdog5000 */ /* */ /* */ /************************************************************************************************/ /* original BTS code if (!isHuman()) { if (GET_TEAM(getTeam()).hasMetHuman()) { iFreeUnits += getNumCities(); // XXX iFreeMilitaryUnits += getNumCities(); // XXX } } */ // Removed hidden AI bonus /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ iPaidUnits = std::max(0, getNumUnits() - iFreeUnits); iPaidMilitaryUnits = std::max(0, getNumMilitaryUnits() - iFreeMilitaryUnits); iSupport = 0; iBaseUnitCost = iPaidUnits * getGoldPerUnit(); iMilitaryCost = iPaidMilitaryUnits * getGoldPerMilitaryUnit(); iExtraCost = getExtraUnitCost(); iSupport = iMilitaryCost + iBaseUnitCost + iExtraCost; iSupport *= GC.getHandicapInfo(getHandicapType()).getUnitCostPercent(); iSupport /= 100; if (!isHuman() && !isBarbarian()) { iSupport *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIUnitCostPercent(); iSupport /= 100; iSupport *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iSupport /= 100; } FAssert(iSupport >= 0); return std::max(0, iSupport); } int CvPlayer::calculateUnitCost() const { if (isAnarchy()) { return 0; } int iFreeUnits; int iFreeMilitaryUnits; int iPaidUnits; int iPaidMilitaryUnits; int iMilitaryCost; int iBaseUnitCost; int iExtraCost; return calculateUnitCost(iFreeUnits, iFreeMilitaryUnits, iPaidUnits, iPaidMilitaryUnits, iBaseUnitCost, iMilitaryCost, iExtraCost); } int CvPlayer::calculateUnitSupply() const { int iPaidUnits; int iBaseSupplyCost; if (isAnarchy()) { return 0; } return calculateUnitSupply(iPaidUnits, iBaseSupplyCost); } int CvPlayer::calculateUnitSupply(int& iPaidUnits, int& iBaseSupplyCost) const { int iSupply; iPaidUnits = std::max(0, (getNumOutsideUnits() - GC.getDefineINT("INITIAL_FREE_OUTSIDE_UNITS"))); iBaseSupplyCost = iPaidUnits * GC.getDefineINT("INITIAL_OUTSIDE_UNIT_GOLD_PERCENT"); iBaseSupplyCost /= 100; iSupply = iBaseSupplyCost; if (!isHuman() && !isBarbarian()) { iSupply *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIUnitSupplyPercent(); iSupply /= 100; iSupply *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iSupply /= 100; } FAssert(iSupply >= 0); return iSupply; } int CvPlayer::calculatePreInflatedCosts() const { CyArgsList argsList; argsList.add(getID()); long lResult; gDLL->getPythonIFace()->callFunction(PYGameModule, "getExtraCost", argsList.makeFunctionArgs(), &lResult); return (calculateUnitCost() + calculateUnitSupply() + getTotalMaintenance() + getCivicUpkeep() + (int)lResult); } int CvPlayer::calculateInflationRate() const { int iTurns = ((GC.getGameINLINE().getGameTurn() + GC.getGameINLINE().getElapsedGameTurns()) / 2); if (GC.getGameINLINE().getMaxTurns() > 0) { iTurns = std::min(GC.getGameINLINE().getMaxTurns(), iTurns); } iTurns += GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getInflationOffset(); if (iTurns <= 0) { return 0; } int iInflationPerTurnTimes10000 = GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getInflationPercent(); iInflationPerTurnTimes10000 *= GC.getHandicapInfo(getHandicapType()).getInflationPercent(); iInflationPerTurnTimes10000 /= 100; int iModifier = m_iInflationModifier; if (!isHuman() && !isBarbarian()) { int iAIModifier = GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIInflationPercent(); iAIModifier *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iAIModifier /= 100; iModifier += iAIModifier - 100; } iInflationPerTurnTimes10000 *= std::max(0, 100 + iModifier); iInflationPerTurnTimes10000 /= 100; // Keep up to second order terms in binomial series int iRatePercent = (iTurns * iInflationPerTurnTimes10000) / 100; iRatePercent += (iTurns * (iTurns - 1) * iInflationPerTurnTimes10000 * iInflationPerTurnTimes10000) / 2000000; FAssert(iRatePercent >= 0); return iRatePercent; } int CvPlayer::calculateInflatedCosts() const { int iCosts; iCosts = calculatePreInflatedCosts(); iCosts *= std::max(0, (calculateInflationRate() + 100)); iCosts /= 100; return iCosts; } int CvPlayer::calculateBaseNetGold() const { int iNetGold; iNetGold = (getCommerceRate(COMMERCE_GOLD) + getGoldPerTurn()); iNetGold -= calculateInflatedCosts(); return iNetGold; } int CvPlayer::calculateResearchModifier(TechTypes eTech) const { int iModifier = 100; if (NO_TECH == eTech) { return iModifier; } int iKnownCount = 0; int iPossibleKnownCount = 0; /************************************************************************************************/ /* BETTER_BTS_AI_MOD 07/27/09 jdog5000 */ /* */ /* Tech Diffusion */ /************************************************************************************************/ if( GC.getTECH_DIFFUSION_ENABLE() ) { double knownExp = 0.0; // Tech flows better through open borders for (int iI = 0; iI < MAX_CIV_TEAMS; iI++) { if (GET_TEAM((TeamTypes)iI).isAlive()) { if (GET_TEAM((TeamTypes)iI).isHasTech(eTech)) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)iI)) { knownExp += 0.5; if( GET_TEAM(getTeam()).isOpenBorders((TeamTypes)iI) || GET_TEAM((TeamTypes)iI).isVassal(getTeam()) ) { knownExp += 1.5; } else if( GET_TEAM(getTeam()).isAtWar((TeamTypes)iI) || GET_TEAM(getTeam()).isVassal((TeamTypes)iI) ) { knownExp += 0.5; } } } } } int techDiffMod = GC.getTECH_DIFFUSION_KNOWN_TEAM_MODIFIER(); if (knownExp > 0.0) { iModifier += techDiffMod - (int)(techDiffMod * pow(0.85, knownExp) + 0.5); } // Tech flows downhill to those who are far behind int iTechScorePercent = GET_TEAM(getTeam()).getBestKnownTechScorePercent(); int iWelfareThreshold = GC.getTECH_DIFFUSION_WELFARE_THRESHOLD(); if( iTechScorePercent < iWelfareThreshold ) { if( knownExp > 0.0 ) { iModifier += (GC.getTECH_DIFFUSION_WELFARE_MODIFIER() * GC.getGameINLINE().getCurrentEra() * (iWelfareThreshold - iTechScorePercent))/200; } } } else { // Default BTS code for (int iI = 0; iI < MAX_CIV_TEAMS; iI++) { if (GET_TEAM((TeamTypes)iI).isAlive()) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)iI)) { if (GET_TEAM((TeamTypes)iI).isHasTech(eTech)) { iKnownCount++; } } iPossibleKnownCount++; } } if (iPossibleKnownCount > 0) { iModifier += (GC.getDefineINT("TECH_COST_TOTAL_KNOWN_TEAM_MODIFIER") * iKnownCount) / iPossibleKnownCount; } } int iPossiblePaths = 0; int iUnknownPaths = 0; for (int iI = 0; iI < GC.getNUM_OR_TECH_PREREQS(); iI++) { if (GC.getTechInfo(eTech).getPrereqOrTechs(iI) != NO_TECH) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getTechInfo(eTech).getPrereqOrTechs(iI))))) { iUnknownPaths++; } iPossiblePaths++; } } FAssertMsg(iPossiblePaths >= iUnknownPaths, "The number of possible paths is expected to match or exceed the number of unknown ones"); if( iPossiblePaths > iUnknownPaths ) { iModifier += GC.getTECH_COST_FIRST_KNOWN_PREREQ_MODIFIER(); iPossiblePaths--; iModifier += (iPossiblePaths - iUnknownPaths) * GC.getTECH_COST_KNOWN_PREREQ_MODIFIER(); } iModifier -= GC.getEraInfo((EraTypes)GC.getTechInfo(eTech).getEra()).getTechCostModifier(); iModifier -= GC.getTECH_COST_MODIFIER(); return iModifier; /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } int CvPlayer::calculateBaseNetResearch(TechTypes eTech) const { TechTypes eResearchTech; if (eTech != NO_TECH) { eResearchTech = eTech; } else { eResearchTech = getCurrentResearch(); } return (((GC.getDefineINT("BASE_RESEARCH_RATE") + getCommerceRate(COMMERCE_RESEARCH)) * calculateResearchModifier(eResearchTech)) / 100); } int CvPlayer::calculateGoldRate() const { int iRate = 0; if (isCommerceFlexible(COMMERCE_RESEARCH)) { iRate = calculateBaseNetGold(); } else { iRate = std::min(0, (calculateBaseNetResearch() + calculateBaseNetGold())); } return iRate; } int CvPlayer::calculateResearchRate(TechTypes eTech) const { int iRate = 0; if (isCommerceFlexible(COMMERCE_RESEARCH)) { iRate = calculateBaseNetResearch(eTech); } else { iRate = std::max(1, (calculateBaseNetResearch(eTech) + calculateBaseNetGold())); } return iRate; } int CvPlayer::calculateTotalCommerce() const { int iTotalCommerce = calculateBaseNetGold() + calculateBaseNetResearch(); for (int i = 0; i < NUM_COMMERCE_TYPES; ++i) { if (COMMERCE_GOLD != i && COMMERCE_RESEARCH != i) { iTotalCommerce += getCommerceRate((CommerceTypes)i); } } return iTotalCommerce; } bool CvPlayer::isResearch() const { if(GC.getUSE_IS_PLAYER_RESEARCH_CALLBACK()) { CyArgsList argsList; long lResult; argsList.add(getID()); lResult = 1; gDLL->getPythonIFace()->callFunction(PYGameModule, "isPlayerResearch", argsList.makeFunctionArgs(), &lResult); if (lResult == 0) { return false; } } if (!isFoundedFirstCity()) { return false; } return true; } bool CvPlayer::canEverResearch(TechTypes eTech) const { if (GC.getTechInfo(eTech).isDisable()) { return false; } if (GC.getCivilizationInfo(getCivilizationType()).isCivilizationDisableTechs(eTech)) { return false; } if(GC.getUSE_CANNOT_RESEARCH_CALLBACK()) { CyArgsList argsList; argsList.add(getID()); argsList.add(eTech); argsList.add(false); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "cannotResearch", argsList.makeFunctionArgs(), &lResult); if (lResult == 1) { return false; } } return true; } bool CvPlayer::canResearch(TechTypes eTech, bool bTrade) const { bool bFoundPossible; bool bFoundValid; int iI; if(GC.getUSE_CAN_RESEARCH_CALLBACK()) { CyArgsList argsList; argsList.add(getID()); argsList.add(eTech); argsList.add(bTrade); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "canResearch", argsList.makeFunctionArgs(), &lResult); if (lResult == 1) { return true; } } if (!isResearch() && getAdvancedStartPoints() < 0) { return false; } if (GET_TEAM(getTeam()).isHasTech(eTech)) { return false; } bFoundPossible = false; bFoundValid = false; for (iI = 0; iI < GC.getNUM_OR_TECH_PREREQS(); iI++) { TechTypes ePrereq = (TechTypes)GC.getTechInfo(eTech).getPrereqOrTechs(iI); if (ePrereq != NO_TECH) { bFoundPossible = true; if (GET_TEAM(getTeam()).isHasTech(ePrereq)) { if (!bTrade || GC.getGameINLINE().isOption(GAMEOPTION_NO_TECH_BROKERING) || !GET_TEAM(getTeam()).isNoTradeTech(ePrereq)) { bFoundValid = true; break; } } } } if (bFoundPossible && !bFoundValid) { return false; } for (iI = 0; iI < GC.getNUM_AND_TECH_PREREQS(); iI++) { TechTypes ePrereq = (TechTypes)GC.getTechInfo(eTech).getPrereqAndTechs(iI); if (ePrereq != NO_TECH) { if (!GET_TEAM(getTeam()).isHasTech(ePrereq)) { return false; } if (bTrade && !GC.getGameINLINE().isOption(GAMEOPTION_NO_TECH_BROKERING) && GET_TEAM(getTeam()).isNoTradeTech(ePrereq)) { return false; } } } if (!canEverResearch(eTech)) { return false; } return true; } TechTypes CvPlayer::getCurrentResearch() const { CLLNode<TechTypes>* pResearchNode; pResearchNode = headResearchQueueNode(); if (pResearchNode != NULL) { return pResearchNode->m_data; } else { return NO_TECH; } } bool CvPlayer::isCurrentResearchRepeat() const { TechTypes eCurrentResearch; eCurrentResearch = getCurrentResearch(); if (eCurrentResearch == NO_TECH) { return false; } return GC.getTechInfo(eCurrentResearch).isRepeat(); } bool CvPlayer::isNoResearchAvailable() const { int iI; if (getCurrentResearch() != NO_TECH) { return false; } for (iI = 0; iI < GC.getNumTechInfos(); iI++) { if (canResearch((TechTypes)iI)) { return false; } } return true; } int CvPlayer::getResearchTurnsLeft(TechTypes eTech, bool bOverflow) const { int iTurnsLeft = getResearchTurnsLeftTimes100(eTech, bOverflow); iTurnsLeft = (iTurnsLeft + 99) / 100; // round up return std::max(1, iTurnsLeft); } int CvPlayer::getResearchTurnsLeftTimes100(TechTypes eTech, bool bOverflow) const { int iResearchRate; int iOverflow; int iResearchLeft; int iTurnsLeft; int iI; iResearchRate = 0; iOverflow = 0; for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == getTeam()) { if ((iI == getID()) || (GET_PLAYER((PlayerTypes)iI).getCurrentResearch() == eTech)) { iResearchRate += GET_PLAYER((PlayerTypes)iI).calculateResearchRate(eTech); iOverflow += (GET_PLAYER((PlayerTypes)iI).getOverflowResearch() * calculateResearchModifier(eTech)) / 100; } } } } /************************************************************************************************/ /* BETTER_BTS_AI_MOD 03/18/10 jdog5000 */ /* */ /* Tech AI */ /************************************************************************************************/ // Mainly just so debug display shows sensible value iResearchLeft = GET_TEAM(getTeam()).getResearchLeft(eTech); if (bOverflow) { iResearchLeft -= iOverflow; } iResearchLeft *= 100; if (iResearchRate == 0) { return iResearchLeft; } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ iTurnsLeft = (iResearchLeft / iResearchRate); if (iTurnsLeft * iResearchRate < iResearchLeft) { ++iTurnsLeft; } return std::max(1, iTurnsLeft); } bool CvPlayer::isCivic(CivicTypes eCivic) const { int iI; for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { if (getCivics((CivicOptionTypes)iI) == eCivic) { return true; } } return false; } bool CvPlayer::canDoCivics(CivicTypes eCivic) const { PROFILE_FUNC(); /************************************************************************************************/ /* UNOFFICIAL_PATCH 02/16/10 jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ // Circumvents second crash bug in simultaneous turns MP games if( eCivic == NO_CIVIC ) { return true; } /************************************************************************************************/ /* UNOFFICIAL_PATCH END */ /************************************************************************************************/ if (GC.getGameINLINE().isForceCivicOption((CivicOptionTypes)(GC.getCivicInfo(eCivic).getCivicOptionType()))) { return GC.getGameINLINE().isForceCivic(eCivic); } if(GC.getUSE_CAN_DO_CIVIC_CALLBACK()) { CyArgsList argsList; argsList.add(getID()); argsList.add(eCivic); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "canDoCivic", argsList.makeFunctionArgs(), &lResult); if (lResult == 1) { return true; } } if (!isHasCivicOption((CivicOptionTypes)(GC.getCivicInfo(eCivic).getCivicOptionType())) && !(GET_TEAM(getTeam()).isHasTech((TechTypes)(GC.getCivicInfo(eCivic).getTechPrereq())))) { return false; } if(GC.getUSE_CANNOT_DO_CIVIC_CALLBACK()) { CyArgsList argsList2; // XXX argsList2.add(getID()); argsList2.add(eCivic); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "cannotDoCivic", argsList2.makeFunctionArgs(), &lResult); if (lResult == 1) { return false; } } return true; } bool CvPlayer::canRevolution(CivicTypes* paeNewCivics) const { int iI; if (isAnarchy()) { return false; } if (getRevolutionTimer() > 0) { return false; } if (paeNewCivics == NULL) { // XXX is this necessary? for (iI = 0; iI < GC.getNumCivicInfos(); iI++) { if (canDoCivics((CivicTypes)iI)) { if (getCivics((CivicOptionTypes)GC.getCivicInfo((CivicTypes) iI).getCivicOptionType()) != iI) { return true; } } } } else { for (iI = 0; iI < GC.getNumCivicOptionInfos(); ++iI) { if (GC.getGameINLINE().isForceCivicOption((CivicOptionTypes)iI)) { if (!GC.getGameINLINE().isForceCivic(paeNewCivics[iI])) { return false; } } if (getCivics((CivicOptionTypes)iI) != paeNewCivics[iI]) { return true; } } } return false; } void CvPlayer::revolution(CivicTypes* paeNewCivics, bool bForce) { int iAnarchyLength; int iI; if (!bForce && !canRevolution(paeNewCivics)) { return; } // BUG - Revolution Event - start CivicTypes* paeOldCivics = new CivicTypes[GC.getNumCivicOptionInfos()]; for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { paeOldCivics[iI] = getCivics(((CivicOptionTypes)iI)); } // BUG - Revolution Event - end iAnarchyLength = getCivicAnarchyLength(paeNewCivics); if (iAnarchyLength > 0) { changeAnarchyTurns(iAnarchyLength); for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { setCivics(((CivicOptionTypes)iI), paeNewCivics[iI]); } } else { for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { setCivics(((CivicOptionTypes)iI), paeNewCivics[iI]); } } setRevolutionTimer(std::max(1, ((100 + getAnarchyModifier()) * GC.getDefineINT("MIN_REVOLUTION_TURNS")) / 100) + iAnarchyLength); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Popup_DIRTY_BIT, true); // to force an update of the civic chooser popup } // BUG - Revolution Event - start CvEventReporter::getInstance().playerRevolution(getID(), iAnarchyLength, paeOldCivics, paeNewCivics); delete [] paeOldCivics; // BUG - Revolution Event - end } int CvPlayer::getCivicPercentAnger(CivicTypes eCivic, bool bIgnore) const { int iCount; int iPossibleCount; int iI; if (GC.getCivicInfo(eCivic).getCivicPercentAnger() == 0) { return 0; } if (!bIgnore && (getCivics((CivicOptionTypes)(GC.getCivicInfo(eCivic).getCivicOptionType())) == eCivic)) { return 0; } iCount = 0; iPossibleCount = 0; for (iI = 0; iI < MAX_CIV_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam()) { if (GET_PLAYER((PlayerTypes)iI).getCivics((CivicOptionTypes)(GC.getCivicInfo(eCivic).getCivicOptionType())) == eCivic) { iCount += GET_PLAYER((PlayerTypes)iI).getNumCities(); } iPossibleCount += GET_PLAYER((PlayerTypes)iI).getNumCities(); } } } if (iPossibleCount == 0) { return 0; } return ((GC.getCivicInfo(eCivic).getCivicPercentAnger() * iCount) / iPossibleCount); } bool CvPlayer::canDoReligion(ReligionTypes eReligion) const { if (GET_TEAM(getTeam()).getHasReligionCount(eReligion) == 0) { return false; } return true; } bool CvPlayer::canChangeReligion() const { int iI; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { if (canConvert((ReligionTypes)iI)) { return true; } } return false; } bool CvPlayer::canConvert(ReligionTypes eReligion) const { if (isBarbarian()) { return false; } if (isAnarchy()) { return false; } if (getConversionTimer() > 0) { return false; } if (!isStateReligion()) { return false; } if (getLastStateReligion() == eReligion) { return false; } if (eReligion != NO_RELIGION) { if (!canDoReligion(eReligion)) { return false; } } return true; } void CvPlayer::convert(ReligionTypes eReligion) { int iAnarchyLength; if (!canConvert(eReligion)) { return; } iAnarchyLength = getReligionAnarchyLength(); changeAnarchyTurns(iAnarchyLength); setLastStateReligion(eReligion); setConversionTimer(std::max(1, ((100 + getAnarchyModifier()) * GC.getDefineINT("MIN_CONVERSION_TURNS")) / 100) + iAnarchyLength); } bool CvPlayer::hasHolyCity(ReligionTypes eReligion) const { CvCity* pHolyCity; FAssertMsg(eReligion != NO_RELIGION, "Religion is not assigned a valid value"); pHolyCity = GC.getGameINLINE().getHolyCity(eReligion); if (pHolyCity != NULL) { return (pHolyCity->getOwnerINLINE() == getID()); } return false; } int CvPlayer::countHolyCities() const { int iCount; int iI; iCount = 0; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { if (hasHolyCity((ReligionTypes)iI)) { iCount++; } } return iCount; } void CvPlayer::foundReligion(ReligionTypes eReligion, ReligionTypes eSlotReligion, bool bAward) { CvCity* pLoopCity; CvCity* pBestCity; UnitTypes eFreeUnit; bool bStarting; int iValue; int iBestValue; int iLoop; if (NO_RELIGION == eReligion) { return; } if (GC.getGameINLINE().isReligionFounded(eReligion)) { if (isHuman()) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_FOUND_RELIGION, eSlotReligion); if (NULL != pInfo) { gDLL->getInterfaceIFace()->addPopup(pInfo, getID()); } } else { foundReligion(AI_chooseReligion(), eSlotReligion, bAward); } return; } GC.getGameINLINE().setReligionSlotTaken(eSlotReligion, true); bStarting = ((GC.getReligionInfo(eSlotReligion).getTechPrereq() == NO_TECH) || (GC.getTechInfo((TechTypes) GC.getReligionInfo(eSlotReligion).getTechPrereq()).getEra() < GC.getGameINLINE().getStartEra())); iBestValue = 0; pBestCity = NULL; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (!bStarting || !(pLoopCity->isHolyCity())) { iValue = 10; iValue += pLoopCity->getPopulation(); iValue += GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("FOUND_RELIGION_CITY_RAND"), "Found Religion"); iValue /= (pLoopCity->getReligionCount() + 1); if (pLoopCity->isCapital()) { iValue /= 8; } iValue = std::max(1, iValue); if (iValue > iBestValue) { iBestValue = iValue; pBestCity = pLoopCity; } } } if (pBestCity != NULL) { GC.getGameINLINE().setHolyCity(eReligion, pBestCity, true); if (bAward) { if (GC.getReligionInfo(eSlotReligion).getNumFreeUnits() > 0) { eFreeUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(GC.getReligionInfo(eReligion).getFreeUnitClass()))); if (eFreeUnit != NO_UNIT) { for (int i = 0; i < GC.getReligionInfo(eSlotReligion).getNumFreeUnits(); ++i) { initUnit(eFreeUnit, pBestCity->getX_INLINE(), pBestCity->getY_INLINE()); } } } } } } bool CvPlayer::hasHeadquarters(CorporationTypes eCorporation) const { CvCity* pHeadquarters = GC.getGameINLINE().getHeadquarters(eCorporation); FAssert(eCorporation != NO_CORPORATION); if (pHeadquarters != NULL) { return (pHeadquarters->getOwnerINLINE() == getID()); } return false; } int CvPlayer::countHeadquarters() const { int iCount = 0; for (int iI = 0; iI < GC.getNumCorporationInfos(); iI++) { if (hasHeadquarters((CorporationTypes)iI)) { iCount++; } } return iCount; } int CvPlayer::countCorporations(CorporationTypes eCorporation) const { int iCount = 0; int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->isHasCorporation(eCorporation)) { ++iCount; } } return iCount; } void CvPlayer::foundCorporation(CorporationTypes eCorporation) { CvCity* pLoopCity; CvCity* pBestCity; bool bStarting; int iValue; int iBestValue; int iLoop; if (GC.getGameINLINE().isCorporationFounded(eCorporation)) { return; } bStarting = ((GC.getCorporationInfo(eCorporation).getTechPrereq() == NO_TECH) || (GC.getTechInfo((TechTypes) GC.getCorporationInfo(eCorporation).getTechPrereq()).getEra() < GC.getGameINLINE().getStartEra())); iBestValue = 0; pBestCity = NULL; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (!bStarting || !(pLoopCity->isHeadquarters())) { iValue = 10; iValue += pLoopCity->getPopulation(); for (int i = 0; i < GC.getNUM_CORPORATION_PREREQ_BONUSES(); ++i) { if (NO_BONUS != GC.getCorporationInfo(eCorporation).getPrereqBonus(i)) { iValue += 10 * pLoopCity->getNumBonuses((BonusTypes)GC.getCorporationInfo(eCorporation).getPrereqBonus(i)); } } iValue += GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("FOUND_CORPORATION_CITY_RAND"), "Found Corporation"); iValue /= (pLoopCity->getCorporationCount() + 1); iValue = std::max(1, iValue); if (iValue > iBestValue) { iBestValue = iValue; pBestCity = pLoopCity; } } } if (pBestCity != NULL) { pBestCity->setHeadquarters(eCorporation); } } int CvPlayer::getCivicAnarchyLength(CivicTypes* paeNewCivics) const { bool bChange; int iAnarchyLength; int iI; if (getMaxAnarchyTurns() == 0) { return 0; } if (isGoldenAge()) { return 0; } iAnarchyLength = 0; bChange = false; for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { if (paeNewCivics[iI] != getCivics((CivicOptionTypes)iI)) { iAnarchyLength += GC.getCivicInfo(paeNewCivics[iI]).getAnarchyLength(); bChange = true; } } if (bChange) { iAnarchyLength += GC.getDefineINT("BASE_CIVIC_ANARCHY_LENGTH"); iAnarchyLength += ((getNumCities() * GC.getWorldInfo(GC.getMapINLINE().getWorldSize()).getNumCitiesAnarchyPercent()) / 100); } iAnarchyLength = ((iAnarchyLength * std::max(0, (getAnarchyModifier() + 100))) / 100); if (iAnarchyLength == 0) { return 0; } iAnarchyLength *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getAnarchyPercent(); iAnarchyLength /= 100; iAnarchyLength *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getAnarchyPercent(); iAnarchyLength /= 100; return range(iAnarchyLength, 1, getMaxAnarchyTurns()); } int CvPlayer::getReligionAnarchyLength() const { int iAnarchyLength; if (getMaxAnarchyTurns() == 0) { return 0; } if (isGoldenAge()) { return 0; } iAnarchyLength = GC.getDefineINT("BASE_RELIGION_ANARCHY_LENGTH"); iAnarchyLength += ((getNumCities() * GC.getWorldInfo(GC.getMapINLINE().getWorldSize()).getNumCitiesAnarchyPercent()) / 100); iAnarchyLength = ((iAnarchyLength * std::max(0, (getAnarchyModifier() + 100))) / 100); if (iAnarchyLength == 0) { return 0; } iAnarchyLength *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getAnarchyPercent(); iAnarchyLength /= 100; iAnarchyLength *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getAnarchyPercent(); iAnarchyLength /= 100; return range(iAnarchyLength, 1, getMaxAnarchyTurns()); } int CvPlayer::unitsRequiredForGoldenAge() const { return (GC.getDefineINT("BASE_GOLDEN_AGE_UNITS") + (getNumUnitGoldenAges() * GC.getDefineINT("GOLDEN_AGE_UNITS_MULTIPLIER"))); } int CvPlayer::unitsGoldenAgeCapable() const { CvUnit* pLoopUnit; int iCount; int iLoop; iCount = 0; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->isGoldenAge()) { iCount++; } } return iCount; } // BUG - Female Great People - start /* * Units are grouped by unit class instead of type so you cannot start your second Golden Age * with two Great Prophets: one male and one female. */ int CvPlayer::unitsGoldenAgeReady() const { PROFILE_FUNC(); CvUnit* pLoopUnit; bool* pabUnitUsed; int iCount; int iLoop; int iI; pabUnitUsed = new bool[GC.getNumUnitClassInfos()]; for (iI = 0; iI < GC.getNumUnitClassInfos(); iI++) { pabUnitUsed[iI] = false; } iCount = 0; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (!(pabUnitUsed[pLoopUnit->getUnitClassType()])) { if (pLoopUnit->isGoldenAge()) { pabUnitUsed[pLoopUnit->getUnitClassType()] = true; iCount++; } } } SAFE_DELETE_ARRAY(pabUnitUsed); return iCount; } void CvPlayer::killGoldenAgeUnits(CvUnit* pUnitAlive) { CvUnit* pLoopUnit; CvUnit* pBestUnit; bool* pabUnitUsed; int iUnitsRequired; int iValue; int iBestValue; int iLoop; int iI; pabUnitUsed = new bool[GC.getNumUnitClassInfos()]; for (iI = 0; iI < GC.getNumUnitClassInfos(); iI++) { pabUnitUsed[iI] = false; } iUnitsRequired = unitsRequiredForGoldenAge(); if (pUnitAlive != NULL) { pabUnitUsed[pUnitAlive->getUnitClassType()] = true; iUnitsRequired--; } for (iI = 0; iI < iUnitsRequired; iI++) { iBestValue = 0; pBestUnit = NULL; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->isGoldenAge()) { if (!(pabUnitUsed[pLoopUnit->getUnitClassType()])) { iValue = 10000; iValue /= (plotDistance(pLoopUnit->getX_INLINE(), pLoopUnit->getY_INLINE(), pUnitAlive->getX_INLINE(), pUnitAlive->getY_INLINE()) + 1); if (iValue > iBestValue) { iBestValue = iValue; pBestUnit = pLoopUnit; } } } } FAssert(pBestUnit != NULL); if (pBestUnit != NULL) { pabUnitUsed[pBestUnit->getUnitClassType()] = true; pBestUnit->kill(true); //play animations if (pBestUnit->plot()->isActiveVisible(false)) { //kill removes bestUnit from any groups pBestUnit->getGroup()->pushMission(MISSION_GOLDEN_AGE, 0); } } } SAFE_DELETE_ARRAY(pabUnitUsed); } // BUG - Female Great People - end int CvPlayer::greatPeopleThreshold(bool bMilitary) const { int iThreshold; if (bMilitary) { iThreshold = ((GC.getDefineINT("GREAT_GENERALS_THRESHOLD") * std::max(0, (getGreatGeneralsThresholdModifier() + 100))) / 100); } else { iThreshold = ((GC.getDefineINT("GREAT_PEOPLE_THRESHOLD") * std::max(0, (getGreatPeopleThresholdModifier() + 100))) / 100); } iThreshold *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getGreatPeoplePercent(); if (bMilitary) { iThreshold /= std::max(1, GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getTrainPercent()); } else { iThreshold /= 100; } iThreshold *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getGreatPeoplePercent(); iThreshold /= 100; return std::max(1, iThreshold); } int CvPlayer::specialistYield(SpecialistTypes eSpecialist, YieldTypes eYield) const { return (GC.getSpecialistInfo(eSpecialist).getYieldChange(eYield) + getSpecialistExtraYield(eSpecialist, eYield)); } int CvPlayer::specialistCommerce(SpecialistTypes eSpecialist, CommerceTypes eCommerce) const { return (GC.getSpecialistInfo(eSpecialist).getCommerceChange(eCommerce) + getSpecialistExtraCommerce(eCommerce)); } CvPlot* CvPlayer::getStartingPlot() const { return GC.getMapINLINE().plotSorenINLINE(m_iStartingX, m_iStartingY); } void CvPlayer::setStartingPlot(CvPlot* pNewValue, bool bUpdateStartDist) { CvPlot* pOldStartingPlot; pOldStartingPlot = getStartingPlot(); if (pOldStartingPlot != pNewValue) { if (pOldStartingPlot != NULL) { pOldStartingPlot->area()->changeNumStartingPlots(-1); if (bUpdateStartDist) { GC.getMapINLINE().updateMinOriginalStartDist(pOldStartingPlot->area()); } } if (pNewValue == NULL) { m_iStartingX = INVALID_PLOT_COORD; m_iStartingY = INVALID_PLOT_COORD; } else { m_iStartingX = pNewValue->getX_INLINE(); m_iStartingY = pNewValue->getY_INLINE(); getStartingPlot()->area()->changeNumStartingPlots(1); if (bUpdateStartDist) { GC.getMapINLINE().updateMinOriginalStartDist(getStartingPlot()->area()); } } } } int CvPlayer::getTotalPopulation() const { return m_iTotalPopulation; } int CvPlayer::getAveragePopulation() const { if (getNumCities() == 0) { return 0; } return ((getTotalPopulation() / getNumCities()) + 1); } void CvPlayer::changeTotalPopulation(int iChange) { changeAssets(-(getPopulationAsset(getTotalPopulation()))); changePower(-(getPopulationPower(getTotalPopulation()))); changePopScore(-(getPopulationScore(getTotalPopulation()))); m_iTotalPopulation = (m_iTotalPopulation + iChange); FAssert(getTotalPopulation() >= 0); changeAssets(getPopulationAsset(getTotalPopulation())); changePower(getPopulationPower(getTotalPopulation())); changePopScore(getPopulationScore(getTotalPopulation())); } long CvPlayer::getRealPopulation() const { CvCity* pLoopCity; __int64 iTotalPopulation = 0; int iLoop = 0; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { iTotalPopulation += pLoopCity->getRealPopulation(); } if (iTotalPopulation > MAX_INT) { iTotalPopulation = MAX_INT; } return ((long)(iTotalPopulation)); } int CvPlayer::getTotalLand() const { return m_iTotalLand; } void CvPlayer::changeTotalLand(int iChange) { m_iTotalLand = (m_iTotalLand + iChange); FAssert(getTotalLand() >= 0); } int CvPlayer::getTotalLandScored() const { return m_iTotalLandScored; } void CvPlayer::changeTotalLandScored(int iChange) { if (iChange != 0) { changeAssets(-(getLandPlotsAsset(getTotalLandScored()))); changeLandScore(-(getLandPlotsScore(getTotalLandScored()))); m_iTotalLandScored = (m_iTotalLandScored + iChange); FAssert(getTotalLandScored() >= 0); changeAssets(getLandPlotsAsset(getTotalLandScored())); changeLandScore(getLandPlotsScore(getTotalLandScored())); } } int CvPlayer::getGold() const { return m_iGold; } void CvPlayer::setGold(int iNewValue) { if (getGold() != iNewValue) { m_iGold = iNewValue; if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(MiscButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } void CvPlayer::changeGold(int iChange) { setGold(getGold() + iChange); } int CvPlayer::getGoldPerTurn() const { return m_iGoldPerTurn; } int CvPlayer::getAdvancedStartPoints() const { return m_iAdvancedStartPoints; } void CvPlayer::setAdvancedStartPoints(int iNewValue) { if (getAdvancedStartPoints() != iNewValue) { m_iAdvancedStartPoints = iNewValue; if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(MiscButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(SelectionButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } void CvPlayer::changeAdvancedStartPoints(int iChange) { setAdvancedStartPoints(getAdvancedStartPoints() + iChange); } int CvPlayer::getGoldenAgeTurns() const { return m_iGoldenAgeTurns; } bool CvPlayer::isGoldenAge() const { return (getGoldenAgeTurns() > 0); } void CvPlayer::changeGoldenAgeTurns(int iChange) { CvWString szBuffer; bool bOldGoldenAge; int iI; if (iChange != 0) { bOldGoldenAge = isGoldenAge(); m_iGoldenAgeTurns = (m_iGoldenAgeTurns + iChange); FAssert(getGoldenAgeTurns() >= 0); if (bOldGoldenAge != isGoldenAge()) { if (isGoldenAge()) { changeAnarchyTurns(-getAnarchyTurns()); } updateYield(); if (isGoldenAge()) { szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_GOLDEN_AGE_BEGINS", getNameKey()); GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szBuffer, -1, -1, (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT")); CvEventReporter::getInstance().goldenAge(getID()); } else { CvEventReporter::getInstance().endGoldenAge(getID()); } for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_TEAM(getTeam()).isHasMet(GET_PLAYER((PlayerTypes)iI).getTeam())) { if (isGoldenAge()) { szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_GOLDEN_AGE_HAS_BEGUN", getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), (((PlayerTypes)iI) == getID()), GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_GOLDAGESTART", MESSAGE_TYPE_MAJOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT")); } else { szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_GOLDEN_AGE_ENDED", getNameKey()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_GOLDAGEEND", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT")); } } } } } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getGoldenAgeLength() const { return (GC.getGameINLINE().goldenAgeLength() * std::max(0, 100 + getGoldenAgeModifier())) / 100; } int CvPlayer::getNumUnitGoldenAges() const { return m_iNumUnitGoldenAges; } void CvPlayer::changeNumUnitGoldenAges(int iChange) { m_iNumUnitGoldenAges = (m_iNumUnitGoldenAges + iChange); FAssert(getNumUnitGoldenAges() >= 0); } int CvPlayer::getStrikeTurns() const { return m_iStrikeTurns; } void CvPlayer::changeStrikeTurns(int iChange) { m_iStrikeTurns = (m_iStrikeTurns + iChange); FAssert(getStrikeTurns() >= 0); } int CvPlayer::getAnarchyTurns() const { return m_iAnarchyTurns; } bool CvPlayer::isAnarchy() const { return (getAnarchyTurns() > 0); } void CvPlayer::changeAnarchyTurns(int iChange) { bool bOldAnarchy; if (iChange != 0) { bOldAnarchy = isAnarchy(); m_iAnarchyTurns = (m_iAnarchyTurns + iChange); FAssert(getAnarchyTurns() >= 0); if (bOldAnarchy != isAnarchy()) { updateCommerce(); updateMaintenance(); updateTradeRoutes(); updateCorporation(); AI_makeAssignWorkDirty(); if (isAnarchy()) { gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MISC_REVOLUTION_HAS_BEGUN").GetCString(), "AS2D_REVOLTSTART", MESSAGE_TYPE_MAJOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); } else { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MISC_REVOLUTION_OVER").GetCString(), "AS2D_REVOLTEND", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(MiscButtons_DIRTY_BIT, true); } if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); } } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getMaxAnarchyTurns() const { return m_iMaxAnarchyTurns; } void CvPlayer::updateMaxAnarchyTurns() { int iBestValue; int iI; iBestValue = GC.getDefineINT("MAX_ANARCHY_TURNS"); FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvPlayer::updateMaxAnarchyTurns"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { if (GC.getTraitInfo((TraitTypes)iI).getMaxAnarchy() >= 0) { if (GC.getTraitInfo((TraitTypes)iI).getMaxAnarchy() < iBestValue) { iBestValue = GC.getTraitInfo((TraitTypes)iI).getMaxAnarchy(); } } } } m_iMaxAnarchyTurns = iBestValue; FAssert(getMaxAnarchyTurns() >= 0); } int CvPlayer::getAnarchyModifier() const { return m_iAnarchyModifier; } void CvPlayer::changeAnarchyModifier(int iChange) { if (0 != iChange) { m_iAnarchyModifier += iChange; setRevolutionTimer(std::max(0, ((100 + iChange) * getRevolutionTimer()) / 100)); setConversionTimer(std::max(0, ((100 + iChange) * getConversionTimer()) / 100)); } } int CvPlayer::getGoldenAgeModifier() const { return m_iGoldenAgeModifier; } void CvPlayer::changeGoldenAgeModifier(int iChange) { m_iGoldenAgeModifier += iChange; } int CvPlayer::getHurryModifier() const { return m_iGlobalHurryModifier; } void CvPlayer::changeHurryModifier(int iChange) { m_iGlobalHurryModifier = (m_iGlobalHurryModifier + iChange); } int CvPlayer::getGreatPeopleCreated() const { return m_iGreatPeopleCreated; } void CvPlayer::incrementGreatPeopleCreated() { m_iGreatPeopleCreated++; } int CvPlayer::getGreatGeneralsCreated() const { return m_iGreatGeneralsCreated; } void CvPlayer::incrementGreatGeneralsCreated() { m_iGreatGeneralsCreated++; } int CvPlayer::getGreatPeopleThresholdModifier() const { return m_iGreatPeopleThresholdModifier; } void CvPlayer::changeGreatPeopleThresholdModifier(int iChange) { m_iGreatPeopleThresholdModifier = (m_iGreatPeopleThresholdModifier + iChange); } int CvPlayer::getGreatGeneralsThresholdModifier() const { return m_iGreatGeneralsThresholdModifier; } void CvPlayer::changeGreatGeneralsThresholdModifier(int iChange) { m_iGreatGeneralsThresholdModifier += iChange; } int CvPlayer::getGreatPeopleRateModifier() const { return m_iGreatPeopleRateModifier; } void CvPlayer::changeGreatPeopleRateModifier(int iChange) { m_iGreatPeopleRateModifier = (m_iGreatPeopleRateModifier + iChange); } int CvPlayer::getGreatGeneralRateModifier() const { return m_iGreatGeneralRateModifier; } void CvPlayer::changeGreatGeneralRateModifier(int iChange) { m_iGreatGeneralRateModifier += iChange; } int CvPlayer::getDomesticGreatGeneralRateModifier() const { return (GC.getDefineINT("COMBAT_EXPERIENCE_IN_BORDERS_PERCENT") + m_iDomesticGreatGeneralRateModifier); } void CvPlayer::changeDomesticGreatGeneralRateModifier(int iChange) { m_iDomesticGreatGeneralRateModifier += iChange; } int CvPlayer::getStateReligionGreatPeopleRateModifier() const { return m_iStateReligionGreatPeopleRateModifier; } void CvPlayer::changeStateReligionGreatPeopleRateModifier(int iChange) { m_iStateReligionGreatPeopleRateModifier = (m_iStateReligionGreatPeopleRateModifier + iChange); } int CvPlayer::getMaxGlobalBuildingProductionModifier() const { return m_iMaxGlobalBuildingProductionModifier; } void CvPlayer::changeMaxGlobalBuildingProductionModifier(int iChange) { m_iMaxGlobalBuildingProductionModifier = (m_iMaxGlobalBuildingProductionModifier + iChange); } int CvPlayer::getMaxTeamBuildingProductionModifier() const { return m_iMaxTeamBuildingProductionModifier; } void CvPlayer::changeMaxTeamBuildingProductionModifier(int iChange) { m_iMaxTeamBuildingProductionModifier = (m_iMaxTeamBuildingProductionModifier + iChange); } int CvPlayer::getMaxPlayerBuildingProductionModifier() const { return m_iMaxPlayerBuildingProductionModifier; } void CvPlayer::changeMaxPlayerBuildingProductionModifier(int iChange) { m_iMaxPlayerBuildingProductionModifier = (m_iMaxPlayerBuildingProductionModifier + iChange); } int CvPlayer::getFreeExperience() const { return m_iFreeExperience; } void CvPlayer::changeFreeExperience(int iChange) { m_iFreeExperience = (m_iFreeExperience + iChange); } int CvPlayer::getFeatureProductionModifier() const { return m_iFeatureProductionModifier; } void CvPlayer::changeFeatureProductionModifier(int iChange) { m_iFeatureProductionModifier = (m_iFeatureProductionModifier + iChange); } int CvPlayer::getWorkerSpeedModifier() const { return m_iWorkerSpeedModifier; } void CvPlayer::changeWorkerSpeedModifier(int iChange) { m_iWorkerSpeedModifier = (m_iWorkerSpeedModifier + iChange); } // BUG - Partial Builds - start /* * Returns the work rate for the first unit that can build <eBuild>. */ int CvPlayer::getWorkRate(BuildTypes eBuild) const { int iRate = 0; CvCivilizationInfo& kCiv = GC.getCivilizationInfo(getCivilizationType()); for (int iI = 0; iI < GC.getNumUnitClassInfos(); iI++) { CvUnitInfo& kUnit = GC.getUnitInfo((UnitTypes)kCiv.getCivilizationUnits(iI)); if (kUnit.getBuilds(eBuild)) { iRate = kUnit.getWorkRate(); break; } } iRate *= std::max(0, getWorkerSpeedModifier() + 100); iRate /= 100; if (!isHuman() && !isBarbarian()) { iRate *= std::max(0, (GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIWorkRateModifier() + 100)); iRate /= 100; } return iRate; } // BUG - Partial Builds - end int CvPlayer::getImprovementUpgradeRateModifier() const { return m_iImprovementUpgradeRateModifier; } void CvPlayer::changeImprovementUpgradeRateModifier(int iChange) { m_iImprovementUpgradeRateModifier = (m_iImprovementUpgradeRateModifier + iChange); } int CvPlayer::getMilitaryProductionModifier() const { return m_iMilitaryProductionModifier; } void CvPlayer::changeMilitaryProductionModifier(int iChange) { m_iMilitaryProductionModifier = (m_iMilitaryProductionModifier + iChange); } int CvPlayer::getSpaceProductionModifier() const { return m_iSpaceProductionModifier; } void CvPlayer::changeSpaceProductionModifier(int iChange) { m_iSpaceProductionModifier = (m_iSpaceProductionModifier + iChange); } int CvPlayer::getCityDefenseModifier() const { return m_iCityDefenseModifier; } void CvPlayer::changeCityDefenseModifier(int iChange) { m_iCityDefenseModifier = (m_iCityDefenseModifier + iChange); } int CvPlayer::getNumNukeUnits() const { return m_iNumNukeUnits; } void CvPlayer::changeNumNukeUnits(int iChange) { m_iNumNukeUnits = (m_iNumNukeUnits + iChange); FAssert(getNumNukeUnits() >= 0); } int CvPlayer::getNumOutsideUnits() const { return m_iNumOutsideUnits; } void CvPlayer::changeNumOutsideUnits(int iChange) { if (iChange != 0) { m_iNumOutsideUnits += iChange; FAssert(getNumOutsideUnits() >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getBaseFreeUnits() const { return m_iBaseFreeUnits; } void CvPlayer::changeBaseFreeUnits(int iChange) { if (iChange != 0) { m_iBaseFreeUnits = (m_iBaseFreeUnits + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getBaseFreeMilitaryUnits() const { return m_iBaseFreeMilitaryUnits; } void CvPlayer::changeBaseFreeMilitaryUnits(int iChange) { if (iChange != 0) { m_iBaseFreeMilitaryUnits = (m_iBaseFreeMilitaryUnits + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getFreeUnitsPopulationPercent() const { return m_iFreeUnitsPopulationPercent; } void CvPlayer::changeFreeUnitsPopulationPercent(int iChange) { if (iChange != 0) { m_iFreeUnitsPopulationPercent = (m_iFreeUnitsPopulationPercent + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getFreeMilitaryUnitsPopulationPercent() const { return m_iFreeMilitaryUnitsPopulationPercent; } void CvPlayer::changeFreeMilitaryUnitsPopulationPercent(int iChange) { if (iChange != 0) { m_iFreeMilitaryUnitsPopulationPercent = (m_iFreeMilitaryUnitsPopulationPercent + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getGoldPerUnit() const { return m_iGoldPerUnit; } void CvPlayer::changeGoldPerUnit(int iChange) { if (iChange != 0) { m_iGoldPerUnit = (m_iGoldPerUnit + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getGoldPerMilitaryUnit() const { return m_iGoldPerMilitaryUnit; } void CvPlayer::changeGoldPerMilitaryUnit(int iChange) { if (iChange != 0) { m_iGoldPerMilitaryUnit = (m_iGoldPerMilitaryUnit + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getExtraUnitCost() const { return m_iExtraUnitCost; } void CvPlayer::changeExtraUnitCost(int iChange) { if (iChange != 0) { m_iExtraUnitCost = (m_iExtraUnitCost + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getNumMilitaryUnits() const { return m_iNumMilitaryUnits; } void CvPlayer::changeNumMilitaryUnits(int iChange) { if (iChange != 0) { m_iNumMilitaryUnits = (m_iNumMilitaryUnits + iChange); FAssert(getNumMilitaryUnits() >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getHappyPerMilitaryUnit() const { return m_iHappyPerMilitaryUnit; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeHappyPerMilitaryUnit(int iChange, bool bLimited) { if (iChange != 0) { m_iHappyPerMilitaryUnit = (m_iHappyPerMilitaryUnit + iChange); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getMilitaryFoodProductionCount() const { return m_iMilitaryFoodProductionCount; } bool CvPlayer::isMilitaryFoodProduction() const { return (getMilitaryFoodProductionCount() > 0); } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeMilitaryFoodProductionCount(int iChange, bool bLimited) { if (iChange != 0) { m_iMilitaryFoodProductionCount = (m_iMilitaryFoodProductionCount + iChange); FAssert(getMilitaryFoodProductionCount() >= 0); if (!bLimited && getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getHighestUnitLevel() const { return m_iHighestUnitLevel; } void CvPlayer::setHighestUnitLevel(int iNewValue) { m_iHighestUnitLevel = iNewValue; FAssert(getHighestUnitLevel() >= 0); } int CvPlayer::getMaxConscript() const { return m_iMaxConscript; } void CvPlayer::changeMaxConscript(int iChange) { m_iMaxConscript = (m_iMaxConscript + iChange); FAssert(getMaxConscript() >= 0); } int CvPlayer::getConscriptCount() const { return m_iConscriptCount; } void CvPlayer::setConscriptCount(int iNewValue) { m_iConscriptCount = iNewValue; FAssert(getConscriptCount() >= 0); } void CvPlayer::changeConscriptCount(int iChange) { setConscriptCount(getConscriptCount() + iChange); } int CvPlayer::getOverflowResearch() const { return m_iOverflowResearch; } void CvPlayer::setOverflowResearch(int iNewValue) { m_iOverflowResearch = iNewValue; FAssert(getOverflowResearch() >= 0); } void CvPlayer::changeOverflowResearch(int iChange) { setOverflowResearch(getOverflowResearch() + iChange); } int CvPlayer::getNoUnhealthyPopulationCount() const { return m_iNoUnhealthyPopulationCount; } bool CvPlayer::isNoUnhealthyPopulation() const { return (getNoUnhealthyPopulationCount() > 0); } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeNoUnhealthyPopulationCount(int iChange, bool bLimited) { if (iChange != 0) { m_iNoUnhealthyPopulationCount = (m_iNoUnhealthyPopulationCount + iChange); FAssert(getNoUnhealthyPopulationCount() >= 0); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getExpInBorderModifier() const { return m_iExpInBorderModifier; } void CvPlayer::changeExpInBorderModifier(int iChange) { if (iChange != 0) { m_iExpInBorderModifier += iChange; FAssert(getExpInBorderModifier() >= 0); } } int CvPlayer::getBuildingOnlyHealthyCount() const { return m_iBuildingOnlyHealthyCount; } bool CvPlayer::isBuildingOnlyHealthy() const { return (getBuildingOnlyHealthyCount() > 0); } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeBuildingOnlyHealthyCount(int iChange, bool bLimited) { if (iChange != 0) { m_iBuildingOnlyHealthyCount = (m_iBuildingOnlyHealthyCount + iChange); FAssert(getBuildingOnlyHealthyCount() >= 0); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getDistanceMaintenanceModifier() const { return m_iDistanceMaintenanceModifier; } void CvPlayer::changeDistanceMaintenanceModifier(int iChange) { if (iChange != 0) { m_iDistanceMaintenanceModifier += iChange; updateMaintenance(); } } int CvPlayer::getNumCitiesMaintenanceModifier() const { return m_iNumCitiesMaintenanceModifier; } void CvPlayer::changeNumCitiesMaintenanceModifier(int iChange) { if (iChange != 0) { m_iNumCitiesMaintenanceModifier += iChange; updateMaintenance(); } } int CvPlayer::getCorporationMaintenanceModifier() const { return m_iCorporationMaintenanceModifier; } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeCorporationMaintenanceModifier(int iChange, bool bLimited) { if (iChange != 0) { m_iCorporationMaintenanceModifier += iChange; if (!bLimited) { updateMaintenance(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getTotalMaintenance() const { return m_iTotalMaintenance / 100; } void CvPlayer::changeTotalMaintenance(int iChange) { m_iTotalMaintenance += iChange; FAssert(m_iTotalMaintenance >= 0); } int CvPlayer::getUpkeepModifier() const { return m_iUpkeepModifier; } void CvPlayer::changeUpkeepModifier(int iChange) { m_iUpkeepModifier = (m_iUpkeepModifier + iChange); } int CvPlayer::getLevelExperienceModifier() const { return m_iLevelExperienceModifier; } void CvPlayer::changeLevelExperienceModifier(int iChange) { m_iLevelExperienceModifier += iChange; } int CvPlayer::getExtraHealth() const { return m_iExtraHealth; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeExtraHealth(int iChange, bool bLimited) { if (iChange != 0) { m_iExtraHealth = (m_iExtraHealth + iChange); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getBuildingGoodHealth() const { return m_iBuildingGoodHealth; } void CvPlayer::changeBuildingGoodHealth(int iChange) { if (iChange != 0) { m_iBuildingGoodHealth = (m_iBuildingGoodHealth + iChange); FAssert(getBuildingGoodHealth() >= 0); AI_makeAssignWorkDirty(); } } int CvPlayer::getBuildingBadHealth() const { return m_iBuildingBadHealth; } void CvPlayer::changeBuildingBadHealth(int iChange) { if (iChange != 0) { m_iBuildingBadHealth = (m_iBuildingBadHealth + iChange); FAssert(getBuildingBadHealth() <= 0); AI_makeAssignWorkDirty(); } } int CvPlayer::getExtraHappiness() const { return m_iExtraHappiness; } void CvPlayer::changeExtraHappiness(int iChange) { if (iChange != 0) { m_iExtraHappiness = (m_iExtraHappiness + iChange); AI_makeAssignWorkDirty(); } } int CvPlayer::getBuildingHappiness() const { return m_iBuildingHappiness; } void CvPlayer::changeBuildingHappiness(int iChange) { if (iChange != 0) { m_iBuildingHappiness = (m_iBuildingHappiness + iChange); AI_makeAssignWorkDirty(); } } int CvPlayer::getLargestCityHappiness() const { return m_iLargestCityHappiness; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeLargestCityHappiness(int iChange, bool bLimited) { if (iChange != 0) { m_iLargestCityHappiness = (m_iLargestCityHappiness + iChange); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getWarWearinessPercentAnger() const { return m_iWarWearinessPercentAnger; } void CvPlayer::updateWarWearinessPercentAnger() { int iNewWarWearinessPercentAnger; int iI; iNewWarWearinessPercentAnger = 0; if (!isBarbarian() && !isMinorCiv()) { for (iI = 0; iI < MAX_CIV_TEAMS; iI++) { CvTeam& kTeam = GET_TEAM((TeamTypes)iI); if (kTeam.isAlive() && !kTeam.isMinorCiv()) { if (kTeam.isAtWar(getTeam())) { iNewWarWearinessPercentAnger += (GET_TEAM(getTeam()).getWarWeariness((TeamTypes)iI) * std::max(0, 100 + kTeam.getEnemyWarWearinessModifier())) / 10000; } } } } iNewWarWearinessPercentAnger = getModifiedWarWearinessPercentAnger(iNewWarWearinessPercentAnger); if (getWarWearinessPercentAnger() != iNewWarWearinessPercentAnger) { m_iWarWearinessPercentAnger = iNewWarWearinessPercentAnger; AI_makeAssignWorkDirty(); } } int CvPlayer::getModifiedWarWearinessPercentAnger(int iWarWearinessPercentAnger) const { iWarWearinessPercentAnger *= GC.getDefineINT("BASE_WAR_WEARINESS_MULTIPLIER"); if (GC.getGameINLINE().isOption(GAMEOPTION_ALWAYS_WAR) || GC.getGameINLINE().isOption(GAMEOPTION_NO_CHANGING_WAR_PEACE)) { iWarWearinessPercentAnger *= std::max(0, (GC.getDefineINT("FORCED_WAR_WAR_WEARINESS_MODIFIER") + 100)); iWarWearinessPercentAnger /= 100; } if (GC.getGameINLINE().isGameMultiPlayer()) { iWarWearinessPercentAnger *= std::max(0, (GC.getDefineINT("MULTIPLAYER_WAR_WEARINESS_MODIFIER") + 100)); iWarWearinessPercentAnger /= 100; } iWarWearinessPercentAnger *= std::max(0, (GC.getWorldInfo(GC.getMapINLINE().getWorldSize()).getWarWearinessModifier() + 100)); iWarWearinessPercentAnger /= 100; if (!isHuman() && !isBarbarian() && !isMinorCiv()) { iWarWearinessPercentAnger *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIWarWearinessPercent(); iWarWearinessPercentAnger /= 100; iWarWearinessPercentAnger *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iWarWearinessPercentAnger /= 100; } return iWarWearinessPercentAnger; } int CvPlayer::getWarWearinessModifier() const { return m_iWarWearinessModifier; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeWarWearinessModifier(int iChange, bool bLimited) { if (iChange != 0) { m_iWarWearinessModifier = (m_iWarWearinessModifier + iChange); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getFreeSpecialist() const { return m_iFreeSpecialist; } void CvPlayer::changeFreeSpecialist(int iChange) { if (iChange != 0) { m_iFreeSpecialist = (m_iFreeSpecialist + iChange); FAssert(getFreeSpecialist() >= 0); AI_makeAssignWorkDirty(); } } int CvPlayer::getNoForeignTradeCount() const { return m_iNoForeignTradeCount; } bool CvPlayer::isNoForeignTrade() const { return (getNoForeignTradeCount() > 0); } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeNoForeignTradeCount(int iChange, bool bLimited) { if (iChange != 0) { m_iNoForeignTradeCount = (m_iNoForeignTradeCount + iChange); FAssert(getNoForeignTradeCount() >= 0); if (!bLimited) { GC.getGameINLINE().updateTradeRoutes(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getNoCorporationsCount() const { return m_iNoCorporationsCount; } bool CvPlayer::isNoCorporations() const { return (getNoCorporationsCount() > 0); } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeNoCorporationsCount(int iChange, bool bLimited) { if (iChange != 0) { m_iNoCorporationsCount += iChange; FAssert(getNoCorporationsCount() >= 0); if (!bLimited) { updateCorporation(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getNoForeignCorporationsCount() const { return m_iNoForeignCorporationsCount; } bool CvPlayer::isNoForeignCorporations() const { return (getNoForeignCorporationsCount() > 0); } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeNoForeignCorporationsCount(int iChange, bool bLimited) { if (iChange != 0) { m_iNoForeignCorporationsCount += iChange; FAssert(getNoForeignCorporationsCount() >= 0); if (!bLimited) { updateCorporation(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getCoastalTradeRoutes() const { return m_iCoastalTradeRoutes; } void CvPlayer::changeCoastalTradeRoutes(int iChange) { if (iChange != 0) { m_iCoastalTradeRoutes = (m_iCoastalTradeRoutes + iChange); FAssert(getCoastalTradeRoutes() >= 0); updateTradeRoutes(); } } int CvPlayer::getTradeRoutes() const { return m_iTradeRoutes; } void CvPlayer::changeTradeRoutes(int iChange) { if (iChange != 0) { m_iTradeRoutes = (m_iTradeRoutes + iChange); FAssert(getTradeRoutes() >= 0); updateTradeRoutes(); } } int CvPlayer::getRevolutionTimer() const { return m_iRevolutionTimer; } void CvPlayer::setRevolutionTimer(int iNewValue) { if (getRevolutionTimer() != iNewValue) { m_iRevolutionTimer = iNewValue; FAssert(getRevolutionTimer() >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(MiscButtons_DIRTY_BIT, true); } } } void CvPlayer::changeRevolutionTimer(int iChange) { setRevolutionTimer(getRevolutionTimer() + iChange); } int CvPlayer::getConversionTimer() const { return m_iConversionTimer; } void CvPlayer::setConversionTimer(int iNewValue) { if (getConversionTimer() != iNewValue) { m_iConversionTimer = iNewValue; FAssert(getConversionTimer() >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(MiscButtons_DIRTY_BIT, true); } } } void CvPlayer::changeConversionTimer(int iChange) { setConversionTimer(getConversionTimer() + iChange); } int CvPlayer::getStateReligionCount() const { return m_iStateReligionCount; } bool CvPlayer::isStateReligion() const { return (getStateReligionCount() > 0); } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeStateReligionCount(int iChange, bool bLimited) { if (iChange != 0) { // religion visibility now part of espionage //GC.getGameINLINE().updateCitySight(false, true); m_iStateReligionCount = (m_iStateReligionCount + iChange); FAssert(getStateReligionCount() >= 0); // religion visibility now part of espionage //GC.getGameINLINE().updateCitySight(true, true); if (!bLimited) { updateMaintenance(); } updateReligionHappiness(bLimited); if (!bLimited) { updateReligionCommerce(); GC.getGameINLINE().AI_makeAssignWorkDirty(); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getNoNonStateReligionSpreadCount() const { return m_iNoNonStateReligionSpreadCount; } bool CvPlayer::isNoNonStateReligionSpread() const { return (getNoNonStateReligionSpreadCount() > 0); } void CvPlayer::changeNoNonStateReligionSpreadCount(int iChange) { m_iNoNonStateReligionSpreadCount = (m_iNoNonStateReligionSpreadCount + iChange); FAssert(getNoNonStateReligionSpreadCount() >= 0); } int CvPlayer::getStateReligionHappiness() const { return m_iStateReligionHappiness; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeStateReligionHappiness(int iChange, bool bLimited) { if (iChange != 0) { m_iStateReligionHappiness = (m_iStateReligionHappiness + iChange); updateReligionHappiness(bLimited); } } int CvPlayer::getNonStateReligionHappiness() const { return m_iNonStateReligionHappiness; } //Fuyu bLimited void CvPlayer::changeNonStateReligionHappiness(int iChange, bool bLimited) { if (iChange != 0) { m_iNonStateReligionHappiness = (m_iNonStateReligionHappiness + iChange); updateReligionHappiness(bLimited); } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getStateReligionUnitProductionModifier() const { return m_iStateReligionUnitProductionModifier; } void CvPlayer::changeStateReligionUnitProductionModifier(int iChange) { if (iChange != 0) { m_iStateReligionUnitProductionModifier = (m_iStateReligionUnitProductionModifier + iChange); if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); } } } int CvPlayer::getStateReligionBuildingProductionModifier() const { return m_iStateReligionBuildingProductionModifier; } void CvPlayer::changeStateReligionBuildingProductionModifier(int iChange) { if (iChange != 0) { m_iStateReligionBuildingProductionModifier = (m_iStateReligionBuildingProductionModifier + iChange); if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); } } } int CvPlayer::getStateReligionFreeExperience() const { return m_iStateReligionFreeExperience; } void CvPlayer::changeStateReligionFreeExperience(int iChange) { m_iStateReligionFreeExperience = (m_iStateReligionFreeExperience + iChange); } CvCity* CvPlayer::getCapitalCity() const { return getCity(m_iCapitalCityID); } void CvPlayer::setCapitalCity(CvCity* pNewCapitalCity) { CvCity* pOldCapitalCity; bool bUpdatePlotGroups; pOldCapitalCity = getCapitalCity(); if (pOldCapitalCity != pNewCapitalCity) { bUpdatePlotGroups = ((pOldCapitalCity == NULL) || (pNewCapitalCity == NULL) || (pOldCapitalCity->plot()->getOwnerPlotGroup() != pNewCapitalCity->plot()->getOwnerPlotGroup())); if (bUpdatePlotGroups) { if (pOldCapitalCity != NULL) { pOldCapitalCity->plot()->updatePlotGroupBonus(false); } if (pNewCapitalCity != NULL) { pNewCapitalCity->plot()->updatePlotGroupBonus(false); } } if (pNewCapitalCity != NULL) { m_iCapitalCityID = pNewCapitalCity->getID(); } else { m_iCapitalCityID = FFreeList::INVALID_INDEX; } if (bUpdatePlotGroups) { if (pOldCapitalCity != NULL) { pOldCapitalCity->plot()->updatePlotGroupBonus(true); } if (pNewCapitalCity != NULL) { pNewCapitalCity->plot()->updatePlotGroupBonus(true); } } updateMaintenance(); updateTradeRoutes(); if (pOldCapitalCity != NULL) { pOldCapitalCity->updateCommerce(); pOldCapitalCity->setInfoDirty(true); } if (pNewCapitalCity != NULL) { pNewCapitalCity->updateCommerce(); pNewCapitalCity->setInfoDirty(true); } } } int CvPlayer::getCitiesLost() const { return m_iCitiesLost; } void CvPlayer::changeCitiesLost(int iChange) { m_iCitiesLost = (m_iCitiesLost + iChange); } int CvPlayer::getWinsVsBarbs() const { return m_iWinsVsBarbs; } void CvPlayer::changeWinsVsBarbs(int iChange) { m_iWinsVsBarbs = (m_iWinsVsBarbs + iChange); FAssert(getWinsVsBarbs() >= 0); } int CvPlayer::getAssets() const { return m_iAssets; } void CvPlayer::changeAssets(int iChange) { m_iAssets = (m_iAssets + iChange); FAssert(getAssets() >= 0); } int CvPlayer::getPower() const { return m_iPower; } void CvPlayer::changePower(int iChange) { m_iPower = (m_iPower + iChange); FAssert(getPower() >= 0); } int CvPlayer::getPopScore(bool bCheckVassal) const { if (bCheckVassal && GET_TEAM(getTeam()).isAVassal()) { return m_iPopulationScore / 2; } int iVassalScore = 0; if (bCheckVassal) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (i != getID()) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)i); if (kLoopPlayer.isAlive() && GET_TEAM(kLoopPlayer.getTeam()).isVassal(getTeam())) { iVassalScore += kLoopPlayer.getPopScore(false) / 2; } } } } return (m_iPopulationScore + iVassalScore / std::max(1, GET_TEAM(getTeam()).getNumMembers())); } void CvPlayer::changePopScore(int iChange) { if (iChange != 0) { m_iPopulationScore += iChange; FAssert(getPopScore() >= 0); GC.getGameINLINE().setScoreDirty(true); } } int CvPlayer::getLandScore(bool bCheckVassal) const { if (bCheckVassal && GET_TEAM(getTeam()).isAVassal()) { return m_iLandScore / 2; } int iVassalScore = 0; if (bCheckVassal) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (i != getID()) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)i); if (kLoopPlayer.isAlive() && GET_TEAM(kLoopPlayer.getTeam()).isVassal(getTeam())) { iVassalScore += kLoopPlayer.getLandScore(false) / 2; } } } } return (m_iLandScore + iVassalScore / std::max(1, GET_TEAM(getTeam()).getNumMembers())); } void CvPlayer::changeLandScore(int iChange) { if (iChange != 0) { m_iLandScore += iChange; FAssert(getLandScore() >= 0); GC.getGameINLINE().setScoreDirty(true); } } int CvPlayer::getWondersScore() const { return m_iWondersScore; } void CvPlayer::changeWondersScore(int iChange) { if (iChange != 0) { m_iWondersScore += iChange; FAssert(getWondersScore() >= 0); GC.getGameINLINE().setScoreDirty(true); } } int CvPlayer::getTechScore() const { return m_iTechScore; } void CvPlayer::changeTechScore(int iChange) { if (iChange != 0) { m_iTechScore += iChange; FAssert(getTechScore() >= 0); GC.getGameINLINE().setScoreDirty(true); } } int CvPlayer::getCombatExperience() const { return m_iCombatExperience; } void CvPlayer::setCombatExperience(int iExperience) { FAssert(iExperience >= 0); if (iExperience != getCombatExperience()) { m_iCombatExperience = iExperience; if (!isBarbarian()) { int iExperienceThreshold = greatPeopleThreshold(true); if (m_iCombatExperience >= iExperienceThreshold && iExperienceThreshold > 0) { // create great person CvCity* pBestCity = NULL; int iBestValue = MAX_INT; int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { int iValue = 4 * GC.getGameINLINE().getSorenRandNum(getNumCities(), "Warlord City Selection"); for (int i = 0; i < NUM_YIELD_TYPES; i++) { iValue += pLoopCity->findYieldRateRank((YieldTypes)i); } iValue += pLoopCity->findPopulationRank(); if (iValue < iBestValue) { pBestCity = pLoopCity; iBestValue = iValue; } } if (pBestCity) { int iRandOffset = GC.getGameINLINE().getSorenRandNum(GC.getNumUnitInfos(), "Warlord Unit Generation"); for (int iI = 0; iI < GC.getNumUnitInfos(); iI++) { UnitTypes eLoopUnit = (UnitTypes)((iI + iRandOffset) % GC.getNumUnitInfos()); if (GC.getUnitInfo(eLoopUnit).getLeaderExperience() > 0 || GC.getUnitInfo(eLoopUnit).getLeaderPromotion() != NO_PROMOTION) { pBestCity->createGreatPeople(eLoopUnit, false, true); setCombatExperience(getCombatExperience() - iExperienceThreshold); break; } } } } } } } void CvPlayer::changeCombatExperience(int iChange) { setCombatExperience(getCombatExperience() + iChange); } bool CvPlayer::isConnected() const { return gDLL->isConnected( getNetID() ); } int CvPlayer::getNetID() const { return GC.getInitCore().getNetID(getID()); } void CvPlayer::setNetID(int iNetID) { GC.getInitCore().setNetID(getID(), iNetID); } void CvPlayer::sendReminder() { CvWString szYearStr; // Only perform this step if we have a valid email address on record, // and we have provided information about how to send emails if ( !getPbemEmailAddress().empty() && !gDLL->GetPitbossSmtpHost().empty() ) { GAMETEXT.setTimeStr(szYearStr, GC.getGameINLINE().getGameTurn(), true); // Generate our arguments CyArgsList argsList; argsList.add(getPbemEmailAddress()); argsList.add(gDLL->GetPitbossSmtpHost()); argsList.add(gDLL->GetPitbossSmtpLogin()); argsList.add(gDLL->GetPitbossSmtpPassword()); argsList.add(GC.getGameINLINE().getName()); argsList.add(GC.getGameINLINE().isMPOption(MPOPTION_TURN_TIMER)); argsList.add(GC.getGameINLINE().getPitbossTurnTime()); argsList.add(gDLL->GetPitbossEmail()); argsList.add(szYearStr); // Now send our email via Python long iResult; bool bOK = gDLL->getPythonIFace()->callFunction(PYPitBossModule, "sendEmail", argsList.makeFunctionArgs(), &iResult); FAssertMsg( bOK, "Pitboss Python call to onSendEmail failed!" ); FAssertMsg( iResult == 0, "Pitboss Python fn onSendEmail encountered an error" ); } } uint CvPlayer::getStartTime() const { return m_uiStartTime; } void CvPlayer::setStartTime(uint uiStartTime) { m_uiStartTime = uiStartTime; } uint CvPlayer::getTotalTimePlayed() const { return ((timeGetTime() - m_uiStartTime)/1000); } bool CvPlayer::isMinorCiv() const { return GC.getInitCore().getMinorNationCiv(m_eID); } bool CvPlayer::isAlive() const { return m_bAlive; } bool CvPlayer::isEverAlive() const { return m_bEverAlive; } void CvPlayer::setAlive(bool bNewValue) { CvWString szBuffer; int iI; if (isAlive() != bNewValue) { m_bAlive = bNewValue; GET_TEAM(getTeam()).changeAliveCount((isAlive()) ? 1 : -1); // Report event to Python CvEventReporter::getInstance().setPlayerAlive(getID(), bNewValue); if (isAlive()) { if (!isEverAlive()) { m_bEverAlive = true; GET_TEAM(getTeam()).changeEverAliveCount(1); } if (getNumCities() == 0) { setFoundedFirstCity(false); } updatePlotGroups(); if (GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS) || (GC.getGameINLINE().getNumGameTurnActive() == 0) || (GC.getGameINLINE().isSimultaneousTeamTurns() && GET_TEAM(getTeam()).isTurnActive())) { setTurnActive(true); } gDLL->openSlot(getID()); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 09/03/09 poyuzhe & jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // From Sanguo Mod Performance, ie the CAR Mod // Attitude cache for( int iI = 0; iI < MAX_PLAYERS; iI++ ) { GET_PLAYER((PlayerTypes)iI).AI_invalidateAttitudeCache(getID()); GET_PLAYER(getID()).AI_invalidateAttitudeCache((PlayerTypes)iI); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } else { clearResearchQueue(); killUnits(); killCities(); killAllDeals(); setTurnActive(false); gDLL->endMPDiplomacy(); gDLL->endDiplomacy(); if (!isHuman()) { gDLL->closeSlot(getID()); } if (GC.getGameINLINE().getElapsedGameTurns() > 0) { if (!isBarbarian()) { szBuffer = gDLL->getText("TXT_KEY_MISC_CIV_DESTROYED", getCivilizationAdjectiveKey()); for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CIVDESTROYED", MESSAGE_TYPE_MAJOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); } } GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szBuffer, -1, -1, (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); } } } GC.getGameINLINE().setScoreDirty(true); } } void CvPlayer::verifyAlive() { bool bKill; if (isAlive()) { bKill = false; if (!bKill) { if (!isBarbarian()) { if (getNumCities() == 0 && getAdvancedStartPoints() < 0) { if ((getNumUnits() == 0) || (!(GC.getGameINLINE().isOption(GAMEOPTION_COMPLETE_KILLS)) && isFoundedFirstCity())) { bKill = true; } } } } if (!bKill) { if (!isBarbarian()) { if (GC.getGameINLINE().getMaxCityElimination() > 0) { if (getCitiesLost() >= GC.getGameINLINE().getMaxCityElimination()) { bKill = true; } } } } if (bKill) { setAlive(false); } } else { if ((getNumCities() > 0) || (getNumUnits() > 0)) { setAlive(true); } } } bool CvPlayer::isTurnActive() const { return m_bTurnActive; } void CvPlayer::setTurnActiveForPbem(bool bActive) { FAssertMsg(GC.getGameINLINE().isPbem(), "You are using setTurnActiveForPbem. Are you sure you know what you're doing?"); // does nothing more than to set the member variable before saving the game // the rest of the turn will be performed upon loading the game // This allows the player to browse the game in paused mode after he has generated the save if (isTurnActive() != bActive) { m_bTurnActive = bActive; GC.getGameINLINE().changeNumGameTurnActive(isTurnActive() ? 1 : -1); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 08/21/09 jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // Plot danger cache //if( GC.getGameINLINE().getNumGameTurnActive() != 1 ) { GC.getMapINLINE().invalidateIsActivePlayerNoDangerCache(); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } } void CvPlayer::setTurnActive(bool bNewValue, bool bDoTurn) { int iI; if (isTurnActive() != bNewValue) { m_bTurnActive = bNewValue; if (isTurnActive()) { if (GC.getLogging()) { if (gDLL->getChtLvl() > 0) { TCHAR szOut[1024]; sprintf(szOut, "Player %d Turn ON\n", getID()); gDLL->messageControlLog(szOut); } } /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/26/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gPlayerLogLevel > 0 ) { logBBAI("Player %d (%S) setTurnActive for turn %d", getID(), getCivilizationDescription(0), GC.getGameINLINE().getGameTurn() ); if( GC.getGameINLINE().getGameTurn() > 0 && (GC.getGameINLINE().getGameTurn() % 25) == 0 && !isBarbarian() ) { CvWStringBuffer szBuffer; GAMETEXT.setScoreHelp(szBuffer, getID()); logBBAI("%S", szBuffer); int iGameTurn = GC.getGameINLINE().getGameTurn(); logBBAI(" Total Score: %d, Population Score: %d (%d total pop), Land Score: %d, Tech Score: %d, Wonder Score: %d", calculateScore(), getPopScore(false), getTotalPopulation(), getLandScore(false), getTechScore(), getWondersScore()); int iEconomy = 0; int iProduction = 0; int iAgri = 0; int iCount = 0; for( int iI = 1; iI <= 5; iI++ ) { if( iGameTurn - iI >= 0 ) { iEconomy += getEconomyHistory(iGameTurn - iI); iProduction += getIndustryHistory(iGameTurn - iI); iAgri += getAgricultureHistory(iGameTurn - iI); iCount++; } } iEconomy /= std::max(1, iCount); iProduction /= std::max(1, iCount); iAgri /= std::max(1, iCount); logBBAI(" Economy avg: %d, Industry avg: %d, Agriculture avg: %d", iEconomy, iProduction, iAgri); } } if( gPlayerLogLevel >= 2 ) { CvWStringBuffer szBuffer; logBBAI(" Player %d (%S) has %d cities, %d pop, %d power, %d tech percent", getID(), getCivilizationDescription(0), getNumCities(), getTotalPopulation(), getPower(), GET_TEAM(getTeam()).getBestKnownTechScorePercent()); if( GET_PLAYER(getID()).AI_isFinancialTrouble() ) { logBBAI(" Financial trouble!"); } szBuffer.append(CvWString::format(L" Team %d has met: ", getTeam())); for( int iI = 0; iI < MAX_CIV_TEAMS; iI++ ) { if( iI != getTeam() && GET_TEAM(getTeam()).isHasMet((TeamTypes)iI) ) { if( GET_TEAM((TeamTypes)iI).isAlive() ) { szBuffer.append(CvWString::format(L"%d,", iI)); } } } if( GET_TEAM(getTeam()).getVassalCount() > 0 ) { szBuffer.append(CvWString::format(L"; vassals: ")); for( int iI = 0; iI < MAX_CIV_TEAMS; iI++ ) { if( iI != getTeam() && GET_TEAM((TeamTypes)iI).isVassal(getTeam()) ) { if( GET_TEAM((TeamTypes)iI).isAlive() ) { szBuffer.append(CvWString::format(L"%d,", iI)); } } } } if( GET_TEAM(getTeam()).getAtWarCount(false) > 0 ) { szBuffer.append(CvWString::format(L"; at war with: ")); for( int iI = 0; iI < MAX_CIV_TEAMS; iI++ ) { if( iI != getTeam() && GET_TEAM(getTeam()).isAtWar((TeamTypes)iI) ) { if( GET_TEAM((TeamTypes)iI).isAlive() ) { szBuffer.append(CvWString::format(L"%d,", iI)); } } } } if( GET_TEAM(getTeam()).getAnyWarPlanCount(true) > 0 ) { szBuffer.append(CvWString::format(L"; planning war with: ")); for( int iI = 0; iI < MAX_CIV_TEAMS; iI++ ) { if( iI != getTeam() && !GET_TEAM(getTeam()).isAtWar((TeamTypes)iI) && GET_TEAM(getTeam()).AI_getWarPlan((TeamTypes)iI) != NO_WARPLAN ) { if( GET_TEAM((TeamTypes)iI).isAlive() ) { szBuffer.append(CvWString::format(L"%d,", iI)); } } } } logBBAI("%S", szBuffer.getCString()); szBuffer.clear(); if( GET_TEAM(getTeam()).getAnyWarPlanCount(true) > 0 ) logBBAI(" Enemy power perc: %d (%d with others reduction)", GET_TEAM(getTeam()).AI_getEnemyPowerPercent(), GET_TEAM(getTeam()).AI_getEnemyPowerPercent(true)); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ FAssertMsg(isAlive(), "isAlive is expected to be true"); setEndTurn(false); GC.getGameINLINE().resetTurnTimer(); // If we are the Pitboss, send this player an email if ( gDLL->IsPitbossHost() ) { // If this guy is not currently connected, try sending him an email if ( isHuman() && !isConnected() ) { sendReminder(); } } if ((GC.getGameINLINE().isHotSeat() || GC.getGameINLINE().isPbem()) && isHuman() && bDoTurn) { gDLL->getInterfaceIFace()->clearEventMessages(); gDLL->getEngineIFace()->setResourceLayer(false); GC.getGameINLINE().setActivePlayer(getID()); } GC.getGameINLINE().changeNumGameTurnActive(1); if (bDoTurn) { if (isAlive() && !isHuman() && !isBarbarian() && (getAdvancedStartPoints() >= 0)) { AI_doAdvancedStart(); } if (GC.getGameINLINE().getElapsedGameTurns() > 0) { if (isAlive()) { if (GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS)) { doTurn(); } doTurnUnits(); } } if ((getID() == GC.getGameINLINE().getActivePlayer()) && (GC.getGameINLINE().getElapsedGameTurns() > 0)) { if (GC.getGameINLINE().isNetworkMultiPlayer()) { gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MISC_TURN_BEGINS").GetCString(), "AS2D_NEWTURN", MESSAGE_TYPE_DISPLAY_ONLY); } else { gDLL->getInterfaceIFace()->playGeneralSound("AS2D_NEWTURN"); } } doWarnings(); } if (getID() == GC.getGameINLINE().getActivePlayer()) { if (gDLL->getInterfaceIFace()->getLengthSelectionList() == 0) { gDLL->getInterfaceIFace()->setCycleSelectionCounter(1); } gDLL->getInterfaceIFace()->setDirty(SelectionCamera_DIRTY_BIT, true); } } else { if (GC.getLogging()) { if (gDLL->getChtLvl() > 0) { TCHAR szOut[1024]; sprintf(szOut, "Player %d Turn OFF\n", getID()); gDLL->messageControlLog(szOut); } } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setForcePopup(false); gDLL->getInterfaceIFace()->clearQueuedPopups(); gDLL->getInterfaceIFace()->flushTalkingHeadMessages(); } // start profiling DLL if desired if (getID() == GC.getGameINLINE().getActivePlayer()) { startProfilingDLL(); } GC.getGameINLINE().changeNumGameTurnActive(-1); if (bDoTurn) { if (!GC.getGameINLINE().isMPOption(MPOPTION_SIMULTANEOUS_TURNS)) { if (isAlive()) { doTurn(); } if ((GC.getGameINLINE().isPbem() || GC.getGameINLINE().isHotSeat()) && isHuman() && GC.getGameINLINE().countHumanPlayersAlive() > 1) { GC.getGameINLINE().setHotPbemBetweenTurns(true); } if (GC.getGameINLINE().isSimultaneousTeamTurns()) { if (!GET_TEAM(getTeam()).isTurnActive()) { for (iI = (getTeam() + 1); iI < MAX_TEAMS; iI++) { if (GET_TEAM((TeamTypes)iI).isAlive()) { GET_TEAM((TeamTypes)iI).setTurnActive(true); break; } } } } else { for (iI = (getID() + 1); iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GC.getGameINLINE().isPbem() && GET_PLAYER((PlayerTypes)iI).isHuman()) { if (!GC.getGameINLINE().getPbemTurnSent()) { gDLL->sendPbemTurn((PlayerTypes)iI); } } else { GET_PLAYER((PlayerTypes)iI).setTurnActive(true); } break; } } } } } } gDLL->getInterfaceIFace()->updateCursorType(); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 08/21/09 jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // Plot danger cache //if( GC.getGameINLINE().getNumGameTurnActive() != 1 ) { GC.getMapINLINE().invalidateIsActivePlayerNoDangerCache(); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } } bool CvPlayer::isAutoMoves() const { return m_bAutoMoves; } void CvPlayer::setAutoMoves(bool bNewValue) { if (isAutoMoves() != bNewValue) { m_bAutoMoves = bNewValue; if (!isAutoMoves()) { if (isEndTurn() || !isHuman()) { setTurnActive(false); } else { if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setCycleSelectionCounter(1); } } } } } bool CvPlayer::isEndTurn() const { return m_bEndTurn; } void CvPlayer::setEndTurn(bool bNewValue) { if (isEndTurn() != bNewValue) { FAssertMsg(isTurnActive(), "isTurnActive is expected to be true"); m_bEndTurn = bNewValue; if (isEndTurn()) { setAutoMoves(true); } } } bool CvPlayer::isTurnDone() const { // if this returns true, popups and diplomacy will wait to appear until next turn if (!GC.getGameINLINE().isPbem() && !GC.getGameINLINE().isHotSeat()) { return false; } if (!isHuman() ) { return true; } if (!isEndTurn()) { return false; } return (!isAutoMoves()); } bool CvPlayer::isExtendedGame() const { return m_bExtendedGame; } void CvPlayer::makeExtendedGame() { m_bExtendedGame = true; } bool CvPlayer::isFoundedFirstCity() const { return m_bFoundedFirstCity; } void CvPlayer::setFoundedFirstCity(bool bNewValue) { if (isFoundedFirstCity() != bNewValue) { m_bFoundedFirstCity = bNewValue; if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(PercentButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(ResearchButtons_DIRTY_BIT, true); } } } bool CvPlayer::isStrike() const { return m_bStrike; } void CvPlayer::setStrike(bool bNewValue) { if (isStrike() != bNewValue) { m_bStrike = bNewValue; if (isStrike()) { if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_MISC_UNITS_ON_STRIKE").GetCString(), "AS2D_STRIKE", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WARNING_TEXT")); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } } PlayerTypes CvPlayer::getID() const { return m_eID; } HandicapTypes CvPlayer::getHandicapType() const { return GC.getInitCore().getHandicap(getID()); } CivilizationTypes CvPlayer::getCivilizationType() const { return GC.getInitCore().getCiv(getID()); } LeaderHeadTypes CvPlayer::getLeaderType() const { return GC.getInitCore().getLeader(getID()); } LeaderHeadTypes CvPlayer::getPersonalityType() const { return m_ePersonalityType; } void CvPlayer::setPersonalityType(LeaderHeadTypes eNewValue) { m_ePersonalityType = eNewValue; } EraTypes CvPlayer::getCurrentEra() const { return m_eCurrentEra; } void CvPlayer::setCurrentEra(EraTypes eNewValue) { CvCity* pLoopCity; CvUnit* pLoopUnit; CvPlot* pLoopPlot; int iLoop; int iI; if (getCurrentEra() != eNewValue) { EraTypes eOldEra = m_eCurrentEra; m_eCurrentEra = eNewValue; if (GC.getGameINLINE().getActiveTeam() != NO_TEAM) { for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); pLoopPlot->updateGraphicEra(); if (pLoopPlot->getRevealedImprovementType(GC.getGameINLINE().getActiveTeam(), true) != NO_IMPROVEMENT) { if ((pLoopPlot->getOwnerINLINE() == getID()) || (!(pLoopPlot->isOwned()) && (getID() == GC.getGameINLINE().getActivePlayer()))) { pLoopPlot->setLayoutDirty(true); } } } } // dirty all of this player's cities... for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getOwnerINLINE() == getID()) { pLoopCity->setLayoutDirty(true); } } //update unit eras for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { gDLL->getEntityIFace()->updateGraphicEra(pLoopUnit->getUnitEntity(), eOldEra); } //update flag eras gDLL->getInterfaceIFace()->setDirty(Flag_DIRTY_BIT, true); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Soundtrack_DIRTY_BIT, true); } if (isHuman() && (getCurrentEra() != GC.getGameINLINE().getStartEra()) && !GC.getGameINLINE().isNetworkMultiPlayer()) { if (GC.getGameINLINE().isFinalInitialized() && !(gDLL->GetWorldBuilderMode())) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_PYTHON_SCREEN); if (NULL != pInfo) { pInfo->setData1(eNewValue); pInfo->setText(L"showEraMovie"); addPopup(pInfo); } } } } } ReligionTypes CvPlayer::getLastStateReligion() const { return m_eLastStateReligion; } ReligionTypes CvPlayer::getStateReligion() const { return ((isStateReligion()) ? getLastStateReligion() : NO_RELIGION); } void CvPlayer::setLastStateReligion(ReligionTypes eNewValue) { ReligionTypes eOldReligion; CvWString szBuffer; int iI; if (getLastStateReligion() != eNewValue) { // religion visibility now part of espionage //GC.getGameINLINE().updateCitySight(false, true); eOldReligion = getLastStateReligion(); m_eLastStateReligion = eNewValue; // religion visibility now part of espionage //GC.getGameINLINE().updateCitySight(true, true); updateMaintenance(); updateReligionHappiness(); updateReligionCommerce(); GC.getGameINLINE().updateSecretaryGeneral(); GC.getGameINLINE().AI_makeAssignWorkDirty(); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); if (GC.getGameINLINE().isFinalInitialized()) { if (gDLL->isDiplomacy() && (gDLL->getDiplomacyPlayer() == getID())) { gDLL->updateDiplomacyAttitude(true); } if (!isBarbarian()) { if (getLastStateReligion() != NO_RELIGION) { for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_TEAM(getTeam()).isHasMet(GET_PLAYER((PlayerTypes)iI).getTeam())) { szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_CONVERT_RELIGION", getNameKey(), GC.getReligionInfo(getLastStateReligion()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_RELIGION_CONVERT", MESSAGE_TYPE_MAJOR_EVENT); } } } szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_CONVERT_RELIGION", getNameKey(), GC.getReligionInfo(getLastStateReligion()).getTextKeyWide()); GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szBuffer); } } // Python Event CvEventReporter::getInstance().playerChangeStateReligion(getID(), eNewValue, eOldReligion); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 09/03/09 poyuzhe & jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // From Sanguo Mod Performance, ie the CAR Mod // Attitude cache for (int iI = 0; iI < GC.getMAX_PLAYERS(); iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive() && GET_PLAYER((PlayerTypes)iI).getStateReligion() != NO_RELIGION) { GET_PLAYER(getID()).AI_invalidateAttitudeCache((PlayerTypes)iI); GET_PLAYER((PlayerTypes)iI).AI_invalidateAttitudeCache(getID()); } } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } } } PlayerTypes CvPlayer::getParent() const { return m_eParent; } void CvPlayer::setParent(PlayerTypes eParent) { /************************************************************************************************/ /* BETTER_BTS_AI_MOD 09/03/09 poyuzhe & jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // From Sanguo Mod Performance, ie the CAR Mod // Attitude cache if (m_eParent != eParent) { GET_PLAYER(getID()).AI_invalidateAttitudeCache(eParent); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ m_eParent = eParent; } TeamTypes CvPlayer::getTeam() const { return m_eTeamType; } void CvPlayer::updateTeamType() { if(getID() == NO_PLAYER) { m_eTeamType = NO_TEAM; } else { m_eTeamType = GC.getInitCore().getTeam(getID()); } } void CvPlayer::setTeam(TeamTypes eTeam) { FAssert(eTeam != NO_TEAM); FAssert(getTeam() != NO_TEAM); GET_TEAM(getTeam()).changeNumMembers(-1); if (isAlive()) { GET_TEAM(getTeam()).changeAliveCount(-1); } if (isEverAlive()) { GET_TEAM(getTeam()).changeEverAliveCount(-1); } GET_TEAM(getTeam()).changeNumCities(-(getNumCities())); GET_TEAM(getTeam()).changeTotalPopulation(-(getTotalPopulation())); GET_TEAM(getTeam()).changeTotalLand(-(getTotalLand())); GC.getInitCore().setTeam(getID(), eTeam); GET_TEAM(getTeam()).changeNumMembers(1); if (isAlive()) { GET_TEAM(getTeam()).changeAliveCount(1); } if (isEverAlive()) { GET_TEAM(getTeam()).changeEverAliveCount(1); } GET_TEAM(getTeam()).changeNumCities(getNumCities()); GET_TEAM(getTeam()).changeTotalPopulation(getTotalPopulation()); GET_TEAM(getTeam()).changeTotalLand(getTotalLand()); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 09/03/09 poyuzhe & jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // From Sanguo Mod Performance, ie the CAR Mod // Attitude cache if (GC.getGameINLINE().isFinalInitialized()) { for (int iI = 0; iI < MAX_PLAYERS; iI++) { if( GET_PLAYER((PlayerTypes)iI).isAlive() ) { GET_PLAYER(getID()).AI_invalidateAttitudeCache((PlayerTypes)iI); GET_PLAYER((PlayerTypes)iI).AI_invalidateAttitudeCache(getID()); } } } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } PlayerColorTypes CvPlayer::getPlayerColor() const { return GC.getInitCore().getColor(getID()); } int CvPlayer::getPlayerTextColorR() const { FAssertMsg(getPlayerColor() != NO_PLAYERCOLOR, "getPlayerColor() is not expected to be equal with NO_PLAYERCOLOR"); return ((int)(GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(getPlayerColor()).getTextColorType()).getColor().r * 255)); } int CvPlayer::getPlayerTextColorG() const { FAssertMsg(getPlayerColor() != NO_PLAYERCOLOR, "getPlayerColor() is not expected to be equal with NO_PLAYERCOLOR"); return ((int)(GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(getPlayerColor()).getTextColorType()).getColor().g * 255)); } int CvPlayer::getPlayerTextColorB() const { FAssertMsg(getPlayerColor() != NO_PLAYERCOLOR, "getPlayerColor() is not expected to be equal with NO_PLAYERCOLOR"); return ((int)(GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(getPlayerColor()).getTextColorType()).getColor().b * 255)); } int CvPlayer::getPlayerTextColorA() const { FAssertMsg(getPlayerColor() != NO_PLAYERCOLOR, "getPlayerColor() is not expected to be equal with NO_PLAYERCOLOR"); return ((int)(GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(getPlayerColor()).getTextColorType()).getColor().a * 255)); } int CvPlayer::getSeaPlotYield(YieldTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiSeaPlotYield[eIndex]; } void CvPlayer::changeSeaPlotYield(YieldTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiSeaPlotYield[eIndex] = (m_aiSeaPlotYield[eIndex] + iChange); updateYield(); } } int CvPlayer::getYieldRateModifier(YieldTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiYieldRateModifier[eIndex]; } void CvPlayer::changeYieldRateModifier(YieldTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiYieldRateModifier[eIndex] = (m_aiYieldRateModifier[eIndex] + iChange); invalidateYieldRankCache(eIndex); if (eIndex == YIELD_COMMERCE) { updateCommerce(); } AI_makeAssignWorkDirty(); if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(CityInfo_DIRTY_BIT, true); } } } int CvPlayer::getCapitalYieldRateModifier(YieldTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiCapitalYieldRateModifier[eIndex]; } void CvPlayer::changeCapitalYieldRateModifier(YieldTypes eIndex, int iChange) { CvCity* pCapitalCity; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiCapitalYieldRateModifier[eIndex] = (m_aiCapitalYieldRateModifier[eIndex] + iChange); invalidateYieldRankCache(eIndex); pCapitalCity = getCapitalCity(); if (pCapitalCity != NULL) { if (eIndex == YIELD_COMMERCE) { pCapitalCity->updateCommerce(); } pCapitalCity->AI_setAssignWorkDirty(true); if (pCapitalCity->getTeam() == GC.getGameINLINE().getActiveTeam()) { pCapitalCity->setInfoDirty(true); } } } } int CvPlayer::getExtraYieldThreshold(YieldTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiExtraYieldThreshold[eIndex]; } void CvPlayer::updateExtraYieldThreshold(YieldTypes eIndex) { int iBestValue; int iI; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); iBestValue = 0; FAssertMsg((GC.getNumTraitInfos() > 0), "GC.getNumTraitInfos() is less than or equal to zero but is expected to be larger than zero in CvPlayer::updateExtraYieldThreshold"); for (iI = 0; iI < GC.getNumTraitInfos(); iI++) { if (hasTrait((TraitTypes)iI)) { if (GC.getTraitInfo((TraitTypes) iI).getExtraYieldThreshold(eIndex) > 0) { if ((iBestValue == 0) || (GC.getTraitInfo((TraitTypes) iI).getExtraYieldThreshold(eIndex) < iBestValue)) { iBestValue = GC.getTraitInfo((TraitTypes) iI).getExtraYieldThreshold(eIndex); } } } } if (getExtraYieldThreshold(eIndex) != iBestValue) { m_aiExtraYieldThreshold[eIndex] = iBestValue; FAssert(getExtraYieldThreshold(eIndex) >= 0); updateYield(); } } int CvPlayer::getTradeYieldModifier(YieldTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiTradeYieldModifier[eIndex]; } void CvPlayer::changeTradeYieldModifier(YieldTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_YIELD_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiTradeYieldModifier[eIndex] = (m_aiTradeYieldModifier[eIndex] + iChange); updateTradeRoutes(); } } int CvPlayer::getFreeCityCommerce(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiFreeCityCommerce[eIndex]; } void CvPlayer::changeFreeCityCommerce(CommerceTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiFreeCityCommerce[eIndex] = (m_aiFreeCityCommerce[eIndex] + iChange); FAssert(getFreeCityCommerce(eIndex) >= 0); updateCommerce(eIndex); } } int CvPlayer::getCommercePercent(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiCommercePercent[eIndex]; } void CvPlayer::setCommercePercent(CommerceTypes eIndex, int iNewValue) { int iTotalCommercePercent; int iOldValue; int iI; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); iOldValue = getCommercePercent(eIndex); m_aiCommercePercent[eIndex] = range(iNewValue, 0, 100); if (iOldValue != getCommercePercent(eIndex)) { iTotalCommercePercent = 0; for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { iTotalCommercePercent += getCommercePercent((CommerceTypes)iI); } for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { if (iI != eIndex) { if (100 != iTotalCommercePercent) { int iAdjustment = std::min(m_aiCommercePercent[iI], iTotalCommercePercent - 100); m_aiCommercePercent[iI] -= iAdjustment; iTotalCommercePercent -= iAdjustment; } else { break; } } } FAssert(100 == iTotalCommercePercent); updateCommerce(); AI_makeAssignWorkDirty(); if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(CityScreen_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Financial_Screen_DIRTY_BIT, true); } } } void CvPlayer::changeCommercePercent(CommerceTypes eIndex, int iChange) { setCommercePercent(eIndex, (getCommercePercent(eIndex) + iChange)); } int CvPlayer::getCommerceRate(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); int iRate = m_aiCommerceRate[eIndex]; if (GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { if (eIndex == COMMERCE_CULTURE) { iRate += m_aiCommerceRate[COMMERCE_ESPIONAGE]; } else if (eIndex == COMMERCE_ESPIONAGE) { iRate = 0; } } return iRate / 100; } void CvPlayer::changeCommerceRate(CommerceTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiCommerceRate[eIndex] += iChange; FAssert(getCommerceRate(eIndex) >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getCommerceRateModifier(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiCommerceRateModifier[eIndex]; } void CvPlayer::changeCommerceRateModifier(CommerceTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiCommerceRateModifier[eIndex] = (m_aiCommerceRateModifier[eIndex] + iChange); updateCommerce(eIndex); AI_makeAssignWorkDirty(); } } int CvPlayer::getCapitalCommerceRateModifier(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiCapitalCommerceRateModifier[eIndex]; } void CvPlayer::changeCapitalCommerceRateModifier(CommerceTypes eIndex, int iChange) { CvCity* pCapitalCity; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiCapitalCommerceRateModifier[eIndex] = (m_aiCapitalCommerceRateModifier[eIndex] + iChange); pCapitalCity = getCapitalCity(); if (pCapitalCity != NULL) { pCapitalCity->updateCommerce(); pCapitalCity->AI_setAssignWorkDirty(true); } } } int CvPlayer::getStateReligionBuildingCommerce(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiStateReligionBuildingCommerce[eIndex]; } void CvPlayer::changeStateReligionBuildingCommerce(CommerceTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiStateReligionBuildingCommerce[eIndex] = (m_aiStateReligionBuildingCommerce[eIndex] + iChange); FAssert(getStateReligionBuildingCommerce(eIndex) >= 0); updateCommerce(eIndex); } } int CvPlayer::getSpecialistExtraCommerce(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiSpecialistExtraCommerce[eIndex]; } void CvPlayer::changeSpecialistExtraCommerce(CommerceTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiSpecialistExtraCommerce[eIndex] = (m_aiSpecialistExtraCommerce[eIndex] + iChange); FAssert(getSpecialistExtraCommerce(eIndex) >= 0); updateCommerce(eIndex); AI_makeAssignWorkDirty(); } } int CvPlayer::getCommerceFlexibleCount(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiCommerceFlexibleCount[eIndex]; } bool CvPlayer::isCommerceFlexible(CommerceTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (!isFoundedFirstCity()) { return false; } if (eIndex == COMMERCE_ESPIONAGE) { if (0 == GET_TEAM(getTeam()).getHasMetCivCount(true) || GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { return false; } } return (GC.getCommerceInfo(eIndex).isFlexiblePercent() || (getCommerceFlexibleCount(eIndex) > 0) || GET_TEAM(getTeam()).isCommerceFlexible(eIndex)); } void CvPlayer::changeCommerceFlexibleCount(CommerceTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_COMMERCE_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_aiCommerceFlexibleCount[eIndex] = (m_aiCommerceFlexibleCount[eIndex] + iChange); FAssert(getCommerceFlexibleCount(eIndex) >= 0); if (!isCommerceFlexible(eIndex)) { setCommercePercent(eIndex, 0); } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(PercentButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getGoldPerTurnByPlayer(PlayerTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < MAX_PLAYERS, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiGoldPerTurnByPlayer[eIndex]; } void CvPlayer::changeGoldPerTurnByPlayer(PlayerTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < MAX_PLAYERS, "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_iGoldPerTurn = (m_iGoldPerTurn + iChange); m_aiGoldPerTurnByPlayer[eIndex] = (m_aiGoldPerTurnByPlayer[eIndex] + iChange); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } if (!isHuman()) { AI_doCommerce(); } } } bool CvPlayer::isFeatAccomplished(FeatTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_FEAT_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_abFeatAccomplished[eIndex]; } void CvPlayer::setFeatAccomplished(FeatTypes eIndex, bool bNewValue) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_FEAT_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); m_abFeatAccomplished[eIndex] = bNewValue; } bool CvPlayer::isOption(PlayerOptionTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_PLAYEROPTION_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_abOptions[eIndex]; } void CvPlayer::setOption(PlayerOptionTypes eIndex, bool bNewValue) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < NUM_PLAYEROPTION_TYPES, "eIndex is expected to be within maximum bounds (invalid Index)"); m_abOptions[eIndex] = bNewValue; } bool CvPlayer::isPlayable() const { return GC.getInitCore().getPlayableCiv(getID()); } void CvPlayer::setPlayable(bool bNewValue) { GC.getInitCore().setPlayableCiv(getID(), bNewValue); } int CvPlayer::getBonusExport(BonusTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBonusInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiBonusExport[eIndex]; } void CvPlayer::changeBonusExport(BonusTypes eIndex, int iChange) { CvCity* pCapitalCity; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBonusInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { pCapitalCity = getCapitalCity(); if (pCapitalCity != NULL) { pCapitalCity->plot()->updatePlotGroupBonus(false); } m_paiBonusExport[eIndex] = (m_paiBonusExport[eIndex] + iChange); FAssert(getBonusExport(eIndex) >= 0); if (pCapitalCity != NULL) { pCapitalCity->plot()->updatePlotGroupBonus(true); } } } int CvPlayer::getBonusImport(BonusTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBonusInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiBonusImport[eIndex]; } void CvPlayer::changeBonusImport(BonusTypes eIndex, int iChange) { CvCity* pCapitalCity; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBonusInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { pCapitalCity = getCapitalCity(); if (pCapitalCity != NULL) { pCapitalCity->plot()->updatePlotGroupBonus(false); } m_paiBonusImport[eIndex] = (m_paiBonusImport[eIndex] + iChange); FAssert(getBonusImport(eIndex) >= 0); if (pCapitalCity != NULL) { pCapitalCity->plot()->updatePlotGroupBonus(true); } } } int CvPlayer::getImprovementCount(ImprovementTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumImprovementInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiImprovementCount[eIndex]; } void CvPlayer::changeImprovementCount(ImprovementTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumImprovementInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiImprovementCount[eIndex] = (m_paiImprovementCount[eIndex] + iChange); FAssert(getImprovementCount(eIndex) >= 0); } int CvPlayer::getFreeBuildingCount(BuildingTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiFreeBuildingCount[eIndex]; } bool CvPlayer::isBuildingFree(BuildingTypes eIndex) const { return (getFreeBuildingCount(eIndex) > 0); } void CvPlayer::changeFreeBuildingCount(BuildingTypes eIndex, int iChange) { CvCity* pLoopCity; int iOldFreeBuildingCount; int iLoop; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { iOldFreeBuildingCount = getFreeBuildingCount(eIndex); m_paiFreeBuildingCount[eIndex] = (m_paiFreeBuildingCount[eIndex] + iChange); FAssert(getFreeBuildingCount(eIndex) >= 0); if (iOldFreeBuildingCount == 0) { FAssertMsg(getFreeBuildingCount(eIndex) > 0, "getFreeBuildingCount(eIndex) is expected to be greater than 0"); for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->setNumFreeBuilding(eIndex, 1); } } else if (getFreeBuildingCount(eIndex) == 0) { FAssertMsg(iOldFreeBuildingCount > 0, "iOldFreeBuildingCount is expected to be greater than 0"); for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->setNumFreeBuilding(eIndex, 0); } } } } int CvPlayer::getExtraBuildingHappiness(BuildingTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraBuildingHappiness[eIndex]; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeExtraBuildingHappiness(BuildingTypes eIndex, int iChange, bool bLimited) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiExtraBuildingHappiness[eIndex] += iChange; updateExtraBuildingHappiness(bLimited); } } int CvPlayer::getExtraBuildingHealth(BuildingTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiExtraBuildingHealth[eIndex]; } //Fuyu bLimited void CvPlayer::changeExtraBuildingHealth(BuildingTypes eIndex, int iChange, bool bLimited) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiExtraBuildingHealth[eIndex] += iChange; updateExtraBuildingHealth(bLimited); } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getFeatureHappiness(FeatureTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiFeatureHappiness[eIndex]; } /********************************************************************************/ /* New Civic AI 02.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeFeatureHappiness(FeatureTypes eIndex, int iChange, bool bLimited) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumFeatureInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiFeatureHappiness[eIndex] = (m_paiFeatureHappiness[eIndex] + iChange); updateFeatureHappiness(bLimited); } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ int CvPlayer::getUnitClassCount(UnitClassTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiUnitClassCount[eIndex]; } bool CvPlayer::isUnitClassMaxedOut(UnitClassTypes eIndex, int iExtra) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (!isNationalUnitClass(eIndex)) { return false; } FAssertMsg(getUnitClassCount(eIndex) <= GC.getUnitClassInfo(eIndex).getMaxPlayerInstances(), "getUnitClassCount is expected to be less than maximum bound of MaxPlayerInstances (invalid index)"); return ((getUnitClassCount(eIndex) + iExtra) >= GC.getUnitClassInfo(eIndex).getMaxPlayerInstances()); } void CvPlayer::changeUnitClassCount(UnitClassTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiUnitClassCount[eIndex] = (m_paiUnitClassCount[eIndex] + iChange); FAssert(getUnitClassCount(eIndex) >= 0); } int CvPlayer::getUnitClassMaking(UnitClassTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiUnitClassMaking[eIndex]; } void CvPlayer::changeUnitClassMaking(UnitClassTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUnitClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiUnitClassMaking[eIndex] = (m_paiUnitClassMaking[eIndex] + iChange); FAssert(getUnitClassMaking(eIndex) >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Help_DIRTY_BIT, true); } } } int CvPlayer::getUnitClassCountPlusMaking(UnitClassTypes eIndex) const { return (getUnitClassCount(eIndex) + getUnitClassMaking(eIndex)); } int CvPlayer::getBuildingClassCount(BuildingClassTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiBuildingClassCount[eIndex]; } bool CvPlayer::isBuildingClassMaxedOut(BuildingClassTypes eIndex, int iExtra) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (!isNationalWonderClass(eIndex)) { return false; } FAssertMsg(getBuildingClassCount(eIndex) <= (GC.getBuildingClassInfo(eIndex).getMaxPlayerInstances() + GC.getBuildingClassInfo(eIndex).getExtraPlayerInstances()), "BuildingClassCount is expected to be less than or match the number of max player instances plus extra player instances"); return ((getBuildingClassCount(eIndex) + iExtra) >= (GC.getBuildingClassInfo(eIndex).getMaxPlayerInstances() + GC.getBuildingClassInfo(eIndex).getExtraPlayerInstances())); } void CvPlayer::changeBuildingClassCount(BuildingClassTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiBuildingClassCount[eIndex] = (m_paiBuildingClassCount[eIndex] + iChange); FAssert(getBuildingClassCount(eIndex) >= 0); } int CvPlayer::getBuildingClassMaking(BuildingClassTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiBuildingClassMaking[eIndex]; } void CvPlayer::changeBuildingClassMaking(BuildingClassTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumBuildingClassInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiBuildingClassMaking[eIndex] = (m_paiBuildingClassMaking[eIndex] + iChange); FAssert(getBuildingClassMaking(eIndex) >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Help_DIRTY_BIT, true); } } } int CvPlayer::getBuildingClassCountPlusMaking(BuildingClassTypes eIndex) const { return (getBuildingClassCount(eIndex) + getBuildingClassMaking(eIndex)); } int CvPlayer::getHurryCount(HurryTypes eIndex) const { FAssert(eIndex >= 0); FAssert(eIndex < GC.getNumHurryInfos()); return m_paiHurryCount[eIndex]; } bool CvPlayer::canHurry(HurryTypes eIndex) const { return (getHurryCount(eIndex) > 0); } bool CvPlayer::canPopRush() { return (m_iPopRushHurryCount > 0); } void CvPlayer::changeHurryCount(HurryTypes eIndex, int iChange) { FAssert(eIndex >= 0); FAssert(eIndex < GC.getNumHurryInfos()); int oldHurryCount = m_paiHurryCount[eIndex]; m_paiHurryCount[eIndex] = (m_paiHurryCount[eIndex] + iChange); FAssert(getHurryCount(eIndex) >= 0); // if we just went from 0 to 1 (or the reverse) if ((oldHurryCount > 0) != (m_paiHurryCount[eIndex] > 0)) { // does this hurry reduce population? if (GC.getHurryInfo(eIndex).getProductionPerPopulation() > 0) { m_iPopRushHurryCount += iChange; FAssert(m_iPopRushHurryCount >= 0); } } } int CvPlayer::getSpecialBuildingNotRequiredCount(SpecialBuildingTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumSpecialBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiSpecialBuildingNotRequiredCount[eIndex]; } bool CvPlayer::isSpecialBuildingNotRequired(SpecialBuildingTypes eIndex) const { return (getSpecialBuildingNotRequiredCount(eIndex) > 0); } void CvPlayer::changeSpecialBuildingNotRequiredCount(SpecialBuildingTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumSpecialBuildingInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiSpecialBuildingNotRequiredCount[eIndex] = (m_paiSpecialBuildingNotRequiredCount[eIndex] + iChange); FAssert(getSpecialBuildingNotRequiredCount(eIndex) >= 0); } int CvPlayer::getHasCivicOptionCount(CivicOptionTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCivicOptionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiHasCivicOptionCount[eIndex]; } bool CvPlayer::isHasCivicOption(CivicOptionTypes eIndex) const { return (getHasCivicOptionCount(eIndex) > 0); } void CvPlayer::changeHasCivicOptionCount(CivicOptionTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCivicOptionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); m_paiHasCivicOptionCount[eIndex] = (m_paiHasCivicOptionCount[eIndex] + iChange); FAssert(getHasCivicOptionCount(eIndex) >= 0); } int CvPlayer::getNoCivicUpkeepCount(CivicOptionTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCivicOptionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiNoCivicUpkeepCount[eIndex]; } bool CvPlayer::isNoCivicUpkeep(CivicOptionTypes eIndex) const { return (getNoCivicUpkeepCount(eIndex) > 0); } void CvPlayer::changeNoCivicUpkeepCount(CivicOptionTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCivicOptionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiNoCivicUpkeepCount[eIndex] = (m_paiNoCivicUpkeepCount[eIndex] + iChange); FAssert(getNoCivicUpkeepCount(eIndex) >= 0); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getHasReligionCount(ReligionTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumReligionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paiHasReligionCount[eIndex]; } int CvPlayer::countTotalHasReligion() const { int iCount; int iI; iCount = 0; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { iCount += getHasReligionCount((ReligionTypes)iI); } return iCount; } int CvPlayer::getHasCorporationCount(CorporationTypes eIndex) const { if (!isActiveCorporation(eIndex)) { return 0; } return m_paiHasCorporationCount[eIndex]; } int CvPlayer::countTotalHasCorporation() const { int iCount = 0; for (int iI = 0; iI < GC.getNumCorporationInfos(); iI++) { iCount += getHasCorporationCount((CorporationTypes)iI); } return iCount; } bool CvPlayer::isActiveCorporation(CorporationTypes eIndex) const { if (isNoCorporations()) { return false; } if (isNoForeignCorporations() && !hasHeadquarters(eIndex)) { return false; } return true; } int CvPlayer::findHighestHasReligionCount() const { int iValue; int iBestValue; int iI; iBestValue = 0; for (iI = 0; iI < GC.getNumReligionInfos(); iI++) { iValue = getHasReligionCount((ReligionTypes)iI); if (iValue > iBestValue) { iBestValue = iValue; } } return iBestValue; } void CvPlayer::changeHasReligionCount(ReligionTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumReligionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiHasReligionCount[eIndex] = (m_paiHasReligionCount[eIndex] + iChange); FAssert(getHasReligionCount(eIndex) >= 0); GC.getGameINLINE().updateBuildingCommerce(); GC.getGameINLINE().AI_makeAssignWorkDirty(); } } void CvPlayer::changeHasCorporationCount(CorporationTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCorporationInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_paiHasCorporationCount[eIndex] += iChange; FAssert(getHasCorporationCount(eIndex) >= 0); GC.getGameINLINE().updateBuildingCommerce(); GC.getGameINLINE().AI_makeAssignWorkDirty(); } } int CvPlayer::getUpkeepCount(UpkeepTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUpkeepInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); FAssertMsg(m_paiUpkeepCount != NULL, "m_paiUpkeepCount is not expected to be equal with NULL"); return m_paiUpkeepCount[eIndex]; } void CvPlayer::changeUpkeepCount(UpkeepTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumUpkeepInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { FAssertMsg(m_paiUpkeepCount != NULL, "m_paiUpkeepCount is not expected to be equal with NULL"); m_paiUpkeepCount[eIndex] = (m_paiUpkeepCount[eIndex] + iChange); FAssertMsg(getUpkeepCount(eIndex) >= 0, "getUpkeepCount(eIndex) is expected to be non-negative (invalid Index)"); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); } } } int CvPlayer::getSpecialistValidCount(SpecialistTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumSpecialistInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); FAssertMsg(m_paiSpecialistValidCount != NULL, "m_paiSpecialistValidCount is not expected to be equal with NULL"); return m_paiSpecialistValidCount[eIndex]; } bool CvPlayer::isSpecialistValid(SpecialistTypes eIndex) const { return (getSpecialistValidCount(eIndex) > 0); } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::changeSpecialistValidCount(SpecialistTypes eIndex, int iChange, bool bLimited) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumSpecialistInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { FAssertMsg(m_paiSpecialistValidCount != NULL, "m_paiSpecialistValidCount is not expected to be equal with NULL"); m_paiSpecialistValidCount[eIndex] = (m_paiSpecialistValidCount[eIndex] + iChange); FAssertMsg(getSpecialistValidCount(eIndex) >= 0, "getSpecialistValidCount(eIndex) is expected to be non-negative (invalid Index)"); if (!bLimited) { AI_makeAssignWorkDirty(); } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ bool CvPlayer::isResearchingTech(TechTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTechInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_pabResearchingTech[eIndex]; } void CvPlayer::setResearchingTech(TechTypes eIndex, bool bNewValue) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumTechInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); if (isResearchingTech(eIndex) != bNewValue) { m_pabResearchingTech[eIndex] = bNewValue; if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Popup_DIRTY_BIT, true); // to check whether we still need the tech chooser popup } } } bool CvPlayer::isLoyalMember(VoteSourceTypes eVoteSource) const { FAssertMsg(eVoteSource >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eVoteSource < GC.getNumVoteSourceInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_pabLoyalMember[eVoteSource]; } void CvPlayer::setLoyalMember(VoteSourceTypes eVoteSource, bool bNewValue) { FAssertMsg(eVoteSource >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eVoteSource < MAX_PLAYERS, "eIndex is expected to be within maximum bounds (invalid Index)"); if (isLoyalMember(eVoteSource) != bNewValue) { processVoteSourceBonus(eVoteSource, false); m_pabLoyalMember[eVoteSource] = bNewValue; processVoteSourceBonus(eVoteSource, true); GC.getGameINLINE().updateSecretaryGeneral(); } } CivicTypes CvPlayer::getCivics(CivicOptionTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCivicOptionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); return m_paeCivics[eIndex]; } int CvPlayer::getSingleCivicUpkeep(CivicTypes eCivic, bool bIgnoreAnarchy) const { int iUpkeep; if (eCivic == NO_CIVIC) { return 0; } if (isNoCivicUpkeep((CivicOptionTypes)(GC.getCivicInfo(eCivic).getCivicOptionType()))) { return 0; } if (GC.getCivicInfo(eCivic).getUpkeep() == NO_UPKEEP) { return 0; } if (!bIgnoreAnarchy) { if (isAnarchy()) { return 0; } } iUpkeep = 0; // BBAI TODO: WTF? civic option type added and subtracted below iUpkeep += ((std::max(0, (getTotalPopulation() + GC.getDefineINT("UPKEEP_POPULATION_OFFSET") - GC.getCivicInfo(eCivic).getCivicOptionType())) * GC.getUpkeepInfo((UpkeepTypes)(GC.getCivicInfo(eCivic).getUpkeep())).getPopulationPercent()) / 100); iUpkeep += ((std::max(0, (getNumCities() + GC.getDefineINT("UPKEEP_CITY_OFFSET") + GC.getCivicInfo(eCivic).getCivicOptionType() - (GC.getNumCivicOptionInfos() / 2))) * GC.getUpkeepInfo((UpkeepTypes)(GC.getCivicInfo(eCivic).getUpkeep())).getCityPercent()) / 100); iUpkeep *= std::max(0, (getUpkeepModifier() + 100)); iUpkeep /= 100; iUpkeep *= GC.getHandicapInfo(getHandicapType()).getCivicUpkeepPercent(); iUpkeep /= 100; if (!isHuman() && !isBarbarian()) { iUpkeep *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAICivicUpkeepPercent(); iUpkeep /= 100; iUpkeep *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iUpkeep /= 100; } return std::max(0, iUpkeep); } int CvPlayer::getCivicUpkeep(CivicTypes* paeCivics, bool bIgnoreAnarchy) const { int iTotalUpkeep; int iI; if (paeCivics == NULL) { paeCivics = m_paeCivics; } iTotalUpkeep = 0; for (iI = 0; iI < GC.getNumCivicOptionInfos(); iI++) { iTotalUpkeep += getSingleCivicUpkeep(paeCivics[iI], bIgnoreAnarchy); } return iTotalUpkeep; } void CvPlayer::setCivics(CivicOptionTypes eIndex, CivicTypes eNewValue) { CvWString szBuffer; CivicTypes eOldCivic; int iI; FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < GC.getNumCivicOptionInfos(), "eIndex is expected to be within maximum bounds (invalid Index)"); FAssertMsg(eNewValue >= 0, "eNewValue is expected to be non-negative (invalid Index)"); FAssertMsg(eNewValue < GC.getNumCivicInfos(), "eNewValue is expected to be within maximum bounds (invalid Index)"); eOldCivic = getCivics(eIndex); if (eOldCivic != eNewValue) { m_paeCivics[eIndex] = eNewValue; if (eOldCivic != NO_CIVIC) { processCivics(eOldCivic, -1); } if (getCivics(eIndex) != NO_CIVIC) { processCivics(getCivics(eIndex), 1); } GC.getGameINLINE().updateSecretaryGeneral(); GC.getGameINLINE().AI_makeAssignWorkDirty(); if (GC.getGameINLINE().isFinalInitialized()) { if (gDLL->isDiplomacy() && (gDLL->getDiplomacyPlayer() == getID())) { gDLL->updateDiplomacyAttitude(true); } if (!isBarbarian()) { if (getCivics(eIndex) != NO_CIVIC) { if (getCivics(eIndex) != GC.getCivilizationInfo(getCivilizationType()).getCivilizationInitialCivics(eIndex)) { for (iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_TEAM(getTeam()).isHasMet(GET_PLAYER((PlayerTypes)iI).getTeam())) { szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_ADOPTED_CIVIC", getNameKey(), GC.getCivicInfo(getCivics(eIndex)).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MAJOR_EVENT); } } } szBuffer = gDLL->getText("TXT_KEY_MISC_PLAYER_ADOPTED_CIVIC", getNameKey(), GC.getCivicInfo(getCivics(eIndex)).getTextKeyWide()); GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szBuffer); } } } } /************************************************************************************************/ /* BETTER_BTS_AI_MOD 09/03/09 poyuzhe & jdog5000 */ /* */ /* Efficiency */ /************************************************************************************************/ // From Sanguo Mod Performance, ie the CAR Mod // Attitude cache for (int iI = 0; iI < MAX_PLAYERS; iI++) { GET_PLAYER(getID()).AI_invalidateAttitudeCache((PlayerTypes)iI); GET_PLAYER((PlayerTypes)iI).AI_invalidateAttitudeCache(getID()); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } } int CvPlayer::getSpecialistExtraYield(SpecialistTypes eIndex1, YieldTypes eIndex2) const { FAssertMsg(eIndex1 >= 0, "eIndex1 expected to be >= 0"); FAssertMsg(eIndex1 < GC.getNumSpecialistInfos(), "eIndex1 expected to be < GC.getNumSpecialistInfos()"); FAssertMsg(eIndex2 >= 0, "eIndex2 expected to be >= 0"); FAssertMsg(eIndex2 < NUM_YIELD_TYPES, "eIndex2 expected to be < NUM_YIELD_TYPES"); return m_ppaaiSpecialistExtraYield[eIndex1][eIndex2]; } void CvPlayer::changeSpecialistExtraYield(SpecialistTypes eIndex1, YieldTypes eIndex2, int iChange) { FAssertMsg(eIndex1 >= 0, "eIndex1 expected to be >= 0"); FAssertMsg(eIndex1 < GC.getNumSpecialistInfos(), "eIndex1 expected to be < GC.getNumSpecialistInfos()"); FAssertMsg(eIndex2 >= 0, "eIndex2 expected to be >= 0"); FAssertMsg(eIndex2 < NUM_YIELD_TYPES, "eIndex2 expected to be < NUM_YIELD_TYPES"); if (iChange != 0) { m_ppaaiSpecialistExtraYield[eIndex1][eIndex2] = (m_ppaaiSpecialistExtraYield[eIndex1][eIndex2] + iChange); FAssert(getSpecialistExtraYield(eIndex1, eIndex2) >= 0); updateExtraSpecialistYield(); AI_makeAssignWorkDirty(); } } int CvPlayer::getImprovementYieldChange(ImprovementTypes eIndex1, YieldTypes eIndex2) const { FAssertMsg(eIndex1 >= 0, "eIndex1 is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex1 < GC.getNumImprovementInfos(), "eIndex1 is expected to be within maximum bounds (invalid Index)"); FAssertMsg(eIndex2 >= 0, "eIndex2 is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex2 < NUM_YIELD_TYPES, "eIndex2 is expected to be within maximum bounds (invalid Index)"); return m_ppaaiImprovementYieldChange[eIndex1][eIndex2]; } void CvPlayer::changeImprovementYieldChange(ImprovementTypes eIndex1, YieldTypes eIndex2, int iChange) { FAssertMsg(eIndex1 >= 0, "eIndex1 is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex1 < GC.getNumImprovementInfos(), "eIndex1 is expected to be within maximum bounds (invalid Index)"); FAssertMsg(eIndex2 >= 0, "eIndex2 is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex2 < NUM_YIELD_TYPES, "eIndex2 is expected to be within maximum bounds (invalid Index)"); if (iChange != 0) { m_ppaaiImprovementYieldChange[eIndex1][eIndex2] = (m_ppaaiImprovementYieldChange[eIndex1][eIndex2] + iChange); FAssert(getImprovementYieldChange(eIndex1, eIndex2) >= 0); updateYield(); } } // XXX should pUnit be a CvSelectionGroup??? void CvPlayer::updateGroupCycle(CvUnit* pUnit) { CLLNode<IDInfo>* pUnitNode; CLLNode<int>* pSelectionGroupNode; CLLNode<int>* pBestSelectionGroupNode; CvSelectionGroup* pLoopSelectionGroup; CvUnit* pHeadUnit; CvUnit* pBeforeUnit; CvUnit* pAfterUnit; CvUnit* pLoopUnit; CvPlot* pPlot; int iValue; int iBestValue; if (!(pUnit->onMap())) { return; } FAssertMsg(pUnit->getGroup() != NULL, "Unit->getGroup() is not assigned a valid value"); removeGroupCycle(pUnit->getGroupID()); pPlot = pUnit->plot(); pBeforeUnit = NULL; pAfterUnit = NULL; pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->isGroupHead()) { if (pLoopUnit != pUnit) { if (!isBeforeUnitCycle(pLoopUnit, pUnit)) { pBeforeUnit = pLoopUnit; break; } else { pAfterUnit = pLoopUnit; } } } } pSelectionGroupNode = headGroupCycleNode(); iBestValue = MAX_INT; pBestSelectionGroupNode = NULL; while (pSelectionGroupNode != NULL) { pLoopSelectionGroup = getSelectionGroup(pSelectionGroupNode->m_data); FAssertMsg(pLoopSelectionGroup != NULL, "LoopSelectionGroup is not assigned a valid value"); pHeadUnit = pLoopSelectionGroup->getHeadUnit(); if (pHeadUnit != NULL) { if (pBeforeUnit != NULL) { if (pBeforeUnit == pHeadUnit) { pBestSelectionGroupNode = pSelectionGroupNode; break; } } else if (pAfterUnit != NULL) { if (pAfterUnit == pHeadUnit) { pBestSelectionGroupNode = nextGroupCycleNode(pSelectionGroupNode); break; } } else { iValue = plotDistance(pUnit->getX_INLINE(), pUnit->getY_INLINE(), pHeadUnit->getX_INLINE(), pHeadUnit->getY_INLINE()); if (iValue < iBestValue) { iBestValue = iValue; pBestSelectionGroupNode = pSelectionGroupNode; } } } pSelectionGroupNode = nextGroupCycleNode(pSelectionGroupNode); } if (pBestSelectionGroupNode != NULL) { m_groupCycle.insertBefore(pUnit->getGroupID(), pBestSelectionGroupNode); } else { m_groupCycle.insertAtEnd(pUnit->getGroupID()); } } void CvPlayer::removeGroupCycle(int iID) { CLLNode<int>* pSelectionGroupNode; pSelectionGroupNode = headGroupCycleNode(); while (pSelectionGroupNode != NULL) { if (pSelectionGroupNode->m_data == iID) { pSelectionGroupNode = deleteGroupCycleNode(pSelectionGroupNode); break; } else { pSelectionGroupNode = nextGroupCycleNode(pSelectionGroupNode); } } } CLLNode<int>* CvPlayer::deleteGroupCycleNode(CLLNode<int>* pNode) { return m_groupCycle.deleteNode(pNode); } CLLNode<int>* CvPlayer::nextGroupCycleNode(CLLNode<int>* pNode) const { return m_groupCycle.next(pNode); } CLLNode<int>* CvPlayer::previousGroupCycleNode(CLLNode<int>* pNode) const { return m_groupCycle.prev(pNode); } CLLNode<int>* CvPlayer::headGroupCycleNode() const { return m_groupCycle.head(); } CLLNode<int>* CvPlayer::tailGroupCycleNode() const { return m_groupCycle.tail(); } // Finds the path length from this tech type to one you already know int CvPlayer::findPathLength(TechTypes eTech, bool bCost) const { int i; int iNumSteps = 0; int iShortestPath = 0; int iPathLength = 0; TechTypes ePreReq; TechTypes eShortestOr; if (GET_TEAM(getTeam()).isHasTech(eTech) || isResearchingTech(eTech)) { // We have this tech, no reason to add this to the pre-reqs // Base case return 0, we know it... return 0; } // Cycle through the and paths and add up their tech lengths for (i = 0; i < GC.getNUM_AND_TECH_PREREQS(); i++) { ePreReq = (TechTypes)GC.getTechInfo(eTech).getPrereqAndTechs(i); if (ePreReq != NO_TECH) { iPathLength += findPathLength(ePreReq, bCost); } } eShortestOr = NO_TECH; iShortestPath = MAX_INT; // Find the shortest OR tech for (i = 0; i < GC.getNUM_OR_TECH_PREREQS(); i++) { // Grab the tech ePreReq = (TechTypes)GC.getTechInfo(eTech).getPrereqOrTechs(i); // If this is a valid tech if (ePreReq != NO_TECH) { // Recursively find the path length (takes into account all ANDs) iNumSteps = findPathLength(ePreReq, bCost); // If the prereq is a valid tech and its the current shortest, mark it as such if (iNumSteps < iShortestPath) { eShortestOr = ePreReq; iShortestPath = iNumSteps; } } } // If the shortest OR is a valid tech, add the steps to it... if (eShortestOr != NO_TECH) { iPathLength += iShortestPath; } return (iPathLength + ((bCost) ? GET_TEAM(getTeam()).getResearchCost(eTech) : 1)); } // Function specifically for python/tech chooser screen int CvPlayer::getQueuePosition(TechTypes eTech) const { int i = 1; CLLNode<TechTypes>* pResearchNode; for (pResearchNode = headResearchQueueNode(); pResearchNode; pResearchNode = nextResearchQueueNode(pResearchNode)) { if (pResearchNode->m_data == eTech) { return i; } i++; } return -1; } void CvPlayer::clearResearchQueue() { int iI; m_researchQueue.clear(); for (iI = 0; iI < GC.getNumTechInfos(); iI++) { setResearchingTech(((TechTypes)iI), false); } if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(ResearchButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); } } // Pushes research onto the queue. If it is an append if will put it // and its pre-reqs into the queue. If it is not an append it will change // research immediately and should be used with clear. Clear will clear the entire queue. bool CvPlayer::pushResearch(TechTypes eTech, bool bClear) { int i; int iNumSteps; int iShortestPath; bool bOrPrereqFound; TechTypes ePreReq; TechTypes eShortestOr; FAssertMsg(eTech != NO_TECH, "Tech is not assigned a valid value"); if (GET_TEAM(getTeam()).isHasTech(eTech) || isResearchingTech(eTech)) { // We have this tech, no reason to add this to the pre-reqs return true; } if (!canEverResearch(eTech)) { return false; } // Pop the entire queue... if (bClear) { clearResearchQueue(); } // Add in all the pre-reqs for the and techs... for (i = 0; i < GC.getNUM_AND_TECH_PREREQS(); i++) { ePreReq = (TechTypes)GC.getTechInfo(eTech).getPrereqAndTechs(i); if (ePreReq != NO_TECH) { if (!pushResearch(ePreReq)) { return false; } } } // Will return the shortest path of all the or techs. Tie breaker goes to the first one... eShortestOr = NO_TECH; iShortestPath = MAX_INT; bOrPrereqFound = false; // Cycle through all the OR techs for (i = 0; i < GC.getNUM_OR_TECH_PREREQS(); i++) { ePreReq = (TechTypes)GC.getTechInfo(eTech).getPrereqOrTechs(i); if (ePreReq != NO_TECH) { bOrPrereqFound = true; // If the pre-req exists, and we have it, it is the shortest path, get out, we're done if (GET_TEAM(getTeam()).isHasTech(ePreReq)) { eShortestOr = ePreReq; break; } if (canEverResearch(ePreReq)) { // Find the length of the path to this pre-req iNumSteps = findPathLength(ePreReq); // If this pre-req is a valid tech, and its the shortest current path, set it as such if (iNumSteps < iShortestPath) { eShortestOr = ePreReq; iShortestPath = iNumSteps; } } } } // If the shortest path tech is valid, push it (and its children) on to the research queue recursively if (eShortestOr != NO_TECH) { if (!pushResearch(eShortestOr)) { return false; } } else if (bOrPrereqFound) { return false; } // Insert this tech at the end of the queue m_researchQueue.insertAtEnd(eTech); setResearchingTech(eTech, true); // Set the dirty bits if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(ResearchButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); } // ONEVENT - Tech selected (any) CvEventReporter::getInstance().techSelected(eTech, getID()); return true; } // If bHead is true we delete the entire queue... void CvPlayer::popResearch(TechTypes eTech) { CLLNode<TechTypes>* pResearchNode; for (pResearchNode = headResearchQueueNode(); pResearchNode; pResearchNode = nextResearchQueueNode(pResearchNode)) { if (pResearchNode->m_data == eTech) { m_researchQueue.deleteNode(pResearchNode); break; } } setResearchingTech(eTech, false); if (getTeam() == GC.getGameINLINE().getActiveTeam()) { gDLL->getInterfaceIFace()->setDirty(ResearchButtons_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(GameData_DIRTY_BIT, true); gDLL->getInterfaceIFace()->setDirty(Score_DIRTY_BIT, true); } } int CvPlayer::getLengthResearchQueue() const { return m_researchQueue.getLength(); } CLLNode<TechTypes>* CvPlayer::nextResearchQueueNode(CLLNode<TechTypes>* pNode) const { return m_researchQueue.next(pNode); } CLLNode<TechTypes>* CvPlayer::headResearchQueueNode() const { return m_researchQueue.head(); } CLLNode<TechTypes>* CvPlayer::tailResearchQueueNode() const { return m_researchQueue.tail(); } void CvPlayer::addCityName(const CvWString& szName) { m_cityNames.insertAtEnd(szName); } int CvPlayer::getNumCityNames() const { return m_cityNames.getLength(); } CvWString CvPlayer::getCityName(int iIndex) const { CLLNode<CvWString>* pCityNameNode; pCityNameNode = m_cityNames.nodeNum(iIndex); if (pCityNameNode != NULL) { return pCityNameNode->m_data; } else { return L""; } } CLLNode<CvWString>* CvPlayer::nextCityNameNode(CLLNode<CvWString>* pNode) const { return m_cityNames.next(pNode); } CLLNode<CvWString>* CvPlayer::headCityNameNode() const { return m_cityNames.head(); } CvPlotGroup* CvPlayer::firstPlotGroup(int *pIterIdx, bool bRev) const { return !bRev ? m_plotGroups.beginIter(pIterIdx) : m_plotGroups.endIter(pIterIdx); } CvPlotGroup* CvPlayer::nextPlotGroup(int *pIterIdx, bool bRev) const { return !bRev ? m_plotGroups.nextIter(pIterIdx) : m_plotGroups.prevIter(pIterIdx); } int CvPlayer::getNumPlotGroups() const { return m_plotGroups.getCount(); } CvPlotGroup* CvPlayer::getPlotGroup(int iID) const { return((CvPlotGroup *)(m_plotGroups.getAt(iID))); } CvPlotGroup* CvPlayer::addPlotGroup() { return((CvPlotGroup *)(m_plotGroups.add())); } void CvPlayer::deletePlotGroup(int iID) { m_plotGroups.removeAt(iID); } CvCity* CvPlayer::firstCity(int *pIterIdx, bool bRev) const { return !bRev ? m_cities.beginIter(pIterIdx) : m_cities.endIter(pIterIdx); } CvCity* CvPlayer::nextCity(int *pIterIdx, bool bRev) const { return !bRev ? m_cities.nextIter(pIterIdx) : m_cities.prevIter(pIterIdx); } int CvPlayer::getNumCities() const { return m_cities.getCount(); } CvCity* CvPlayer::getCity(int iID) const { return(m_cities.getAt(iID)); } CvCity* CvPlayer::addCity() { return(m_cities.add()); } void CvPlayer::deleteCity(int iID) { m_cities.removeAt(iID); } CvUnit* CvPlayer::firstUnit(int *pIterIdx, bool bRev) const { return !bRev ? m_units.beginIter(pIterIdx) : m_units.endIter(pIterIdx); } CvUnit* CvPlayer::nextUnit(int *pIterIdx, bool bRev) const { return !bRev ? m_units.nextIter(pIterIdx) : m_units.prevIter(pIterIdx); } int CvPlayer::getNumUnits() const { return m_units.getCount(); } CvUnit* CvPlayer::getUnit(int iID) const { return (m_units.getAt(iID)); } CvUnit* CvPlayer::addUnit() { return (m_units.add()); } void CvPlayer::deleteUnit(int iID) { m_units.removeAt(iID); } CvSelectionGroup* CvPlayer::firstSelectionGroup(int *pIterIdx, bool bRev) const { return !bRev ? m_selectionGroups.beginIter(pIterIdx) : m_selectionGroups.endIter(pIterIdx); } CvSelectionGroup* CvPlayer::nextSelectionGroup(int *pIterIdx, bool bRev) const { return !bRev ? m_selectionGroups.nextIter(pIterIdx) : m_selectionGroups.prevIter(pIterIdx); } int CvPlayer::getNumSelectionGroups() const { return m_selectionGroups.getCount(); } CvSelectionGroup* CvPlayer::getSelectionGroup(int iID) const { return ((CvSelectionGroup *)(m_selectionGroups.getAt(iID))); } CvSelectionGroup* CvPlayer::addSelectionGroup() { return ((CvSelectionGroup *)(m_selectionGroups.add())); } void CvPlayer::deleteSelectionGroup(int iID) { bool bRemoved = m_selectionGroups.removeAt(iID); FAssertMsg(bRemoved, "could not find group, delete failed"); } EventTriggeredData* CvPlayer::firstEventTriggered(int *pIterIdx, bool bRev) const { return !bRev ? m_eventsTriggered.beginIter(pIterIdx) : m_eventsTriggered.endIter(pIterIdx); } EventTriggeredData* CvPlayer::nextEventTriggered(int *pIterIdx, bool bRev) const { return !bRev ? m_eventsTriggered.nextIter(pIterIdx) : m_eventsTriggered.prevIter(pIterIdx); } int CvPlayer::getNumEventsTriggered() const { return m_eventsTriggered.getCount(); } EventTriggeredData* CvPlayer::getEventTriggered(int iID) const { return ((EventTriggeredData*)(m_eventsTriggered.getAt(iID))); } EventTriggeredData* CvPlayer::addEventTriggered() { return ((EventTriggeredData*)(m_eventsTriggered.add())); } void CvPlayer::deleteEventTriggered(int iID) { m_eventsTriggered.removeAt(iID); } void CvPlayer::addMessage(const CvTalkingHeadMessage& message) { m_listGameMessages.push_back(message); } void CvPlayer::clearMessages() { m_listGameMessages.clear(); } const CvMessageQueue& CvPlayer::getGameMessages() const { return (m_listGameMessages); } void CvPlayer::expireMessages() { CvMessageQueue::iterator it = m_listGameMessages.begin(); bool bFoundExpired = false; while(it != m_listGameMessages.end()) { CvTalkingHeadMessage& message = *it; if (GC.getGameINLINE().getGameTurn() >= message.getExpireTurn()) { it = m_listGameMessages.erase(it); bFoundExpired = true; } else { ++it; } } if (bFoundExpired) { gDLL->getInterfaceIFace()->dirtyTurnLog(getID()); } } void CvPlayer::addPopup(CvPopupInfo* pInfo, bool bFront) { if (isHuman()) { if (bFront) { m_listPopups.push_front(pInfo); } else { m_listPopups.push_back(pInfo); } } else { SAFE_DELETE(pInfo); } } void CvPlayer::clearPopups() { CvPopupQueue::iterator it; for (it = m_listPopups.begin(); it != m_listPopups.end(); ++it) { CvPopupInfo* pInfo = *it; if (NULL != pInfo) { delete pInfo; } } m_listPopups.clear(); } CvPopupInfo* CvPlayer::popFrontPopup() { CvPopupInfo* pInfo = NULL; if (!m_listPopups.empty()) { pInfo = m_listPopups.front(); m_listPopups.pop_front(); } return pInfo; } const CvPopupQueue& CvPlayer::getPopups() const { return (m_listPopups); } void CvPlayer::addDiplomacy(CvDiploParameters* pDiplo) { if (NULL != pDiplo) { m_listDiplomacy.push_back(pDiplo); } } void CvPlayer::clearDiplomacy() { CvDiploQueue::iterator it; for (it = m_listDiplomacy.begin(); it != m_listDiplomacy.end(); ++it) { CvDiploParameters* pDiplo = *it; if (NULL != pDiplo) { delete pDiplo; } } m_listDiplomacy.clear(); } const CvDiploQueue& CvPlayer::getDiplomacy() const { return (m_listDiplomacy); } CvDiploParameters* CvPlayer::popFrontDiplomacy() { CvDiploParameters* pDiplo = NULL; if (!m_listDiplomacy.empty()) { pDiplo = m_listDiplomacy.front(); m_listDiplomacy.pop_front(); } return pDiplo; } void CvPlayer::showSpaceShip() { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_PYTHON_SCREEN); pInfo->setData1(-1); pInfo->setText(L"showSpaceShip"); addPopup(pInfo); } void CvPlayer::clearSpaceShipPopups() { //clear all spaceship popups CvPopupQueue::iterator it; for (it = m_listPopups.begin(); it != m_listPopups.end(); ) { CvPopupInfo* pInfo = *it; if (NULL != pInfo) { if(pInfo->getText().compare(L"showSpaceShip") == 0) { it = m_listPopups.erase(it); SAFE_DELETE(pInfo); } else { it++; } } else { it++; } } } int CvPlayer::getScoreHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapScoreHistory.find(iTurn); if (it != m_mapScoreHistory.end()) { return it->second; } return 0; } void CvPlayer::updateScoreHistory(int iTurn, int iBestScore) { m_mapScoreHistory[iTurn] = iBestScore; } int CvPlayer::getEconomyHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapEconomyHistory.find(iTurn); if (it != m_mapEconomyHistory.end()) { return it->second; } return 0; } void CvPlayer::updateEconomyHistory(int iTurn, int iBestEconomy) { m_mapEconomyHistory[iTurn] = iBestEconomy; } int CvPlayer::getIndustryHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapIndustryHistory.find(iTurn); if (it != m_mapIndustryHistory.end()) { return it->second; } return 0; } void CvPlayer::updateIndustryHistory(int iTurn, int iBestIndustry) { m_mapIndustryHistory[iTurn] = iBestIndustry; } int CvPlayer::getAgricultureHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapAgricultureHistory.find(iTurn); if (it != m_mapAgricultureHistory.end()) { return it->second; } return 0; } void CvPlayer::updateAgricultureHistory(int iTurn, int iBestAgriculture) { m_mapAgricultureHistory[iTurn] = iBestAgriculture; } int CvPlayer::getPowerHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapPowerHistory.find(iTurn); if (it != m_mapPowerHistory.end()) { return it->second; } return 0; } void CvPlayer::updatePowerHistory(int iTurn, int iBestPower) { m_mapPowerHistory[iTurn] = iBestPower; } int CvPlayer::getCultureHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapCultureHistory.find(iTurn); if (it != m_mapCultureHistory.end()) { return it->second; } return 0; } void CvPlayer::updateCultureHistory(int iTurn, int iBestCulture) { m_mapCultureHistory[iTurn] = iBestCulture; } int CvPlayer::getEspionageHistory(int iTurn) const { CvTurnScoreMap::const_iterator it = m_mapEspionageHistory.find(iTurn); if (it != m_mapEspionageHistory.end()) { return it->second; } return 0; } void CvPlayer::updateEspionageHistory(int iTurn, int iBestEspionage) { m_mapEspionageHistory[iTurn] = iBestEspionage; } std::string CvPlayer::getScriptData() const { return m_szScriptData; } void CvPlayer::setScriptData(std::string szNewValue) { m_szScriptData = szNewValue; } const CvString CvPlayer::getPbemEmailAddress() const { return GC.getInitCore().getEmail(getID()); } void CvPlayer::setPbemEmailAddress(const char* szAddress) { GC.getInitCore().setEmail(getID(), szAddress); } const CvString CvPlayer::getSmtpHost() const { return GC.getInitCore().getSmtpHost(getID()); } void CvPlayer::setSmtpHost(const char* szHost) { GC.getInitCore().setSmtpHost(getID(), szHost); } // Protected Functions... void CvPlayer::doGold() { bool bStrike; int iGoldChange; int iDisbandUnit; int iI; CyArgsList argsList; argsList.add(getID()); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "doGold", argsList.makeFunctionArgs(), &lResult); if (lResult == 1) { return; } iGoldChange = calculateGoldRate(); FAssert(isHuman() || isBarbarian() || ((getGold() + iGoldChange) >= 0) || isAnarchy()); changeGold(iGoldChange); bStrike = false; if (getGold() < 0) { setGold(0); if (!isBarbarian() && (getNumCities() > 0)) { bStrike = true; } } if (bStrike) { setStrike(true); changeStrikeTurns(1); if (getStrikeTurns() > 1) { iDisbandUnit = (getStrikeTurns() / 2); // XXX mod? for (iI = 0; iI < iDisbandUnit; iI++) { disbandUnit(true); if (calculateGoldRate() >= 0) { break; } } } } else { setStrike(false); } } void CvPlayer::doResearch() { bool bForceResearchChoice; int iOverflowResearch; CyArgsList argsList; argsList.add(getID()); long lResult=0; gDLL->getPythonIFace()->callFunction(PYGameModule, "doResearch", argsList.makeFunctionArgs(), &lResult); if (lResult == 1) { return; } if (isResearch()) { bForceResearchChoice = false; if (getCurrentResearch() == NO_TECH) { if (getID() == GC.getGameINLINE().getActivePlayer()) { chooseTech(); } if (GC.getGameINLINE().getElapsedGameTurns() > 4) { AI_chooseResearch(); bForceResearchChoice = true; } } TechTypes eCurrentTech = getCurrentResearch(); if (eCurrentTech == NO_TECH) { int iOverflow = (100 * calculateResearchRate()) / std::max(1, calculateResearchModifier(eCurrentTech)); changeOverflowResearch(iOverflow); } else { iOverflowResearch = (getOverflowResearch() * calculateResearchModifier(eCurrentTech)) / 100; setOverflowResearch(0); GET_TEAM(getTeam()).changeResearchProgress(eCurrentTech, (calculateResearchRate() + iOverflowResearch), getID()); } if (bForceResearchChoice) { clearResearchQueue(); } } } void CvPlayer::doEspionagePoints() { if (getCommerceRate(COMMERCE_ESPIONAGE) > 0) { GET_TEAM(getTeam()).changeEspionagePointsEver(getCommerceRate(COMMERCE_ESPIONAGE)); int iSpending = 0; // Divide up Espionage between Teams for (int iLoop = 0; iLoop < MAX_CIV_TEAMS; iLoop++) { if (getTeam() != iLoop) { if (GET_TEAM((TeamTypes)iLoop).isAlive()) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)iLoop)) { iSpending = getEspionageSpending((TeamTypes)iLoop); if (iSpending > 0) { GET_TEAM(getTeam()).changeEspionagePointsAgainstTeam((TeamTypes)iLoop, iSpending); } } } } } } } int CvPlayer::getEspionageSpending(TeamTypes eAgainstTeam) const { int iSpendingValue = 0; int iTotalPoints = getCommerceRate(COMMERCE_ESPIONAGE); int iAvailablePoints = iTotalPoints; int iTotalWeight = 0; int iBestWeight = 0; bool bFoundTeam = false; int iLoop; // Get sum of all weights to be used later on for (iLoop = 0; iLoop < MAX_CIV_TEAMS; iLoop++) { if (getTeam() != iLoop) { if (GET_TEAM((TeamTypes)iLoop).isAlive()) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)iLoop)) { if (iLoop == int(eAgainstTeam)) { bFoundTeam = true; } int iWeight = getEspionageSpendingWeightAgainstTeam((TeamTypes)iLoop); if (iWeight > iBestWeight) { iBestWeight = iWeight; } iTotalWeight += iWeight; } } } } // The player requested is not valid if (!bFoundTeam) { return -1; } // Split up Espionage Point budget based on weights (if any weights have been assigned) if (iTotalWeight > 0) { for (iLoop = 0; iLoop < MAX_CIV_TEAMS; iLoop++) { if (getTeam() != iLoop) { if (GET_TEAM((TeamTypes)iLoop).isAlive()) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)iLoop)) { int iChange = (iTotalPoints * getEspionageSpendingWeightAgainstTeam((TeamTypes)iLoop) / iTotalWeight); iAvailablePoints -= iChange; if (iLoop == int(eAgainstTeam)) { iSpendingValue += iChange; } } } } } } // Divide remainder evenly among top Teams while (iAvailablePoints > 0) { for (iLoop = 0; iLoop < MAX_CIV_TEAMS; iLoop++) { if (getTeam() != iLoop) { if (GET_TEAM((TeamTypes)iLoop).isAlive()) { if (GET_TEAM(getTeam()).isHasMet((TeamTypes)iLoop)) { if (getEspionageSpendingWeightAgainstTeam((TeamTypes)iLoop) == iBestWeight) { if (iLoop == int(eAgainstTeam)) { ++iSpendingValue; } --iAvailablePoints; if (iAvailablePoints <= 0) { break; } } } } } } } return iSpendingValue; } bool CvPlayer::canDoEspionageMission(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot, int iExtraData, const CvUnit* pUnit) const { if (getID() == eTargetPlayer || NO_PLAYER == eTargetPlayer) { return false; } if (!GET_PLAYER(eTargetPlayer).isAlive() || !GET_TEAM(getTeam()).isHasMet(GET_PLAYER(eTargetPlayer).getTeam())) { return false; } CvEspionageMissionInfo& kMission = GC.getEspionageMissionInfo(eMission); // Need Tech Prereq, if applicable if (kMission.getTechPrereq() != NO_TECH) { if (!GET_TEAM(getTeam()).isHasTech((TechTypes)kMission.getTechPrereq())) { return false; } } int iCost = getEspionageMissionCost(eMission, eTargetPlayer, pPlot, iExtraData, pUnit); if (iCost < 0) { return false; } if (NO_PLAYER != eTargetPlayer) { int iEspionagePoints = GET_TEAM(getTeam()).getEspionagePointsAgainstTeam(GET_PLAYER(eTargetPlayer).getTeam()); if (iEspionagePoints < iCost) { return false; } if (iEspionagePoints <= 0) { return false; } } return true; } int CvPlayer::getEspionageMissionCost(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot, int iExtraData, const CvUnit* pSpyUnit) const { int iMissionCost = getEspionageMissionBaseCost(eMission, eTargetPlayer, pPlot, iExtraData, pSpyUnit); if (-1 == iMissionCost) { return -1; } iMissionCost *= getEspionageMissionCostModifier(eMission, eTargetPlayer, pPlot, iExtraData, pSpyUnit); iMissionCost /= 100; // Multiply cost of mission * number of team members iMissionCost *= GET_TEAM(getTeam()).getNumMembers(); return std::max(0, iMissionCost); } int CvPlayer::getEspionageMissionBaseCost(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot, int iExtraData, const CvUnit* pSpyUnit) const { CvEspionageMissionInfo& kMission = GC.getEspionageMissionInfo(eMission); int iBaseMissionCost = kMission.getCost(); // -1 means this mission is disabled if (iBaseMissionCost == -1) { return -1; } CvCity* pCity = NULL; if (NULL != pPlot) { pCity = pPlot->getPlotCity(); } if (kMission.isSelectPlot()) { if (NULL == pPlot) { return -1; } if (!pPlot->isRevealed(getTeam(), false)) { return -1; } } if (NULL == pCity && kMission.isTargetsCity()) { return -1; } int iMissionCost = -1; if (kMission.getStealTreasuryTypes() > 0) { // Steal Treasury int iNumTotalGold = (GET_PLAYER(eTargetPlayer).getGold() * kMission.getStealTreasuryTypes()) / 100; if (NULL != pCity) { iNumTotalGold *= pCity->getPopulation(); iNumTotalGold /= std::max(1, GET_PLAYER(eTargetPlayer).getTotalPopulation()); } if (iNumTotalGold > 0) { iMissionCost = (iBaseMissionCost * iNumTotalGold) / 100; } } else if (kMission.getBuyTechCostFactor() > 0) { // Buy (Steal) Tech TechTypes eTech = (TechTypes)iExtraData; int iProdCost = MAX_INT; if (NO_TECH == eTech) { for (int iTech = 0; iTech < GC.getNumTechInfos(); ++iTech) { if (canStealTech(eTargetPlayer, (TechTypes)iTech)) { int iCost = GET_TEAM(getTeam()).getResearchCost((TechTypes)iTech); if (iCost < iProdCost) { iProdCost = iCost; eTech = (TechTypes)iTech; } } } } else { iProdCost = GET_TEAM(getTeam()).getResearchCost(eTech); } if (NO_TECH != eTech) { if (canStealTech(eTargetPlayer, eTech)) { iMissionCost = iBaseMissionCost + ((100 + kMission.getBuyTechCostFactor()) * iProdCost) / 100; } } } else if (kMission.getSwitchCivicCostFactor() > 0) { // Switch Civics CivicTypes eCivic = (CivicTypes)iExtraData; if (NO_CIVIC == eCivic) { for (int iCivic = 0; iCivic < GC.getNumCivicInfos(); ++iCivic) { if (canForceCivics(eTargetPlayer, (CivicTypes)iCivic)) { eCivic = (CivicTypes)iCivic; break; } } } if (NO_CIVIC != eCivic) { if (canForceCivics(eTargetPlayer, eCivic)) { iMissionCost = iBaseMissionCost + (kMission.getSwitchCivicCostFactor() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getAnarchyPercent()) / 10000; } } } else if (kMission.getSwitchReligionCostFactor() > 0) { // Switch Religions ReligionTypes eReligion = (ReligionTypes)iExtraData; if (NO_RELIGION == eReligion) { for (int iReligion = 0; iReligion < GC.getNumReligionInfos(); ++iReligion) { if (canForceReligion(eTargetPlayer, (ReligionTypes)iReligion)) { eReligion = (ReligionTypes)iReligion; break; } } } if (NO_RELIGION != eReligion) { if (canForceReligion(eTargetPlayer, eReligion)) { iMissionCost = iBaseMissionCost + (kMission.getSwitchReligionCostFactor() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getAnarchyPercent()) / 10000; } } } else if (kMission.getDestroyUnitCostFactor() > 0) { // Destroys Unit CvUnit* pUnit = GET_PLAYER(eTargetPlayer).getUnit(iExtraData); int iCost = MAX_INT; if (NULL == pUnit) { if (NULL != pPlot) { CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (canSpyDestroyUnit(eTargetPlayer, *pLoopUnit)) { int iValue = getProductionNeeded(pLoopUnit->getUnitType()); if (iValue < iCost) { iCost = iValue; pUnit = pLoopUnit; } } } } } else { iCost = getProductionNeeded(pUnit->getUnitType()); } if (NULL != pUnit) { if (canSpyDestroyUnit(eTargetPlayer, *pUnit)) { iMissionCost = iBaseMissionCost + ((100 + kMission.getDestroyUnitCostFactor()) * iCost) / 100; } } } else if (kMission.getDestroyProjectCostFactor() > 0) { ProjectTypes eProject = (ProjectTypes) iExtraData; int iCost = MAX_INT; if (NO_PROJECT == eProject) { for (int iProject = 0; iProject < GC.getNumProjectInfos(); ++iProject) { if (canSpyDestroyProject(eTargetPlayer, (ProjectTypes)iProject)) { int iValue = getProductionNeeded((ProjectTypes)iProject); if (iValue < iCost) { iCost = iValue; eProject = (ProjectTypes)iProject; } } } } else { iCost = getProductionNeeded(eProject); } if (NO_PROJECT != eProject) { if (canSpyDestroyProject(eTargetPlayer, eProject)) { iMissionCost = iBaseMissionCost + ((100 + kMission.getDestroyProjectCostFactor()) * iCost) / 100; } } } else if (kMission.getDestroyProductionCostFactor() > 0) { FAssert(NULL != pCity); if (NULL != pCity) { iMissionCost = iBaseMissionCost + ((100 + kMission.getDestroyProductionCostFactor()) * pCity->getProduction()) / 100; } } else if (kMission.getBuyUnitCostFactor() > 0) { // Buy Unit CvUnit* pUnit = GET_PLAYER(eTargetPlayer).getUnit(iExtraData); int iCost = MAX_INT; if (NULL == pUnit) { if (NULL != pPlot) { CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (canSpyBribeUnit(eTargetPlayer, *pLoopUnit)) { int iValue = getProductionNeeded(pLoopUnit->getUnitType()); if (iValue < iCost) { iCost = iValue; pUnit = pLoopUnit; } } } } } else { iCost = getProductionNeeded(pUnit->getUnitType()); } if (NULL != pUnit) { if (canSpyBribeUnit(eTargetPlayer, *pUnit)) { iMissionCost = iBaseMissionCost + ((100 + kMission.getBuyUnitCostFactor()) * iCost) / 100; } } } else if (kMission.getDestroyBuildingCostFactor() > 0) { BuildingTypes eBuilding = (BuildingTypes) iExtraData; int iCost = MAX_INT; if (NO_BUILDING == eBuilding) { for (int iBuilding = 0; iBuilding < GC.getNumBuildingInfos(); ++iBuilding) { if (NULL != pCity && pCity->getNumRealBuilding((BuildingTypes)iBuilding) > 0) { if (canSpyDestroyBuilding(eTargetPlayer, (BuildingTypes)iBuilding)) { int iValue = getProductionNeeded((BuildingTypes)iBuilding); if (iValue < iCost) { iCost = iValue; eBuilding = (BuildingTypes)iBuilding; } } } } } else { iCost = getProductionNeeded(eBuilding); } if (NO_BUILDING != eBuilding) { if (NULL != pCity && pCity->getNumRealBuilding(eBuilding) > 0) { if (canSpyDestroyBuilding(eTargetPlayer, eBuilding)) { iMissionCost = iBaseMissionCost + ((100 + kMission.getDestroyBuildingCostFactor()) * iCost) / 100; } } } } else if (kMission.getBuyCityCostFactor() > 0) { // Buy City if (NULL != pCity) { iMissionCost = iBaseMissionCost + (kMission.getBuyCityCostFactor() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getGrowthPercent()) / 10000; } } else if (kMission.getCityInsertCultureCostFactor() > 0) { // Insert Culture into City if (NULL != pPlot && pPlot->getCulture(getID()) > 0) { int iCultureAmount = kMission.getCityInsertCultureAmountFactor() * pCity->countTotalCultureTimes100(); iCultureAmount /= 10000; iCultureAmount = std::max(1, iCultureAmount); iMissionCost = iBaseMissionCost + (kMission.getCityInsertCultureCostFactor() * iCultureAmount) / 100; } } else if (kMission.isDestroyImprovement()) { if (NULL != pPlot && !pPlot->isCity()) { if (pPlot->getImprovementType() != NO_IMPROVEMENT || pPlot->getRouteType() != NO_ROUTE) { iMissionCost = (iBaseMissionCost * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getBuildPercent()) / 100; } } } else if (kMission.getCityPoisonWaterCounter() > 0) { FAssert(NULL != pCity); // Cannot poison a city's water supply if it's already poisoned (value is negative when active) if (NULL != pCity && pCity->getEspionageHealthCounter() <= 0) { iMissionCost = iBaseMissionCost; } } // Make city unhappy else if (kMission.getCityUnhappinessCounter() > 0) { FAssert(NULL != pCity); // Cannot make a city unhappy if you've already done it (value is negative when active) if (NULL != pCity && pCity->getEspionageHappinessCounter() <= 0) { iMissionCost = iBaseMissionCost; } } // Make city Revolt else if (kMission.getCityRevoltCounter() > 0) { FAssert(NULL != pCity); // Cannot make a city revolt if it's already revolting if (NULL != pCity && pCity->getOccupationTimer() == 0) { iMissionCost = iBaseMissionCost; } } else if (kMission.getCounterespionageMod() > 0) { if (GET_TEAM(getTeam()).getCounterespionageTurnsLeftAgainstTeam(GET_PLAYER(eTargetPlayer).getTeam()) <= 0) { iMissionCost = (iBaseMissionCost * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getResearchPercent()) / 100; } } else if (kMission.getPlayerAnarchyCounter() > 0) { // Player anarchy timer: can't add more turns of anarchy to player already in the midst of it if (!GET_PLAYER(eTargetPlayer).isAnarchy()) { iMissionCost = (iBaseMissionCost * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getAnarchyPercent()) / 100; } } else if (kMission.isPassive()) { iMissionCost = (iBaseMissionCost * (100 + GET_TEAM(GET_PLAYER(eTargetPlayer).getTeam()).getEspionagePointsAgainstTeam(getTeam()))) / 100; } else { iMissionCost = (iBaseMissionCost * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getResearchPercent()) / 100; } if (iMissionCost < 0) { return -1; } return iMissionCost; } int CvPlayer::getEspionageMissionCostModifier(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, const CvPlot* pPlot, int iExtraData, const CvUnit* pSpyUnit) const { CvEspionageMissionInfo& kMission = GC.getEspionageMissionInfo(eMission); int iModifier = 100; CvCity* pCity = NULL; if (NULL != pPlot) { pCity = pPlot->getPlotCity(); } if (NO_PLAYER == eTargetPlayer) { eTargetPlayer = getID(); } if (pCity != NULL && kMission.isTargetsCity()) { // City Population iModifier *= 100 + (GC.getDefineINT("ESPIONAGE_CITY_POP_EACH_MOD") * (pCity->getPopulation() - 1)); iModifier /= 100; // Trade Route if (pCity->isTradeRoute(getID())) { iModifier *= 100 + GC.getDefineINT("ESPIONAGE_CITY_TRADE_ROUTE_MOD"); iModifier /= 100; } ReligionTypes eReligion = getStateReligion(); if (NO_RELIGION != eReligion) { int iReligionModifier = 0; // City has Your State Religion if (pCity->isHasReligion(eReligion)) { if (GET_PLAYER(eTargetPlayer).getStateReligion() != eReligion) { iReligionModifier += GC.getDefineINT("ESPIONAGE_CITY_RELIGION_STATE_MOD"); } if (hasHolyCity(eReligion)) { iReligionModifier += GC.getDefineINT("ESPIONAGE_CITY_HOLY_CITY_MOD"); } } iModifier *= 100 + iReligionModifier; iModifier /= 100; } // City's culture affects cost iModifier *= 100 - (pCity->getCultureTimes100(getID()) * GC.getDefineINT("ESPIONAGE_CULTURE_MULTIPLIER_MOD")) / std::max(1, pCity->getCultureTimes100(eTargetPlayer) + pCity->getCultureTimes100(getID())); iModifier /= 100; iModifier *= 100 + pCity->getEspionageDefenseModifier(); iModifier /= 100; } // Distance mod if (pPlot != NULL) { int iDistance = GC.getMap().maxPlotDistance(); CvCity* pOurCapital = getCapitalCity(); if (NULL != pOurCapital) { if (kMission.isSelectPlot() || kMission.isTargetsCity()) { iDistance = plotDistance(pOurCapital->getX_INLINE(), pOurCapital->getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()); } else { CvCity* pTheirCapital = GET_PLAYER(eTargetPlayer).getCapitalCity(); if (NULL != pTheirCapital) { iDistance = plotDistance(pOurCapital->getX_INLINE(), pOurCapital->getY_INLINE(), pTheirCapital->getX_INLINE(), pTheirCapital->getY_INLINE()); } } } iModifier *= (iDistance + GC.getMapINLINE().maxPlotDistance()) * GC.getDefineINT("ESPIONAGE_DISTANCE_MULTIPLIER_MOD") / GC.getMapINLINE().maxPlotDistance(); iModifier /= 100; } // Spy presence mission cost alteration if (NULL != pSpyUnit) { iModifier *= 100 - (pSpyUnit->getFortifyTurns() * GC.getDefineINT("ESPIONAGE_EACH_TURN_UNIT_COST_DECREASE")); iModifier /= 100; } // My points VS. Your points to mod cost int iTargetPoints = GET_TEAM(GET_PLAYER(eTargetPlayer).getTeam()).getEspionagePointsEver(); int iOurPoints = GET_TEAM(getTeam()).getEspionagePointsEver(); iModifier *= (GC.getDefineINT("ESPIONAGE_SPENDING_MULTIPLIER") * (2 * iTargetPoints + iOurPoints)) / std::max(1, iTargetPoints + 2 * iOurPoints); iModifier /= 100; // Counterespionage Mission Mod CvTeam& kTargetTeam = GET_TEAM(GET_PLAYER(eTargetPlayer).getTeam()); if (kTargetTeam.getCounterespionageModAgainstTeam(getTeam()) > 0) { iModifier *= kTargetTeam.getCounterespionageModAgainstTeam(getTeam()); iModifier /= 100; } return iModifier; } bool CvPlayer::doEspionageMission(EspionageMissionTypes eMission, PlayerTypes eTargetPlayer, CvPlot* pPlot, int iExtraData, CvUnit* pSpyUnit) { if (!canDoEspionageMission(eMission, eTargetPlayer, pPlot, iExtraData, pSpyUnit)) { return false; } TeamTypes eTargetTeam = NO_TEAM; if (NO_PLAYER != eTargetPlayer) { eTargetTeam = GET_PLAYER(eTargetPlayer).getTeam(); } CvEspionageMissionInfo& kMission = GC.getEspionageMissionInfo(eMission); bool bSomethingHappened = false; bool bShowExplosion = false; CvWString szBuffer; int iMissionCost = getEspionageMissionCost(eMission, eTargetPlayer, pPlot, iExtraData, pSpyUnit); ////////////////////////////// // Destroy Improvement if (kMission.isDestroyImprovement()) { if (NULL != pPlot) { // Blow it up if (pPlot->getImprovementType() != NO_IMPROVEMENT) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SOMETHING_DESTROYED", GC.getImprovementInfo(pPlot->getImprovementType()).getDescription()).GetCString(); pPlot->setImprovementType((ImprovementTypes)(GC.getImprovementInfo(pPlot->getImprovementType()).getImprovementPillage())); bSomethingHappened = true; } else if (pPlot->getRouteType() != NO_ROUTE) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SOMETHING_DESTROYED", GC.getRouteInfo(pPlot->getRouteType()).getDescription()).GetCString(); pPlot->setRouteType(NO_ROUTE, true); bSomethingHappened = true; } if (bSomethingHappened) { bShowExplosion = true; } } } ////////////////////////////// // Destroy Building if (kMission.getDestroyBuildingCostFactor() > 0) { BuildingTypes eTargetBuilding = (BuildingTypes)iExtraData; if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SOMETHING_DESTROYED_IN", GC.getBuildingInfo(eTargetBuilding).getDescription(), pCity->getNameKey()).GetCString(); pCity->setNumRealBuilding(eTargetBuilding, pCity->getNumRealBuilding(eTargetBuilding) - 1); bSomethingHappened = true; bShowExplosion = true; } } } ////////////////////////////// // Destroy Project if (kMission.getDestroyProjectCostFactor() > 0) { ProjectTypes eTargetProject = (ProjectTypes)iExtraData; if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SOMETHING_DESTROYED_IN", GC.getProjectInfo(eTargetProject).getDescription(), pCity->getNameKey()).GetCString(); GET_TEAM(eTargetTeam).changeProjectCount(eTargetProject, -1); bSomethingHappened = true; bShowExplosion = true; } } } ////////////////////////////// // Destroy Production if (kMission.getDestroyProductionCostFactor() > 0) { if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_PRODUCTION_DESTROYED_IN", pCity->getProductionName(), pCity->getNameKey()); pCity->setProduction(0); bSomethingHappened = true; bShowExplosion = true; } } } ////////////////////////////// // Destroy Unit if (kMission.getDestroyUnitCostFactor() > 0) { if (NO_PLAYER != eTargetPlayer) { int iTargetUnitID = iExtraData; CvUnit* pUnit = GET_PLAYER(eTargetPlayer).getUnit(iTargetUnitID); if (NULL != pUnit) { FAssert(pUnit->plot() == pPlot); szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SOMETHING_DESTROYED", pUnit->getNameKey()).GetCString(); pUnit->kill(false, getID()); bSomethingHappened = true; bShowExplosion = true; } } } ////////////////////////////// // Buy Unit if (kMission.getBuyUnitCostFactor() > 0) { if (NO_PLAYER != eTargetPlayer) { int iTargetUnitID = iExtraData; CvUnit* pUnit = GET_PLAYER(eTargetPlayer).getUnit(iTargetUnitID); if (NULL != pUnit) { FAssert(pUnit->plot() == pPlot); szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_UNIT_BOUGHT", pUnit->getNameKey()).GetCString(); UnitTypes eUnitType = pUnit->getUnitType(); int iX = pUnit->getX_INLINE(); int iY = pUnit->getY_INLINE(); pUnit->kill(false, getID()); initUnit(eUnitType, iX, iY, NO_UNITAI); bSomethingHappened = true; } } } ////////////////////////////// // Buy City if (kMission.getBuyCityCostFactor() > 0) { if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_CITY_BOUGHT", pCity->getNameKey()).GetCString(); acquireCity(pCity, false, true, true); bSomethingHappened = true; } } } ////////////////////////////// // Insert Culture into City if (kMission.getCityInsertCultureCostFactor() > 0) { if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_CITY_CULTURE_INSERTED", pCity->getNameKey()).GetCString(); int iCultureAmount = kMission.getCityInsertCultureAmountFactor() * pCity->countTotalCultureTimes100(); iCultureAmount /= 10000; iCultureAmount = std::max(1, iCultureAmount); int iNumTurnsApplied = (GC.getDefineINT("GREAT_WORKS_CULTURE_TURNS") * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getUnitGreatWorkPercent()) / 100; for (int i = 0; i < iNumTurnsApplied; ++i) { pCity->changeCulture(getID(), iCultureAmount / iNumTurnsApplied, true, true); } if (iNumTurnsApplied > 0) { pCity->changeCulture(getID(), iCultureAmount % iNumTurnsApplied, false, true); } bSomethingHappened = true; } } } ////////////////////////////// // Poison City's Water Supply if (kMission.getCityPoisonWaterCounter() > 0) { if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_CITY_POISONED", pCity->getNameKey()).GetCString(); pCity->changeEspionageHealthCounter(kMission.getCityPoisonWaterCounter()); bShowExplosion = true; bSomethingHappened = true; } } } ////////////////////////////// // Make city Unhappy if (kMission.getCityUnhappinessCounter() > 0) { if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_CITY_UNHAPPY", pCity->getNameKey()).GetCString(); pCity->changeEspionageHappinessCounter(kMission.getCityUnhappinessCounter()); bShowExplosion = true; bSomethingHappened = true; } } } ////////////////////////////// // Make city Revolt if (kMission.getCityRevoltCounter() > 0) { if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_CITY_REVOLT", pCity->getNameKey()).GetCString(); pCity->changeCultureUpdateTimer(kMission.getCityRevoltCounter()); pCity->changeOccupationTimer(kMission.getCityRevoltCounter()); bSomethingHappened = true; bShowExplosion = true; /************************************************************************************************/ /* BETTER_BTS_AI_MOD 01/12/10 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gUnitLogLevel >= 2 ) { logBBAI(" Spy for player %d (%S) causes revolt in %S, owned by %S (%d)", getID(), getCivilizationDescription(0), pCity->getName().GetCString(), GET_PLAYER(pCity->getOwner()).getCivilizationDescription(0), pCity->getOwner() ); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } } } ////////////////////////////// // Steal Treasury if (kMission.getStealTreasuryTypes() > 0) { if (NO_PLAYER != eTargetPlayer) { int iNumTotalGold = (GET_PLAYER(eTargetPlayer).getGold() * kMission.getStealTreasuryTypes()) / 100; if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { iNumTotalGold *= pCity->getPopulation(); iNumTotalGold /= std::max(1, GET_PLAYER(eTargetPlayer).getTotalPopulation()); } } szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_STEAL_TREASURY").GetCString(); changeGold(iNumTotalGold); if (NO_PLAYER != eTargetPlayer) { GET_PLAYER(eTargetPlayer).changeGold(-iNumTotalGold); } bSomethingHappened = true; } } ////////////////////////////// // Buy (Steal) Tech if (kMission.getBuyTechCostFactor() > 0) { int iTech = iExtraData; szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_TECH_BOUGHT", GC.getTechInfo((TechTypes) iTech).getDescription()).GetCString(); GET_TEAM(getTeam()).setHasTech((TechTypes) iTech, true, getID(), false, true); GET_TEAM(getTeam()).setNoTradeTech((TechTypes)iTech, true); bSomethingHappened = true; } ////////////////////////////// // Switch Civic if (kMission.getSwitchCivicCostFactor() > 0) { if (NO_PLAYER != eTargetPlayer) { int iCivic = iExtraData; szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SWITCH_CIVIC", GC.getCivicInfo((CivicTypes) iCivic).getDescription()).GetCString(); GET_PLAYER(eTargetPlayer).setCivics((CivicOptionTypes) GC.getCivicInfo((CivicTypes) iCivic).getCivicOptionType(), (CivicTypes) iCivic); GET_PLAYER(eTargetPlayer).setRevolutionTimer(std::max(1, ((100 + GET_PLAYER(eTargetPlayer).getAnarchyModifier()) * GC.getDefineINT("MIN_REVOLUTION_TURNS")) / 100)); bSomethingHappened = true; } } ////////////////////////////// // Switch Religion if (kMission.getSwitchReligionCostFactor() > 0) { if (NO_PLAYER != eTargetPlayer) { int iReligion = iExtraData; szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_SWITCH_RELIGION", GC.getReligionInfo((ReligionTypes) iReligion).getDescription()).GetCString(); GET_PLAYER(eTargetPlayer).setLastStateReligion((ReligionTypes) iReligion); GET_PLAYER(eTargetPlayer).setConversionTimer(std::max(1, ((100 + GET_PLAYER(eTargetPlayer).getAnarchyModifier()) * GC.getDefineINT("MIN_CONVERSION_TURNS")) / 100)); bSomethingHappened = true; } } ////////////////////////////// // Player Anarchy if (kMission.getPlayerAnarchyCounter() > 0) { if (NO_PLAYER != eTargetPlayer) { int iTurns = (kMission.getPlayerAnarchyCounter() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getAnarchyPercent()) / 100; szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_PLAYER_ANARCHY").GetCString(); GET_PLAYER(eTargetPlayer).changeAnarchyTurns(iTurns); bSomethingHappened = true; } } ////////////////////////////// // Counterespionage if (kMission.getCounterespionageNumTurns() > 0 && kMission.getCounterespionageMod() > 0) { szBuffer = gDLL->getText("TXT_KEY_ESPIONAGE_TARGET_COUNTERESPIONAGE").GetCString(); if (NO_TEAM != eTargetTeam) { int iTurns = (kMission.getCounterespionageNumTurns() * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getResearchPercent()) / 100; GET_TEAM(getTeam()).changeCounterespionageTurnsLeftAgainstTeam(eTargetTeam, iTurns); GET_TEAM(getTeam()).changeCounterespionageModAgainstTeam(eTargetTeam, kMission.getCounterespionageMod()); bSomethingHappened = true; } } int iHave = 0; if (NO_TEAM != eTargetTeam) { iHave = GET_TEAM(getTeam()).getEspionagePointsAgainstTeam(eTargetTeam); if (bSomethingHappened) { GET_TEAM(getTeam()).changeEspionagePointsAgainstTeam(eTargetTeam, -iMissionCost); } } if (bShowExplosion) { if (pPlot) { if (pPlot->isVisible(GC.getGame().getActiveTeam(), false)) { EffectTypes eEffect = GC.getEntityEventInfo(GC.getMissionInfo(MISSION_BOMBARD).getEntityEvent()).getEffectType(); gDLL->getEngineIFace()->TriggerEffect(eEffect, pPlot->getPoint(), (float)(GC.getASyncRand().get(360))); gDLL->getInterfaceIFace()->playGeneralSound("AS3D_UN_CITY_EXPLOSION", pPlot->getPoint()); } } } if (bSomethingHappened) { int iX = -1; int iY = -1; if (NULL != pPlot) { iX = pPlot->getX_INLINE(); iY = pPlot->getY_INLINE(); } gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), gDLL->getText("TXT_KEY_ESPIONAGE_MISSION_PERFORMED"), "AS2D_POSITIVE_DINK", MESSAGE_TYPE_INFO, ARTFILEMGR.getInterfaceArtInfo("ESPIONAGE_BUTTON")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), iX, iY, true, true); } else if (getID() == GC.getGameINLINE().getActivePlayer()) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_TEXT); if (iHave < iMissionCost) { pInfo->setText(gDLL->getText("TXT_KEY_ESPIONAGE_TOO_EXPENSIVE", iMissionCost, iHave)); } else { pInfo->setText(gDLL->getText("TXT_KEY_ESPIONAGE_CANNOT_DO_MISSION")); } addPopup(pInfo); } if (bSomethingHappened && !szBuffer.empty()) { int iX = -1; int iY = -1; if (NULL != pPlot) { iX = pPlot->getX_INLINE(); iY = pPlot->getY_INLINE(); } if (NO_PLAYER != eTargetPlayer) { gDLL->getInterfaceIFace()->addMessage(eTargetPlayer, true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_DEAL_CANCELLED", MESSAGE_TYPE_INFO, ARTFILEMGR.getInterfaceArtInfo("ESPIONAGE_BUTTON")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), iX, iY, true, true); } } return bSomethingHappened; } int CvPlayer::getEspionageSpendingWeightAgainstTeam(TeamTypes eIndex) const { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < MAX_TEAMS, "eIndex is expected to be within maximum bounds (invalid Index)"); return m_aiEspionageSpendingWeightAgainstTeam[eIndex]; } void CvPlayer::setEspionageSpendingWeightAgainstTeam(TeamTypes eIndex, int iValue) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < MAX_TEAMS, "eIndex is expected to be within maximum bounds (invalid Index)"); FAssert(iValue >= 0); iValue = std::min(std::max(0, iValue), 99); if (iValue != getEspionageSpendingWeightAgainstTeam(eIndex)) { m_aiEspionageSpendingWeightAgainstTeam[eIndex] = iValue; gDLL->getInterfaceIFace()->setDirty(Espionage_Advisor_DIRTY_BIT, true); } } void CvPlayer::changeEspionageSpendingWeightAgainstTeam(TeamTypes eIndex, int iChange) { FAssertMsg(eIndex >= 0, "eIndex is expected to be non-negative (invalid Index)"); FAssertMsg(eIndex < MAX_TEAMS, "eIndex is expected to be within maximum bounds (invalid Index)"); setEspionageSpendingWeightAgainstTeam(eIndex, getEspionageSpendingWeightAgainstTeam(eIndex) + iChange); } void CvPlayer::doAdvancedStartAction(AdvancedStartActionTypes eAction, int iX, int iY, int iData, bool bAdd) { if (getAdvancedStartPoints() < 0) { return; } CvPlot* pPlot = GC.getMap().plot(iX, iY); if (0 == getNumCities()) { switch (eAction) { case ADVANCEDSTARTACTION_EXIT: //Try to build this player's empire if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setBusy(true); } AI_doAdvancedStart(true); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setBusy(false); } break; case ADVANCEDSTARTACTION_AUTOMATE: case ADVANCEDSTARTACTION_CITY: break; default: // The first action must be to place a city // so players can lose by spending everything return; } } switch (eAction) { case ADVANCEDSTARTACTION_EXIT: changeGold(getAdvancedStartPoints()); setAdvancedStartPoints(-1); if (GC.getGameINLINE().getActivePlayer() == getID()) { gDLL->getInterfaceIFace()->setInAdvancedStart(false); } if (isHuman()) { int iLoop; for (CvCity* pCity = firstCity(&iLoop); NULL != pCity; pCity = nextCity(&iLoop)) { pCity->chooseProduction(); } chooseTech(); if (canRevolution(NULL)) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_CHANGECIVIC); if (NULL != pInfo) { gDLL->getInterfaceIFace()->addPopup(pInfo, getID()); } } } break; case ADVANCEDSTARTACTION_AUTOMATE: if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setBusy(true); } AI_doAdvancedStart(true); if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setBusy(false); } break; case ADVANCEDSTARTACTION_UNIT: { if(pPlot == NULL) return; UnitTypes eUnit = (UnitTypes) iData; int iCost = getAdvancedStartUnitCost(eUnit, bAdd, pPlot); if (bAdd && iCost < 0) { return; } // Add unit to the map if (bAdd) { if (getAdvancedStartPoints() >= iCost) { CvUnit* pUnit = initUnit(eUnit, iX, iY); if (NULL != pUnit) { pUnit->finishMoves(); changeAdvancedStartPoints(-iCost); } } } // Remove unit from the map else { // If cost is -1 we already know this unit isn't present if (iCost != -1) { CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getUnitType() == eUnit) { pLoopUnit->kill(false); changeAdvancedStartPoints(iCost); return; } } } // Proper unit not found above, delete first found CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); if (pUnitNode != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode->m_data); iCost = getAdvancedStartUnitCost(pUnit->getUnitType(), false); FAssertMsg(iCost != -1, "If this is -1 then that means it's going to try to delete a unit which shouldn't exist"); pUnit->kill(false); changeAdvancedStartPoints(iCost); } } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Advanced_Start_DIRTY_BIT, true); } } break; case ADVANCEDSTARTACTION_CITY: { if(pPlot == NULL) return; int iCost = getAdvancedStartCityCost(bAdd, pPlot); if (iCost < 0) { return; } // Add City to the map if (bAdd) { if (0 == getNumCities()) { PlayerTypes eClosestPlayer = NO_PLAYER; int iMinDistance = MAX_INT; for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; iPlayer++) { CvPlayer& kPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kPlayer.isAlive()) { if (kPlayer.getTeam() == getTeam()) { if (0 == kPlayer.getNumCities()) { FAssert(kPlayer.getStartingPlot() != NULL); int iDistance = plotDistance(iX, iY, kPlayer.getStartingPlot()->getX_INLINE(), kPlayer.getStartingPlot()->getY_INLINE()); if (iDistance < iMinDistance) { eClosestPlayer = kPlayer.getID(); iMinDistance = iDistance; } } } } } FAssertMsg(eClosestPlayer != NO_PLAYER, "Self at a minimum should always be valid"); if (eClosestPlayer != getID()) { CvPlot* pTempPlot = GET_PLAYER(eClosestPlayer).getStartingPlot(); GET_PLAYER(eClosestPlayer).setStartingPlot(getStartingPlot(), false); setStartingPlot(pTempPlot, false); } } if (getAdvancedStartPoints() >= iCost || 0 == getNumCities()) { found(iX, iY); changeAdvancedStartPoints(-std::min(iCost, getAdvancedStartPoints())); GC.getGameINLINE().updateColoredPlots(); CvCity* pCity = pPlot->getPlotCity(); if (pCity != NULL) { if (pCity->getPopulation() > 1) { pCity->setFood(pCity->growthThreshold() / 2); } } } } // Remove City from the map else { pPlot->setRouteType(NO_ROUTE, true); pPlot->getPlotCity()->kill(true); pPlot->setImprovementType(NO_IMPROVEMENT); changeAdvancedStartPoints(iCost); } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Advanced_Start_DIRTY_BIT, true); } } break; case ADVANCEDSTARTACTION_POP: { if(pPlot == NULL) return; CvCity* pCity = pPlot->getPlotCity(); if (pCity != NULL) { int iCost = getAdvancedStartPopCost(bAdd, pCity); if (iCost < 0) { return; } bool bPopChanged = false; if (bAdd) { if (getAdvancedStartPoints() >= iCost) { pCity->changePopulation(1); changeAdvancedStartPoints(-iCost); bPopChanged = true; } } else { pCity->changePopulation(-1); changeAdvancedStartPoints(iCost); bPopChanged = true; } if (bPopChanged) { pCity->setHighestPopulation(pCity->getPopulation()); if (pCity->getPopulation() == 1) { pCity->setFood(0); pCity->setFoodKept(0); } else if (pCity->getPopulation() > 1) { pCity->setFood(pCity->growthThreshold() / 2); pCity->setFoodKept((pCity->getFood() * pCity->getMaxFoodKeptPercent()) / 100); } } } } break; case ADVANCEDSTARTACTION_CULTURE: { if(pPlot == NULL) return; CvCity* pCity = pPlot->getPlotCity(); if (pCity != NULL) { int iCost = getAdvancedStartCultureCost(bAdd, pCity); if (iCost < 0) { return; } // Add Culture to the City if (bAdd) { if (getAdvancedStartPoints() >= iCost) { pCity->setCulture(getID(), pCity->getCultureThreshold(), true, true); changeAdvancedStartPoints(-iCost); } } // Remove Culture from the city else { CultureLevelTypes eLevel = (CultureLevelTypes)std::max(0, pCity->getCultureLevel() - 1); pCity->setCulture(getID(), CvCity::getCultureThreshold(eLevel), true, true); changeAdvancedStartPoints(iCost); } } } break; case ADVANCEDSTARTACTION_BUILDING: { if(pPlot == NULL) return; CvCity* pCity = pPlot->getPlotCity(); if (pCity != NULL) { BuildingTypes eBuilding = (BuildingTypes) iData; int iCost = getAdvancedStartBuildingCost(eBuilding, bAdd, pCity); if (iCost < 0) { return; } // Add Building to the City if (bAdd) { if (getAdvancedStartPoints() >= iCost) { pCity->setNumRealBuilding(eBuilding, pCity->getNumRealBuilding(eBuilding)+1); changeAdvancedStartPoints(-iCost); if (GC.getBuildingInfo(eBuilding).getFoodKept() != 0) { pCity->setFoodKept((pCity->getFood() * pCity->getMaxFoodKeptPercent()) / 100); } } } // Remove Building from the map else { pCity->setNumRealBuilding(eBuilding, pCity->getNumRealBuilding(eBuilding)-1); changeAdvancedStartPoints(iCost); if (GC.getBuildingInfo(eBuilding).getFoodKept() != 0) { pCity->setFoodKept((pCity->getFood() * pCity->getMaxFoodKeptPercent()) / 100); } } } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Advanced_Start_DIRTY_BIT, true); } } break; case ADVANCEDSTARTACTION_ROUTE: { if(pPlot == NULL) return; RouteTypes eRoute = (RouteTypes) iData; int iCost = getAdvancedStartRouteCost(eRoute, bAdd, pPlot); if (bAdd && iCost < 0) { return; } // Add Route to the plot if (bAdd) { if (getAdvancedStartPoints() >= iCost) { pPlot->setRouteType(eRoute, true); changeAdvancedStartPoints(-iCost); } } // Remove Route from the Plot else { if (pPlot->getRouteType() != eRoute) { eRoute = pPlot->getRouteType(); iCost = getAdvancedStartRouteCost(eRoute, bAdd); } if (iCost < 0) { return; } pPlot->setRouteType(NO_ROUTE, true); changeAdvancedStartPoints(iCost); } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Advanced_Start_DIRTY_BIT, true); } } break; case ADVANCEDSTARTACTION_IMPROVEMENT: { if(pPlot == NULL) return; ImprovementTypes eImprovement = (ImprovementTypes) iData; int iCost = getAdvancedStartImprovementCost(eImprovement, bAdd, pPlot); if (bAdd && iCost < 0) { return; } // Add Improvement to the plot if (bAdd) { if (getAdvancedStartPoints() >= iCost) { if (pPlot->getFeatureType() != NO_FEATURE) { for (int iI = 0; iI < GC.getNumBuildInfos(); ++iI) { ImprovementTypes eLoopImprovement = ((ImprovementTypes)(GC.getBuildInfo((BuildTypes)iI).getImprovement())); if (eImprovement == eLoopImprovement) { if (GC.getBuildInfo((BuildTypes)iI).isFeatureRemove(pPlot->getFeatureType()) && canBuild(pPlot, (BuildTypes)iI)) { pPlot->setFeatureType(NO_FEATURE); break; } } } } pPlot->setImprovementType(eImprovement); changeAdvancedStartPoints(-iCost); } } // Remove Improvement from the Plot else { if (pPlot->getImprovementType() != eImprovement) { eImprovement = pPlot->getImprovementType(); iCost = getAdvancedStartImprovementCost(eImprovement, bAdd, pPlot); } if (iCost < 0) { return; } pPlot->setImprovementType(NO_IMPROVEMENT); changeAdvancedStartPoints(iCost); } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Advanced_Start_DIRTY_BIT, true); } } break; case ADVANCEDSTARTACTION_TECH: { TechTypes eTech = (TechTypes) iData; int iCost = getAdvancedStartTechCost(eTech, bAdd); if (iCost < 0) { return; } // Add Tech to team if (bAdd) { if (getAdvancedStartPoints() >= iCost) { GET_TEAM(getTeam()).setHasTech(eTech, true, getID(), false, false); changeAdvancedStartPoints(-iCost); } } // Remove Tech from the Team else { GET_TEAM(getTeam()).setHasTech(eTech, false, getID(), false, false); changeAdvancedStartPoints(iCost); } if (getID() == GC.getGameINLINE().getActivePlayer()) { gDLL->getInterfaceIFace()->setDirty(Advanced_Start_DIRTY_BIT, true); } } break; case ADVANCEDSTARTACTION_VISIBILITY: { if(pPlot == NULL) return; int iCost = getAdvancedStartVisibilityCost(bAdd, pPlot); if (iCost < 0) { return; } // Add Visibility to the plot if (bAdd) { if (getAdvancedStartPoints() >= iCost) { pPlot->setRevealed(getTeam(), true, true, NO_TEAM, true); changeAdvancedStartPoints(-iCost); } } // Remove Visibility from the Plot else { pPlot->setRevealed(getTeam(), false, true, NO_TEAM, true); changeAdvancedStartPoints(iCost); } } break; default: FAssert(false); break; } } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing a unit ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartUnitCost(UnitTypes eUnit, bool bAdd, CvPlot* pPlot) const { int iLoop; int iNumUnitType = 0; if (0 == getNumCities()) { return -1; } int iCost = (getProductionNeeded(eUnit) * GC.getUnitInfo(eUnit).getAdvancedStartCost()) / 100; if (iCost < 0) { return -1; } if (NULL == pPlot) { if (bAdd) { bool bValid = false; int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->canTrain(eUnit)) { bValid = true; break; } } if (!bValid) { return -1; } } } else { CvCity* pCity = NULL; if (0 == GC.getDefineINT("ADVANCED_START_ALLOW_UNITS_OUTSIDE_CITIES")) { pCity = pPlot->getPlotCity(); if (NULL == pCity || pCity->getOwnerINLINE() != getID()) { return -1; } iCost *= 100; iCost /= std::max(1, 100 + pCity->getProductionModifier(eUnit)); } else { if (pPlot->getOwnerINLINE() != getID()) { return -1; } iCost *= 100; iCost /= std::max(1, 100 + getProductionModifier(eUnit)); } if (bAdd) { int iMaxUnitsPerCity = GC.getDefineINT("ADVANCED_START_MAX_UNITS_PER_CITY"); if (iMaxUnitsPerCity >= 0) { if (GC.getUnitInfo(eUnit).isMilitarySupport() && getNumMilitaryUnits() >= iMaxUnitsPerCity * getNumCities()) { return -1; } } if (NULL != pCity) { if (!pCity->canTrain(eUnit)) { return -1; } } else { if (!pPlot->canTrain(eUnit, false, false)) { return -1; } if (pPlot->isImpassable() && !GC.getUnitInfo(eUnit).isCanMoveImpassable()) { return -1; } if (pPlot->getFeatureType() != NO_FEATURE) { if (GC.getUnitInfo(eUnit).getFeatureImpassable(pPlot->getFeatureType())) { TechTypes eTech = (TechTypes)GC.getUnitInfo(eUnit).getFeaturePassableTech(pPlot->getFeatureType()); if (NO_TECH == eTech || !GET_TEAM(getTeam()).isHasTech(eTech)) { return -1; } } } else { if (GC.getUnitInfo(eUnit).getTerrainImpassable(pPlot->getTerrainType())) { TechTypes eTech = (TechTypes)GC.getUnitInfo(eUnit).getTerrainPassableTech(pPlot->getTerrainType()); if (NO_TECH == eTech || !GET_TEAM(getTeam()).isHasTech(eTech)) { return -1; } } } } } // Must be this unit at plot in order to remove else { bool bUnitFound = false; CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pPlot->nextUnitNode(pUnitNode); if (pLoopUnit->getUnitType() == eUnit) { bUnitFound = true; } } if (!bUnitFound) { return -1; } } } // Increase cost if the XML defines that additional units will cost more if (0 != GC.getUnitInfo(eUnit).getAdvancedStartCostIncrease()) { for (CvUnit* pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->getUnitType() == eUnit) { ++iNumUnitType; } } if (!bAdd) { --iNumUnitType; } if (iNumUnitType > 0) { iCost *= 100 + GC.getUnitInfo(eUnit).getAdvancedStartCostIncrease() * iNumUnitType; iCost /= 100; } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing a City ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartCityCost(bool bAdd, CvPlot* pPlot) const { int iNumCities = getNumCities(); int iCost = getNewCityProductionValue(); if (iCost < 0) { return -1; } // Valid plot? if (pPlot != NULL) { // Need valid plot to found on if adding if (bAdd) { if (!canFound(pPlot->getX(), pPlot->getY(), false)) { return -1; } } // Need your own city present to remove else { if (pPlot->isCity()) { if (pPlot->getPlotCity()->getOwnerINLINE() != getID()) { return -1; } } else { return -1; } } // Is there a distance limit on how far a city can be placed from a player's start/another city? if (GC.getDefineINT("ADVANCED_START_CITY_PLACEMENT_MAX_RANGE") > 0) { PlayerTypes eClosestPlayer = NO_PLAYER; int iClosestDistance = MAX_INT; for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kPlayer.isAlive()) { CvPlot* pStartingPlot = kPlayer.getStartingPlot(); if (NULL != pStartingPlot) { int iDistance = ::plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pStartingPlot->getX_INLINE(), pStartingPlot->getY_INLINE()); if (iDistance <= GC.getDefineINT("ADVANCED_START_CITY_PLACEMENT_MAX_RANGE")) { if (iDistance < iClosestDistance || (iDistance == iClosestDistance && getTeam() != kPlayer.getTeam())) { iClosestDistance = iDistance; eClosestPlayer = kPlayer.getID(); } } } } } if (NO_PLAYER == eClosestPlayer || GET_PLAYER(eClosestPlayer).getTeam() != getTeam()) { return -1; } //Only allow founding a city at someone elses start point if //We have no cities and they have no cities. if ((getID() != eClosestPlayer) && ((getNumCities() > 0) || (GET_PLAYER(eClosestPlayer).getNumCities() > 0))) { return -1; } } } // Increase cost if the XML defines that additional units will cost more if (0 != GC.getDefineINT("ADVANCED_START_CITY_COST_INCREASE")) { if (!bAdd) { --iNumCities; } if (iNumCities > 0) { iCost *= 100 + GC.getDefineINT("ADVANCED_START_CITY_COST_INCREASE") * iNumCities; iCost /= 100; } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing Population ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartPopCost(bool bAdd, CvCity* pCity) const { if (0 == getNumCities()) { return -1; } int iCost = (getGrowthThreshold(1) * GC.getDefineINT("ADVANCED_START_POPULATION_COST")) / 100; if (NULL != pCity) { if (pCity->getOwnerINLINE() != getID()) { return -1; } int iPopulation = pCity->getPopulation(); // Need to have Population to remove it if (!bAdd) { --iPopulation; if (iPopulation < GC.getDefineINT("INITIAL_CITY_POPULATION") + GC.getEraInfo(GC.getGameINLINE().getStartEra()).getFreePopulation()) { return -1; } } iCost = (getGrowthThreshold(iPopulation) * GC.getDefineINT("ADVANCED_START_POPULATION_COST")) / 100; // Increase cost if the XML defines that additional Pop will cost more if (0 != GC.getDefineINT("ADVANCED_START_POPULATION_COST_INCREASE")) { --iPopulation; if (iPopulation > 0) { iCost *= 100 + GC.getDefineINT("ADVANCED_START_POPULATION_COST_INCREASE") * iPopulation; iCost /= 100; } } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing Culture ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartCultureCost(bool bAdd, CvCity* pCity) const { if (0 == getNumCities()) { return -1; } int iCost = GC.getDefineINT("ADVANCED_START_CULTURE_COST"); if (iCost < 0) { return -1; } if (NULL != pCity) { if (pCity->getOwnerINLINE() != getID()) { return -1; } // Need to have enough culture to remove it if (!bAdd) { if (pCity->getCultureLevel() <= 0) { return -1; } } int iCulture; if (bAdd) { iCulture = CvCity::getCultureThreshold((CultureLevelTypes)(pCity->getCultureLevel() + 1)) - pCity->getCulture(getID()); } else { iCulture = pCity->getCulture(getID()) - CvCity::getCultureThreshold((CultureLevelTypes)(pCity->getCultureLevel() - 1)); } iCost *= iCulture; iCost /= std::max(1, GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getHurryPercent()); } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing a Building from a city ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartBuildingCost(BuildingTypes eBuilding, bool bAdd, CvCity* pCity) const { if (0 == getNumCities()) { return -1; } int iNumBuildingType = 0; int iCost = (getProductionNeeded(eBuilding) * GC.getBuildingInfo(eBuilding).getAdvancedStartCost()) / 100; if (iCost < 0) { return -1; } if (GC.getBuildingInfo(eBuilding).getFreeStartEra() != NO_ERA && GC.getGameINLINE().getStartEra() >= GC.getBuildingInfo(eBuilding).getFreeStartEra()) { // you get this building for free return -1; } if (NULL == pCity) { if (bAdd) { bool bValid = false; int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->canConstruct(eBuilding)) { bValid = true; break; } } if (!bValid) { return -1; } } } if (NULL != pCity) { if (pCity->getOwnerINLINE() != getID()) { return -1; } iCost *= 100; iCost /= std::max(1, 100 + pCity->getProductionModifier(eBuilding)); if (bAdd) { if (!pCity->canConstruct(eBuilding, true, false, false)) { return -1; } } else { if (pCity->getNumRealBuilding(eBuilding) <= 0) { return -1; } // Check other buildings in this city and make sure none of them require this one // Loop through Buildings to see which are present for (int iBuildingLoop = 0; iBuildingLoop < GC.getNumBuildingInfos(); iBuildingLoop++) { BuildingTypes eBuildingLoop = (BuildingTypes) iBuildingLoop; if (pCity->getNumBuilding(eBuildingLoop) > 0) { // Loop through present Building's requirements for (int iBuildingClassPrereqLoop = 0; iBuildingClassPrereqLoop < GC.getNumBuildingClassInfos(); iBuildingClassPrereqLoop++) { if (GC.getBuildingInfo(eBuildingLoop).isBuildingClassNeededInCity(iBuildingClassPrereqLoop)) { if ((BuildingTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iBuildingClassPrereqLoop)) == eBuilding) { return -1; } } } } } } } // Increase cost if the XML defines that additional Buildings will cost more if (0 != GC.getBuildingInfo(eBuilding).getAdvancedStartCostIncrease()) { iNumBuildingType = countNumBuildings(eBuilding); if (!bAdd) { --iNumBuildingType; } if (iNumBuildingType > 0) { iCost *= 100 + GC.getBuildingInfo(eBuilding).getAdvancedStartCostIncrease() * std::max(0, iNumBuildingType - getNumCities()); iCost /= 100; } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing Route ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartRouteCost(RouteTypes eRoute, bool bAdd, CvPlot* pPlot) const { if (0 == getNumCities()) { return -1; } if (eRoute == NO_ROUTE) { return -1; } int iNumRoutes = 0; int iCost = GC.getRouteInfo(eRoute).getAdvancedStartCost(); // This denotes cities may not be purchased through Advanced Start if (iCost < 0) { return -1; } iCost *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getBuildPercent(); iCost /= 100; // No invalid plots! if (pPlot != NULL) { if (pPlot->isCity()) { return -1; } if (bAdd) { if (pPlot->isImpassable() || pPlot->isWater()) { return -1; } // Can't place twice if (pPlot->getRouteType() == eRoute) { return -1; } } else { // Need Route to remove it if (pPlot->getRouteType() != eRoute) { return -1; } } // Must be owned by me if (pPlot->getOwnerINLINE() != getID()) { return -1; } } // Tech requirement for (int iBuildLoop = 0; iBuildLoop < GC.getNumBuildInfos(); iBuildLoop++) { if (GC.getBuildInfo((BuildTypes) iBuildLoop).getRoute() == eRoute) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)GC.getBuildInfo((BuildTypes) iBuildLoop).getTechPrereq()))) { return -1; } } } // Increase cost if the XML defines that additional units will cost more if (0 != GC.getRouteInfo(eRoute).getAdvancedStartCostIncrease()) { int iPlotLoop = 0; CvPlot* pPlot; for (iPlotLoop = 0; iPlotLoop < GC.getMapINLINE().numPlots(); iPlotLoop++) { pPlot = GC.getMapINLINE().plotByIndex(iPlotLoop); if (pPlot->getRouteType() == eRoute) { ++iNumRoutes; } } if (!bAdd) { --iNumRoutes; } if (iNumRoutes > 0) { iCost *= 100 + GC.getRouteInfo(eRoute).getAdvancedStartCostIncrease() * iNumRoutes; iCost /= 100; } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing Improvement ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartImprovementCost(ImprovementTypes eImprovement, bool bAdd, CvPlot* pPlot) const { if (eImprovement == NO_IMPROVEMENT) { return -1; } if (0 == getNumCities()) { return -1; } int iNumImprovements = 0; int iCost = GC.getImprovementInfo(eImprovement).getAdvancedStartCost(); // This denotes cities may not be purchased through Advanced Start if (iCost < 0) { return -1; } iCost *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getBuildPercent(); iCost /= 100; // Can this Improvement be on our plot? if (pPlot != NULL) { if (bAdd) { // Valid Plot if (!pPlot->canHaveImprovement(eImprovement, getTeam(), false)) { return -1; } bool bValid = false; for (int iI = 0; iI < GC.getNumBuildInfos(); ++iI) { CvBuildInfo& kBuild = GC.getBuildInfo((BuildTypes)iI); ImprovementTypes eLoopImprovement = ((ImprovementTypes)(kBuild.getImprovement())); if (eImprovement == eLoopImprovement && canBuild(pPlot, (BuildTypes)iI)) { bValid = true; FeatureTypes eFeature = pPlot->getFeatureType(); if (NO_FEATURE != eFeature && kBuild.isFeatureRemove(eFeature)) { iCost += GC.getFeatureInfo(eFeature).getAdvancedStartRemoveCost(); } break; } } if (!bValid) { return -1; } // Can't place twice if (pPlot->getImprovementType() == eImprovement) { return -1; } } else { // Need this improvement in order to remove it if (pPlot->getImprovementType() != eImprovement) { return -1; } } // Must be owned by me if (pPlot->getOwnerINLINE() != getID()) { return -1; } } // Tech requirement for (int iBuildLoop = 0; iBuildLoop < GC.getNumBuildInfos(); iBuildLoop++) { if (GC.getBuildInfo((BuildTypes) iBuildLoop).getImprovement() == eImprovement) { if (!(GET_TEAM(getTeam()).isHasTech((TechTypes)GC.getBuildInfo((BuildTypes) iBuildLoop).getTechPrereq()))) { return -1; } } } // Increase cost if the XML defines that additional units will cost more if (0 != GC.getImprovementInfo(eImprovement).getAdvancedStartCostIncrease()) { int iPlotLoop = 0; CvPlot* pPlot; for (iPlotLoop = 0; iPlotLoop < GC.getMapINLINE().numPlots(); iPlotLoop++) { pPlot = GC.getMapINLINE().plotByIndex(iPlotLoop); if (pPlot->getImprovementType() == eImprovement) { ++iNumImprovements; } } if (!bAdd) { --iNumImprovements; } if (iNumImprovements > 0) { iCost *= 100 + GC.getImprovementInfo(eImprovement).getAdvancedStartCostIncrease() * iNumImprovements; iCost /= 100; } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing Tech ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartTechCost(TechTypes eTech, bool bAdd) const { if (eTech == NO_TECH) { return -1; } if (0 == getNumCities()) { return -1; } int iNumTechs = 0; int iCost = (GET_TEAM(getTeam()).getResearchCost(eTech) * GC.getTechInfo(eTech).getAdvancedStartCost()) / 100; if (iCost < 0) { return -1; } if (bAdd) { if (!canResearch(eTech, false)) { return -1; } } else if (!bAdd) { if (!GET_TEAM(getTeam()).isHasTech(eTech)) { return -1; } // Search through all techs to see if any of the currently owned ones requires this tech for (int iTechLoop = 0; iTechLoop < GC.getNumTechInfos(); iTechLoop++) { TechTypes eTechLoop = (TechTypes) iTechLoop; if (GET_TEAM(getTeam()).isHasTech(eTechLoop)) { int iPrereqLoop; // Or Prereqs for (iPrereqLoop = 0; iPrereqLoop < GC.getNUM_OR_TECH_PREREQS(); iPrereqLoop++) { if (GC.getTechInfo(eTechLoop).getPrereqOrTechs(iPrereqLoop) == eTech) { return -1; } } // And Prereqs for (iPrereqLoop = 0; iPrereqLoop < GC.getNUM_AND_TECH_PREREQS(); iPrereqLoop++) { if (GC.getTechInfo(eTechLoop).getPrereqAndTechs(iPrereqLoop) == eTech) { return -1; } } } } // If player has placed anything on the map which uses this tech then you cannot remove it int iLoop; // Units CvUnit* pLoopUnit; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->getUnitInfo().getPrereqAndTech() == eTech) { return -1; } for (int iI = 0; iI < GC.getNUM_UNIT_AND_TECH_PREREQS(); iI++) { if (pLoopUnit->getUnitInfo().getPrereqAndTechs(iI) == eTech) { return -1; } } } // Cities CvCity* pLoopCity; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { // All Buildings for (int iBuildingLoop = 0; iBuildingLoop < GC.getNumBuildingInfos(); iBuildingLoop++) { BuildingTypes eBuilding = (BuildingTypes) iBuildingLoop; if (pLoopCity->getNumRealBuilding(eBuilding) > 0) { if (GC.getBuildingInfo(eBuilding).getPrereqAndTech() == eTech) { return -1; } for (int iI = 0; iI < GC.getNUM_BUILDING_AND_TECH_PREREQS(); iI++) { if (GC.getBuildingInfo(eBuilding).getPrereqAndTechs(iI) == eTech) { return -1; } } } } } } // Increase cost if the XML defines that additional units will cost more if (0 != GC.getTechInfo(eTech).getAdvancedStartCostIncrease()) { for (int iTechLoop = 0; iTechLoop < GC.getNumTechInfos(); iTechLoop++) { if (GET_TEAM(getTeam()).isHasTech((TechTypes) iTechLoop)) { ++iNumTechs; } } if (!bAdd) { --iNumTechs; } if (iNumTechs > 0) { iCost *= 100 + GC.getTechInfo(eTech).getAdvancedStartCostIncrease() * iNumTechs; iCost /= 100; } } return iCost; } ///////////////////////////////////////////////////////////////////////////////////////////// // Adding or removing Visibility ///////////////////////////////////////////////////////////////////////////////////////////// int CvPlayer::getAdvancedStartVisibilityCost(bool bAdd, CvPlot* pPlot) const { if (0 == getNumCities()) { return -1; } int iNumVisiblePlots = 0; int iCost = GC.getDefineINT("ADVANCED_START_VISIBILITY_COST"); // This denotes Visibility may not be purchased through Advanced Start if (iCost == -1) { return -1; } // Valid Plot? if (pPlot != NULL) { if (bAdd) { if (pPlot->isRevealed(getTeam(), false)) { return -1; } if (!pPlot->isAdjacentRevealed(getTeam())) { return -1; } } else { if (!pPlot->isRevealed(getTeam(), false)) { return -1; } } } // Increase cost if the XML defines that additional units will cost more if (0 != GC.getDefineINT("ADVANCED_START_VISIBILITY_COST_INCREASE")) { int iPlotLoop = 0; CvPlot* pPlot; for (iPlotLoop = 0; iPlotLoop < GC.getMapINLINE().numPlots(); iPlotLoop++) { pPlot = GC.getMapINLINE().plotByIndex(iPlotLoop); if (pPlot->isRevealed(getTeam(), false)) { ++iNumVisiblePlots; } } if (!bAdd) { --iNumVisiblePlots; } if (iNumVisiblePlots > 0) { iCost *= 100 + GC.getDefineINT("ADVANCED_START_VISIBILITY_COST_INCREASE") * iNumVisiblePlots; iCost /= 100; } } return iCost; } void CvPlayer::doWarnings() { CvCity* pNearestCity; CvPlot* pLoopPlot; CvUnit* pLoopUnit; wchar szBuffer[1024]; int iMaxCount; int iI; //update enemy unit in your territory glow int iLoop; for(pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { //update glow gDLL->getEntityIFace()->updateEnemyGlow(pLoopUnit->getUnitEntity()); } // BUG - Ignore Harmless Barbarians - start bool bCheckBarbarians = false; bool bCheckBarbariansInitialized = !isHuman(); // BUG - Ignore Harmless Barbarians - end //update enemy units close to your territory iMaxCount = range(((getNumCities() + 4) / 7), 2, 5); for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { if (iMaxCount == 0) { break; } pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if (pLoopPlot->isAdjacentPlayer(getID())) { if (!(pLoopPlot->isCity())) { if (pLoopPlot->isVisible(getTeam(), false)) { CvUnit *pUnit = pLoopPlot->getVisibleEnemyDefender(getID()); if (pUnit != NULL) { if (!pUnit->isAnimal()) { // BUG - Ignore Harmless Barbarians - start if (!bCheckBarbariansInitialized && GC.getGameINLINE().getElapsedGameTurns() > 0) { bCheckBarbarians = getBugOptionBOOL("Actions__IgnoreHarmlessBarbarians", true, "BUG_IGNORE_HARMLESS_BARBARIANS"); bCheckBarbariansInitialized = true; } if (bCheckBarbarians && pUnit->isBarbarian() && pUnit->getDomainType() == DOMAIN_LAND) { CvArea* pArea = pUnit->area(); if (pArea && pArea->isBorderObstacle(getTeam())) { // don't show warning for land-based barbarians when player has Great Wall continue; } } // BUG - Ignore Harmless Barbarians - end pNearestCity = GC.getMapINLINE().findCity(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), getID(), NO_TEAM, !(pLoopPlot->isWater())); if (pNearestCity != NULL) { swprintf(szBuffer, gDLL->getText("TXT_KEY_MISC_ENEMY_TROOPS_SPOTTED", pNearestCity->getNameKey()).GetCString()); gDLL->getInterfaceIFace()->addMessage(getID(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_ENEMY_TROOPS", MESSAGE_TYPE_INFO, pUnit->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), true, true); iMaxCount--; } } } } } } } } void CvPlayer::verifyGoldCommercePercent() { while ((getGold() + calculateGoldRate()) < 0) { changeCommercePercent(COMMERCE_GOLD, GC.getDefineINT("COMMERCE_PERCENT_CHANGE_INCREMENTS")); if (getCommercePercent(COMMERCE_GOLD) == 100) { break; } } } /********************************************************************************/ /* New Civic AI 19.08.2010 Fuyu */ /********************************************************************************/ //Fuyu bLimited void CvPlayer::processCivics(CivicTypes eCivic, int iChange, bool bLimited) { int iI, iJ; if (bLimited) { CvCivicInfo& kCivic = GC.getCivicInfo(eCivic); //+: doesn't change values of other civics but maybe should //changeGreatPeopleRateModifier(kCivic.getGreatPeopleRateModifier() * iChange); //changeGreatGeneralRateModifier(kCivic.getGreatGeneralRateModifier() * iChange); //changeDomesticGreatGeneralRateModifier(kCivic.getDomesticGreatGeneralRateModifier() * iChange); //changeStateReligionGreatPeopleRateModifier(kCivic.getStateReligionGreatPeopleRateModifier() * iChange); //changeDistanceMaintenanceModifier(kCivic.getDistanceMaintenanceModifier() * iChange); //changeNumCitiesMaintenanceModifier(kCivic.getNumCitiesMaintenanceModifier() * iChange); changeCorporationMaintenanceModifier(kCivic.getCorporationMaintenanceModifier() * iChange, bLimited); changeExtraHealth(kCivic.getExtraHealth() * iChange, bLimited); //changeFreeExperience(kCivic.getFreeExperience() * iChange); //changeWorkerSpeedModifier(kCivic.getWorkerSpeedModifier() * iChange); //changeImprovementUpgradeRateModifier(kCivic.getImprovementUpgradeRateModifier() * iChange); //changeMilitaryProductionModifier(kCivic.getMilitaryProductionModifier() * iChange); //changeBaseFreeUnits(kCivic.getBaseFreeUnits() * iChange); //changeBaseFreeMilitaryUnits(kCivic.getBaseFreeMilitaryUnits() * iChange); //changeFreeUnitsPopulationPercent(kCivic.getFreeUnitsPopulationPercent() * iChange); //changeFreeMilitaryUnitsPopulationPercent(kCivic.getFreeMilitaryUnitsPopulationPercent() * iChange); //changeGoldPerUnit(kCivic.getGoldPerUnit() * iChange); //changeGoldPerMilitaryUnit(kCivic.getGoldPerMilitaryUnit() * iChange); changeHappyPerMilitaryUnit(kCivic.getHappyPerMilitaryUnit() * iChange, bLimited); changeMilitaryFoodProductionCount(((kCivic.isMilitaryFoodProduction()) ? iChange : 0), bLimited); //changeMaxConscript(getWorldSizeMaxConscript(eCivic) * iChange); changeNoUnhealthyPopulationCount(((kCivic.isNoUnhealthyPopulation()) ? iChange : 0), bLimited); changeBuildingOnlyHealthyCount(((kCivic.isBuildingOnlyHealthy()) ? iChange : 0), bLimited); changeLargestCityHappiness((kCivic.getLargestCityHappiness() * iChange), bLimited); if (getWarWearinessPercentAnger() != 0) { changeWarWearinessModifier((kCivic.getWarWearinessModifier() * iChange), bLimited); } //changeFreeSpecialist(kCivic.getFreeSpecialist() * iChange); //changeTradeRoutes(kCivic.getTradeRoutes() * iChange); changeNoForeignTradeCount(kCivic.isNoForeignTrade() * iChange, bLimited); changeNoCorporationsCount(kCivic.isNoCorporations() * iChange, bLimited); changeNoForeignCorporationsCount(kCivic.isNoForeignCorporations() * iChange, bLimited); changeStateReligionCount(((kCivic.isStateReligion()) ? iChange : 0), bLimited); changeNoNonStateReligionSpreadCount((kCivic.isNoNonStateReligionSpread()) ? iChange : 0); changeStateReligionHappiness(kCivic.getStateReligionHappiness() * iChange, bLimited); changeNonStateReligionHappiness(kCivic.getNonStateReligionHappiness() * iChange, bLimited); //changeStateReligionUnitProductionModifier(kCivic.getStateReligionUnitProductionModifier() * iChange); //changeStateReligionBuildingProductionModifier(kCivic.getStateReligionBuildingProductionModifier() * iChange); //changeStateReligionFreeExperience(kCivic.getStateReligionFreeExperience() * iChange); //changeExpInBorderModifier(kCivic.getExpInBorderModifier() * iChange); //for (iI = 0; iI < NUM_YIELD_TYPES; iI++) //{ // changeYieldRateModifier(((YieldTypes)iI), (kCivic.getYieldModifier(iI) * iChange)); // changeCapitalYieldRateModifier(((YieldTypes)iI), (kCivic.getCapitalYieldModifier(iI) * iChange)); // changeTradeYieldModifier(((YieldTypes)iI), (kCivic.getTradeYieldModifier(iI) * iChange)); //} //for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) //{ // changeCommerceRateModifier(((CommerceTypes)iI), (kCivic.getCommerceModifier(iI) * iChange)); // changeCapitalCommerceRateModifier(((CommerceTypes)iI), (kCivic.getCapitalCommerceModifier(iI) * iChange)); // changeSpecialistExtraCommerce(((CommerceTypes)iI), (kCivic.getSpecialistExtraCommerce(iI) * iChange)); //} if (kCivic.isAnyBuildingHappinessChange() || kCivic.isAnyBuildingHealthChange()) { for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++) { BuildingTypes eOurBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iI); if (NO_BUILDING != eOurBuilding) { changeExtraBuildingHappiness(eOurBuilding, (kCivic.getBuildingHappinessChanges(iI) * iChange), bLimited); changeExtraBuildingHealth(eOurBuilding, (kCivic.getBuildingHealthChanges(iI) * iChange), bLimited); } } } if (kCivic.isAnyFeatureHappinessChange()) { for (iI = 0; iI < GC.getNumFeatureInfos(); iI++) { changeFeatureHappiness(((FeatureTypes)iI), (kCivic.getFeatureHappinessChanges(iI) * iChange), bLimited); } } for (iI = 0; iI < GC.getNumHurryInfos(); iI++) { changeHurryCount(((HurryTypes)iI), ((kCivic.isHurry(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumSpecialBuildingInfos(); iI++) { changeSpecialBuildingNotRequiredCount(((SpecialBuildingTypes)iI), ((kCivic.isSpecialBuildingNotRequired(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumSpecialistInfos(); iI++) { changeSpecialistValidCount(((SpecialistTypes)iI), ((kCivic.isSpecialistValid(iI)) ? iChange : 0), bLimited); } //for (iI = 0; iI < GC.getNumImprovementInfos(); iI++) //{ // for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) // { // changeImprovementYieldChange(((ImprovementTypes)iI), ((YieldTypes)iJ), (kCivic.getImprovementYieldChanges(iI, iJ) * iChange)); // } //} } else { //original code: changeGreatPeopleRateModifier(GC.getCivicInfo(eCivic).getGreatPeopleRateModifier() * iChange); changeGreatGeneralRateModifier(GC.getCivicInfo(eCivic).getGreatGeneralRateModifier() * iChange); changeDomesticGreatGeneralRateModifier(GC.getCivicInfo(eCivic).getDomesticGreatGeneralRateModifier() * iChange); changeStateReligionGreatPeopleRateModifier(GC.getCivicInfo(eCivic).getStateReligionGreatPeopleRateModifier() * iChange); changeDistanceMaintenanceModifier(GC.getCivicInfo(eCivic).getDistanceMaintenanceModifier() * iChange); changeNumCitiesMaintenanceModifier(GC.getCivicInfo(eCivic).getNumCitiesMaintenanceModifier() * iChange); changeCorporationMaintenanceModifier(GC.getCivicInfo(eCivic).getCorporationMaintenanceModifier() * iChange); changeExtraHealth(GC.getCivicInfo(eCivic).getExtraHealth() * iChange); changeFreeExperience(GC.getCivicInfo(eCivic).getFreeExperience() * iChange); changeWorkerSpeedModifier(GC.getCivicInfo(eCivic).getWorkerSpeedModifier() * iChange); changeImprovementUpgradeRateModifier(GC.getCivicInfo(eCivic).getImprovementUpgradeRateModifier() * iChange); changeMilitaryProductionModifier(GC.getCivicInfo(eCivic).getMilitaryProductionModifier() * iChange); changeBaseFreeUnits(GC.getCivicInfo(eCivic).getBaseFreeUnits() * iChange); changeBaseFreeMilitaryUnits(GC.getCivicInfo(eCivic).getBaseFreeMilitaryUnits() * iChange); changeFreeUnitsPopulationPercent(GC.getCivicInfo(eCivic).getFreeUnitsPopulationPercent() * iChange); changeFreeMilitaryUnitsPopulationPercent(GC.getCivicInfo(eCivic).getFreeMilitaryUnitsPopulationPercent() * iChange); changeGoldPerUnit(GC.getCivicInfo(eCivic).getGoldPerUnit() * iChange); changeGoldPerMilitaryUnit(GC.getCivicInfo(eCivic).getGoldPerMilitaryUnit() * iChange); changeHappyPerMilitaryUnit(GC.getCivicInfo(eCivic).getHappyPerMilitaryUnit() * iChange); changeMilitaryFoodProductionCount((GC.getCivicInfo(eCivic).isMilitaryFoodProduction()) ? iChange : 0); changeMaxConscript(getWorldSizeMaxConscript(eCivic) * iChange); changeNoUnhealthyPopulationCount((GC.getCivicInfo(eCivic).isNoUnhealthyPopulation()) ? iChange : 0); changeBuildingOnlyHealthyCount((GC.getCivicInfo(eCivic).isBuildingOnlyHealthy()) ? iChange : 0); changeLargestCityHappiness(GC.getCivicInfo(eCivic).getLargestCityHappiness() * iChange); changeWarWearinessModifier(GC.getCivicInfo(eCivic).getWarWearinessModifier() * iChange); changeFreeSpecialist(GC.getCivicInfo(eCivic).getFreeSpecialist() * iChange); changeTradeRoutes(GC.getCivicInfo(eCivic).getTradeRoutes() * iChange); changeNoForeignTradeCount(GC.getCivicInfo(eCivic).isNoForeignTrade() * iChange); changeNoCorporationsCount(GC.getCivicInfo(eCivic).isNoCorporations() * iChange); changeNoForeignCorporationsCount(GC.getCivicInfo(eCivic).isNoForeignCorporations() * iChange); changeStateReligionCount((GC.getCivicInfo(eCivic).isStateReligion()) ? iChange : 0); changeNoNonStateReligionSpreadCount((GC.getCivicInfo(eCivic).isNoNonStateReligionSpread()) ? iChange : 0); changeStateReligionHappiness(GC.getCivicInfo(eCivic).getStateReligionHappiness() * iChange); changeNonStateReligionHappiness(GC.getCivicInfo(eCivic).getNonStateReligionHappiness() * iChange); changeStateReligionUnitProductionModifier(GC.getCivicInfo(eCivic).getStateReligionUnitProductionModifier() * iChange); changeStateReligionBuildingProductionModifier(GC.getCivicInfo(eCivic).getStateReligionBuildingProductionModifier() * iChange); changeStateReligionFreeExperience(GC.getCivicInfo(eCivic).getStateReligionFreeExperience() * iChange); changeExpInBorderModifier(GC.getCivicInfo(eCivic).getExpInBorderModifier() * iChange); for (iI = 0; iI < NUM_YIELD_TYPES; iI++) { changeYieldRateModifier(((YieldTypes)iI), (GC.getCivicInfo(eCivic).getYieldModifier(iI) * iChange)); changeCapitalYieldRateModifier(((YieldTypes)iI), (GC.getCivicInfo(eCivic).getCapitalYieldModifier(iI) * iChange)); changeTradeYieldModifier(((YieldTypes)iI), (GC.getCivicInfo(eCivic).getTradeYieldModifier(iI) * iChange)); } for (iI = 0; iI < NUM_COMMERCE_TYPES; iI++) { changeCommerceRateModifier(((CommerceTypes)iI), (GC.getCivicInfo(eCivic).getCommerceModifier(iI) * iChange)); changeCapitalCommerceRateModifier(((CommerceTypes)iI), (GC.getCivicInfo(eCivic).getCapitalCommerceModifier(iI) * iChange)); changeSpecialistExtraCommerce(((CommerceTypes)iI), (GC.getCivicInfo(eCivic).getSpecialistExtraCommerce(iI) * iChange)); } for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++) { BuildingTypes eOurBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iI); if (NO_BUILDING != eOurBuilding) { changeExtraBuildingHappiness(eOurBuilding, (GC.getCivicInfo(eCivic).getBuildingHappinessChanges(iI) * iChange)); changeExtraBuildingHealth(eOurBuilding, (GC.getCivicInfo(eCivic).getBuildingHealthChanges(iI) * iChange)); } } for (iI = 0; iI < GC.getNumFeatureInfos(); iI++) { changeFeatureHappiness(((FeatureTypes)iI), (GC.getCivicInfo(eCivic).getFeatureHappinessChanges(iI) * iChange)); } for (iI = 0; iI < GC.getNumHurryInfos(); iI++) { changeHurryCount(((HurryTypes)iI), ((GC.getCivicInfo(eCivic).isHurry(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumSpecialBuildingInfos(); iI++) { changeSpecialBuildingNotRequiredCount(((SpecialBuildingTypes)iI), ((GC.getCivicInfo(eCivic).isSpecialBuildingNotRequired(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumSpecialistInfos(); iI++) { changeSpecialistValidCount(((SpecialistTypes)iI), ((GC.getCivicInfo(eCivic).isSpecialistValid(iI)) ? iChange : 0)); } for (iI = 0; iI < GC.getNumImprovementInfos(); iI++) { for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++) { changeImprovementYieldChange(((ImprovementTypes)iI), ((YieldTypes)iJ), (GC.getCivicInfo(eCivic).getImprovementYieldChanges(iI, iJ) * iChange)); } } } } /********************************************************************************/ /* New Civic AI END */ /********************************************************************************/ void CvPlayer::showMissedMessages() { CvMessageQueue::iterator it = m_listGameMessages.begin(); while (it != m_listGameMessages.end()) { CvTalkingHeadMessage& msg = *it; if (!msg.getShown()) { msg.setShown(true); gDLL->getInterfaceIFace()->showMessage(msg); } ++it; } } bool CvPlayer::isPbemNewTurn() const { return m_bPbemNewTurn; } void CvPlayer::setPbemNewTurn(bool bNew) { m_bPbemNewTurn = bNew; } // // read object from a stream // used during load // void CvPlayer::read(FDataStreamBase* pStream) { int iI; // Init data before load reset(); uint uiFlag=0; pStream->Read(&uiFlag); // flags for expansion pStream->Read(&m_iStartingX); pStream->Read(&m_iStartingY); pStream->Read(&m_iTotalPopulation); pStream->Read(&m_iTotalLand); pStream->Read(&m_iTotalLandScored); pStream->Read(&m_iGold); pStream->Read(&m_iGoldPerTurn); pStream->Read(&m_iAdvancedStartPoints); pStream->Read(&m_iGoldenAgeTurns); pStream->Read(&m_iNumUnitGoldenAges); pStream->Read(&m_iStrikeTurns); pStream->Read(&m_iAnarchyTurns); pStream->Read(&m_iMaxAnarchyTurns); pStream->Read(&m_iAnarchyModifier); pStream->Read(&m_iGoldenAgeModifier); pStream->Read(&m_iGlobalHurryModifier); pStream->Read(&m_iGreatPeopleCreated); pStream->Read(&m_iGreatGeneralsCreated); pStream->Read(&m_iGreatPeopleThresholdModifier); pStream->Read(&m_iGreatGeneralsThresholdModifier); pStream->Read(&m_iGreatPeopleRateModifier); pStream->Read(&m_iGreatGeneralRateModifier); pStream->Read(&m_iDomesticGreatGeneralRateModifier); pStream->Read(&m_iStateReligionGreatPeopleRateModifier); pStream->Read(&m_iMaxGlobalBuildingProductionModifier); pStream->Read(&m_iMaxTeamBuildingProductionModifier); pStream->Read(&m_iMaxPlayerBuildingProductionModifier); pStream->Read(&m_iFreeExperience); pStream->Read(&m_iFeatureProductionModifier); pStream->Read(&m_iWorkerSpeedModifier); pStream->Read(&m_iImprovementUpgradeRateModifier); pStream->Read(&m_iMilitaryProductionModifier); pStream->Read(&m_iSpaceProductionModifier); pStream->Read(&m_iCityDefenseModifier); pStream->Read(&m_iNumNukeUnits); pStream->Read(&m_iNumOutsideUnits); pStream->Read(&m_iBaseFreeUnits); pStream->Read(&m_iBaseFreeMilitaryUnits); pStream->Read(&m_iFreeUnitsPopulationPercent); pStream->Read(&m_iFreeMilitaryUnitsPopulationPercent); pStream->Read(&m_iGoldPerUnit); pStream->Read(&m_iGoldPerMilitaryUnit); pStream->Read(&m_iExtraUnitCost); pStream->Read(&m_iNumMilitaryUnits); pStream->Read(&m_iHappyPerMilitaryUnit); pStream->Read(&m_iMilitaryFoodProductionCount); pStream->Read(&m_iConscriptCount); pStream->Read(&m_iMaxConscript); pStream->Read(&m_iHighestUnitLevel); pStream->Read(&m_iOverflowResearch); pStream->Read(&m_iNoUnhealthyPopulationCount); pStream->Read(&m_iExpInBorderModifier); pStream->Read(&m_iBuildingOnlyHealthyCount); pStream->Read(&m_iDistanceMaintenanceModifier); pStream->Read(&m_iNumCitiesMaintenanceModifier); pStream->Read(&m_iCorporationMaintenanceModifier); pStream->Read(&m_iTotalMaintenance); pStream->Read(&m_iUpkeepModifier); pStream->Read(&m_iLevelExperienceModifier); pStream->Read(&m_iExtraHealth); pStream->Read(&m_iBuildingGoodHealth); pStream->Read(&m_iBuildingBadHealth); pStream->Read(&m_iExtraHappiness); pStream->Read(&m_iBuildingHappiness); pStream->Read(&m_iLargestCityHappiness); pStream->Read(&m_iWarWearinessPercentAnger); pStream->Read(&m_iWarWearinessModifier); pStream->Read(&m_iFreeSpecialist); pStream->Read(&m_iNoForeignTradeCount); pStream->Read(&m_iNoCorporationsCount); pStream->Read(&m_iNoForeignCorporationsCount); pStream->Read(&m_iCoastalTradeRoutes); pStream->Read(&m_iTradeRoutes); pStream->Read(&m_iRevolutionTimer); pStream->Read(&m_iConversionTimer); pStream->Read(&m_iStateReligionCount); pStream->Read(&m_iNoNonStateReligionSpreadCount); pStream->Read(&m_iStateReligionHappiness); pStream->Read(&m_iNonStateReligionHappiness); pStream->Read(&m_iStateReligionUnitProductionModifier); pStream->Read(&m_iStateReligionBuildingProductionModifier); pStream->Read(&m_iStateReligionFreeExperience); pStream->Read(&m_iCapitalCityID); pStream->Read(&m_iCitiesLost); pStream->Read(&m_iWinsVsBarbs); pStream->Read(&m_iAssets); pStream->Read(&m_iPower); pStream->Read(&m_iPopulationScore); pStream->Read(&m_iLandScore); pStream->Read(&m_iWondersScore); pStream->Read(&m_iTechScore); pStream->Read(&m_iCombatExperience); pStream->Read(&m_bAlive); pStream->Read(&m_bEverAlive); pStream->Read(&m_bTurnActive); pStream->Read(&m_bAutoMoves); pStream->Read(&m_bEndTurn); pStream->Read(&m_bPbemNewTurn); pStream->Read(&m_bExtendedGame); pStream->Read(&m_bFoundedFirstCity); pStream->Read(&m_bStrike); pStream->Read((int*)&m_eID); pStream->Read((int*)&m_ePersonalityType); pStream->Read((int*)&m_eCurrentEra); pStream->Read((int*)&m_eLastStateReligion); pStream->Read((int*)&m_eParent); updateTeamType(); //m_eTeamType not saved updateHuman(); pStream->Read(NUM_YIELD_TYPES, m_aiSeaPlotYield); pStream->Read(NUM_YIELD_TYPES, m_aiYieldRateModifier); pStream->Read(NUM_YIELD_TYPES, m_aiCapitalYieldRateModifier); pStream->Read(NUM_YIELD_TYPES, m_aiExtraYieldThreshold); pStream->Read(NUM_YIELD_TYPES, m_aiTradeYieldModifier); pStream->Read(NUM_COMMERCE_TYPES, m_aiFreeCityCommerce); pStream->Read(NUM_COMMERCE_TYPES, m_aiCommercePercent); pStream->Read(NUM_COMMERCE_TYPES, m_aiCommerceRate); pStream->Read(NUM_COMMERCE_TYPES, m_aiCommerceRateModifier); pStream->Read(NUM_COMMERCE_TYPES, m_aiCapitalCommerceRateModifier); pStream->Read(NUM_COMMERCE_TYPES, m_aiStateReligionBuildingCommerce); pStream->Read(NUM_COMMERCE_TYPES, m_aiSpecialistExtraCommerce); pStream->Read(NUM_COMMERCE_TYPES, m_aiCommerceFlexibleCount); pStream->Read(MAX_PLAYERS, m_aiGoldPerTurnByPlayer); pStream->Read(MAX_TEAMS, m_aiEspionageSpendingWeightAgainstTeam); pStream->Read(NUM_FEAT_TYPES, m_abFeatAccomplished); pStream->Read(NUM_PLAYEROPTION_TYPES, m_abOptions); pStream->ReadString(m_szScriptData); FAssertMsg((0 < GC.getNumBonusInfos()), "GC.getNumBonusInfos() is not greater than zero but it is expected to be in CvPlayer::read"); pStream->Read(GC.getNumBonusInfos(), m_paiBonusExport); pStream->Read(GC.getNumBonusInfos(), m_paiBonusImport); pStream->Read(GC.getNumImprovementInfos(), m_paiImprovementCount); pStream->Read(GC.getNumBuildingInfos(), m_paiFreeBuildingCount); pStream->Read(GC.getNumBuildingInfos(), m_paiExtraBuildingHappiness); pStream->Read(GC.getNumBuildingInfos(), m_paiExtraBuildingHealth); pStream->Read(GC.getNumFeatureInfos(), m_paiFeatureHappiness); pStream->Read(GC.getNumUnitClassInfos(), m_paiUnitClassCount); pStream->Read(GC.getNumUnitClassInfos(), m_paiUnitClassMaking); pStream->Read(GC.getNumBuildingClassInfos(), m_paiBuildingClassCount); pStream->Read(GC.getNumBuildingClassInfos(), m_paiBuildingClassMaking); pStream->Read(GC.getNumHurryInfos(), m_paiHurryCount); pStream->Read(GC.getNumSpecialBuildingInfos(), m_paiSpecialBuildingNotRequiredCount); pStream->Read(GC.getNumCivicOptionInfos(), m_paiHasCivicOptionCount); pStream->Read(GC.getNumCivicOptionInfos(), m_paiNoCivicUpkeepCount); pStream->Read(GC.getNumReligionInfos(), m_paiHasReligionCount); pStream->Read(GC.getNumCorporationInfos(), m_paiHasCorporationCount); pStream->Read(GC.getNumUpkeepInfos(), m_paiUpkeepCount); pStream->Read(GC.getNumSpecialistInfos(), m_paiSpecialistValidCount); FAssertMsg((0 < GC.getNumTechInfos()), "GC.getNumTechInfos() is not greater than zero but it is expected to be in CvPlayer::read"); pStream->Read(GC.getNumTechInfos(), m_pabResearchingTech); pStream->Read(GC.getNumVoteSourceInfos(), m_pabLoyalMember); for (iI=0;iI<GC.getNumCivicOptionInfos();iI++) { pStream->Read((int*)&m_paeCivics[iI]); } for (iI=0;iI<GC.getNumSpecialistInfos();iI++) { pStream->Read(NUM_YIELD_TYPES, m_ppaaiSpecialistExtraYield[iI]); } for (iI=0;iI<GC.getNumImprovementInfos();iI++) { pStream->Read(NUM_YIELD_TYPES, m_ppaaiImprovementYieldChange[iI]); } m_groupCycle.Read(pStream); m_researchQueue.Read(pStream); { m_cityNames.clear(); CvWString szBuffer; uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { pStream->ReadString(szBuffer); m_cityNames.insertAtEnd(szBuffer); } } ReadStreamableFFreeListTrashArray(m_plotGroups, pStream); ReadStreamableFFreeListTrashArray(m_cities, pStream); ReadStreamableFFreeListTrashArray(m_units, pStream); ReadStreamableFFreeListTrashArray(m_selectionGroups, pStream); ReadStreamableFFreeListTrashArray(m_eventsTriggered, pStream); { CvMessageQueue::_Alloc::size_type iSize; pStream->Read(&iSize); for (CvMessageQueue::_Alloc::size_type i = 0; i < iSize; i++) { CvTalkingHeadMessage message; message.read(*pStream); m_listGameMessages.push_back(message); } } { clearPopups(); CvPopupQueue::_Alloc::size_type iSize; pStream->Read(&iSize); for (CvPopupQueue::_Alloc::size_type i = 0; i < iSize; i++) { CvPopupInfo* pInfo = new CvPopupInfo(); if (NULL != pInfo) { pInfo->read(*pStream); m_listPopups.push_back(pInfo); } } } { clearDiplomacy(); CvDiploQueue::_Alloc::size_type iSize; pStream->Read(&iSize); for (CvDiploQueue::_Alloc::size_type i = 0; i < iSize; i++) { CvDiploParameters* pDiplo = new CvDiploParameters(NO_PLAYER); if (NULL != pDiplo) { pDiplo->read(*pStream); m_listDiplomacy.push_back(pDiplo); } } } { uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapScoreHistory[iTurn] = iScore; } } { m_mapEconomyHistory.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapEconomyHistory[iTurn] = iScore; } } { m_mapIndustryHistory.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapIndustryHistory[iTurn] = iScore; } } { m_mapAgricultureHistory.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapAgricultureHistory[iTurn] = iScore; } } { m_mapPowerHistory.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapPowerHistory[iTurn] = iScore; } } { m_mapCultureHistory.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapCultureHistory[iTurn] = iScore; } } { m_mapEspionageHistory.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTurn; int iScore; pStream->Read(&iTurn); pStream->Read(&iScore); m_mapEspionageHistory[iTurn] = iScore; } } { m_mapEventsOccured.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { EventTriggeredData kData; EventTypes eEvent; pStream->Read((int*)&eEvent); kData.read(pStream); m_mapEventsOccured[eEvent] = kData; } } { m_mapEventCountdown.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { EventTriggeredData kData; EventTypes eEvent; pStream->Read((int*)&eEvent); kData.read(pStream); m_mapEventCountdown[eEvent] = kData; } } { m_aFreeUnitCombatPromotions.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iUnitCombat; int iPromotion; pStream->Read(&iUnitCombat); pStream->Read(&iPromotion); m_aFreeUnitCombatPromotions.push_back(std::make_pair((UnitCombatTypes)iUnitCombat, (PromotionTypes)iPromotion)); } } { m_aFreeUnitClassPromotions.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iUnitClass; int iPromotion; pStream->Read(&iUnitClass); pStream->Read(&iPromotion); m_aFreeUnitClassPromotions.push_back(std::make_pair((UnitClassTypes)iUnitClass, (PromotionTypes)iPromotion)); } } { m_aVote.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iId; PlayerVoteTypes eVote; pStream->Read(&iId); pStream->Read((int*)&eVote); m_aVote.push_back(std::make_pair(iId, eVote)); } } { m_aUnitExtraCosts.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iCost; UnitClassTypes eUnit; pStream->Read((int*)&eUnit); pStream->Read(&iCost); m_aUnitExtraCosts.push_back(std::make_pair(eUnit, iCost)); } } if (uiFlag > 0) { m_triggersFired.clear(); uint iSize; pStream->Read(&iSize); for (uint i = 0; i < iSize; i++) { int iTrigger; pStream->Read(&iTrigger); m_triggersFired.push_back((EventTriggerTypes)iTrigger); } } else { int iNumEventTriggers = std::min(176, GC.getNumEventTriggerInfos()); // yuck, hardcoded number of eventTriggers in the epic game in initial release for (iI=0; iI < iNumEventTriggers; iI++) { bool bTriggered; pStream->Read(&bTriggered); if (bTriggered) { m_triggersFired.push_back((EventTriggerTypes)iI); } } } if (!isBarbarian()) { // Get the NetID from the initialization structure setNetID(gDLL->getAssignedNetworkID(getID())); } pStream->Read(&m_iPopRushHurryCount); pStream->Read(&m_iInflationModifier); } // // save object to a stream // used during save // void CvPlayer::write(FDataStreamBase* pStream) { int iI; uint uiFlag = 1; pStream->Write(uiFlag); // flag for expansion pStream->Write(m_iStartingX); pStream->Write(m_iStartingY); pStream->Write(m_iTotalPopulation); pStream->Write(m_iTotalLand); pStream->Write(m_iTotalLandScored); pStream->Write(m_iGold); pStream->Write(m_iGoldPerTurn); pStream->Write(m_iAdvancedStartPoints); pStream->Write(m_iGoldenAgeTurns); pStream->Write(m_iNumUnitGoldenAges); pStream->Write(m_iStrikeTurns); pStream->Write(m_iAnarchyTurns); pStream->Write(m_iMaxAnarchyTurns); pStream->Write(m_iAnarchyModifier); pStream->Write(m_iGoldenAgeModifier); pStream->Write(m_iGlobalHurryModifier); pStream->Write(m_iGreatPeopleCreated); pStream->Write(m_iGreatGeneralsCreated); pStream->Write(m_iGreatPeopleThresholdModifier); pStream->Write(m_iGreatGeneralsThresholdModifier); pStream->Write(m_iGreatPeopleRateModifier); pStream->Write(m_iGreatGeneralRateModifier); pStream->Write(m_iDomesticGreatGeneralRateModifier); pStream->Write(m_iStateReligionGreatPeopleRateModifier); pStream->Write(m_iMaxGlobalBuildingProductionModifier); pStream->Write(m_iMaxTeamBuildingProductionModifier); pStream->Write(m_iMaxPlayerBuildingProductionModifier); pStream->Write(m_iFreeExperience); pStream->Write(m_iFeatureProductionModifier); pStream->Write(m_iWorkerSpeedModifier); pStream->Write(m_iImprovementUpgradeRateModifier); pStream->Write(m_iMilitaryProductionModifier); pStream->Write(m_iSpaceProductionModifier); pStream->Write(m_iCityDefenseModifier); pStream->Write(m_iNumNukeUnits); pStream->Write(m_iNumOutsideUnits); pStream->Write(m_iBaseFreeUnits); pStream->Write(m_iBaseFreeMilitaryUnits); pStream->Write(m_iFreeUnitsPopulationPercent); pStream->Write(m_iFreeMilitaryUnitsPopulationPercent); pStream->Write(m_iGoldPerUnit); pStream->Write(m_iGoldPerMilitaryUnit); pStream->Write(m_iExtraUnitCost); pStream->Write(m_iNumMilitaryUnits); pStream->Write(m_iHappyPerMilitaryUnit); pStream->Write(m_iMilitaryFoodProductionCount); pStream->Write(m_iConscriptCount); pStream->Write(m_iMaxConscript); pStream->Write(m_iHighestUnitLevel); pStream->Write(m_iOverflowResearch); pStream->Write(m_iNoUnhealthyPopulationCount); pStream->Write(m_iExpInBorderModifier); pStream->Write(m_iBuildingOnlyHealthyCount); pStream->Write(m_iDistanceMaintenanceModifier); pStream->Write(m_iNumCitiesMaintenanceModifier); pStream->Write(m_iCorporationMaintenanceModifier); pStream->Write(m_iTotalMaintenance); pStream->Write(m_iUpkeepModifier); pStream->Write(m_iLevelExperienceModifier); pStream->Write(m_iExtraHealth); pStream->Write(m_iBuildingGoodHealth); pStream->Write(m_iBuildingBadHealth); pStream->Write(m_iExtraHappiness); pStream->Write(m_iBuildingHappiness); pStream->Write(m_iLargestCityHappiness); pStream->Write(m_iWarWearinessPercentAnger); pStream->Write(m_iWarWearinessModifier); pStream->Write(m_iFreeSpecialist); pStream->Write(m_iNoForeignTradeCount); pStream->Write(m_iNoCorporationsCount); pStream->Write(m_iNoForeignCorporationsCount); pStream->Write(m_iCoastalTradeRoutes); pStream->Write(m_iTradeRoutes); pStream->Write(m_iRevolutionTimer); pStream->Write(m_iConversionTimer); pStream->Write(m_iStateReligionCount); pStream->Write(m_iNoNonStateReligionSpreadCount); pStream->Write(m_iStateReligionHappiness); pStream->Write(m_iNonStateReligionHappiness); pStream->Write(m_iStateReligionUnitProductionModifier); pStream->Write(m_iStateReligionBuildingProductionModifier); pStream->Write(m_iStateReligionFreeExperience); pStream->Write(m_iCapitalCityID); pStream->Write(m_iCitiesLost); pStream->Write(m_iWinsVsBarbs); pStream->Write(m_iAssets); pStream->Write(m_iPower); pStream->Write(m_iPopulationScore); pStream->Write(m_iLandScore); pStream->Write(m_iWondersScore); pStream->Write(m_iTechScore); pStream->Write(m_iCombatExperience); pStream->Write(m_bAlive); pStream->Write(m_bEverAlive); pStream->Write(m_bTurnActive); pStream->Write(m_bAutoMoves); pStream->Write(m_bEndTurn); pStream->Write(m_bPbemNewTurn && GC.getGameINLINE().isPbem()); pStream->Write(m_bExtendedGame); pStream->Write(m_bFoundedFirstCity); pStream->Write(m_bStrike); pStream->Write(m_eID); pStream->Write(m_ePersonalityType); pStream->Write(m_eCurrentEra); pStream->Write(m_eLastStateReligion); pStream->Write(m_eParent); //m_eTeamType not saved pStream->Write(NUM_YIELD_TYPES, m_aiSeaPlotYield); pStream->Write(NUM_YIELD_TYPES, m_aiYieldRateModifier); pStream->Write(NUM_YIELD_TYPES, m_aiCapitalYieldRateModifier); pStream->Write(NUM_YIELD_TYPES, m_aiExtraYieldThreshold); pStream->Write(NUM_YIELD_TYPES, m_aiTradeYieldModifier); pStream->Write(NUM_COMMERCE_TYPES, m_aiFreeCityCommerce); pStream->Write(NUM_COMMERCE_TYPES, m_aiCommercePercent); pStream->Write(NUM_COMMERCE_TYPES, m_aiCommerceRate); pStream->Write(NUM_COMMERCE_TYPES, m_aiCommerceRateModifier); pStream->Write(NUM_COMMERCE_TYPES, m_aiCapitalCommerceRateModifier); pStream->Write(NUM_COMMERCE_TYPES, m_aiStateReligionBuildingCommerce); pStream->Write(NUM_COMMERCE_TYPES, m_aiSpecialistExtraCommerce); pStream->Write(NUM_COMMERCE_TYPES, m_aiCommerceFlexibleCount); pStream->Write(MAX_PLAYERS, m_aiGoldPerTurnByPlayer); pStream->Write(MAX_TEAMS, m_aiEspionageSpendingWeightAgainstTeam); pStream->Write(NUM_FEAT_TYPES, m_abFeatAccomplished); pStream->Write(NUM_PLAYEROPTION_TYPES, m_abOptions); pStream->WriteString(m_szScriptData); FAssertMsg((0 < GC.getNumBonusInfos()), "GC.getNumBonusInfos() is not greater than zero but an array is being allocated in CvPlayer::write"); pStream->Write(GC.getNumBonusInfos(), m_paiBonusExport); pStream->Write(GC.getNumBonusInfos(), m_paiBonusImport); pStream->Write(GC.getNumImprovementInfos(), m_paiImprovementCount); pStream->Write(GC.getNumBuildingInfos(), m_paiFreeBuildingCount); pStream->Write(GC.getNumBuildingInfos(), m_paiExtraBuildingHappiness); pStream->Write(GC.getNumBuildingInfos(), m_paiExtraBuildingHealth); pStream->Write(GC.getNumFeatureInfos(), m_paiFeatureHappiness); pStream->Write(GC.getNumUnitClassInfos(), m_paiUnitClassCount); pStream->Write(GC.getNumUnitClassInfos(), m_paiUnitClassMaking); pStream->Write(GC.getNumBuildingClassInfos(), m_paiBuildingClassCount); pStream->Write(GC.getNumBuildingClassInfos(), m_paiBuildingClassMaking); pStream->Write(GC.getNumHurryInfos(), m_paiHurryCount); pStream->Write(GC.getNumSpecialBuildingInfos(), m_paiSpecialBuildingNotRequiredCount); pStream->Write(GC.getNumCivicOptionInfos(), m_paiHasCivicOptionCount); pStream->Write(GC.getNumCivicOptionInfos(), m_paiNoCivicUpkeepCount); pStream->Write(GC.getNumReligionInfos(), m_paiHasReligionCount); pStream->Write(GC.getNumCorporationInfos(), m_paiHasCorporationCount); pStream->Write(GC.getNumUpkeepInfos(), m_paiUpkeepCount); pStream->Write(GC.getNumSpecialistInfos(), m_paiSpecialistValidCount); FAssertMsg((0 < GC.getNumTechInfos()), "GC.getNumTechInfos() is not greater than zero but it is expected to be in CvPlayer::write"); pStream->Write(GC.getNumTechInfos(), m_pabResearchingTech); pStream->Write(GC.getNumVoteSourceInfos(), m_pabLoyalMember); for (iI=0;iI<GC.getNumCivicOptionInfos();iI++) { pStream->Write(m_paeCivics[iI]); } for (iI=0;iI<GC.getNumSpecialistInfos();iI++) { pStream->Write(NUM_YIELD_TYPES, m_ppaaiSpecialistExtraYield[iI]); } for (iI=0;iI<GC.getNumImprovementInfos();iI++) { pStream->Write(NUM_YIELD_TYPES, m_ppaaiImprovementYieldChange[iI]); } m_groupCycle.Write(pStream); m_researchQueue.Write(pStream); { CLLNode<CvWString>* pNode; uint iSize = m_cityNames.getLength(); pStream->Write(iSize); pNode = m_cityNames.head(); while (pNode != NULL) { pStream->WriteString(pNode->m_data); pNode = m_cityNames.next(pNode); } } WriteStreamableFFreeListTrashArray(m_plotGroups, pStream); WriteStreamableFFreeListTrashArray(m_cities, pStream); WriteStreamableFFreeListTrashArray(m_units, pStream); WriteStreamableFFreeListTrashArray(m_selectionGroups, pStream); WriteStreamableFFreeListTrashArray(m_eventsTriggered, pStream); { CvMessageQueue::_Alloc::size_type iSize = m_listGameMessages.size(); pStream->Write(iSize); CvMessageQueue::iterator it; for (it = m_listGameMessages.begin(); it != m_listGameMessages.end(); ++it) { CvTalkingHeadMessage& message = *it; message.write(*pStream); } } { CvPopupQueue currentPopups; if (GC.getGameINLINE().isNetworkMultiPlayer()) { // don't save open popups in MP to avoid having different state on different machines currentPopups.clear(); } else { gDLL->getInterfaceIFace()->getDisplayedButtonPopups(currentPopups); } CvPopupQueue::_Alloc::size_type iSize = m_listPopups.size() + currentPopups.size(); pStream->Write(iSize); CvPopupQueue::iterator it; for (it = currentPopups.begin(); it != currentPopups.end(); ++it) { CvPopupInfo* pInfo = *it; if (NULL != pInfo) { pInfo->write(*pStream); } } for (it = m_listPopups.begin(); it != m_listPopups.end(); ++it) { CvPopupInfo* pInfo = *it; if (NULL != pInfo) { pInfo->write(*pStream); } } } { CvDiploQueue::_Alloc::size_type iSize = m_listDiplomacy.size(); pStream->Write(iSize); CvDiploQueue::iterator it; for (it = m_listDiplomacy.begin(); it != m_listDiplomacy.end(); ++it) { CvDiploParameters* pDiplo = *it; if (NULL != pDiplo) { pDiplo->write(*pStream); } } } { uint iSize = m_mapScoreHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapScoreHistory.begin(); it != m_mapScoreHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapEconomyHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapEconomyHistory.begin(); it != m_mapEconomyHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapIndustryHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapIndustryHistory.begin(); it != m_mapIndustryHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapAgricultureHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapAgricultureHistory.begin(); it != m_mapAgricultureHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapPowerHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapPowerHistory.begin(); it != m_mapPowerHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapCultureHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapCultureHistory.begin(); it != m_mapCultureHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapEspionageHistory.size(); pStream->Write(iSize); CvTurnScoreMap::iterator it; for (it = m_mapEspionageHistory.begin(); it != m_mapEspionageHistory.end(); ++it) { pStream->Write(it->first); pStream->Write(it->second); } } { uint iSize = m_mapEventsOccured.size(); pStream->Write(iSize); CvEventMap::iterator it; for (it = m_mapEventsOccured.begin(); it != m_mapEventsOccured.end(); ++it) { pStream->Write(it->first); it->second.write(pStream); } } { uint iSize = m_mapEventCountdown.size(); pStream->Write(iSize); CvEventMap::iterator it; for (it = m_mapEventCountdown.begin(); it != m_mapEventCountdown.end(); ++it) { pStream->Write(it->first); it->second.write(pStream); } } { uint iSize = m_aFreeUnitCombatPromotions.size(); pStream->Write(iSize); UnitCombatPromotionArray::iterator it; for (it = m_aFreeUnitCombatPromotions.begin(); it != m_aFreeUnitCombatPromotions.end(); ++it) { pStream->Write((*it).first); pStream->Write((*it).second); } } { uint iSize = m_aFreeUnitClassPromotions.size(); pStream->Write(iSize); UnitClassPromotionArray::iterator it; for (it = m_aFreeUnitClassPromotions.begin(); it != m_aFreeUnitClassPromotions.end(); ++it) { pStream->Write((*it).first); pStream->Write((*it).second); } } { uint iSize = m_aVote.size(); pStream->Write(iSize); std::vector< std::pair<int, PlayerVoteTypes> >::iterator it; for (it = m_aVote.begin(); it != m_aVote.end(); ++it) { pStream->Write((*it).first); pStream->Write((*it).second); } } { uint iSize = m_aUnitExtraCosts.size(); pStream->Write(iSize); std::vector< std::pair<UnitClassTypes, int> >::iterator it; for (it = m_aUnitExtraCosts.begin(); it != m_aUnitExtraCosts.end(); ++it) { pStream->Write((*it).first); pStream->Write((*it).second); } } { uint iSize = m_triggersFired.size(); pStream->Write(iSize); std::vector<EventTriggerTypes>::iterator it; for (it = m_triggersFired.begin(); it != m_triggersFired.end(); ++it) { pStream->Write((*it)); } } pStream->Write(m_iPopRushHurryCount); pStream->Write(m_iInflationModifier); } void CvPlayer::createGreatPeople(UnitTypes eGreatPersonUnit, bool bIncrementThreshold, bool bIncrementExperience, int iX, int iY) { // BUG - Female Great People - start CvUnitInfo& kUnit = GC.getUnitInfo(eGreatPersonUnit); if (!kUnit.isFemale()) { UnitTypes eFemaleGreatPersonUnit = (UnitTypes) kUnit.getFemaleUnitType(); if (eFemaleGreatPersonUnit != NO_UNIT) { int iFemalePercent = isCivic((CivicTypes)GC.getInfoTypeForString("CIVIC_EMANCIPATION")) ? 50 : 20; if (GC.getGameINLINE().getSorenRandNum(100, "Female great person") < iFemalePercent) { eGreatPersonUnit = eFemaleGreatPersonUnit; } } } // BUG - Female Great People - end CvUnit* pGreatPeopleUnit = initUnit(eGreatPersonUnit, iX, iY); if (NULL == pGreatPeopleUnit) { FAssert(false); return; } if (bIncrementThreshold) { incrementGreatPeopleCreated(); changeGreatPeopleThresholdModifier(GC.getDefineINT("GREAT_PEOPLE_THRESHOLD_INCREASE") * ((getGreatPeopleCreated() / 10) + 1)); for (int iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == getTeam()) { GET_PLAYER((PlayerTypes)iI).changeGreatPeopleThresholdModifier(GC.getDefineINT("GREAT_PEOPLE_THRESHOLD_INCREASE_TEAM") * ((getGreatPeopleCreated() / 10) + 1)); } } } if (bIncrementExperience) { incrementGreatGeneralsCreated(); changeGreatGeneralsThresholdModifier(GC.getDefineINT("GREAT_GENERALS_THRESHOLD_INCREASE") * ((getGreatGeneralsCreated() / 10) + 1)); for (int iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == getTeam()) { GET_PLAYER((PlayerTypes)iI).changeGreatGeneralsThresholdModifier(GC.getDefineINT("GREAT_GENERALS_THRESHOLD_INCREASE_TEAM") * ((getGreatGeneralsCreated() / 10) + 1)); } } } CvPlot* pPlot = GC.getMapINLINE().plot(iX, iY); CvCity* pCity = pPlot->getPlotCity(); CvWString szReplayMessage; if (pPlot) { if (pCity) { CvWString szCity; szCity.Format(L"%s (%s)", pCity->getName().GetCString(), GET_PLAYER(pCity->getOwnerINLINE()).getName()); szReplayMessage = gDLL->getText("TXT_KEY_MISC_GP_BORN", pGreatPeopleUnit->getName().GetCString(), szCity.GetCString()); } else { szReplayMessage = gDLL->getText("TXT_KEY_MISC_GP_BORN_FIELD", pGreatPeopleUnit->getName().GetCString()); } GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szReplayMessage, iX, iY, (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT")); } for (int iI = 0; iI < MAX_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (pPlot->isRevealed(GET_PLAYER((PlayerTypes)iI).getTeam(), false)) { gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szReplayMessage, "AS2D_UNIT_GREATPEOPLE", MESSAGE_TYPE_MAJOR_EVENT, pGreatPeopleUnit->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT"), iX, iY, true, true); } else { CvWString szMessage = gDLL->getText("TXT_KEY_MISC_GP_BORN_SOMEWHERE", pGreatPeopleUnit->getName().GetCString()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szMessage, "AS2D_UNIT_GREATPEOPLE", MESSAGE_TYPE_MAJOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_UNIT_TEXT")); } } } // Python Event if (pCity) { CvEventReporter::getInstance().greatPersonBorn(pGreatPeopleUnit, getID(), pCity); } } const EventTriggeredData* CvPlayer::getEventOccured(EventTypes eEvent) const { FAssert(eEvent >= 0 && eEvent < GC.getNumEventInfos()); CvEventMap::const_iterator it = m_mapEventsOccured.find(eEvent); if (it == m_mapEventsOccured.end()) { return NULL; } return &(it->second); } bool CvPlayer::isTriggerFired(EventTriggerTypes eEventTrigger) const { return (std::find(m_triggersFired.begin(), m_triggersFired.end(), eEventTrigger) != m_triggersFired.end()); } void CvPlayer::resetEventOccured(EventTypes eEvent, bool bAnnounce) { FAssert(eEvent >= 0 && eEvent < GC.getNumEventInfos()); CvEventMap::iterator it = m_mapEventsOccured.find(eEvent); if (it != m_mapEventsOccured.end()) { expireEvent(it->first, it->second, bAnnounce); m_mapEventsOccured.erase(it); } } void CvPlayer::setEventOccured(EventTypes eEvent, const EventTriggeredData& kEventTriggered, bool bOthers) { FAssert(eEvent >= 0 && eEvent < GC.getNumEventInfos()); m_mapEventsOccured[eEvent] = kEventTriggered; if (GC.getEventInfo(eEvent).isQuest()) { CvWStringBuffer szMessageBuffer; szMessageBuffer.append(GC.getEventInfo(eEvent).getDescription()); GAMETEXT.setEventHelp(szMessageBuffer, eEvent, kEventTriggered.getID(), getID()); gDLL->getInterfaceIFace()->addQuestMessage(getID(), szMessageBuffer.getCString(), kEventTriggered.getID()); } if (bOthers) { if (GC.getEventInfo(eEvent).isGlobal()) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (i != getID()) { GET_PLAYER((PlayerTypes)i).setEventOccured(eEvent, kEventTriggered, false); } } } else if (GC.getEventInfo(eEvent).isTeam()) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (i != getID() && getTeam() == GET_PLAYER((PlayerTypes)i).getTeam()) { GET_PLAYER((PlayerTypes)i).setEventOccured(eEvent, kEventTriggered, false); } } } } } const EventTriggeredData* CvPlayer::getEventCountdown(EventTypes eEvent) const { FAssert(eEvent >= 0 && eEvent < GC.getNumEventInfos()); CvEventMap::const_iterator it = m_mapEventCountdown.find(eEvent); if (it == m_mapEventCountdown.end()) { return NULL; } return &(it->second); } void CvPlayer::setEventCountdown(EventTypes eEvent, const EventTriggeredData& kEventTriggered) { FAssert(eEvent >= 0 && eEvent < GC.getNumEventInfos()); m_mapEventCountdown[eEvent] = kEventTriggered; } void CvPlayer::resetEventCountdown(EventTypes eEvent) { FAssert(eEvent >= 0 && eEvent < GC.getNumEventInfos()); CvEventMap::iterator it = m_mapEventCountdown.find(eEvent); if (it != m_mapEventCountdown.end()) { m_mapEventCountdown.erase(it); } } void CvPlayer::resetTriggerFired(EventTriggerTypes eTrigger) { std::vector<EventTriggerTypes>::iterator it = std::find(m_triggersFired.begin(), m_triggersFired.end(), eTrigger); if (it != m_triggersFired.end()) { m_triggersFired.erase(it); } } void CvPlayer::setTriggerFired(const EventTriggeredData& kTriggeredData, bool bOthers, bool bAnnounce) { FAssert(kTriggeredData.m_eTrigger >= 0 && kTriggeredData.m_eTrigger < GC.getNumEventTriggerInfos()); CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(kTriggeredData.m_eTrigger); if (!isTriggerFired(kTriggeredData.m_eTrigger)) { m_triggersFired.push_back(kTriggeredData.m_eTrigger); if (bOthers) { if (kTrigger.isGlobal()) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (i != getID()) { GET_PLAYER((PlayerTypes)i).setTriggerFired(kTriggeredData, false, false); } } } else if (kTrigger.isTeam()) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (i != getID() && getTeam() == GET_PLAYER((PlayerTypes)i).getTeam()) { GET_PLAYER((PlayerTypes)i).setTriggerFired(kTriggeredData, false, false); } } } } } if (!CvString(kTrigger.getPythonCallback()).empty()) { long lResult; CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(&kTriggeredData)); gDLL->getPythonIFace()->callFunction(PYRandomEventModule, kTrigger.getPythonCallback(), argsList.makeFunctionArgs(), &lResult); } if (bAnnounce) { CvPlot* pPlot = GC.getMapINLINE().plot(kTriggeredData.m_iPlotX, kTriggeredData.m_iPlotY); if (!kTriggeredData.m_szGlobalText.empty()) { for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kLoopPlayer.isAlive()) { if (GET_TEAM(kLoopPlayer.getTeam()).isHasMet(getTeam()) && (NO_PLAYER == kTriggeredData.m_eOtherPlayer || GET_TEAM(GET_PLAYER(kTriggeredData.m_eOtherPlayer).getTeam()).isHasMet(getTeam()))) { bool bShowPlot = kTrigger.isShowPlot(); if (bShowPlot) { if (kLoopPlayer.getTeam() != getTeam()) { if (NULL == pPlot || !pPlot->isRevealed(kLoopPlayer.getTeam(), false)) { bShowPlot = false; } } } if (bShowPlot) { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)iPlayer, false, GC.getEVENT_MESSAGE_TIME(), kTriggeredData.m_szGlobalText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), kTriggeredData.m_iPlotX, kTriggeredData.m_iPlotY, true, true); } else { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)iPlayer, false, GC.getEVENT_MESSAGE_TIME(), kTriggeredData.m_szGlobalText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT); } } } } GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), kTriggeredData.m_szGlobalText, kTriggeredData.m_iPlotX, kTriggeredData.m_iPlotY, (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT")); } else if (!kTriggeredData.m_szText.empty()) { if (kTrigger.isShowPlot() && NULL != pPlot && pPlot->isRevealed(getTeam(), false)) { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), kTriggeredData.m_szText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), kTriggeredData.m_iPlotX, kTriggeredData.m_iPlotY, true, true); } else { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), kTriggeredData.m_szText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE")); } } } } EventTriggeredData* CvPlayer::initTriggeredData(EventTriggerTypes eEventTrigger, bool bFire, int iCityId, int iPlotX, int iPlotY, PlayerTypes eOtherPlayer, int iOtherPlayerCityId, ReligionTypes eReligion, CorporationTypes eCorporation, int iUnitId, BuildingTypes eBuilding) { CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(eEventTrigger); CvCity* pCity = getCity(iCityId); CvCity* pOtherPlayerCity = NULL; if (NO_PLAYER != eOtherPlayer) { pOtherPlayerCity = GET_PLAYER(eOtherPlayer).getCity(iOtherPlayerCityId); } CvPlot* pPlot = GC.getMapINLINE().plot(iPlotX, iPlotY); CvUnit* pUnit = getUnit(iUnitId); std::vector<CvPlot*> apPlots; bool bPickPlot = ::isPlotEventTrigger(eEventTrigger); if (kTrigger.isPickCity()) { if (NULL == pCity) { pCity = pickTriggerCity(eEventTrigger); } if (NULL != pCity) { if (bPickPlot) { for (int iPlot = 0; iPlot < NUM_CITY_PLOTS; ++iPlot) { if (CITY_HOME_PLOT != iPlot) { CvPlot* pLoopPlot = pCity->getCityIndexPlot(iPlot); if (NULL != pLoopPlot) { if (pLoopPlot->canTrigger(eEventTrigger, getID())) { apPlots.push_back(pLoopPlot); } } } } } } else { return NULL; } } else { if (kTrigger.getNumBuildings() > 0 && kTrigger.getNumBuildingsRequired() > 0) { int iFoundValid = 0; for (int i = 0; i < kTrigger.getNumBuildingsRequired(); ++i) { if (kTrigger.getBuildingRequired(i) != NO_BUILDINGCLASS) { iFoundValid += getBuildingClassCount((BuildingClassTypes)kTrigger.getBuildingRequired(i)); } } if (iFoundValid < kTrigger.getNumBuildings()) { return NULL; } } if (kTrigger.getNumReligions() > 0) { int iFoundValid = 0; if (kTrigger.getNumReligionsRequired() > 0) { for (int i = 0; i < kTrigger.getNumReligionsRequired(); ++i) { if (kTrigger.getReligionRequired(i) != NO_RELIGION) { if (getHasReligionCount((ReligionTypes)kTrigger.getReligionRequired(i)) > 0) { ++iFoundValid; } } } } else { for (int i = 0; i < GC.getNumReligionInfos(); ++i) { if (getHasReligionCount((ReligionTypes)i) > 0) { ++iFoundValid; } } } if (iFoundValid < kTrigger.getNumReligions()) { return NULL; } } if (kTrigger.getNumCorporations() > 0) { int iFoundValid = 0; if (kTrigger.getNumCorporationsRequired() > 0) { for (int i = 0; i < kTrigger.getNumCorporationsRequired(); ++i) { if (kTrigger.getCorporationRequired(i) != NO_CORPORATION) { if (getHasCorporationCount((CorporationTypes)kTrigger.getCorporationRequired(i)) > 0) { ++iFoundValid; } } } } else { for (int i = 0; i < GC.getNumCorporationInfos(); ++i) { if (getHasCorporationCount((CorporationTypes)i) > 0) { ++iFoundValid; } } } if (iFoundValid < kTrigger.getNumCorporations()) { return NULL; } } if (kTrigger.getMinPopulation() > 0) { if (getTotalPopulation() < kTrigger.getMinPopulation()) { return NULL; } } if (kTrigger.getMaxPopulation() > 0) { if (getTotalPopulation() > kTrigger.getMaxPopulation()) { return NULL; } } if (bPickPlot) { for (int iPlot = 0; iPlot < GC.getMapINLINE().numPlotsINLINE(); ++iPlot) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iPlot); if (pLoopPlot->canTrigger(eEventTrigger, getID())) { apPlots.push_back(pLoopPlot); } } } } if (kTrigger.isPickReligion()) { if (NO_RELIGION == eReligion) { if (kTrigger.isStateReligion()) { ReligionTypes eStateReligion = getStateReligion(); if (NO_RELIGION != eStateReligion && isValidTriggerReligion(kTrigger, pCity, eStateReligion)) { eReligion = getStateReligion(); } } else { int iOffset = GC.getGameINLINE().getSorenRandNum(GC.getNumReligionInfos(), "Event pick religion"); for (int i = 0; i < GC.getNumReligionInfos(); ++i) { int iReligion = (i + iOffset) % GC.getNumReligionInfos(); if (isValidTriggerReligion(kTrigger, pCity, (ReligionTypes)iReligion)) { eReligion = (ReligionTypes)iReligion; break; } } } } if (NO_RELIGION == eReligion) { return NULL; } } if (kTrigger.isPickCorporation()) { if (NO_CORPORATION == eCorporation) { int iOffset = GC.getGameINLINE().getSorenRandNum(GC.getNumCorporationInfos(), "Event pick corporation"); for (int i = 0; i < GC.getNumCorporationInfos(); ++i) { int iCorporation = (i + iOffset) % GC.getNumCorporationInfos(); if (isValidTriggerCorporation(kTrigger, pCity, (CorporationTypes)iCorporation)) { eCorporation = (CorporationTypes)iCorporation; break; } } } if (NO_CORPORATION == eCorporation) { return NULL; } } if (NULL == pPlot) { if (apPlots.size() > 0) { int iChosen = GC.getGameINLINE().getSorenRandNum(apPlots.size(), "Event pick plot"); pPlot = apPlots[iChosen]; if (NULL == pCity) { pCity = GC.getMapINLINE().findCity(pPlot->getX_INLINE(), pPlot->getY_INLINE(), getID(), NO_TEAM, false); } } else { if (bPickPlot) { return NULL; } if (NULL != pCity) { pPlot = pCity->plot(); } } } if (kTrigger.getNumBuildings() > 0) { if (NULL != pCity && NO_BUILDING == eBuilding) { std::vector<BuildingTypes> aeBuildings; for (int i = 0; i < kTrigger.getNumBuildingsRequired(); ++i) { if (kTrigger.getBuildingRequired(i) != NO_BUILDINGCLASS) { BuildingTypes eTestBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(kTrigger.getBuildingRequired(i)); if (NO_BUILDING != eTestBuilding && pCity->getNumRealBuilding(eTestBuilding) > 0) { aeBuildings.push_back(eTestBuilding); } } } if (aeBuildings.size() > 0) { int iChosen = GC.getGameINLINE().getSorenRandNum(aeBuildings.size(), "Event pick building"); eBuilding = aeBuildings[iChosen]; } else { return NULL; } } } if (NULL == pUnit) { pUnit = pickTriggerUnit(eEventTrigger, pPlot, bPickPlot); } if (NULL == pUnit && kTrigger.getNumUnits() > 0) { return NULL; } if (NULL == pPlot && NULL != pUnit) { pPlot = pUnit->plot(); } if (NULL == pPlot && bPickPlot) { return NULL; } if (kTrigger.getNumUnitsGlobal() > 0) { int iNumUnits = 0; for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kLoopPlayer.isAlive()) { int iLoop; for (CvUnit* pLoopUnit = kLoopPlayer.firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = kLoopPlayer.nextUnit(&iLoop)) { if (MIN_INT != pLoopUnit->getTriggerValue(eEventTrigger, pPlot, true)) { ++iNumUnits; } } } } if (iNumUnits < kTrigger.getNumUnitsGlobal()) { return NULL; } } if (kTrigger.getNumBuildingsGlobal() > 0) { int iNumBuildings = 0; for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kLoopPlayer.isAlive()) { for (int i = 0; i < kTrigger.getNumBuildingsRequired(); ++i) { if (kTrigger.getBuildingRequired(i) != NO_BUILDINGCLASS) { iNumBuildings += getBuildingClassCount((BuildingClassTypes)kTrigger.getBuildingRequired(i)); } } } } if (iNumBuildings < kTrigger.getNumBuildingsGlobal()) { return NULL; } } if (kTrigger.isPickPlayer()) { std::vector<PlayerTypes> aePlayers; std::vector<CvCity*> apCities; if (NO_PLAYER == eOtherPlayer) { for (int i = 0; i < MAX_CIV_PLAYERS; i++) { if (GET_PLAYER((PlayerTypes)i).canTrigger(eEventTrigger, getID(), eReligion)) { if (kTrigger.isPickOtherPlayerCity()) { CvCity* pBestCity = NULL; if (NULL != pCity) { pBestCity = GC.getMapINLINE().findCity(pCity->getX_INLINE(), pCity->getY_INLINE(), (PlayerTypes)i); } else { pBestCity = GET_PLAYER((PlayerTypes)i).pickTriggerCity(eEventTrigger); } if (NULL != pBestCity) { apCities.push_back(pBestCity); aePlayers.push_back((PlayerTypes)i); } } else { apCities.push_back(NULL); aePlayers.push_back((PlayerTypes)i); } } } if (aePlayers.size() > 0) { int iChosen = GC.getGameINLINE().getSorenRandNum(aePlayers.size(), "Event pick player"); eOtherPlayer = aePlayers[iChosen]; pOtherPlayerCity = apCities[iChosen]; } else { return NULL; } } } EventTriggeredData* pTriggerData = addEventTriggered(); if (NULL != pTriggerData) { pTriggerData->m_eTrigger = eEventTrigger; pTriggerData->m_ePlayer = getID(); pTriggerData->m_iTurn = GC.getGameINLINE().getGameTurn(); pTriggerData->m_iCityId = (NULL != pCity) ? pCity->getID() : -1; pTriggerData->m_iPlotX = (NULL != pPlot) ? pPlot->getX_INLINE() : INVALID_PLOT_COORD; pTriggerData->m_iPlotY = (NULL != pPlot) ? pPlot->getY_INLINE() : INVALID_PLOT_COORD; pTriggerData->m_eOtherPlayer = eOtherPlayer; pTriggerData->m_iOtherPlayerCityId = (NULL != pOtherPlayerCity) ? pOtherPlayerCity->getID() : -1; pTriggerData->m_eReligion = eReligion; pTriggerData->m_eCorporation = eCorporation; pTriggerData->m_iUnitId = (NULL != pUnit) ? pUnit->getID() : -1; pTriggerData->m_eBuilding = eBuilding; } else { return NULL; } if (!CvString(kTrigger.getPythonCanDo()).empty()) { long lResult; CyArgsList argsList; argsList.add(gDLL->getPythonIFace()->makePythonObject(pTriggerData)); gDLL->getPythonIFace()->callFunction(PYRandomEventModule, kTrigger.getPythonCanDo(), argsList.makeFunctionArgs(), &lResult); if (0 == lResult) { deleteEventTriggered(pTriggerData->getID()); return NULL; } // python may change pTriggerData pCity = getCity(pTriggerData->m_iCityId); pPlot = GC.getMapINLINE().plot(pTriggerData->m_iPlotX, pTriggerData->m_iPlotY); pUnit = getUnit(pTriggerData->m_iUnitId); eOtherPlayer = pTriggerData->m_eOtherPlayer; if (NO_PLAYER != eOtherPlayer) { pOtherPlayerCity = GET_PLAYER(eOtherPlayer).getCity(pTriggerData->m_iOtherPlayerCityId); } eReligion = pTriggerData->m_eReligion; eCorporation = pTriggerData->m_eCorporation; eBuilding = pTriggerData->m_eBuilding; } std::vector<CvWString> aszTexts; for (int i = 0; i < kTrigger.getNumTexts(); ++i) { if (NO_ERA == kTrigger.getTextEra(i) || kTrigger.getTextEra(i) == getCurrentEra()) { aszTexts.push_back(kTrigger.getText(i)); } } if (aszTexts.size() > 0) { int iText = GC.getGameINLINE().getSorenRandNum(aszTexts.size(), "Event Text choice"); pTriggerData->m_szText = gDLL->getText(aszTexts[iText].GetCString(), eOtherPlayer != NO_PLAYER ? GET_PLAYER(eOtherPlayer).getCivilizationAdjectiveKey() : L"", NULL != pCity ? pCity->getNameKey() : L"", NULL != pUnit ? pUnit->getNameKey() : L"", NO_RELIGION != eReligion ? GC.getReligionInfo(eReligion).getAdjectiveKey() : L"", NO_BUILDING != eBuilding ? GC.getBuildingInfo(eBuilding).getTextKeyWide() : L"", NULL != pOtherPlayerCity ? pOtherPlayerCity->getNameKey() : L"", NULL != pPlot && NO_TERRAIN != pPlot->getTerrainType() ? GC.getTerrainInfo(pPlot->getTerrainType()).getTextKeyWide() : L"", NULL != pPlot && NO_IMPROVEMENT != pPlot->getImprovementType() ? GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide() : L"", NULL != pPlot && NO_BONUS != pPlot->getBonusType() ? GC.getBonusInfo(pPlot->getBonusType()).getTextKeyWide() : L"", NULL != pPlot && NO_ROUTE != pPlot->getRouteType() ? GC.getRouteInfo(pPlot->getRouteType()).getTextKeyWide() : L"", NO_CORPORATION != eCorporation ? GC.getCorporationInfo(eCorporation).getTextKeyWide() : L"" ); } else { pTriggerData->m_szText = L""; } if (kTrigger.getNumWorldNews() > 0) { int iText = GC.getGameINLINE().getSorenRandNum(kTrigger.getNumWorldNews(), "Trigger World News choice"); pTriggerData->m_szGlobalText = gDLL->getText(kTrigger.getWorldNews(iText).GetCString(), getCivilizationAdjectiveKey(), NULL != pCity ? pCity->getNameKey() : L"", pTriggerData->m_eReligion != NO_RELIGION ? GC.getReligionInfo(pTriggerData->m_eReligion).getAdjectiveKey() : L"", eOtherPlayer != NO_PLAYER ? GET_PLAYER(eOtherPlayer).getCivilizationAdjectiveKey() : L"", NULL != pOtherPlayerCity ? pOtherPlayerCity->getNameKey() : L"", pTriggerData->m_eCorporation != NO_CORPORATION ? GC.getCorporationInfo(pTriggerData->m_eCorporation).getTextKeyWide() : L"" ); } else { pTriggerData->m_szGlobalText.clear(); } if (bFire) { trigger(*pTriggerData); } return pTriggerData; } bool CvPlayer::canDoEvent(EventTypes eEvent, const EventTriggeredData& kTriggeredData) const { if (eEvent == NO_EVENT) { FAssert(false); return false; } CvEventInfo& kEvent = GC.getEventInfo(eEvent); int iGold = std::min(getEventCost(eEvent, kTriggeredData.m_eOtherPlayer, false), getEventCost(eEvent, kTriggeredData.m_eOtherPlayer, true)); if (iGold != 0) { if (iGold > 0 && NO_PLAYER != kTriggeredData.m_eOtherPlayer && kEvent.isGoldToPlayer()) { if (GET_PLAYER(kTriggeredData.m_eOtherPlayer).getGold() < iGold) { return false; } } else if (iGold < 0) { if (getGold() < -iGold) { return false; } } } if (0 != kEvent.getSpaceProductionModifier()) { bool bValid = false; for (int iProject = 0; iProject < GC.getNumProjectInfos(); ++iProject) { CvProjectInfo& kProject = GC.getProjectInfo((ProjectTypes)iProject); if (kProject.isSpaceship()) { if (kProject.getVictoryPrereq() != NO_VICTORY) { if (GC.getGameINLINE().isVictoryValid((VictoryTypes)(kProject.getVictoryPrereq()))) { bValid = true; break; } } } } if (!bValid) { return false; } } if (kEvent.getEspionagePoints() > 0 && GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { return false; } if (NO_PLAYER != kTriggeredData.m_eOtherPlayer) { if (kEvent.getEspionagePoints() + GET_TEAM(getTeam()).getEspionagePointsAgainstTeam(GET_PLAYER(kTriggeredData.m_eOtherPlayer).getTeam()) < 0) { return false; } } if (0 != kEvent.getTechPercent() || 0 != kEvent.getTechCostPercent()) { if (NO_TECH == getBestEventTech(eEvent, kTriggeredData.m_eOtherPlayer)) { return false; } } if (NO_TECH != kEvent.getPrereqTech()) { if (!GET_TEAM(getTeam()).isHasTech((TechTypes)kEvent.getPrereqTech())) { return false; } } if (NO_BONUS != kEvent.getBonusGift()) { BonusTypes eBonus = (BonusTypes)kEvent.getBonusGift(); if (NO_PLAYER == kTriggeredData.m_eOtherPlayer) { return false; } if (!canTradeNetworkWith(kTriggeredData.m_eOtherPlayer)) { return false; } if (GET_PLAYER(kTriggeredData.m_eOtherPlayer).getNumAvailableBonuses(eBonus) > 0) { return false; } if (getNumTradeableBonuses(eBonus) <= 1) { return false; } } if (kEvent.getUnitClass() != NO_UNITCLASS) { UnitTypes eUnit = (UnitTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(kEvent.getUnitClass()); if (eUnit == NO_UNIT) { return false; } } if (kEvent.isCityEffect()) { CvCity* pCity = getCity(kTriggeredData.m_iCityId); if (NULL == pCity || !pCity->canApplyEvent(eEvent, kTriggeredData)) { return false; } } else if (kEvent.isOtherPlayerCityEffect()) { if (NO_PLAYER == kTriggeredData.m_eOtherPlayer) { return false; } CvCity* pCity = GET_PLAYER(kTriggeredData.m_eOtherPlayer).getCity(kTriggeredData.m_iOtherPlayerCityId); if (NULL == pCity || !pCity->canApplyEvent(eEvent, kTriggeredData)) { return false; } } if (::isPlotEventTrigger(kTriggeredData.m_eTrigger)) { CvPlot* pPlot = GC.getMapINLINE().plotINLINE(kTriggeredData.m_iPlotX, kTriggeredData.m_iPlotY); if (NULL != pPlot) { if (!pPlot->canApplyEvent(eEvent)) { return false; } } } CvUnit* pUnit = getUnit(kTriggeredData.m_iUnitId); if (NULL != pUnit) { if (!pUnit->canApplyEvent(eEvent)) { return false; } } if (NO_BONUS != kEvent.getBonusRevealed()) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)GC.getBonusInfo((BonusTypes)kEvent.getBonusRevealed()).getTechReveal())) { return false; } if (GET_TEAM(getTeam()).isForceRevealedBonus((BonusTypes)kEvent.getBonusRevealed())) { return false; } } if (kEvent.getConvertOwnCities() > 0) { bool bFoundValid = false; if (NO_RELIGION != kTriggeredData.m_eReligion) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (!pLoopCity->isHasReligion(kTriggeredData.m_eReligion)) { if (-1 == kEvent.getMaxNumReligions() || pLoopCity->getReligionCount() <= kEvent.getMaxNumReligions()) { bFoundValid = true; break; } } } } if (!bFoundValid) { return false; } } if (kEvent.getConvertOtherCities() > 0) { bool bFoundValid = false; if (NO_RELIGION != kTriggeredData.m_eReligion) { if (NO_PLAYER != kTriggeredData.m_eOtherPlayer) { int iLoop; for (CvCity* pLoopCity = GET_PLAYER(kTriggeredData.m_eOtherPlayer).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(kTriggeredData.m_eOtherPlayer).nextCity(&iLoop)) { if (!pLoopCity->isHasReligion(kTriggeredData.m_eReligion)) { if (-1 == kEvent.getMaxNumReligions() || pLoopCity->getReligionCount() <= kEvent.getMaxNumReligions()) { bFoundValid = true; break; } } } } } if (!bFoundValid) { return false; } } if (0 != kEvent.getAttitudeModifier()) { if (NO_PLAYER == kTriggeredData.m_eOtherPlayer) { return false; } if (GET_PLAYER(kTriggeredData.m_eOtherPlayer).getTeam() == getTeam()) { return false; } if (GET_PLAYER(kTriggeredData.m_eOtherPlayer).isHuman()) { if (0 == kEvent.getOurAttitudeModifier()) { return false; } } } if (0 != kEvent.getTheirEnemyAttitudeModifier()) { if (NO_PLAYER == kTriggeredData.m_eOtherPlayer) { return false; } TeamTypes eWorstEnemy = GET_TEAM(GET_PLAYER(kTriggeredData.m_eOtherPlayer).getTeam()).AI_getWorstEnemy(); if (NO_TEAM == eWorstEnemy || eWorstEnemy == getTeam()) { return false; } if (!GET_TEAM(eWorstEnemy).isAlive()) { return false; } if (eWorstEnemy == getTeam()) { return false; } } if (kEvent.isDeclareWar()) { if (NO_PLAYER == kTriggeredData.m_eOtherPlayer) { return false; } if (!GET_TEAM(GET_PLAYER(kTriggeredData.m_eOtherPlayer).getTeam()).canDeclareWar(getTeam()) || !GET_TEAM(getTeam()).canDeclareWar(GET_PLAYER(kTriggeredData.m_eOtherPlayer).getTeam())) { return false; } } if (kEvent.isQuest()) { for (int iTrigger = 0; iTrigger < GC.getNumEventTriggerInfos(); ++iTrigger) { CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo((EventTriggerTypes)iTrigger); if (!kTrigger.isRecurring()) { for (int i = 0; i < kTrigger.getNumPrereqEvents(); ++i) { if (kTrigger.getPrereqEvent(i) == eEvent) { if (isTriggerFired((EventTriggerTypes)iTrigger)) { return false; } } } } } } if (!CvString(kEvent.getPythonCanDo()).empty()) { long lResult; CyArgsList argsList; argsList.add(eEvent); argsList.add(gDLL->getPythonIFace()->makePythonObject(&kTriggeredData)); gDLL->getPythonIFace()->callFunction(PYRandomEventModule, kEvent.getPythonCanDo(), argsList.makeFunctionArgs(), &lResult); if (0 == lResult) { return false; } } return true; } void CvPlayer::applyEvent(EventTypes eEvent, int iEventTriggeredId, bool bUpdateTrigger) { FAssert(eEvent != NO_EVENT); EventTriggeredData* pTriggeredData = getEventTriggered(iEventTriggeredId); if (NULL == pTriggeredData) { deleteEventTriggered(iEventTriggeredId); return; } if (bUpdateTrigger) { setTriggerFired(*pTriggeredData, true); } if (!canDoEvent(eEvent, *pTriggeredData)) { if (bUpdateTrigger) { deleteEventTriggered(iEventTriggeredId); } return; } setEventOccured(eEvent, *pTriggeredData); CvEventInfo& kEvent = GC.getEventInfo(eEvent); CvCity* pCity = getCity(pTriggeredData->m_iCityId); CvCity* pOtherPlayerCity = NULL; if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { pOtherPlayerCity = GET_PLAYER(pTriggeredData->m_eOtherPlayer).getCity(pTriggeredData->m_iOtherPlayerCityId); } int iGold = getEventCost(eEvent, pTriggeredData->m_eOtherPlayer, false); int iRandomGold = getEventCost(eEvent, pTriggeredData->m_eOtherPlayer, true); iGold += GC.getGameINLINE().getSorenRandNum(iRandomGold - iGold + 1, "Event random gold"); if (iGold != 0) { changeGold(iGold); if (NO_PLAYER != pTriggeredData->m_eOtherPlayer && kEvent.isGoldToPlayer()) { GET_PLAYER(pTriggeredData->m_eOtherPlayer).changeGold(-iGold); } } if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { if (kEvent.getEspionagePoints() != 0) { GET_TEAM(getTeam()).changeEspionagePointsAgainstTeam(GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam(), kEvent.getEspionagePoints()); } } if (0 != kEvent.getTechPercent()) { TechTypes eBestTech = getBestEventTech(eEvent, pTriggeredData->m_eOtherPlayer); if (eBestTech != NO_TECH) { int iBeakers = GET_TEAM(getTeam()).changeResearchProgressPercent(eBestTech, kEvent.getTechPercent(), getID()); if (iBeakers > 0) { for (int iI = 0; iI < MAX_CIV_PLAYERS; iI++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { if (GET_PLAYER((PlayerTypes)iI).getTeam() == getID()) { CvWString szBuffer = gDLL->getText("TXT_KEY_MISC_PROGRESS_TOWARDS_TECH", iBeakers, GC.getTechInfo(eBestTech).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)iI), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, NULL, MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_TECH_TEXT")); } } } } } } if (kEvent.isGoldenAge()) { changeGoldenAgeTurns(getGoldenAgeLength()); } if (0 != kEvent.getInflationModifier()) { m_iInflationModifier += kEvent.getInflationModifier(); } if (0 != kEvent.getSpaceProductionModifier()) { changeSpaceProductionModifier(kEvent.getSpaceProductionModifier()); } if (0 != kEvent.getFreeUnitSupport()) { changeBaseFreeUnits(kEvent.getFreeUnitSupport()); } if (kEvent.isDeclareWar()) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { /************************************************************************************************/ /* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */ /* */ /* AI logging */ /************************************************************************************************/ if( gTeamLogLevel >= 2 ) { logBBAI(" Team %d (%S) declares war on team %d due to event", GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam(), GET_PLAYER(pTriggeredData->m_eOtherPlayer).getCivilizationDescription(0), getTeam() ); } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ GET_TEAM(GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam()).declareWar(getTeam(), false, WARPLAN_LIMITED); } } if (NO_BONUS != kEvent.getBonusGift()) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { CLinkList<TradeData> ourList; CLinkList<TradeData> theirList; TradeData kTradeData; setTradeItem(&kTradeData, TRADE_RESOURCES, kEvent.getBonusGift()); ourList.insertAtEnd(kTradeData); GC.getGameINLINE().implementDeal(getID(), pTriggeredData->m_eOtherPlayer, &ourList, &theirList); } } bool bClear = false; for (int iEvent = 0; iEvent < GC.getNumEventInfos(); ++iEvent) { if (kEvent.getClearEventChance(iEvent) > 0) { bClear = GC.getGameINLINE().getSorenRandNum(100, "Event Clear") < kEvent.getClearEventChance(iEvent); if (bClear) { if (kEvent.isGlobal()) { for (int j = 0; j < MAX_CIV_PLAYERS; j++) { GET_PLAYER((PlayerTypes)j).resetEventOccured((EventTypes)iEvent, j != getID()); } } else if (kEvent.isTeam()) { for (int j = 0; j < MAX_CIV_PLAYERS; j++) { if (getTeam() == GET_PLAYER((PlayerTypes)j).getTeam()) { GET_PLAYER((PlayerTypes)j).resetEventOccured((EventTypes)iEvent, j != getID()); } } } else { resetEventOccured((EventTypes)iEvent, false); } } } } if (NULL != pCity && kEvent.isCityEffect()) { pCity->applyEvent(eEvent, *pTriggeredData, bClear); } else if (NULL != pOtherPlayerCity && kEvent.isOtherPlayerCityEffect()) { pOtherPlayerCity->applyEvent(eEvent, *pTriggeredData, bClear); } if (!kEvent.isCityEffect() && !kEvent.isOtherPlayerCityEffect()) { if (kEvent.getHappy() != 0) { changeExtraHappiness(kEvent.getHappy()); } if (kEvent.getHealth() != 0) { changeExtraHealth(kEvent.getHealth()); } if (kEvent.getNumBuildingYieldChanges() > 0) { int iLoop; for (int iBuildingClass = 0; iBuildingClass < GC.getNumBuildingClassInfos(); ++iBuildingClass) { for (int iYield = 0; iYield < NUM_YIELD_TYPES; ++iYield) { for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { pLoopCity->changeBuildingYieldChange((BuildingClassTypes)iBuildingClass, (YieldTypes)iYield, kEvent.getBuildingYieldChange(iBuildingClass, iYield)); } } } } if (kEvent.getNumBuildingCommerceChanges() > 0) { int iLoop; for (int iBuildingClass = 0; iBuildingClass < GC.getNumBuildingClassInfos(); ++iBuildingClass) { for (int iCommerce = 0; iCommerce < NUM_COMMERCE_TYPES; ++iCommerce) { for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { pLoopCity->changeBuildingCommerceChange((BuildingClassTypes)iBuildingClass, (CommerceTypes)iCommerce, kEvent.getBuildingCommerceChange(iBuildingClass, iCommerce)); } } } } if (kEvent.getNumBuildingHappyChanges() > 0) { for (int i = 0; i < GC.getNumBuildingClassInfos(); ++i) { if (0 != kEvent.getBuildingHappyChange(i)) { BuildingTypes eBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(i); if (NO_BUILDING != eBuilding) { changeExtraBuildingHappiness(eBuilding, kEvent.getBuildingHappyChange(i)); } } } } if (kEvent.getNumBuildingHealthChanges() > 0) { for (int i = 0; i < GC.getNumBuildingClassInfos(); ++i) { if (0 != kEvent.getBuildingHealthChange(i)) { BuildingTypes eBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(i); if (NO_BUILDING != eBuilding) { changeExtraBuildingHealth(eBuilding, kEvent.getBuildingHealthChange(i)); } } } } if (kEvent.getHurryAnger() != 0) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { pLoopCity->changeHurryAngerTimer(kEvent.getHurryAnger() * pLoopCity->flatHurryAngerLength()); } } if (kEvent.getHappyTurns() > 0) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { pLoopCity->changeHappinessTimer(kEvent.getHappyTurns()); } } if (kEvent.getMaxPillage() > 0) { FAssert(kEvent.getMaxPillage() >= kEvent.getMinPillage()); int iNumPillage = kEvent.getMinPillage() + GC.getGameINLINE().getSorenRandNum(kEvent.getMaxPillage() - kEvent.getMinPillage(), "Pick number of event pillaged plots"); int iNumPillaged = 0; for (int i = 0; i < iNumPillage; ++i) { int iRandOffset = GC.getGameINLINE().getSorenRandNum(GC.getMapINLINE().numPlotsINLINE(), "Pick event pillage plot (any city)"); for (int j = 0; j < GC.getMapINLINE().numPlotsINLINE(); ++j) { int iPlot = (j + iRandOffset) % GC.getMapINLINE().numPlotsINLINE(); CvPlot* pPlot = GC.getMapINLINE().plotByIndexINLINE(iPlot); if (NULL != pPlot && pPlot->getOwnerINLINE() == getID() && pPlot->isCity()) { if (NO_IMPROVEMENT != pPlot->getImprovementType() && !GC.getImprovementInfo(pPlot->getImprovementType()).isPermanent()) { CvWString szBuffer = gDLL->getText("TXT_KEY_EVENT_CITY_IMPROVEMENT_DESTROYED", GC.getImprovementInfo(pPlot->getImprovementType()).getTextKeyWide()); gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGED", MESSAGE_TYPE_INFO, GC.getImprovementInfo(pPlot->getImprovementType()).getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE(), true, true); pPlot->setImprovementType(NO_IMPROVEMENT); ++iNumPillaged; break; } } } } if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { CvWString szBuffer = gDLL->getText("TXT_KEY_EVENT_NUM_CITY_IMPROVEMENTS_DESTROYED", iNumPillaged, getCivilizationAdjectiveKey()); gDLL->getInterfaceIFace()->addMessage(pTriggeredData->m_eOtherPlayer, false, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_PILLAGED", MESSAGE_TYPE_INFO); } } if (kEvent.getFood() != 0) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { pLoopCity->changeFood(kEvent.getFood()); } } if (kEvent.getFoodPercent() != 0) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { pLoopCity->changeFood((pLoopCity->getFood() * kEvent.getFoodPercent()) / 100); } } if (kEvent.getPopulationChange() != 0) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getPopulation() + kEvent.getPopulationChange() > 0) { pLoopCity->changePopulation(kEvent.getPopulationChange()); } } } if (kEvent.getCulture() != 0) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->getCultureTimes100(pLoopCity->getOwnerINLINE()) + 100 * kEvent.getCulture() > 0) { pLoopCity->changeCulture(pLoopCity->getOwnerINLINE(), kEvent.getCulture(), true, true); } } } if (kEvent.getUnitClass() != NO_UNITCLASS) { UnitTypes eUnit = (UnitTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(kEvent.getUnitClass()); if (eUnit != NO_UNIT) { CvCity* pUnitCity = pCity; if (NULL == pUnitCity) { pUnitCity = getCapitalCity(); } if (NULL != pUnitCity) { for (int i = 0; i < kEvent.getNumUnits(); ++i) { initUnit(eUnit, pUnitCity->getX_INLINE(), pUnitCity->getY_INLINE()); } } } } } CvPlot* pPlot = GC.getMapINLINE().plotINLINE(pTriggeredData->m_iPlotX, pTriggeredData->m_iPlotY); if (NULL != pPlot) { if (::isPlotEventTrigger(pTriggeredData->m_eTrigger)) { FAssert(pPlot->canApplyEvent(eEvent)); pPlot->applyEvent(eEvent); } } CvUnit* pUnit = getUnit(pTriggeredData->m_iUnitId); if (NULL != pUnit) { FAssert(pUnit->canApplyEvent(eEvent)); pUnit->applyEvent(eEvent); // might kill the unit } for (int i = 0; i < GC.getNumUnitCombatInfos(); ++i) { if (NO_PROMOTION != kEvent.getUnitCombatPromotion(i)) { int iLoop; for (CvUnit* pLoopUnit = firstUnit(&iLoop); NULL != pLoopUnit; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->getUnitCombatType() == i) { pLoopUnit->setHasPromotion((PromotionTypes)kEvent.getUnitCombatPromotion(i), true); } } setFreePromotion((UnitCombatTypes)i, (PromotionTypes)kEvent.getUnitCombatPromotion(i), true); } } for (int i = 0; i < GC.getNumUnitClassInfos(); ++i) { if (NO_PROMOTION != kEvent.getUnitClassPromotion(i)) { int iLoop; for (CvUnit* pLoopUnit = firstUnit(&iLoop); NULL != pLoopUnit; pLoopUnit = nextUnit(&iLoop)) { if (pLoopUnit->getUnitClassType() == i) { pLoopUnit->setHasPromotion((PromotionTypes)kEvent.getUnitClassPromotion(i), true); } } setFreePromotion((UnitClassTypes)i, (PromotionTypes)kEvent.getUnitClassPromotion(i), true); } } if (NO_BONUS != kEvent.getBonusRevealed()) { GET_TEAM(getTeam()).setForceRevealedBonus((BonusTypes)kEvent.getBonusRevealed(), true); } std::vector<CvCity*> apSpreadReligionCities; if (kEvent.getConvertOwnCities() > 0) { if (NO_RELIGION != pTriggeredData->m_eReligion) { int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (!pLoopCity->isHasReligion(pTriggeredData->m_eReligion)) { if (-1 == kEvent.getMaxNumReligions() || pLoopCity->getReligionCount() <= kEvent.getMaxNumReligions()) { apSpreadReligionCities.push_back(pLoopCity); } } } } } while ((int)apSpreadReligionCities.size() > kEvent.getConvertOwnCities()) { int iChosen = GC.getGameINLINE().getSorenRandNum(apSpreadReligionCities.size(), "Even Spread Religion (own)"); int i = 0; for (std::vector<CvCity*>::iterator it = apSpreadReligionCities.begin(); it != apSpreadReligionCities.end(); ++it) { if (i == iChosen) { apSpreadReligionCities.erase(it); break; } ++i; } } for (std::vector<CvCity*>::iterator it = apSpreadReligionCities.begin(); it != apSpreadReligionCities.end(); ++it) { (*it)->setHasReligion(pTriggeredData->m_eReligion, true, true, false); } apSpreadReligionCities.clear(); if (kEvent.getConvertOtherCities() > 0) { if (NO_RELIGION != pTriggeredData->m_eReligion) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { std::vector<CvCity*> apCities; int iLoop; for (CvCity* pLoopCity = GET_PLAYER(pTriggeredData->m_eOtherPlayer).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(pTriggeredData->m_eOtherPlayer).nextCity(&iLoop)) { if (!pLoopCity->isHasReligion(pTriggeredData->m_eReligion)) { if (-1 == kEvent.getMaxNumReligions() || pLoopCity->getReligionCount() <= kEvent.getMaxNumReligions()) { apSpreadReligionCities.push_back(pLoopCity); } } } } } } while ((int)apSpreadReligionCities.size() > kEvent.getConvertOtherCities()) { int iChosen = GC.getGameINLINE().getSorenRandNum(apSpreadReligionCities.size(), "Even Spread Religion (other)"); int i = 0; for (std::vector<CvCity*>::iterator it = apSpreadReligionCities.begin(); it != apSpreadReligionCities.end(); ++it) { if (i == iChosen) { apSpreadReligionCities.erase(it); break; } ++i; } } for (std::vector<CvCity*>::iterator it = apSpreadReligionCities.begin(); it != apSpreadReligionCities.end(); ++it) { (*it)->setHasReligion(pTriggeredData->m_eReligion, true, true, false); } if (0 != kEvent.getOurAttitudeModifier()) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { if (kEvent.getOurAttitudeModifier() > 0) { AI_changeMemoryCount(pTriggeredData->m_eOtherPlayer, MEMORY_EVENT_GOOD_TO_US, kEvent.getOurAttitudeModifier()); } else { AI_changeMemoryCount(pTriggeredData->m_eOtherPlayer, MEMORY_EVENT_BAD_TO_US, -kEvent.getOurAttitudeModifier()); } } } if (0 != kEvent.getAttitudeModifier()) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { if (kEvent.getAttitudeModifier() > 0) { GET_PLAYER(pTriggeredData->m_eOtherPlayer).AI_changeMemoryCount(getID(), MEMORY_EVENT_GOOD_TO_US, kEvent.getAttitudeModifier()); } else { GET_PLAYER(pTriggeredData->m_eOtherPlayer).AI_changeMemoryCount(getID(), MEMORY_EVENT_BAD_TO_US, -kEvent.getAttitudeModifier()); } } } if (0 != kEvent.getTheirEnemyAttitudeModifier()) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { TeamTypes eWorstEnemy = GET_TEAM(GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam()).AI_getWorstEnemy(); if (NO_TEAM != eWorstEnemy) { for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kLoopPlayer.isAlive() && kLoopPlayer.getTeam() == eWorstEnemy) { if (kEvent.getTheirEnemyAttitudeModifier() > 0) { kLoopPlayer.AI_changeMemoryCount(getID(), MEMORY_EVENT_GOOD_TO_US, kEvent.getTheirEnemyAttitudeModifier()); AI_changeMemoryCount((PlayerTypes)iPlayer, MEMORY_EVENT_GOOD_TO_US, kEvent.getTheirEnemyAttitudeModifier()); } else { kLoopPlayer.AI_changeMemoryCount(getID(), MEMORY_EVENT_BAD_TO_US, -kEvent.getTheirEnemyAttitudeModifier()); AI_changeMemoryCount((PlayerTypes)iPlayer, MEMORY_EVENT_BAD_TO_US, -kEvent.getTheirEnemyAttitudeModifier()); } } } } } } if (!CvString(kEvent.getPythonCallback()).empty()) { long lResult; CyArgsList argsList; argsList.add(eEvent); argsList.add(gDLL->getPythonIFace()->makePythonObject(pTriggeredData)); gDLL->getPythonIFace()->callFunction(PYRandomEventModule, kEvent.getPythonCallback(), argsList.makeFunctionArgs(), &lResult); } if (kEvent.getNumWorldNews() > 0) { int iText = GC.getGameINLINE().getSorenRandNum(kEvent.getNumWorldNews(), "Event World News choice"); CvWString szGlobalText; TeamTypes eTheirWorstEnemy = NO_TEAM; if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { eTheirWorstEnemy = GET_TEAM(GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam()).AI_getWorstEnemy(); } szGlobalText = gDLL->getText(kEvent.getWorldNews(iText).GetCString(), getCivilizationAdjectiveKey(), NULL != pCity ? pCity->getNameKey() : L"", pTriggeredData->m_eOtherPlayer != NO_PLAYER ? GET_PLAYER(pTriggeredData->m_eOtherPlayer).getCivilizationAdjectiveKey() : L"", NULL != pOtherPlayerCity ? pOtherPlayerCity->getNameKey() : L"", NO_RELIGION != pTriggeredData->m_eReligion ? GC.getReligionInfo(pTriggeredData->m_eReligion).getAdjectiveKey() : L"", NO_TEAM != eTheirWorstEnemy ? GET_TEAM(eTheirWorstEnemy).getName().GetCString() : L"", NO_CORPORATION != pTriggeredData->m_eCorporation ? GC.getCorporationInfo(pTriggeredData->m_eCorporation).getTextKeyWide() : L"" ); for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kLoopPlayer.isAlive()) { if (GET_TEAM(kLoopPlayer.getTeam()).isHasMet(getTeam()) && (NO_PLAYER == pTriggeredData->m_eOtherPlayer || GET_TEAM(GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam()).isHasMet(getTeam()))) { bool bShowPlot = GC.getEventTriggerInfo(pTriggeredData->m_eTrigger).isShowPlot(); if (bShowPlot) { if (kLoopPlayer.getTeam() != getTeam()) { if (NULL == pPlot || !pPlot->isRevealed(kLoopPlayer.getTeam(), false)) { bShowPlot = false; } } } if (bShowPlot) { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)iPlayer, false, GC.getEVENT_MESSAGE_TIME(), szGlobalText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pTriggeredData->m_iPlotX, pTriggeredData->m_iPlotY, true, true); } else { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)iPlayer, false, GC.getEVENT_MESSAGE_TIME(), szGlobalText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT); } } } } GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szGlobalText, pTriggeredData->m_iPlotX, pTriggeredData->m_iPlotY, (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT")); } if (!CvWString(kEvent.getLocalInfoTextKey()).empty()) { CvWString szLocalText; TeamTypes eTheirWorstEnemy = NO_TEAM; if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { eTheirWorstEnemy = GET_TEAM(GET_PLAYER(pTriggeredData->m_eOtherPlayer).getTeam()).AI_getWorstEnemy(); } szLocalText = gDLL->getText(kEvent.getLocalInfoTextKey(), getCivilizationAdjectiveKey(), NULL != pCity ? pCity->getNameKey() : L"", pTriggeredData->m_eOtherPlayer != NO_PLAYER ? GET_PLAYER(pTriggeredData->m_eOtherPlayer).getCivilizationAdjectiveKey() : L"", NULL != pOtherPlayerCity ? pOtherPlayerCity->getNameKey() : L"", NO_RELIGION != pTriggeredData->m_eReligion ? GC.getReligionInfo(pTriggeredData->m_eReligion).getAdjectiveKey() : L"", NO_TEAM != eTheirWorstEnemy ? GET_TEAM(eTheirWorstEnemy).getName().GetCString() : L"", NO_CORPORATION != pTriggeredData->m_eCorporation ? GC.getCorporationInfo(pTriggeredData->m_eCorporation).getTextKeyWide() : L"" ); if (GC.getEventTriggerInfo(pTriggeredData->m_eTrigger).isShowPlot()) { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), szLocalText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE"), pTriggeredData->m_iPlotX, pTriggeredData->m_iPlotY, true, true); } else { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), szLocalText, "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_WHITE")); } } if (!CvWString(kEvent.getOtherPlayerPopup()).empty()) { if (NO_PLAYER != pTriggeredData->m_eOtherPlayer) { CvWString szText = gDLL->getText(kEvent.getOtherPlayerPopup(), getCivilizationAdjectiveKey(), NULL != pCity ? pCity->getNameKey() : L"", pTriggeredData->m_eOtherPlayer != NO_PLAYER ? GET_PLAYER(pTriggeredData->m_eOtherPlayer).getCivilizationAdjectiveKey() : L"", NULL != pOtherPlayerCity ? pOtherPlayerCity->getNameKey() : L"", NO_RELIGION != pTriggeredData->m_eReligion ? GC.getReligionInfo(pTriggeredData->m_eReligion).getAdjectiveKey() : L"", NO_CORPORATION != pTriggeredData->m_eCorporation ? GC.getCorporationInfo(pTriggeredData->m_eCorporation).getTextKeyWide() : L"" ); CvPopupInfo* pInfo = new CvPopupInfo(); if (NULL != pInfo) { pInfo->setText(szText); GET_PLAYER(pTriggeredData->m_eOtherPlayer).addPopup(pInfo); } } } bool bDeleteTrigger = bUpdateTrigger; for (int iEvent = 0; iEvent < GC.getNumEventInfos(); ++iEvent) { if (0 == kEvent.getAdditionalEventTime(iEvent)) { if (kEvent.getAdditionalEventChance(iEvent) > 0) { if (canDoEvent((EventTypes)iEvent, *pTriggeredData)) { if (GC.getGameINLINE().getSorenRandNum(100, "Additional Event") < kEvent.getAdditionalEventChance(iEvent)) { applyEvent((EventTypes)iEvent, iEventTriggeredId, false); } } } } else { bool bSetTimer = true; if (kEvent.getAdditionalEventChance(iEvent) > 0) { if (GC.getGameINLINE().getSorenRandNum(100, "Additional Event 2") >= kEvent.getAdditionalEventChance(iEvent)) { bSetTimer = false; } } if (bSetTimer) { EventTriggeredData kTriggered = *pTriggeredData; kTriggered.m_iTurn = (GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getGrowthPercent() * kEvent.getAdditionalEventTime((EventTypes)iEvent)) / 100 + GC.getGameINLINE().getGameTurn(); const EventTriggeredData* pExistingTriggered = getEventCountdown((EventTypes)iEvent); if (NULL != pExistingTriggered) { kTriggered.m_iTurn = std::min(kTriggered.m_iTurn, pExistingTriggered->m_iTurn); } setEventCountdown((EventTypes)iEvent, kTriggered); bDeleteTrigger = false; } } } if (bDeleteTrigger) { deleteEventTriggered(iEventTriggeredId); } } bool CvPlayer::isValidEventTech(TechTypes eTech, EventTypes eEvent, PlayerTypes eOtherPlayer) const { CvEventInfo& kEvent = GC.getEventInfo(eEvent); if (0 == kEvent.getTechPercent() && 0 == kEvent.getTechCostPercent()) { return false; } if (kEvent.getTechPercent() < 0 && GET_TEAM(getTeam()).getResearchProgress(eTech) <= 0) { return false; } if (!canResearch(eTech)) { return false; } if (getResearchTurnsLeft(eTech, true) < kEvent.getTechMinTurnsLeft()) { return false; } if (NO_PLAYER != eOtherPlayer && !GET_TEAM(GET_PLAYER(eOtherPlayer).getTeam()).isHasTech(eTech)) { return false; } return true; } TechTypes CvPlayer::getBestEventTech(EventTypes eEvent, PlayerTypes eOtherPlayer) const { TechTypes eBestTech = NO_TECH; CvEventInfo& kEvent = GC.getEventInfo(eEvent); if (0 == kEvent.getTechPercent() && 0 == kEvent.getTechCostPercent()) { return NO_TECH; } if (NO_TECH != kEvent.getTech()) { eBestTech = (TechTypes)kEvent.getTech(); } else { bool bFoundFlavor = false; for (int i = 0; i < GC.getNumFlavorTypes(); ++i) { if (0 != kEvent.getTechFlavorValue(i)) { bFoundFlavor = true; break; } } if (!bFoundFlavor) { eBestTech = getCurrentResearch(); } } if (NO_TECH != eBestTech) { if (!isValidEventTech(eBestTech, eEvent, eOtherPlayer)) { eBestTech = NO_TECH; } } else { int iBestValue = 0; for (int iTech = 0; iTech < GC.getNumTechInfos(); ++iTech) { if (isValidEventTech((TechTypes)iTech, eEvent, eOtherPlayer)) { int iValue = 0; for (int i = 0; i < GC.getNumFlavorTypes(); ++i) { iValue += kEvent.getTechFlavorValue(i) * GC.getTechInfo((TechTypes)iTech).getFlavorValue(i); } if (iValue > iBestValue) { eBestTech = (TechTypes)iTech; iBestValue = iValue; } } } } return eBestTech; } int CvPlayer::getEventCost(EventTypes eEvent, PlayerTypes eOtherPlayer, bool bRandom) const { CvEventInfo& kEvent = GC.getEventInfo(eEvent); int iGold = kEvent.getGold(); if (bRandom) { iGold += kEvent.getRandomGold(); } iGold *= std::max(0, calculateInflationRate() + 100); iGold /= 100; TechTypes eBestTech = getBestEventTech(eEvent, eOtherPlayer); if (NO_TECH != eBestTech) { iGold -= (kEvent.getTechCostPercent() * GET_TEAM(getTeam()).getResearchCost(eBestTech)) / 100; } return iGold; } void CvPlayer::doEvents() { if (GC.getGameINLINE().isOption(GAMEOPTION_NO_EVENTS)) { return; } if (isBarbarian() || isMinorCiv()) { return; } CvEventMap::iterator it = m_mapEventsOccured.begin(); while (it != m_mapEventsOccured.end()) { if (checkExpireEvent(it->first, it->second)) { expireEvent(it->first, it->second, true); it = m_mapEventsOccured.erase(it); } else { ++it; } } bool bNewEventEligible = true; if (GC.getGameINLINE().getElapsedGameTurns() < GC.getDefineINT("FIRST_EVENT_DELAY_TURNS")) { bNewEventEligible = false; } if (bNewEventEligible) { if (GC.getGameINLINE().getSorenRandNum(GC.getDefineINT("EVENT_PROBABILITY_ROLL_SIDES"), "Global event check") >= GC.getEraInfo(getCurrentEra()).getEventChancePerTurn()) { bNewEventEligible = false; } } std::vector< std::pair<EventTriggeredData*, int> > aePossibleEventTriggerWeights; int iTotalWeight = 0; for (int i = 0; i < GC.getNumEventTriggerInfos(); ++i) { int iWeight = getEventTriggerWeight((EventTriggerTypes)i); if (iWeight == -1) { trigger((EventTriggerTypes)i); } else if (iWeight > 0 && bNewEventEligible) { EventTriggeredData* pTriggerData = initTriggeredData((EventTriggerTypes)i); if (NULL != pTriggerData) { iTotalWeight += iWeight; aePossibleEventTriggerWeights.push_back(std::make_pair(pTriggerData, iTotalWeight)); } } } if (iTotalWeight > 0) { bool bFired = false; int iValue = GC.getGameINLINE().getSorenRandNum(iTotalWeight, "Event trigger"); for (std::vector< std::pair<EventTriggeredData*, int> >::iterator it = aePossibleEventTriggerWeights.begin(); it != aePossibleEventTriggerWeights.end(); ++it) { EventTriggeredData* pTriggerData = (*it).first; if (NULL != pTriggerData) { if (iValue < (*it).second && !bFired) { trigger(*pTriggerData); bFired = true; } else { deleteEventTriggered(pTriggerData->getID()); } } } } std::vector<int> aCleanup; for (int i = 0; i < GC.getNumEventInfos(); ++i) { const EventTriggeredData* pTriggeredData = getEventCountdown((EventTypes)i); if (NULL != pTriggeredData) { if (GC.getGameINLINE().getGameTurn() >= pTriggeredData->m_iTurn) { applyEvent((EventTypes)i, pTriggeredData->m_iId); resetEventCountdown((EventTypes)i); aCleanup.push_back(pTriggeredData->m_iId); } } } for (std::vector<int>::iterator it = aCleanup.begin(); it != aCleanup.end(); ++it) { bool bDelete = true; for (int i = 0; i < GC.getNumEventInfos(); ++i) { const EventTriggeredData* pTriggeredData = getEventCountdown((EventTypes)i); if (NULL != pTriggeredData) { if (pTriggeredData->m_iId == *it) { bDelete = false; break; } } } if (bDelete) { deleteEventTriggered(*it); } } } void CvPlayer::expireEvent(EventTypes eEvent, const EventTriggeredData& kTriggeredData, bool bFail) { FAssert(getEventOccured(eEvent) == &kTriggeredData); FAssert(GC.getEventInfo(eEvent).isQuest() || GC.getGameINLINE().getGameTurn() - kTriggeredData.m_iTurn <= 4); if (GC.getEventInfo(eEvent).isQuest()) { CvMessageQueue::iterator it; for (it = m_listGameMessages.begin(); it != m_listGameMessages.end(); ++it) { CvTalkingHeadMessage& message = *it; // the trigger ID is stored in the otherwise unused length field if (message.getLength() == kTriggeredData.getID()) { m_listGameMessages.erase(it); gDLL->getInterfaceIFace()->dirtyTurnLog(getID()); break; } } if (bFail) { gDLL->getInterfaceIFace()->addMessage(getID(), false, GC.getEVENT_MESSAGE_TIME(), gDLL->getText(GC.getEventInfo(eEvent).getQuestFailTextKey()), "AS2D_CIVIC_ADOPT", MESSAGE_TYPE_MINOR_EVENT, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED")); } } } bool CvPlayer::checkExpireEvent(EventTypes eEvent, const EventTriggeredData& kTriggeredData) const { CvEventInfo& kEvent = GC.getEventInfo(eEvent); if (!CvString(kEvent.getPythonExpireCheck()).empty()) { long lResult; CyArgsList argsList; argsList.add(eEvent); argsList.add(gDLL->getPythonIFace()->makePythonObject(&kTriggeredData)); gDLL->getPythonIFace()->callFunction(PYRandomEventModule, kEvent.getPythonExpireCheck(), argsList.makeFunctionArgs(), &lResult); if (0 != lResult) { return true; } } if (!kEvent.isQuest()) { if (GC.getGameINLINE().getGameTurn() - kTriggeredData.m_iTurn > 2) { return true; } return false; } CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(kTriggeredData.m_eTrigger); FAssert(kTriggeredData.m_ePlayer != NO_PLAYER); CvPlayer& kPlayer = GET_PLAYER(kTriggeredData.m_ePlayer); if (kTrigger.isStateReligion() & kTrigger.isPickReligion()) { if (kPlayer.getStateReligion() != kTriggeredData.m_eReligion) { return true; } } if (NO_CIVIC != kTrigger.getCivic()) { if (!kPlayer.isCivic((CivicTypes)kTrigger.getCivic())) { return true; } } if (kTriggeredData.m_iCityId != -1) { if (NULL == kPlayer.getCity(kTriggeredData.m_iCityId)) { return true; } } if (kTriggeredData.m_iUnitId != -1) { if (NULL == kPlayer.getUnit(kTriggeredData.m_iUnitId)) { return true; } } if (NO_PLAYER != kTriggeredData.m_eOtherPlayer) { if (!GET_PLAYER(kTriggeredData.m_eOtherPlayer).isAlive()) { return true; } if (kTriggeredData.m_iOtherPlayerCityId != -1) { if (NULL == GET_PLAYER(kTriggeredData.m_eOtherPlayer).getCity(kTriggeredData.m_iOtherPlayerCityId)) { return true; } } } if (kTrigger.getNumObsoleteTechs() > 0) { for (int iI = 0; iI < kTrigger.getNumObsoleteTechs(); iI++) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)(kTrigger.getObsoleteTech(iI)))) { return true; } } } return false; } void CvPlayer::trigger(EventTriggerTypes eTrigger) { initTriggeredData(eTrigger, true); } void CvPlayer::trigger(const EventTriggeredData& kData) { if (isHuman()) { CvPopupInfo* pInfo = new CvPopupInfo(BUTTONPOPUP_EVENT, kData.getID()); addPopup(pInfo); } else { EventTypes eEvent = AI_chooseEvent(kData.getID()); if (NO_EVENT != eEvent) { applyEvent(eEvent, kData.getID()); } } } bool CvPlayer::canTrigger(EventTriggerTypes eTrigger, PlayerTypes ePlayer, ReligionTypes eReligion) const { if (!isAlive()) { return false; } if (getID() == ePlayer) { return false; } CvPlayer& kPlayer = GET_PLAYER(ePlayer); CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(eTrigger); if (getTeam() == kPlayer.getTeam()) { return false; } if (!kTrigger.isPickPlayer()) { return false; } if (!GET_TEAM(getTeam()).isHasMet(kPlayer.getTeam())) { return false; } if (isHuman() && kTrigger.isOtherPlayerAI()) { return false; } if (GET_TEAM(getTeam()).isAtWar(kPlayer.getTeam()) != kTrigger.isOtherPlayerWar()) { return false; } if (NO_TECH != kTrigger.getOtherPlayerHasTech()) { if (!GET_TEAM(getTeam()).isHasTech((TechTypes)kTrigger.getOtherPlayerHasTech())) { return false; } } if (kTrigger.getOtherPlayerShareBorders() > 0) { int iCount = 0; for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); ++iI) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if (!pLoopPlot->isWater()) { if ((pLoopPlot->getOwnerINLINE() == getID()) && pLoopPlot->isAdjacentPlayer(ePlayer, true)) { ++iCount; } } } if (iCount < kTrigger.getOtherPlayerShareBorders()) { return false; } } if (NO_RELIGION != eReligion) { bool bHasReligion = kTrigger.isStateReligion() ? (getStateReligion() == eReligion) : (getHasReligionCount(eReligion) > 0); if (kTrigger.isOtherPlayerHasReligion()) { if (!bHasReligion) { return false; } } if (kTrigger.isOtherPlayerHasOtherReligion()) { if (bHasReligion) { return false; } if (kTrigger.isStateReligion() && getStateReligion() == NO_RELIGION) { return false; } } } return true; } CvCity* CvPlayer::pickTriggerCity(EventTriggerTypes eTrigger) const { CvCity* pCity = NULL; std::vector<CvCity*> apCities; int iLoop; int iBestValue = MIN_INT; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { int iValue = pLoopCity->getTriggerValue(eTrigger); if (iValue >= iBestValue && iValue != MIN_INT) { if (iValue > iBestValue) { apCities.clear(); iBestValue = iValue; } apCities.push_back(pLoopCity); } } if (apCities.size() > 0) { int iChosen = GC.getGameINLINE().getSorenRandNum(apCities.size(), "Event pick city"); pCity = apCities[iChosen]; } return pCity; } CvUnit* CvPlayer::pickTriggerUnit(EventTriggerTypes eTrigger, CvPlot* pPlot, bool bPickPlot) const { CvUnit* pUnit = NULL; std::vector<CvUnit*> apUnits; int iLoop; int iBestValue = MIN_INT; for (CvUnit* pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { int iValue = pLoopUnit->getTriggerValue(eTrigger, pPlot, bPickPlot); if (iValue >= iBestValue && iValue != MIN_INT) { if (iValue > iBestValue) { apUnits.clear(); iBestValue = iValue; } apUnits.push_back(pLoopUnit); } } if (apUnits.size() > 0) { int iChosen = GC.getGameINLINE().getSorenRandNum(apUnits.size(), "Event pick unit"); pUnit = apUnits[iChosen]; } return pUnit; } int CvPlayer::getEventTriggerWeight(EventTriggerTypes eTrigger) const { CvEventTriggerInfo& kTrigger = GC.getEventTriggerInfo(eTrigger); if (NO_HANDICAP != kTrigger.getMinDifficulty()) { if (GC.getGameINLINE().getHandicapType() < kTrigger.getMinDifficulty()) { return 0; } } if (kTrigger.isSinglePlayer() && GC.getGameINLINE().isGameMultiPlayer()) { return 0; } if (!GC.getGameINLINE().isEventActive(eTrigger)) { return 0; } if (kTrigger.getNumObsoleteTechs() > 0) { for (int iI = 0; iI < kTrigger.getNumObsoleteTechs(); iI++) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)(kTrigger.getObsoleteTech(iI)))) { return 0; } } } if (!kTrigger.isRecurring()) { if (isTriggerFired(eTrigger)) { return 0; } } if (kTrigger.getNumPrereqOrTechs() > 0) { bool bFoundValid = false; for (int iI = 0; iI < kTrigger.getNumPrereqOrTechs(); iI++) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)(kTrigger.getPrereqOrTechs(iI)))) { bFoundValid = true; break; } } if (!bFoundValid) { return 0; } } if (kTrigger.getNumPrereqAndTechs() > 0) { bool bFoundValid = true; for (int iI = 0; iI < kTrigger.getNumPrereqAndTechs(); iI++) { if (!GET_TEAM(getTeam()).isHasTech((TechTypes)(kTrigger.getPrereqAndTechs(iI)))) { bFoundValid = false; break; } } if (!bFoundValid) { return 0; } } if (kTrigger.getNumPrereqEvents() > 0) { bool bFoundValid = true; for (int iI = 0; iI < kTrigger.getNumPrereqEvents(); iI++) { if (NULL == getEventOccured((EventTypes)kTrigger.getPrereqEvent(iI))) { bFoundValid = false; break; } } if (!bFoundValid) { return 0; } } if (NO_CIVIC != kTrigger.getCivic()) { bool bFoundValid = false; for (int iI = 0; iI < GC.getNumCivicOptionInfos(); ++iI) { if (getCivics((CivicOptionTypes)iI) == kTrigger.getCivic()) { bFoundValid = true; break; } } if (!bFoundValid) { return 0; } } if (kTrigger.getMinTreasury() > 0) { if (getGold() < kTrigger.getMinTreasury()) { return 0; } } if (GC.getMapINLINE().getNumLandAreas() < kTrigger.getMinMapLandmass()) { return 0; } if (kTrigger.getMinOurLandmass() > 0 || kTrigger.getMaxOurLandmass() != -1) { int iNumLandmass = 0; int iLoop; for (CvArea* pArea = GC.getMapINLINE().firstArea(&iLoop); NULL != pArea; pArea = GC.getMapINLINE().nextArea(&iLoop)) { if (!pArea->isWater()) { if (pArea->getCitiesPerPlayer(getID()) > 0) { ++iNumLandmass; } } } if (iNumLandmass < kTrigger.getMinOurLandmass()) { return 0; } if (kTrigger.getMaxOurLandmass() != -1 && iNumLandmass > kTrigger.getMaxOurLandmass()) { return 0; } } if (kTrigger.getProbability() < 0) { return kTrigger.getProbability(); } int iProbability = kTrigger.getProbability(); if (kTrigger.isProbabilityUnitMultiply() && kTrigger.getNumUnits() > 0) { int iNumUnits = 0; int iLoop; for (CvUnit* pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { if (MIN_INT != pLoopUnit->getTriggerValue(eTrigger, NULL, true)) { ++iNumUnits; } } iProbability *= iNumUnits; } if (kTrigger.isProbabilityBuildingMultiply() && kTrigger.getNumBuildings() > 0) { int iNumBuildings = 0; for (int i = 0; i < kTrigger.getNumBuildingsRequired(); ++i) { if (kTrigger.getBuildingRequired(i) != NO_BUILDINGCLASS) { iNumBuildings += getBuildingClassCount((BuildingClassTypes)kTrigger.getBuildingRequired(i)); } } iProbability *= iNumBuildings; } return iProbability; } PlayerTypes CvPlayer::getSplitEmpirePlayer(int iAreaId) const { // can't create different derivative civs on the same continent for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer) { CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer); if (kLoopPlayer.isAlive() && kLoopPlayer.getParent() == getID()) { CvCity* pLoopCapital = kLoopPlayer.getCapitalCity(); if (NULL != pLoopCapital) { if (pLoopCapital->area()->getID() == iAreaId) { return NO_PLAYER; } } } } PlayerTypes eNewPlayer = NO_PLAYER; // Try to find a player who's never been in the game before for (int i = 0; i < MAX_CIV_PLAYERS; ++i) { if (!GET_PLAYER((PlayerTypes)i).isEverAlive()) { eNewPlayer = (PlayerTypes)i; break; } } if (eNewPlayer == NO_PLAYER) { // Try to recycle a dead player for (int i = 0; i < MAX_CIV_PLAYERS; ++i) { if (!GET_PLAYER((PlayerTypes)i).isAlive()) { eNewPlayer = (PlayerTypes)i; break; } } } return eNewPlayer; } bool CvPlayer::canSplitEmpire() const { int iLoopArea; if (GC.getGameINLINE().isOption(GAMEOPTION_NO_VASSAL_STATES)) { return false; } if (GET_TEAM(getTeam()).isAVassal()) { return false; } CivLeaderArray aLeaders; if (!getSplitEmpireLeaders(aLeaders)) { return false; } bool bFoundArea = false; for (CvArea* pLoopArea = GC.getMapINLINE().firstArea(&iLoopArea); pLoopArea != NULL; pLoopArea = GC.getMapINLINE().nextArea(&iLoopArea)) { if (canSplitArea(pLoopArea->getID())) { bFoundArea = true; break; } } if (!bFoundArea) { return false; } return true; } bool CvPlayer::canSplitArea(int iAreaId) const { CvArea* pArea = GC.getMapINLINE().getArea(iAreaId); CvCity* pCapital = getCapitalCity(); if (NULL == pCapital) { return false; } if (NULL == pArea || pArea == pCapital->area()) { return false; } if (0 == pArea->getCitiesPerPlayer(getID())) { return false; } PlayerTypes ePlayer = getSplitEmpirePlayer(pArea->getID()); if (NO_PLAYER == ePlayer) { return false; } if (!GET_PLAYER(ePlayer).isAlive()) { if (pArea->getCitiesPerPlayer(getID()) <= 1) { return false; } } return true; } bool CvPlayer::getSplitEmpireLeaders(CivLeaderArray& aLeaders) const { aLeaders.clear(); for (int i = 0; i < GC.getNumCivilizationInfos(); ++i) { bool bValid = true; if (getCivilizationType() == i) { bValid = false; } if (bValid) { if (!GC.getCivilizationInfo((CivilizationTypes)i).isPlayable() || !GC.getCivilizationInfo((CivilizationTypes)i).isAIPlayable()) { bValid = false; } } if (bValid) { for (int j = 0; j < MAX_CIV_PLAYERS; ++j) { if (getID() != j && GET_PLAYER((PlayerTypes)j).isEverAlive() && GET_PLAYER((PlayerTypes)j).getCivilizationType() == i) { bValid = false; break; } } } if (bValid) { for (int j = 0; j < GC.getNumLeaderHeadInfos(); ++j) { bool bLeaderValid = true; if (!GC.getCivilizationInfo((CivilizationTypes)i).isLeaders(j) && !GC.getGameINLINE().isOption(GAMEOPTION_LEAD_ANY_CIV)) { bLeaderValid = false; } if (bLeaderValid) { for (int k = 0; k < MAX_CIV_PLAYERS; ++k) { if (GET_PLAYER((PlayerTypes)k).isEverAlive() && GET_PLAYER((PlayerTypes)k).getPersonalityType() == j) { bLeaderValid = false; } } } if (bLeaderValid) { aLeaders.push_back(std::make_pair((CivilizationTypes)i, (LeaderHeadTypes)j)); } } } } return (aLeaders.size() > 0); } bool CvPlayer::splitEmpire(int iAreaId) { PROFILE_FUNC(); if (!canSplitEmpire()) { return false; } if (!canSplitArea(iAreaId)) { return false; } CvArea* pArea = GC.getMapINLINE().getArea(iAreaId); if (NULL == pArea) { return false; } PlayerTypes eNewPlayer = getSplitEmpirePlayer(iAreaId); if (eNewPlayer == NO_PLAYER) { return false; } bool bPlayerExists = GET_TEAM(GET_PLAYER(eNewPlayer).getTeam()).isAlive(); FAssert(!bPlayerExists); if (!bPlayerExists) { int iBestValue = -1; LeaderHeadTypes eBestLeader = NO_LEADER; CivilizationTypes eBestCiv = NO_CIVILIZATION; CivLeaderArray aLeaders; if (getSplitEmpireLeaders(aLeaders)) { CivLeaderArray::iterator it; for (it = aLeaders.begin(); it != aLeaders.end(); ++it) { int iValue = (1 + GC.getGameINLINE().getSorenRandNum(100, "Choosing Split Personality")); if (GC.getCivilizationInfo(getCivilizationType()).getDerivativeCiv() == it->first) { iValue += 1000; } if (iValue > iBestValue) { iBestValue = iValue; eBestLeader = it->second; eBestCiv = it->first; } } } if (eBestLeader == NO_LEADER || eBestCiv == NO_CIVILIZATION) { return false; } CvWString szMessage = gDLL->getText("TXT_KEY_MISC_EMPIRE_SPLIT", getNameKey(), GC.getCivilizationInfo(eBestCiv).getShortDescriptionKey(), GC.getLeaderHeadInfo(eBestLeader).getTextKeyWide()); for (int i = 0; i < MAX_CIV_PLAYERS; ++i) { if (GET_PLAYER((PlayerTypes)i).isAlive()) { if (i == getID() || i == eNewPlayer || GET_TEAM(GET_PLAYER((PlayerTypes)i).getTeam()).isHasMet(getTeam())) { gDLL->getInterfaceIFace()->addMessage((PlayerTypes)i, false, GC.getEVENT_MESSAGE_TIME(), szMessage, "AS2D_REVOLTEND", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getInterfaceArtInfo("INTERFACE_CITY_BAR_CAPITAL_TEXTURE")->getPath()); } } } GC.getGameINLINE().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, getID(), szMessage, -1, -1, (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT")); /************************************************************************************************/ /* BETTER_BTS_AI_MOD 12/30/08 jdog5000 */ /* */ /* Bugfix */ /************************************************************************************************/ /* // remove leftover culture from old recycled player for (int iPlot = 0; iPlot < GC.getMapINLINE().numPlotsINLINE(); ++iPlot) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iPlot); pLoopPlot->setCulture(eNewPlayer, 0, false, false); } */ // Clearing plot culture along with many other bits of data now handled by CvGame::addPlayer /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ GC.getGameINLINE().addPlayer(eNewPlayer, eBestLeader, eBestCiv); GET_PLAYER(eNewPlayer).setParent(getID()); GC.getInitCore().setLeaderName(eNewPlayer, GC.getLeaderHeadInfo(eBestLeader).getTextKeyWide()); CvTeam& kNewTeam = GET_TEAM(GET_PLAYER(eNewPlayer).getTeam()); for (int i = 0; i < GC.getNumTechInfos(); ++i) { if (GET_TEAM(getTeam()).isHasTech((TechTypes)i)) { kNewTeam.setHasTech((TechTypes)i, true, eNewPlayer, false, false); if (GET_TEAM(getTeam()).isNoTradeTech((TechTypes)i) || GC.getGameINLINE().isOption(GAMEOPTION_NO_TECH_BROKERING)) { kNewTeam.setNoTradeTech((TechTypes)i, true); } } } for (int iTeam = 0; iTeam < MAX_TEAMS; ++iTeam) { CvTeam& kLoopTeam = GET_TEAM((TeamTypes)iTeam); if (kLoopTeam.isAlive()) { kNewTeam.setEspionagePointsAgainstTeam((TeamTypes)iTeam, GET_TEAM(getTeam()).getEspionagePointsAgainstTeam((TeamTypes)iTeam)); kLoopTeam.setEspionagePointsAgainstTeam(GET_PLAYER(eNewPlayer).getTeam(), kLoopTeam.getEspionagePointsAgainstTeam(getTeam())); } } kNewTeam.setEspionagePointsEver(GET_TEAM(getTeam()).getEspionagePointsEver()); GET_TEAM(getTeam()).assignVassal(GET_PLAYER(eNewPlayer).getTeam(), false); AI_updateBonusValue(); } std::vector< std::pair<int, int> > aCultures; for (int iPlot = 0; iPlot < GC.getMapINLINE().numPlotsINLINE(); ++iPlot) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iPlot); bool bTranferPlot = false; if (!bTranferPlot && pLoopPlot->area() == pArea) { bTranferPlot = true; } if (!bTranferPlot) { CvCity* pWorkingCity = pLoopPlot->getWorkingCity(); if (NULL != pWorkingCity && pWorkingCity->getOwnerINLINE() == getID() && pWorkingCity->area() == pArea) { bTranferPlot = true; } } if (!bTranferPlot && pLoopPlot->isWater() && pLoopPlot->isAdjacentToArea(pArea)) { bTranferPlot = true; } if (bTranferPlot) { int iCulture = pLoopPlot->getCulture(getID()); if (bPlayerExists) { iCulture = std::max(iCulture, pLoopPlot->getCulture(eNewPlayer)); } aCultures.push_back(std::make_pair(iPlot, iCulture)); } if (pLoopPlot->isRevealed(getTeam(), false)) { pLoopPlot->setRevealed(GET_PLAYER(eNewPlayer).getTeam(), true, false, getTeam(), false); } } int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { if (pLoopCity->area() == pArea) { int iCulture = pLoopCity->getCultureTimes100(getID()); CvPlot* pPlot = pLoopCity->plot(); GET_PLAYER(eNewPlayer).acquireCity(pLoopCity, false, true, false); if (NULL != pPlot) { CvCity* pCity = pPlot->getPlotCity(); if (NULL != pCity) { pCity->setCultureTimes100(eNewPlayer, iCulture, false, false); } for (int i = 0; i < GC.getDefineINT("COLONY_NUM_FREE_DEFENDERS"); ++i) { pCity->initConscriptedUnit(); } } } } for (uint i = 0; i < aCultures.size(); ++i) { CvPlot* pPlot = GC.getMapINLINE().plotByIndexINLINE(aCultures[i].first); pPlot->setCulture(eNewPlayer, aCultures[i].second, true, false); pPlot->setCulture(getID(), 0, true, false); for (int iTeam = 0; iTeam < MAX_TEAMS; ++iTeam) { if (pPlot->getRevealedOwner((TeamTypes)iTeam, false) == getID()) { pPlot->setRevealedOwner((TeamTypes)iTeam, eNewPlayer); } } } GC.getGameINLINE().updatePlotGroups(); return true; } bool CvPlayer::isValidTriggerReligion(const CvEventTriggerInfo& kTrigger, CvCity* pCity, ReligionTypes eReligion) const { if (kTrigger.getNumReligionsRequired() > 0) { bool bFound = false; for (int i = 0; i < kTrigger.getNumReligionsRequired(); ++i) { if (eReligion == kTrigger.getReligionRequired(i)) { bFound = true; break; } } if (!bFound) { return false; } } if (NULL != pCity) { if (!pCity->isHasReligion(eReligion)) { return false; } if (kTrigger.isHolyCity()) { if (!pCity->isHolyCity(eReligion)) { return false; } } } else { if (0 == getHasReligionCount(eReligion)) { return false; } if (kTrigger.isHolyCity()) { CvCity* pHolyCity = GC.getGameINLINE().getHolyCity(eReligion); if (NULL == pHolyCity || pHolyCity->getOwnerINLINE() != getID()) { return false; } } } return true; } bool CvPlayer::isValidTriggerCorporation(const CvEventTriggerInfo& kTrigger, CvCity* pCity, CorporationTypes eCorporation) const { if (kTrigger.getNumCorporationsRequired() > 0) { bool bFound = false; for (int i = 0; i < kTrigger.getNumCorporationsRequired(); ++i) { if (eCorporation == kTrigger.getCorporationRequired(i)) { bFound = true; break; } } if (!bFound) { return false; } } if (NULL != pCity) { if (!pCity->isHasCorporation(eCorporation)) { return false; } if (kTrigger.isHeadquarters()) { if (!pCity->isHeadquarters(eCorporation)) { return false; } } } else { if (getHasCorporationCount(eCorporation) > 0) { return true; } if (kTrigger.isHeadquarters()) { CvCity* pHeadquarters = GC.getGameINLINE().getHeadquarters(eCorporation); if (NULL == pHeadquarters || pHeadquarters->getOwnerINLINE() != getID()) { return false; } } } return false; } void CvPlayer::launch(VictoryTypes eVictory) { CvTeam& kTeam = GET_TEAM(getTeam()); if (!kTeam.canLaunch(eVictory)) { return; } kTeam.finalizeProjectArtTypes(); kTeam.setVictoryCountdown(eVictory, kTeam.getVictoryDelay(eVictory)); gDLL->getEngineIFace()->AddLaunch(getID()); kTeam.setCanLaunch(eVictory, false); CvCity *capital = getCapitalCity(); //message CvWString szBuffer; for(int i = 0; i < MAX_PLAYERS; ++i) { if (GET_PLAYER((PlayerTypes)i).isAlive()) { int plotX = -1; int plotY = -1; if((capital != NULL) && capital->isRevealed(GET_PLAYER((PlayerTypes) i).getTeam(), false)) { plotX = capital->getX(); plotY = capital->getY(); } if (GET_PLAYER((PlayerTypes)i).getTeam() == getTeam()) { szBuffer = gDLL->getText("TXT_KEY_VICTORY_YOU_HAVE_LAUNCHED"); } else { szBuffer = gDLL->getText("TXT_KEY_VICTORY_TEAM_HAS_LAUNCHED", GET_TEAM(getTeam()).getName().GetCString()); } gDLL->getInterfaceIFace()->addMessage(((PlayerTypes)i), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_CULTURELEVEL", MESSAGE_TYPE_MAJOR_EVENT, ARTFILEMGR.getMiscArtInfo("SPACE_SHIP_BUTTON")->getPath(), (ColorTypes)GC.getInfoTypeForString("COLOR_HIGHLIGHT_TEXT"), plotX, plotY, true, true); } } } bool CvPlayer::isFreePromotion(UnitCombatTypes eUnitCombat, PromotionTypes ePromotion) const { for (UnitCombatPromotionArray::const_iterator it = m_aFreeUnitCombatPromotions.begin(); it != m_aFreeUnitCombatPromotions.end(); ++it) { if ((*it).first == eUnitCombat && (*it).second == ePromotion) { return true; } } return false; } void CvPlayer::setFreePromotion(UnitCombatTypes eUnitCombat, PromotionTypes ePromotion, bool bFree) { for (UnitCombatPromotionArray::iterator it = m_aFreeUnitCombatPromotions.begin(); it != m_aFreeUnitCombatPromotions.end(); ++it) { if ((*it).first == eUnitCombat && (*it).second == ePromotion) { if (!bFree) { m_aFreeUnitCombatPromotions.erase(it); } return; } } if (bFree) { m_aFreeUnitCombatPromotions.push_back(std::make_pair(eUnitCombat, ePromotion)); } } bool CvPlayer::isFreePromotion(UnitClassTypes eUnitClass, PromotionTypes ePromotion) const { for (UnitClassPromotionArray::const_iterator it = m_aFreeUnitClassPromotions.begin(); it != m_aFreeUnitClassPromotions.end(); ++it) { if ((*it).first == eUnitClass && (*it).second == ePromotion) { return true; } } return false; } void CvPlayer::setFreePromotion(UnitClassTypes eUnitClass, PromotionTypes ePromotion, bool bFree) { for (UnitClassPromotionArray::iterator it = m_aFreeUnitClassPromotions.begin(); it != m_aFreeUnitClassPromotions.end(); ++it) { if ((*it).first == eUnitClass && (*it).second == ePromotion) { if (!bFree) { m_aFreeUnitClassPromotions.erase(it); } return; } } if (bFree) { m_aFreeUnitClassPromotions.push_back(std::make_pair(eUnitClass, ePromotion)); } } PlayerVoteTypes CvPlayer::getVote(int iId) const { for (std::vector< std::pair<int, PlayerVoteTypes> >::const_iterator it = m_aVote.begin(); it != m_aVote.end(); ++it) { if ((*it).first == iId) { return ((*it).second); } } return NO_PLAYER_VOTE; } void CvPlayer::setVote(int iId, PlayerVoteTypes ePlayerVote) { for (std::vector< std::pair<int, PlayerVoteTypes> >::iterator it = m_aVote.begin(); it != m_aVote.end(); ++it) { if ((*it).first == iId) { if (ePlayerVote == NO_PLAYER_VOTE) { m_aVote.erase(it); } else { (*it).second = ePlayerVote; } return; } } if (ePlayerVote != NO_PLAYER_VOTE) { m_aVote.push_back(std::make_pair(iId, ePlayerVote)); } } int CvPlayer::getUnitExtraCost(UnitClassTypes eUnitClass) const { for (std::vector< std::pair<UnitClassTypes, int> >::const_iterator it = m_aUnitExtraCosts.begin(); it != m_aUnitExtraCosts.end(); ++it) { if ((*it).first == eUnitClass) { return ((*it).second); } } return 0; } void CvPlayer::setUnitExtraCost(UnitClassTypes eUnitClass, int iCost) { for (std::vector< std::pair<UnitClassTypes, int> >::iterator it = m_aUnitExtraCosts.begin(); it != m_aUnitExtraCosts.end(); ++it) { if ((*it).first == eUnitClass) { if (0 == iCost) { m_aUnitExtraCosts.erase(it); } else { (*it).second = iCost; } return; } } if (0 != iCost) { m_aUnitExtraCosts.push_back(std::make_pair(eUnitClass, iCost)); } } // CACHE: cache frequently used values /////////////////////////////////////// bool CvPlayer::hasShrine(ReligionTypes eReligion) { bool bHasShrine = false; if (eReligion != NO_RELIGION) { CvCity* pHolyCity = GC.getGameINLINE().getHolyCity(eReligion); // if the holy city exists, and we own it if (pHolyCity != NULL && pHolyCity->getOwnerINLINE() == getID()) bHasShrine = pHolyCity->hasShrine(eReligion); } return bHasShrine; } void CvPlayer::invalidatePopulationRankCache() { int iLoop; CvCity* pLoopCity; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->invalidatePopulationRankCache(); } } void CvPlayer::invalidateYieldRankCache(YieldTypes eYield) { int iLoop; CvCity* pLoopCity; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->invalidateYieldRankCache(); } } void CvPlayer::invalidateCommerceRankCache(CommerceTypes eCommerce) { int iLoop; CvCity* pLoopCity; for (pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { pLoopCity->invalidateCommerceRankCache(); } } void CvPlayer::doUpdateCacheOnTurn() { // add this back, after testing without it // invalidateYieldRankCache(); } void CvPlayer::processVoteSourceBonus(VoteSourceTypes eVoteSource, bool bActive) { int iLoop; for (CvCity* pCity = firstCity(&iLoop); NULL != pCity; pCity = nextCity(&iLoop)) { pCity->processVoteSourceBonus(eVoteSource, bActive); } } int CvPlayer::getVotes(VoteTypes eVote, VoteSourceTypes eVoteSource) const { int iVotes = 0; ReligionTypes eReligion = GC.getGameINLINE().getVoteSourceReligion(eVoteSource); if (NO_VOTE == eVote) { if (NO_RELIGION != eReligion) { iVotes = getReligionPopulation(eReligion); } else { iVotes = getTotalPopulation(); } } else { if (!GC.getVoteInfo(eVote).isVoteSourceType(eVoteSource)) { return 0; } if (GC.getVoteInfo(eVote).isCivVoting()) { if (NO_RELIGION == eReligion || getHasReligionCount(eReligion) > 0) { iVotes = 1; } } else if (GC.getVoteInfo(eVote).isCityVoting()) { if (NO_RELIGION != eReligion) { iVotes = getHasReligionCount(eReligion); } else { iVotes = getNumCities(); } } else { if (NO_RELIGION == eReligion) { iVotes = getTotalPopulation(); } else { iVotes = getReligionPopulation(eReligion); } } if (NO_RELIGION != eReligion && getStateReligion() == eReligion) { iVotes *= (100 + GC.getVoteInfo(eVote).getStateReligionVotePercent()); iVotes /= 100; } } return iVotes; } bool CvPlayer::canDoResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData) const { CvTeam& kOurTeam = GET_TEAM(getTeam()); if (NO_PLAYER != kData.ePlayer) { if (!kOurTeam.isHasMet(GET_PLAYER(kData.ePlayer).getTeam())) { return false; } } if (GC.getVoteInfo(kData.eVote).isOpenBorders()) { for (int iTeam2 = 0; iTeam2 < MAX_CIV_TEAMS; ++iTeam2) { if (GET_TEAM((TeamTypes)iTeam2).isVotingMember(eVoteSource)) { if (!kOurTeam.isOpenBordersTrading() && !GET_TEAM((TeamTypes)iTeam2).isOpenBordersTrading()) { return false; } if (kOurTeam.isAtWar((TeamTypes)iTeam2)) { return false; } } } } else if (GC.getVoteInfo(kData.eVote).isDefensivePact()) { for (int iTeam2 = 0; iTeam2 < MAX_CIV_TEAMS; ++iTeam2) { if (GET_TEAM((TeamTypes)iTeam2).isVotingMember(eVoteSource)) { if (!kOurTeam.isDefensivePactTrading() && !GET_TEAM((TeamTypes)iTeam2).isDefensivePactTrading()) { return false; } if (kOurTeam.getAtWarCount(true) > 0 || GET_TEAM((TeamTypes)iTeam2).getAtWarCount(true) > 0) { return false; } if (!kOurTeam.canSignDefensivePact((TeamTypes)iTeam2)) { return false; } } } } else if (GC.getVoteInfo(kData.eVote).isForcePeace()) { FAssert(NO_PLAYER != kData.ePlayer); CvPlayer& kPlayer = GET_PLAYER(kData.ePlayer); if (kPlayer.getTeam() != getTeam()) { if (kOurTeam.isAtWar(kPlayer.getTeam())) { TeamTypes eMaster = getTeam(); for (int iMaster = 0; iMaster < MAX_CIV_TEAMS; ++iMaster) { if (iMaster != getID() && kOurTeam.isVassal((TeamTypes)iMaster)) { if (GET_TEAM((TeamTypes)iMaster).isVotingMember(eVoteSource)) { eMaster = (TeamTypes)iMaster; break; } } } if (!GET_TEAM(eMaster).canContact(kPlayer.getTeam())) { return false; } } } } else if (GC.getVoteInfo(kData.eVote).isForceWar()) { FAssert(NO_PLAYER != kData.ePlayer); CvPlayer& kPlayer = GET_PLAYER(kData.ePlayer); if (!kOurTeam.isAtWar(kPlayer.getTeam())) { TeamTypes eMaster = getTeam(); for (int iMaster = 0; iMaster < MAX_CIV_TEAMS; ++iMaster) { if (iMaster != getID() && kOurTeam.isVassal((TeamTypes)iMaster)) { if (GET_TEAM((TeamTypes)iMaster).isVotingMember(eVoteSource)) { eMaster = (TeamTypes)iMaster; break; } } } if (!GET_TEAM(eMaster).canDeclareWar(kPlayer.getTeam())) { return false; } } } else if (GC.getVoteInfo(kData.eVote).isForceNoTrade()) { FAssert(NO_PLAYER != kData.ePlayer); CvPlayer& kPlayer = GET_PLAYER(kData.ePlayer); if (!canStopTradingWithTeam(kPlayer.getTeam(), true)) { return false; } } else if (GC.getVoteInfo(kData.eVote).isAssignCity()) { if (GET_TEAM(GET_PLAYER(kData.eOtherPlayer).getTeam()).isVassal(GET_PLAYER(kData.ePlayer).getTeam())) { return false; } } return true; } bool CvPlayer::canDefyResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData) const { if (GC.getGameINLINE().getSecretaryGeneral(eVoteSource) == getTeam()) { return false; } if (GC.getVoteInfo(kData.eVote).isOpenBorders()) { for (int iTeam = 0; iTeam < MAX_CIV_TEAMS; ++iTeam) { CvTeam& kTeam = GET_TEAM((TeamTypes)iTeam); if ((PlayerTypes)iTeam != getTeam()) { if (kTeam.isVotingMember(eVoteSource)) { if (!kTeam.isOpenBorders(getTeam())) { return true; } } } } } else if (GC.getVoteInfo(kData.eVote).isDefensivePact()) { for (int iTeam = 0; iTeam < MAX_CIV_TEAMS; ++iTeam) { CvTeam& kTeam = GET_TEAM((TeamTypes)iTeam); if ((PlayerTypes)iTeam != getTeam()) { if (kTeam.isVotingMember(eVoteSource)) { if (!kTeam.isDefensivePact(getTeam())) { return true; } } } } } else if (GC.getVoteInfo(kData.eVote).isForceNoTrade()) { return true; } else if (GC.getVoteInfo(kData.eVote).isForceWar()) { if (!::atWar(getTeam(), GET_PLAYER(kData.ePlayer).getTeam())) { /************************************************************************************************/ /* BETTER_BTS_AI_MOD 12/31/08 jdog5000 */ /* */ /* */ /************************************************************************************************/ // Vassals can't defy declarations of war if( !GET_TEAM(getTeam()).isAVassal() ) { return true; } /************************************************************************************************/ /* BETTER_BTS_AI_MOD END */ /************************************************************************************************/ } } else if (GC.getVoteInfo(kData.eVote).isForcePeace()) { if (GET_PLAYER(kData.ePlayer).getTeam() == getTeam()) { return true; } if (::atWar(getTeam(), GET_PLAYER(kData.ePlayer).getTeam())) { return true; } } else if (GC.getVoteInfo(kData.eVote).isAssignCity()) { if (kData.ePlayer == getID()) { return true; } } else if (!GC.getGameINLINE().isTeamVote(kData.eVote)) { return true; } return false; } void CvPlayer::setDefiedResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData) { FAssert(canDefyResolution(eVoteSource, kData)); // cities get unhappiness int iLoop; for (CvCity* pLoopCity = firstCity(&iLoop); NULL != pLoopCity; pLoopCity = nextCity(&iLoop)) { ReligionTypes eReligion = GC.getGameINLINE().getVoteSourceReligion(eVoteSource); if (NO_RELIGION == eReligion || pLoopCity->isHasReligion(eReligion)) { int iAngerLength = pLoopCity->flatDefyResolutionAngerLength(); if (NO_RELIGION != eReligion && pLoopCity->isHasReligion(eReligion)) { iAngerLength /= std::max(1, pLoopCity->getReligionCount()); } pLoopCity->changeDefyResolutionAngerTimer(iAngerLength); } } setLoyalMember(eVoteSource, false); } void CvPlayer::setEndorsedResolution(VoteSourceTypes eVoteSource, const VoteSelectionSubData& kData) { setLoyalMember(eVoteSource, true); } bool CvPlayer::isFullMember(VoteSourceTypes eVoteSource) const { if (NO_RELIGION != GC.getGameINLINE().getVoteSourceReligion(eVoteSource)) { if (getStateReligion() != GC.getGameINLINE().getVoteSourceReligion(eVoteSource)) { return false; } } if (NO_CIVIC != GC.getVoteSourceInfo(eVoteSource).getCivic()) { if (!isCivic((CivicTypes)GC.getVoteSourceInfo(eVoteSource).getCivic())) { return false; } } if (!isLoyalMember(eVoteSource)) { return false; } return isVotingMember(eVoteSource); } bool CvPlayer::isVotingMember(VoteSourceTypes eVoteSource) const { return (getVotes(NO_VOTE, eVoteSource) > 0); } PlayerTypes CvPlayer::pickConqueredCityOwner(const CvCity& kCity) const { PlayerTypes eBestPlayer = kCity.getLiberationPlayer(true); if (NO_PLAYER != eBestPlayer) { if (GET_TEAM(getTeam()).isVassal(GET_PLAYER(eBestPlayer).getTeam())) { return eBestPlayer; } } return getID(); } bool CvPlayer::canHaveTradeRoutesWith(PlayerTypes ePlayer) const { CvPlayer& kOtherPlayer = GET_PLAYER(ePlayer); if (!kOtherPlayer.isAlive()) { return false; } if (getTeam() == kOtherPlayer.getTeam()) { return true; } if (GET_TEAM(getTeam()).isFreeTrade(kOtherPlayer.getTeam())) { if (GET_TEAM(getTeam()).isVassal(kOtherPlayer.getTeam())) { return true; } if (GET_TEAM(kOtherPlayer.getTeam()).isVassal(getTeam())) { return true; } if (!isNoForeignTrade() && !kOtherPlayer.isNoForeignTrade()) { return true; } } return false; } bool CvPlayer::canStealTech(PlayerTypes eTarget, TechTypes eTech) const { if (GET_TEAM(GET_PLAYER(eTarget).getTeam()).isHasTech(eTech)) { if (canResearch(eTech)) { return true; } } return false; } bool CvPlayer::canForceCivics(PlayerTypes eTarget, CivicTypes eCivic) const { return (GET_PLAYER(eTarget).canDoCivics(eCivic) && !GET_PLAYER(eTarget).isCivic(eCivic) && isCivic(eCivic)); } bool CvPlayer::canForceReligion(PlayerTypes eTarget, ReligionTypes eReligion) const { return (GET_PLAYER(eTarget).canDoReligion(eReligion) && GET_PLAYER(eTarget).getStateReligion() != eReligion && getStateReligion() == eReligion); } bool CvPlayer::canSpyDestroyUnit(PlayerTypes eTarget, CvUnit& kUnit) const { if (kUnit.getTeam() == getTeam()) { return false; } if (kUnit.getUnitInfo().getProductionCost() <= 0) { return false; } if (!kUnit.plot()->isVisible(getTeam(), false)) { return false; } return true; } bool CvPlayer::canSpyBribeUnit(PlayerTypes eTarget, CvUnit& kUnit) const { if (!canSpyDestroyUnit(eTarget, kUnit)) { return false; } // Can't buy units when at war if (kUnit.isEnemy(getTeam())) { return false; } // Can't buy units if they are not in a legal plot if (!GET_TEAM(getTeam()).isFriendlyTerritory(GET_PLAYER(eTarget).getTeam()) && !GET_TEAM(getTeam()).isOpenBorders(GET_PLAYER(eTarget).getTeam())) { return false; } CLLNode<IDInfo>* pUnitNode = kUnit.plot()->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data); pUnitNode = kUnit.plot()->nextUnitNode(pUnitNode); if (NULL != pLoopUnit && pLoopUnit != &kUnit) { if (pLoopUnit->isEnemy(getTeam())) { // If we buy the unit, we will be on the same plot as an enemy unit! Not good. return false; } } } return true; } bool CvPlayer::canSpyDestroyBuilding(PlayerTypes eTarget, BuildingTypes eBuilding) const { CvBuildingInfo& kBuilding = GC.getBuildingInfo(eBuilding); if (kBuilding.getProductionCost() <= 0) { return false; } if (::isLimitedWonderClass((BuildingClassTypes)kBuilding.getBuildingClassType())) { return false; } return true; } bool CvPlayer::canSpyDestroyProject(PlayerTypes eTarget, ProjectTypes eProject) const { CvProjectInfo& kProject = GC.getProjectInfo(eProject); if (kProject.getProductionCost() <= 0) { return false; } if (GET_TEAM(GET_PLAYER(eTarget).getTeam()).getProjectCount(eProject) <= 0) { return false; } if (::isWorldProject(eProject)) { return false; } if (!kProject.isSpaceship()) { return false; } else { VictoryTypes eVicotry = (VictoryTypes)kProject.getVictoryPrereq(); if (NO_VICTORY != eVicotry) { // Can't destroy spaceship components if we have already launched if (GET_TEAM(GET_PLAYER(eTarget).getTeam()).getVictoryCountdown(eVicotry) >= 0) { return false; } } } return true; } void CvPlayer::forcePeace(PlayerTypes ePlayer) { if (!GET_TEAM(getTeam()).isAVassal()) { FAssert(GET_TEAM(getTeam()).canChangeWarPeace(GET_PLAYER(ePlayer).getTeam())); CLinkList<TradeData> playerList; CLinkList<TradeData> loopPlayerList; TradeData kTradeData; setTradeItem(&kTradeData, TRADE_PEACE_TREATY); playerList.insertAtEnd(kTradeData); loopPlayerList.insertAtEnd(kTradeData); GC.getGameINLINE().implementDeal(getID(), ePlayer, &playerList, &loopPlayerList); } } bool CvPlayer::canSpiesEnterBorders(PlayerTypes ePlayer) const { for (int iMission = 0; iMission < GC.getNumEspionageMissionInfos(); ++iMission) { if (GC.getEspionageMissionInfo((EspionageMissionTypes)iMission).isNoActiveMissions() && GC.getEspionageMissionInfo((EspionageMissionTypes)iMission).isPassive()) { if (GET_PLAYER(ePlayer).canDoEspionageMission((EspionageMissionTypes)iMission, getID(), NULL, -1, NULL)) { return false; } } } return true; } int CvPlayer::getReligionPopulation(ReligionTypes eReligion) const { int iPopulation = 0; int iLoop; for (CvCity* pCity = firstCity(&iLoop); NULL != pCity; pCity = nextCity(&iLoop)) { if (pCity->isHasReligion(eReligion)) { iPopulation += pCity->getPopulation(); } } return iPopulation; } int CvPlayer::getNewCityProductionValue() const { int iValue = 0; for (int iJ = 0; iJ < GC.getNumBuildingClassInfos(); iJ++) { BuildingTypes eBuilding = ((BuildingTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iJ))); if (NO_BUILDING != eBuilding) { if (GC.getBuildingInfo(eBuilding).getFreeStartEra() != NO_ERA) { if (GC.getGameINLINE().getStartEra() >= GC.getBuildingInfo(eBuilding).getFreeStartEra()) { iValue += (100 * getProductionNeeded(eBuilding)) / std::max(1, 100 + getProductionModifier(eBuilding)); } } } } iValue *= 100 + GC.getDefineINT("NEW_CITY_BUILDING_VALUE_MODIFIER"); iValue /= 100; iValue += (GC.getDefineINT("ADVANCED_START_CITY_COST") * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getGrowthPercent()) / 100; int iPopulation = GC.getDefineINT("INITIAL_CITY_POPULATION") + GC.getEraInfo(GC.getGameINLINE().getStartEra()).getFreePopulation(); for (int i = 1; i <= iPopulation; ++i) { iValue += (getGrowthThreshold(i) * GC.getDefineINT("ADVANCED_START_POPULATION_COST")) / 100; } return iValue; } int CvPlayer::getGrowthThreshold(int iPopulation) const { int iThreshold; iThreshold = (GC.getDefineINT("BASE_CITY_GROWTH_THRESHOLD") + (iPopulation * GC.getDefineINT("CITY_GROWTH_MULTIPLIER"))); iThreshold *= GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getGrowthPercent(); iThreshold /= 100; iThreshold *= GC.getEraInfo(GC.getGameINLINE().getStartEra()).getGrowthPercent(); iThreshold /= 100; if (!isHuman() && !isBarbarian()) { iThreshold *= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIGrowthPercent(); iThreshold /= 100; iThreshold *= std::max(0, ((GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAIPerEraModifier() * getCurrentEra()) + 100)); iThreshold /= 100; } return std::max(1, iThreshold); } void CvPlayer::verifyUnitStacksValid() { int iLoop; for(CvUnit* pLoopUnit = firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = nextUnit(&iLoop)) { pLoopUnit->verifyStackValid(); } } UnitTypes CvPlayer::getTechFreeUnit(TechTypes eTech) const { UnitClassTypes eUnitClass = (UnitClassTypes) GC.getTechInfo(eTech).getFirstFreeUnitClass(); if (eUnitClass == NO_UNITCLASS) { return NO_UNIT; } UnitTypes eUnit = ((UnitTypes)(GC.getCivilizationInfo(getCivilizationType()).getCivilizationUnits(eUnitClass))); if (eUnit == NO_UNIT) { return NO_UNIT; } if (GC.getUnitInfo(eUnit).getEspionagePoints() > 0 && GC.getGameINLINE().isOption(GAMEOPTION_NO_ESPIONAGE)) { return NO_UNIT; } return eUnit; } // BUG - Trade Totals - start /* * Adds the yield and count for each trade route with eWithPlayer. * * The yield and counts are not reset to zero. * If Fractional Trade Routes is enabled and bRound is false, the yield values are left times 100. */ void CvPlayer::calculateTradeTotals(YieldTypes eIndex, int& iDomesticYield, int& iDomesticRoutes, int& iForeignYield, int& iForeignRoutes, PlayerTypes eWithPlayer, bool bRound, bool bBase) const { int iIter; for (CvCity* pCity = firstCity(&iIter); NULL != pCity; pCity = nextCity(&iIter)) { pCity->calculateTradeTotals(eIndex, iDomesticYield, iDomesticRoutes, iForeignYield, iForeignRoutes, eWithPlayer, bRound, bBase); } } /* * Returns the total trade yield with eWithPlayer. * * If Fractional Trade Routes is enabled, the yield value is left times 100. * UNUSED */ int CvPlayer::calculateTotalTradeYield(YieldTypes eIndex, PlayerTypes eWithPlayer, bool bRound, bool bBase) const { int iDomesticYield = 0; int iDomesticRoutes = 0; int iForeignYield = 0; int iForeignRoutes = 0; calculateTradeTotals(eIndex, iDomesticYield, iDomesticRoutes, iForeignYield, iForeignRoutes, eWithPlayer, bRound, bBase); return iDomesticYield + iForeignRoutes; } // BUG - Trade Totals - end void CvPlayer::buildTradeTable(PlayerTypes eOtherPlayer, CLinkList<TradeData>& ourList) const { TradeData item; int iLoop; // Put the gold and maps into the table setTradeItem(&item, TRADE_GOLD); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } // Gold per turn setTradeItem(&item, TRADE_GOLD_PER_TURN); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } // Maps setTradeItem(&item, TRADE_MAPS, 0); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } // Vassal setTradeItem(&item, TRADE_VASSAL, 0); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } // Open Borders setTradeItem(&item, TRADE_OPEN_BORDERS); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } // Defensive Pact setTradeItem(&item, TRADE_DEFENSIVE_PACT); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } // Permanent Alliance setTradeItem(&item, TRADE_PERMANENT_ALLIANCE); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } if (::atWar(getTeam(), GET_PLAYER(eOtherPlayer).getTeam())) { // We are at war, allow a peace treaty option setTradeItem(&item, TRADE_PEACE_TREATY); ourList.insertAtEnd(item); // Capitulation setTradeItem(&item, TRADE_SURRENDER, 0); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); } } // Initial build of the inventory lists and buttons. // Go through all the possible headings for (int i = NUM_BASIC_ITEMS; i < NUM_TRADEABLE_HEADINGS; i++) { bool bFoundItemUs = false; // Build what we need to build for this item switch (i) { case TRADE_TECHNOLOGIES: for (int j = 0; j < GC.getNumTechInfos(); j++) { setTradeItem(&item, TRADE_TECHNOLOGIES, j); if (canTradeItem(eOtherPlayer, item)) { bFoundItemUs = true; ourList.insertAtEnd(item); } } break; case TRADE_RESOURCES: for (int j = 0; j < GC.getNumBonusInfos(); j++) { setTradeItem(&item, TRADE_RESOURCES, j); if (canTradeItem(eOtherPlayer, item)) { bFoundItemUs = true; ourList.insertAtEnd(item); } } break; case TRADE_CITIES: for (CvCity* pLoopCity = firstCity(&iLoop); pLoopCity != NULL; pLoopCity = nextCity(&iLoop)) { setTradeItem(&item, TRADE_CITIES, pLoopCity->getID()); if (canTradeItem(eOtherPlayer, item)) { bFoundItemUs = true; ourList.insertAtEnd(item); } } break; case TRADE_PEACE: if (!isHuman()) { for (int j = 0; j < MAX_CIV_TEAMS; j++) { if (GET_TEAM((TeamTypes)j).isAlive()) { if (j != getTeam() && j != GET_PLAYER(eOtherPlayer).getTeam()) { setTradeItem(&item, TRADE_PEACE, j); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); bFoundItemUs = true; } } } } } break; case TRADE_WAR: if (!isHuman()) { for (int j = 0; j < MAX_CIV_TEAMS; j++) { if (GET_TEAM((TeamTypes)j).isAlive()) { if (j != getTeam() && j != GET_PLAYER(eOtherPlayer).getTeam()) { setTradeItem(&item, TRADE_WAR, j); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); bFoundItemUs = true; } } } } } break; case TRADE_EMBARGO: if (!isHuman()) { for (int j = 0; j < MAX_CIV_TEAMS; j++) { if (GET_TEAM((TeamTypes)j).isAlive()) { if (j != getTeam() && j != GET_PLAYER(eOtherPlayer).getTeam()) { setTradeItem(&item, TRADE_EMBARGO, j); if (canTradeItem(eOtherPlayer, item)) { ourList.insertAtEnd(item); bFoundItemUs = true; } } } } } break; case TRADE_CIVIC: for (int j = 0; j < GC.getNumCivicInfos(); j++) { setTradeItem(&item, TRADE_CIVIC, j); if (canTradeItem(eOtherPlayer, item)) { bFoundItemUs = true; ourList.insertAtEnd(item); } } break; case TRADE_RELIGION: for (int j = 0; j < GC.getNumReligionInfos(); j++) { setTradeItem(&item, TRADE_RELIGION, j); if (canTradeItem(eOtherPlayer, item)) { bFoundItemUs = true; ourList.insertAtEnd(item); } } break; } } } bool CvPlayer::getHeadingTradeString(PlayerTypes eOtherPlayer, TradeableItems eItem, CvWString& szString, CvString& szIcon) const { szIcon.clear(); switch ( eItem ) { case TRADE_TECHNOLOGIES: szString = gDLL->getText("TXT_KEY_CONCEPT_TECHNOLOGY"); break; case TRADE_RESOURCES: szString = gDLL->getText("TXT_KEY_TRADE_RESOURCES"); break; case TRADE_CITIES: szString = gDLL->getText("TXT_KEY_TRADE_CITIES"); break; case TRADE_PEACE: szString = gDLL->getText("TXT_KEY_TRADE_MAKE_PEACE_WITH"); break; case TRADE_WAR: szString = gDLL->getText("TXT_KEY_TRADE_DECLARE_WAR_ON"); break; case TRADE_EMBARGO: szString = gDLL->getText("TXT_KEY_TRADE_STOP_TRADING_WITH"); break; case TRADE_CIVIC: szString = gDLL->getText("TXT_KEY_TRADE_ADOPT"); break; case TRADE_RELIGION: szString = gDLL->getText("TXT_KEY_TRADE_CONVERT"); break; default: szString.clear(); return false; break; } return true; } bool CvPlayer::getItemTradeString(PlayerTypes eOtherPlayer, bool bOffer, bool bShowingCurrent, const TradeData& zTradeData, CvWString& szString, CvString& szIcon) const { szIcon.clear(); switch (zTradeData.m_eItemType) { case TRADE_GOLD: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_GOLD_NUM", zTradeData.m_iData); } else { szString = gDLL->getText("TXT_KEY_TRADE_GOLD_NUM", AI_maxGoldTrade(eOtherPlayer)); } break; case TRADE_GOLD_PER_TURN: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_GOLD_PER_TURN_NUM", zTradeData.m_iData); } else { szString = gDLL->getText("TXT_KEY_TRADE_GOLD_PER_TURN_NUM", AI_maxGoldPerTurnTrade(eOtherPlayer)); } break; case TRADE_MAPS: szString = gDLL->getText("TXT_KEY_TRADE_WORLD_MAP_STRING"); break; case TRADE_VASSAL: szString = gDLL->getText("TXT_KEY_TRADE_VASSAL_STRING"); break; case TRADE_SURRENDER: szString = gDLL->getText("TXT_KEY_TRADE_CAPITULATE_STRING"); break; case TRADE_OPEN_BORDERS: szString = gDLL->getText("TXT_KEY_TRADE_OPEN_BORDERS_STRING"); break; case TRADE_DEFENSIVE_PACT: szString = gDLL->getText("TXT_KEY_TRADE_DEFENSIVE_PACT_STRING"); break; case TRADE_PERMANENT_ALLIANCE: szString = gDLL->getText("TXT_KEY_TRADE_PERMANENT_ALLIANCE_STRING"); break; case TRADE_PEACE_TREATY: szString = gDLL->getText("TXT_KEY_TRADE_PEACE_TREATY_STRING", GC.getDefineINT("PEACE_TREATY_LENGTH")); break; case TRADE_TECHNOLOGIES: szString = GC.getTechInfo((TechTypes)zTradeData.m_iData).getDescription(); szIcon = GC.getTechInfo((TechTypes)zTradeData.m_iData).getButton(); break; case TRADE_RESOURCES: if (bOffer) { int iNumResources = GET_PLAYER(eOtherPlayer).getNumTradeableBonuses((BonusTypes)zTradeData.m_iData); if (bShowingCurrent) { ++iNumResources; } szString = gDLL->getText("TXT_KEY_TRADE_RESOURCE", GC.getBonusInfo((BonusTypes)zTradeData.m_iData).getDescription(), iNumResources); } else { szString.Format( L"%s (%d)", GC.getBonusInfo((BonusTypes)zTradeData.m_iData).getDescription(), getNumTradeableBonuses((BonusTypes)zTradeData.m_iData)); } szIcon = GC.getBonusInfo((BonusTypes)zTradeData.m_iData).getButton(); break; case TRADE_CITIES: { CvCity* pCity = NULL; if (bOffer) { pCity = GET_PLAYER(eOtherPlayer).getCity(zTradeData.m_iData); } else { pCity = getCity(zTradeData.m_iData); } if (NULL != pCity) { if (pCity->getLiberationPlayer(false) == eOtherPlayer) { szString.Format(L"%s (%s)", pCity->getName().GetCString(), gDLL->getText("TXT_KEY_LIBERATE_CITY").GetCString()); } else { szString = gDLL->getText("TXT_KEY_CITY_OF", pCity->getNameKey()); } } } break; case TRADE_PEACE: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_PEACE_WITH"); szString += GET_TEAM((TeamTypes)zTradeData.m_iData).getName(); } else { szString = GET_TEAM((TeamTypes)zTradeData.m_iData).getName(); } break; case TRADE_WAR: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_WAR_WITH"); szString += GET_TEAM((TeamTypes)zTradeData.m_iData).getName(); } else { szString = GET_TEAM((TeamTypes)zTradeData.m_iData).getName(); } break; case TRADE_EMBARGO: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_STOP_TRADING_WITH"); szString += L" " + GET_TEAM((TeamTypes)zTradeData.m_iData).getName(); } else { szString = GET_TEAM((TeamTypes)zTradeData.m_iData).getName(); } break; case TRADE_CIVIC: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_ADOPT"); szString += GC.getCivicInfo((CivicTypes)zTradeData.m_iData).getDescription(); } else { szString = GC.getCivicInfo((CivicTypes)zTradeData.m_iData).getDescription(); } szIcon = GC.getCivicInfo((CivicTypes)zTradeData.m_iData).getButton(); break; case TRADE_RELIGION: if (bOffer) { szString = gDLL->getText("TXT_KEY_TRADE_CONVERT"); szString += GC.getReligionInfo((ReligionTypes)zTradeData.m_iData).getDescription(); } else { szString = GC.getReligionInfo((ReligionTypes)zTradeData.m_iData).getDescription(); } szIcon = GC.getReligionInfo((ReligionTypes)zTradeData.m_iData).getButton(); break; default: szString.clear(); return false; } return true; } void CvPlayer::updateTradeList(PlayerTypes eOtherPlayer, CLinkList<TradeData>& ourInventory, const CLinkList<TradeData>& ourOffer, const CLinkList<TradeData>& theirOffer) const { for (CLLNode<TradeData>* pNode = ourInventory.head(); pNode != NULL; pNode = ourInventory.next(pNode)) { pNode->m_data.m_bHidden = false; // Don't show peace treaties when not at war if (!::atWar(getTeam(), GET_PLAYER(eOtherPlayer).getTeam())) { if (pNode->m_data.m_eItemType == TRADE_PEACE_TREATY || pNode->m_data.m_eItemType == TRADE_SURRENDER) { pNode->m_data.m_bHidden = true; } } // Don't show technologies with no tech trading game option if (GC.getGame().isOption(GAMEOPTION_NO_TECH_TRADING) && pNode->m_data.m_eItemType == TRADE_TECHNOLOGIES) { pNode->m_data.m_bHidden = true; } } for (CLLNode<TradeData>* pNode = ourInventory.head(); pNode != NULL; pNode = ourInventory.next(pNode)) { switch (pNode->m_data.m_eItemType) { case TRADE_PEACE_TREATY: for (CLLNode<TradeData>* pOfferNode = ourOffer.head(); pOfferNode != NULL; pOfferNode = ourOffer.next(pOfferNode)) { // Don't show vassal deals if peace treaty is already on the table if (CvDeal::isVassal(pOfferNode->m_data.m_eItemType)) { pNode->m_data.m_bHidden = true; break; } } break; case TRADE_VASSAL: case TRADE_SURRENDER: for (CLLNode<TradeData>* pOfferNode = theirOffer.head(); pOfferNode != NULL; pOfferNode = theirOffer.next(pOfferNode)) { // Don't show vassal deals if another type of vassal deal is on the table if (CvDeal::isVassal(pOfferNode->m_data.m_eItemType)) { pNode->m_data.m_bHidden = true; break; } } if (!pNode->m_data.m_bHidden) { for (CLLNode<TradeData>* pOfferNode = ourOffer.head(); pOfferNode != NULL; pOfferNode = ourOffer.next(pOfferNode)) { // Don't show peace deals if the other player is offering to be a vassal if (CvDeal::isEndWar(pOfferNode->m_data.m_eItemType)) { pNode->m_data.m_bHidden = true; break; } } } break; default: break; } } if (!isHuman() || !GET_PLAYER(eOtherPlayer).isHuman()) // everything allowed in human-human trades { CLLNode<TradeData>* pFirstOffer = ourOffer.head(); if (pFirstOffer == NULL) { pFirstOffer = theirOffer.head(); } if (pFirstOffer != NULL) { if (!CvDeal::isEndWar(pFirstOffer->m_data.m_eItemType) || !::atWar(getTeam(), GET_PLAYER(eOtherPlayer).getTeam())) { for (CLLNode<TradeData>* pNode = ourInventory.head(); pNode != NULL; pNode = ourInventory.next(pNode)) { if (pFirstOffer->m_data.m_eItemType == TRADE_CITIES || pNode->m_data.m_eItemType == TRADE_CITIES) { pNode->m_data.m_bHidden = true; } else if (CvDeal::isAnnual(pFirstOffer->m_data.m_eItemType) != CvDeal::isAnnual(pNode->m_data.m_eItemType)) { pNode->m_data.m_bHidden = true; } } } } } } int CvPlayer::getIntroMusicScriptId(PlayerTypes eForPlayer) const { CvPlayer& kForPlayer = GET_PLAYER(eForPlayer); EraTypes eEra = kForPlayer.getCurrentEra(); CvLeaderHeadInfo& kLeader = GC.getLeaderHeadInfo(getLeaderType()); if (GET_TEAM(kForPlayer.getTeam()).isAtWar(getTeam())) { return kLeader.getDiploWarIntroMusicScriptIds(eEra); } else { return kLeader.getDiploPeaceIntroMusicScriptIds(eEra); } } int CvPlayer::getMusicScriptId(PlayerTypes eForPlayer) const { CvPlayer& kForPlayer = GET_PLAYER(eForPlayer); EraTypes eEra = kForPlayer.getCurrentEra(); CvLeaderHeadInfo& kLeader = GC.getLeaderHeadInfo(getLeaderType()); if (GET_TEAM(kForPlayer.getTeam()).isAtWar(getTeam())) { return kLeader.getDiploWarMusicScriptIds(eEra); } else { return kLeader.getDiploPeaceMusicScriptIds(eEra); } } void CvPlayer::getGlobeLayerColors(GlobeLayerTypes eGlobeLayerType, int iOption, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const { switch (eGlobeLayerType) { case GLOBE_LAYER_TRADE: getTradeLayerColors(aColors, aIndicators); break; case GLOBE_LAYER_UNIT: getUnitLayerColors((GlobeLayerUnitOptionTypes) iOption, aColors, aIndicators); break; case GLOBE_LAYER_RESOURCE: getResourceLayerColors((GlobeLayerResourceOptionTypes) iOption, aColors, aIndicators); break; case GLOBE_LAYER_RELIGION: getReligionLayerColors((ReligionTypes) iOption, aColors, aIndicators); break; case GLOBE_LAYER_CULTURE: getCultureLayerColors(aColors, aIndicators); break; default: FAssertMsg(false, "Unknown globe layer type"); break; } } void CvPlayer::getTradeLayerColors(std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const { aColors.resize(GC.getMapINLINE().numPlotsINLINE(), NiColorA(0, 0, 0, 0)); aIndicators.clear(); typedef std::map< int, std::vector<int> > PlotGroupMap; PlotGroupMap mapPlotGroups; for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); ++iI) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); CvPlotGroup* pPlotGroup = pLoopPlot->getPlotGroup(getID()); if (pPlotGroup != NULL && pLoopPlot->isRevealed(getTeam(), true) && pLoopPlot->getTeam() == getTeam()) { mapPlotGroups[pPlotGroup->getID()].push_back(iI); } } CvRandom kRandom; kRandom.init(42); for (PlotGroupMap::iterator it = mapPlotGroups.begin(); it != mapPlotGroups.end(); ++it) { NiColorA kColor(kRandom.getFloat(), kRandom.getFloat(), kRandom.getFloat(), 0.8f); std::vector<int>& aPlots = it->second; for (size_t i = 0; i < aPlots.size(); ++i) { aColors[aPlots[i]] = kColor; } } } void CvPlayer::getUnitLayerColors(GlobeLayerUnitOptionTypes eOption, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const { aColors.resize(GC.getMapINLINE().numPlotsINLINE(), NiColorA(0, 0, 0, 0)); aIndicators.clear(); std::vector< std::vector<float> > aafPlayerPlotStrength(MAX_PLAYERS); for (int i = 0; i < MAX_PLAYERS; i++) { if (GET_PLAYER((PlayerTypes)i).isAlive()) { aafPlayerPlotStrength[i].resize(GC.getMapINLINE().numPlotsINLINE()); } } float fMaxPlotStrength = 0.0f; // create unit plot indicators... // build the trade group texture typedef std::map<int, NiColor> GroupMap; GroupMap mapColors; // Loop through all the players CvWStringBuffer szBuffer; for (int iPlayer = 0; iPlayer < MAX_PLAYERS; iPlayer++) { if (GET_PLAYER((PlayerTypes)iPlayer).isAlive()) { for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); ++iI) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); int iNumUnits = pLoopPlot->getNumUnits(); float fPlotStrength = 0.0f; if (iNumUnits > 0 && pLoopPlot->isVisible(getTeam(), true)) { bool bShowIndicator = false; CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode(); while (pUnitNode != NULL) { CvUnit* pUnit = ::getUnit(pUnitNode->m_data); pUnitNode = pLoopPlot->nextUnitNode(pUnitNode); if (pUnit->getVisualOwner() == iPlayer && !pUnit->isInvisible(getTeam(), GC.getGameINLINE().isDebugMode())) { // now, is this unit of interest? bool bIsMilitary = pUnit->baseCombatStr() > 0; bool bIsEnemy = pUnit->isEnemy(getTeam()); bool bIsOnOurTeam = pUnit->getTeam() == getTeam(); bool bOfInterest = false; switch (eOption) { case SHOW_ALL_MILITARY: { bOfInterest = bIsMilitary; if (bOfInterest) { fPlotStrength += ((float) pUnit->currHitPoints() / (float) pUnit->maxHitPoints() * (float) pUnit->baseCombatStr()); } break; } case SHOW_TEAM_MILITARY: { bOfInterest = bIsMilitary && bIsOnOurTeam; if (bOfInterest) fPlotStrength += ((float) pUnit->currHitPoints() / (float) pUnit->maxHitPoints() * (float) pUnit->baseCombatStr()); break; } case SHOW_ENEMIES: { bOfInterest = bIsMilitary && bIsEnemy; if (bOfInterest) fPlotStrength += ((float) pUnit->currHitPoints() / (float) pUnit->maxHitPoints() * (float) pUnit->baseCombatStr()); break; } case SHOW_ENEMIES_IN_TERRITORY: { bOfInterest = bIsMilitary; break; } case SHOW_PLAYER_DOMESTICS: { bOfInterest = !bIsMilitary;// && (pUnit->getVisualOwner() == eCurPlayer); break; } default: bOfInterest = false; break; } // create the indicator if (bOfInterest) { bShowIndicator = true; } fMaxPlotStrength = std::max(fPlotStrength, fMaxPlotStrength); aafPlayerPlotStrength[iPlayer][iI] = fPlotStrength; } } if (bShowIndicator) { CvUnit* pUnit = pLoopPlot->getBestDefender(NO_PLAYER); if (pUnit != NULL) { PlayerColorTypes eUnitColor = GET_PLAYER(pUnit->getVisualOwner()).getPlayerColor(); const NiColorA& kColor = GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(eUnitColor).getColorTypePrimary()).getColor(); szBuffer.clear(); GAMETEXT.setPlotListHelp(szBuffer, pLoopPlot, true, true); CvPlotIndicatorData kIndicator; kIndicator.m_pUnit = pUnit; kIndicator.m_strLabel = "UNITS"; kIndicator.m_strIcon = pUnit->getButton(); if (eOption == SHOW_ENEMIES_IN_TERRITORY) { kIndicator.m_kColor.r = 1; kIndicator.m_kColor.g = 0; kIndicator.m_kColor.b = 0; } else { kIndicator.m_kColor.r = kColor.r; kIndicator.m_kColor.g = kColor.g; kIndicator.m_kColor.b = kColor.b; } kIndicator.m_strHelpText = szBuffer.getCString(); //setup visibility switch (eOption) { case SHOW_ENEMIES_IN_TERRITORY: kIndicator.m_bTestEnemyVisibility = true; kIndicator.m_eVisibility = PLOT_INDICATOR_VISIBLE_ALWAYS; break; case SHOW_ENEMIES: kIndicator.m_eVisibility = PLOT_INDICATOR_VISIBLE_ALWAYS; break; default: kIndicator.m_eVisibility = PLOT_INDICATOR_VISIBLE_ONSCREEN_ONLY; break; } aIndicators.push_back(kIndicator); } } } } } } if (fMaxPlotStrength > 0) { for (int iPlayer = 0; iPlayer < MAX_PLAYERS; iPlayer++) { if (GET_PLAYER((PlayerTypes)iPlayer).isAlive()) { PlayerColorTypes eCurPlayerColor = GET_PLAYER((PlayerTypes) iPlayer).getPlayerColor(); const NiColorA& kColor = GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(eCurPlayerColor).getColorTypePrimary()).getColor(); for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); if (pLoopPlot->isVisible(getTeam(), true)) { float fPlotStrength = aafPlayerPlotStrength[iPlayer][iI]; if (fPlotStrength > 0) { float fAlpha = (fPlotStrength / fMaxPlotStrength * 0.75f + 0.25f) * 0.8f; if (fAlpha > aColors[iI].a) { aColors[iI] = kColor; aColors[iI].a = fAlpha; } } } } } } } } void CvPlayer::getResourceLayerColors(GlobeLayerResourceOptionTypes eOption, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const { aColors.clear(); aIndicators.clear(); PlayerColorTypes ePlayerColor = getPlayerColor(); CvWStringBuffer szBuffer; for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); PlayerTypes eOwner = pLoopPlot->getRevealedOwner(getTeam(), true); if (pLoopPlot->isRevealed(getTeam(), true)) { BonusTypes eCurType = pLoopPlot->getBonusType((GC.getGame().isDebugMode()) ? NO_TEAM : getTeam()); if (eCurType != NO_BONUS) { CvBonusInfo& kBonusInfo = GC.getBonusInfo(eCurType); bool bOfInterest = false; switch (eOption) { case SHOW_ALL_RESOURCES: bOfInterest = true; break; case SHOW_STRATEGIC_RESOURCES: bOfInterest = (kBonusInfo.getHappiness() == 0) && (kBonusInfo.getHealth() == 0); break; case SHOW_HAPPY_RESOURCES: bOfInterest = (kBonusInfo.getHappiness() != 0 ) && (kBonusInfo.getHealth() == 0); break; case SHOW_HEALTH_RESOURCES: bOfInterest = (kBonusInfo.getHappiness() == 0) && (kBonusInfo.getHealth() != 0); break; } if (bOfInterest) { CvPlotIndicatorData kData; kData.m_strLabel = "RESOURCES"; kData.m_eVisibility = PLOT_INDICATOR_VISIBLE_ONSCREEN_ONLY; kData.m_strIcon = GC.getBonusInfo(eCurType).getButton(); int x = pLoopPlot->getX(); int y = pLoopPlot->getY(); kData.m_Target = NiPoint2(GC.getMapINLINE().plotXToPointX(x), GC.getMapINLINE().plotYToPointY(y)); if (eOwner == NO_PLAYER) { kData.m_kColor.r = 0.8f; kData.m_kColor.g = 0.8f; kData.m_kColor.b = 0.8f; } else { PlayerColorTypes eCurPlayerColor = GET_PLAYER(eOwner).getPlayerColor(); const NiColorA& kColor = GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(eCurPlayerColor).getColorTypePrimary()).getColor(); kData.m_kColor.r = kColor.r; kData.m_kColor.g = kColor.g; kData.m_kColor.b = kColor.b; } szBuffer.clear(); GAMETEXT.setBonusHelp(szBuffer, eCurType, false); kData.m_strHelpText = szBuffer.getCString(); aIndicators.push_back(kData); } } } } } void CvPlayer::getReligionLayerColors(ReligionTypes eSelectedReligion, std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const { aColors.resize(GC.getMapINLINE().numPlotsINLINE(), NiColorA(0, 0, 0, 0)); aIndicators.clear(); CvRandom kRandom; kRandom.init(42 * eSelectedReligion); const NiColorA kBaseColor(kRandom.getFloat(), kRandom.getFloat(), kRandom.getFloat(), 1.0f); for (int iI = 0; iI < MAX_PLAYERS; iI ++) { if (GET_PLAYER((PlayerTypes)iI).isAlive()) { int iLoop; for (CvCity* pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop)) { if (pLoopCity->isRevealed(getTeam(), true)) { if (pLoopCity->isHasReligion(eSelectedReligion)) { float fAlpha = 0.8f; if (!pLoopCity->isHolyCity(eSelectedReligion)) { fAlpha *= 0.5f; } // loop through the city's plots for (int iJ = 0; iJ < NUM_CITY_PLOTS; iJ++) { CvPlot* pLoopPlot = plotCity(pLoopCity->getX(), pLoopCity->getY(), iJ); if (pLoopPlot != NULL) { // visibility query if (pLoopPlot->isRevealed(getTeam(), true)) { int iIndex = GC.getMapINLINE().plotNumINLINE(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()); if (fAlpha > aColors[iIndex].a) { aColors[iIndex] = kBaseColor; aColors[iIndex].a = fAlpha; } } } } } } } } } } void CvPlayer::getCultureLayerColors(std::vector<NiColorA>& aColors, std::vector<CvPlotIndicatorData>& aIndicators) const { const int iColorsPerPlot = 4; aColors.resize(GC.getMapINLINE().numPlotsINLINE() * iColorsPerPlot, NiColorA(0, 0, 0, 0)); aIndicators.clear(); // find maximum total culture int iMaxTotalCulture = INT_MIN; int iMinTotalCulture = INT_MAX; for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); int iTotalCulture = pLoopPlot->countTotalCulture(); if (iTotalCulture > iMaxTotalCulture) { iMaxTotalCulture = iTotalCulture; } if (iTotalCulture < iMinTotalCulture && iTotalCulture > 0) { iMinTotalCulture = iTotalCulture; } } iMinTotalCulture = 0; // find culture percentages for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++) { CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI); PlayerTypes eOwner = pLoopPlot->getRevealedOwner(getTeam(), true); // how many people own this plot? std::vector < std::pair<int,int> > plot_owners; int iNumNonzeroOwners = 0; for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; iPlayer++) { if (GET_PLAYER((PlayerTypes)iPlayer).isAlive()) { int iCurCultureAmount = pLoopPlot->getCulture((PlayerTypes)iPlayer); if (iCurCultureAmount != 0) { iNumNonzeroOwners ++; plot_owners.push_back(std::pair<int,int>(iCurCultureAmount, iPlayer)); } } } // ensure that it is revealed if (!plot_owners.empty() && pLoopPlot->getRevealedOwner(getTeam(), true) != NO_PLAYER) { for (int i = 0; i < iColorsPerPlot; ++i) { int iCurOwnerIdx = i % plot_owners.size(); PlayerTypes eCurOwnerID = (PlayerTypes) plot_owners[iCurOwnerIdx].second; int iCurCulture = plot_owners[iCurOwnerIdx].first; const NiColorA& kCurColor = GC.getColorInfo((ColorTypes) GC.getPlayerColorInfo(GET_PLAYER(eCurOwnerID).getPlayerColor()).getColorTypePrimary()).getColor(); // damp the color by the value... aColors[iI * iColorsPerPlot + i] = kCurColor; float blend_factor = 0.5f * std::min(1.0f, std::max(0.0f, (float)(iCurCulture - iMinTotalCulture) / iMaxTotalCulture)); aColors[iI * iColorsPerPlot + i].a = std::min(0.8f * blend_factor + 0.5f, 1.0f); } } } } void CvPlayer::cheat(bool bCtrl, bool bAlt, bool bShift) { if (gDLL->getChtLvl() > 0) { GET_TEAM(getTeam()).setHasTech(getCurrentResearch(), true, getID(), true, false); } } const CvArtInfoUnit* CvPlayer::getUnitArtInfo(UnitTypes eUnit, int iMeshGroup) const { CivilizationTypes eCivilization = getCivilizationType(); if (eCivilization == NO_CIVILIZATION) { eCivilization = (CivilizationTypes) GC.getDefineINT("BARBARIAN_CIVILIZATION"); } UnitArtStyleTypes eStyle = (UnitArtStyleTypes) GC.getCivilizationInfo(eCivilization).getUnitArtStyleType(); EraTypes eEra = getCurrentEra(); if (eEra == NO_ERA) { eEra = (EraTypes) 0; } return GC.getUnitInfo(eUnit).getArtInfo(iMeshGroup, eEra, eStyle); } bool CvPlayer::hasSpaceshipArrived() const { VictoryTypes eSpaceVictory = GC.getGameINLINE().getSpaceVictory(); if (eSpaceVictory != NO_VICTORY) { int iVictoryCountdown = GET_TEAM(getTeam()).getVictoryCountdown(eSpaceVictory); if (((GC.getGameINLINE().getGameState() == GAMESTATE_EXTENDED) && (iVictoryCountdown > 0)) || (iVictoryCountdown == 0)) { return true; } } return false; } // BUG - Reminder Mod - start #include "CvMessageControl.h" void CvPlayer::addReminder(int iGameTurn, CvWString szMessage) const { CvMessageControl::getInstance().sendAddReminder(getID(), iGameTurn, szMessage); } // BUG - Reminder Mod - end
[ "jdog5000@31ee56aa-37e8-4f44-8bdf-1f84a3affbab", "fim-fuyu@31ee56aa-37e8-4f44-8bdf-1f84a3affbab" ]
[ [ [ 1, 33 ], [ 39, 39 ], [ 56, 107 ], [ 113, 113 ], [ 128, 333 ], [ 339, 598 ], [ 602, 791 ], [ 813, 813 ], [ 815, 1068 ], [ 1074, 1083 ], [ 1087, 1087 ], [ 1093, 1203 ], [ 1207, 1207 ], [ 1213, 1265 ], [ 1269, 1269 ], [ 1275, 1315 ], [ 1319, 1319 ], [ 1325, 1359 ], [ 1363, 1363 ], [ 1369, 1521 ], [ 1525, 1525 ], [ 1531, 1544 ], [ 1548, 2418 ], [ 2420, 2512 ], [ 2526, 3055 ], [ 3061, 3069 ], [ 3073, 3086 ], [ 3092, 3102 ], [ 3106, 3379 ], [ 3385, 3386 ], [ 3390, 3394 ], [ 3434, 3463 ], [ 3469, 3472 ], [ 3476, 3640 ], [ 3646, 3651 ], [ 3653, 3656 ], [ 3659, 3664 ], [ 3666, 3669 ], [ 3672, 3677 ], [ 3679, 3682 ], [ 3685, 3690 ], [ 3692, 3693 ], [ 3697, 3940 ], [ 3951, 3951 ], [ 3959, 3961 ], [ 3976, 4057 ], [ 4064, 4083 ], [ 4101, 4103 ], [ 4105, 4120 ], [ 4138, 4139 ], [ 4143, 4609 ], [ 4622, 4658 ], [ 4671, 4920 ], [ 4930, 4999 ], [ 5006, 5006 ], [ 5012, 5026 ], [ 5033, 5033 ], [ 5039, 5746 ], [ 5751, 6037 ], [ 6045, 6045 ], [ 6047, 6047 ], [ 6060, 6061 ], [ 6065, 6110 ], [ 6112, 6192 ], [ 6206, 6932 ], [ 6945, 7105 ], [ 7110, 7317 ], [ 7323, 7333 ], [ 7337, 7513 ], [ 7520, 7545 ], [ 7547, 7553 ], [ 7555, 7558 ], [ 7560, 7607 ], [ 7609, 7609 ], [ 7611, 7614 ], [ 7616, 7617 ], [ 7621, 7911 ], [ 7918, 7918 ], [ 7920, 7926 ], [ 7935, 7967 ], [ 7982, 8082 ], [ 8092, 8116 ], [ 8122, 8596 ], [ 8603, 8612 ], [ 8614, 8614 ], [ 8616, 8623 ], [ 8625, 8625 ], [ 8629, 8650 ], [ 8652, 8652 ], [ 8654, 8661 ], [ 8663, 8674 ], [ 8676, 8692 ], [ 8694, 8707 ], [ 8709, 9630 ], [ 9636, 9640 ], [ 9645, 9646 ], [ 9650, 9663 ], [ 9669, 9674 ], [ 9676, 9680 ], [ 9684, 9761 ], [ 9767, 9772 ], [ 9777, 9778 ], [ 9782, 9811 ], [ 9817, 9822 ], [ 9827, 9828 ], [ 9832, 9873 ], [ 9879, 9883 ], [ 9888, 9889 ], [ 9893, 9937 ], [ 9943, 9947 ], [ 9952, 9953 ], [ 9957, 10034 ], [ 10040, 10044 ], [ 10049, 10050 ], [ 10054, 10131 ], [ 10137, 10141 ], [ 10146, 10147 ], [ 10151, 10182 ], [ 10188, 10193 ], [ 10198, 10199 ], [ 10203, 10216 ], [ 10222, 10227 ], [ 10232, 10233 ], [ 10237, 10250 ], [ 10256, 10261 ], [ 10266, 10267 ], [ 10271, 10374 ], [ 10380, 10391 ], [ 10396, 10396 ], [ 10398, 10398 ], [ 10407, 10408 ], [ 10412, 10438 ], [ 10444, 10448 ], [ 10450, 10459 ], [ 10462, 10466 ], [ 10468, 10469 ], [ 10473, 10945 ], [ 10951, 10957 ], [ 10961, 11070 ], [ 11076, 11080 ], [ 11084, 11106 ], [ 11228, 11382 ], [ 11388, 11392 ], [ 11396, 11707 ], [ 11713, 11722 ], [ 11726, 11736 ], [ 11742, 11747 ], [ 11751, 11803 ], [ 11809, 11821 ], [ 11825, 12526 ], [ 12532, 12539 ], [ 12541, 12551 ], [ 12554, 12561 ], [ 12563, 12564 ], [ 12568, 12577 ], [ 12583, 12590 ], [ 12592, 12593 ], [ 12597, 13007 ], [ 13013, 13022 ], [ 13027, 13028 ], [ 13032, 13222 ], [ 13228, 13234 ], [ 13238, 15001 ], [ 15003, 15344 ], [ 15358, 17073 ], [ 17079, 17100 ], [ 17118, 17149 ], [ 17155, 17157 ], [ 17231, 17231 ], [ 17239, 17239 ], [ 17244, 17244 ], [ 17266, 17266 ], [ 17308, 17308 ], [ 17312, 17313 ], [ 17320, 17320 ], [ 17330, 17330 ], [ 17335, 17335 ], [ 17340, 17340 ], [ 17352, 17352 ], [ 17357, 17359 ], [ 17363, 18276 ], [ 18296, 19544 ], [ 19557, 21199 ], [ 21205, 21214 ], [ 21218, 21947 ], [ 21953, 21957 ], [ 21961, 23122 ], [ 23125, 23415 ] ], [ [ 34, 38 ], [ 40, 55 ], [ 108, 112 ], [ 114, 127 ], [ 334, 338 ], [ 599, 601 ], [ 792, 812 ], [ 814, 814 ], [ 1069, 1073 ], [ 1084, 1086 ], [ 1088, 1092 ], [ 1204, 1206 ], [ 1208, 1212 ], [ 1266, 1268 ], [ 1270, 1274 ], [ 1316, 1318 ], [ 1320, 1324 ], [ 1360, 1362 ], [ 1364, 1368 ], [ 1522, 1524 ], [ 1526, 1530 ], [ 1545, 1547 ], [ 2419, 2419 ], [ 2513, 2525 ], [ 3056, 3060 ], [ 3070, 3072 ], [ 3087, 3091 ], [ 3103, 3105 ], [ 3380, 3384 ], [ 3387, 3389 ], [ 3395, 3433 ], [ 3464, 3468 ], [ 3473, 3475 ], [ 3641, 3645 ], [ 3652, 3652 ], [ 3657, 3658 ], [ 3665, 3665 ], [ 3670, 3671 ], [ 3678, 3678 ], [ 3683, 3684 ], [ 3691, 3691 ], [ 3694, 3696 ], [ 3941, 3950 ], [ 3952, 3958 ], [ 3962, 3975 ], [ 4058, 4063 ], [ 4084, 4100 ], [ 4104, 4104 ], [ 4121, 4137 ], [ 4140, 4142 ], [ 4610, 4621 ], [ 4659, 4670 ], [ 4921, 4929 ], [ 5000, 5005 ], [ 5007, 5011 ], [ 5027, 5032 ], [ 5034, 5038 ], [ 5747, 5750 ], [ 6038, 6044 ], [ 6046, 6046 ], [ 6048, 6059 ], [ 6062, 6064 ], [ 6111, 6111 ], [ 6193, 6205 ], [ 6933, 6944 ], [ 7106, 7109 ], [ 7318, 7322 ], [ 7334, 7336 ], [ 7514, 7519 ], [ 7546, 7546 ], [ 7554, 7554 ], [ 7559, 7559 ], [ 7608, 7608 ], [ 7610, 7610 ], [ 7615, 7615 ], [ 7618, 7620 ], [ 7912, 7917 ], [ 7919, 7919 ], [ 7927, 7934 ], [ 7968, 7981 ], [ 8083, 8091 ], [ 8117, 8121 ], [ 8597, 8602 ], [ 8613, 8613 ], [ 8615, 8615 ], [ 8624, 8624 ], [ 8626, 8628 ], [ 8651, 8651 ], [ 8653, 8653 ], [ 8662, 8662 ], [ 8675, 8675 ], [ 8693, 8693 ], [ 8708, 8708 ], [ 9631, 9635 ], [ 9641, 9644 ], [ 9647, 9649 ], [ 9664, 9668 ], [ 9675, 9675 ], [ 9681, 9683 ], [ 9762, 9766 ], [ 9773, 9776 ], [ 9779, 9781 ], [ 9812, 9816 ], [ 9823, 9826 ], [ 9829, 9831 ], [ 9874, 9878 ], [ 9884, 9887 ], [ 9890, 9892 ], [ 9938, 9942 ], [ 9948, 9951 ], [ 9954, 9956 ], [ 10035, 10039 ], [ 10045, 10048 ], [ 10051, 10053 ], [ 10132, 10136 ], [ 10142, 10145 ], [ 10148, 10150 ], [ 10183, 10187 ], [ 10194, 10197 ], [ 10200, 10202 ], [ 10217, 10221 ], [ 10228, 10231 ], [ 10234, 10236 ], [ 10251, 10255 ], [ 10262, 10265 ], [ 10268, 10270 ], [ 10375, 10379 ], [ 10392, 10395 ], [ 10397, 10397 ], [ 10399, 10406 ], [ 10409, 10411 ], [ 10439, 10443 ], [ 10449, 10449 ], [ 10460, 10461 ], [ 10467, 10467 ], [ 10470, 10472 ], [ 10946, 10950 ], [ 10958, 10960 ], [ 11071, 11075 ], [ 11081, 11083 ], [ 11107, 11227 ], [ 11383, 11387 ], [ 11393, 11395 ], [ 11708, 11712 ], [ 11723, 11725 ], [ 11737, 11741 ], [ 11748, 11750 ], [ 11804, 11808 ], [ 11822, 11824 ], [ 12527, 12531 ], [ 12540, 12540 ], [ 12552, 12553 ], [ 12562, 12562 ], [ 12565, 12567 ], [ 12578, 12582 ], [ 12591, 12591 ], [ 12594, 12596 ], [ 13008, 13012 ], [ 13023, 13026 ], [ 13029, 13031 ], [ 13223, 13227 ], [ 13235, 13237 ], [ 15002, 15002 ], [ 15345, 15357 ], [ 17074, 17078 ], [ 17101, 17117 ], [ 17150, 17154 ], [ 17158, 17230 ], [ 17232, 17238 ], [ 17240, 17243 ], [ 17245, 17265 ], [ 17267, 17307 ], [ 17309, 17311 ], [ 17314, 17319 ], [ 17321, 17329 ], [ 17331, 17334 ], [ 17336, 17339 ], [ 17341, 17351 ], [ 17353, 17356 ], [ 17360, 17362 ], [ 18277, 18295 ], [ 19545, 19556 ], [ 21200, 21204 ], [ 21215, 21217 ], [ 21948, 21952 ], [ 21958, 21960 ], [ 23123, 23124 ], [ 23416, 23423 ] ] ]
d262aa1f6542d3f9fdcb976c25b17f9368172c64
aecc6d0ee5b767cc9c6ad2b22718f55e43abfe53
/Aesir/Attic/MapView.cpp
4154f2e7d10110e40817f538cd7d6766b103d734
[]
no_license
yeah-dude/aesirtk
72ab3427535ee6c4535f4a7a16b5bd580309a2cd
fe43bedb45cdfb894935411b84c55197601a5702
refs/heads/master
2021-01-18T11:43:09.961319
2007-06-27T21:42:10
2007-06-27T21:42:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
#include "stdwx.h" #include "MapView.h" #include "MapEditor.h" #include "BasicCanvas.h" #include "TileManager.h" #include <wx/docmdi.h> IMPLEMENT_DYNAMIC_CLASS(MapView, wxView) class MapView::GraphicsCanvas : public BasicCanvas { public: inline GraphicsCanvas(wxWindow *parent) : BasicCanvas(parent) { } void Render(); }; class MapView::ChildFrame : public wxDocMDIChildFrame { public: ChildFrame(wxDocument *doc, MapView *mapView_, wxMDIParentFrame *parent); private: GraphicsCanvas *graphicsCanvas; wxScrollBar *scrollHoriz, *scrollVert; MapView *mapView; void OnSize(wxSizeEvent &event); DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(MapView::ChildFrame, wxDocMDIChildFrame) EVT_SIZE(MapView::ChildFrame::OnSize) END_EVENT_TABLE() MapView::ChildFrame::ChildFrame(wxDocument *doc, MapView *mapView_, wxMDIParentFrame *parent) : wxDocMDIChildFrame(doc, mapView_, parent, -1, ""), mapView(mapView_) { this->Show(); graphicsCanvas = new GraphicsCanvas(this); } void MapView::ChildFrame::OnSize(wxSizeEvent &event) { } void MapView::GraphicsCanvas::Render() { this->SetCurrent(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); this->SwapBuffers(); } bool MapView::OnCreate(wxDocument *doc, long flags) { this->SetFrame(new ChildFrame(doc, this, mainFrame)); return true; } bool MapView::OnClose(bool deleteWindow) { if(!GetDocument()->Close()) return false; this->Activate(false); if(deleteWindow) delete GetFrame(); return true; }
[ "MisterPhyrePhox@6418936e-2d2e-0410-bd97-81d43f9d527b" ]
[ [ [ 1, 49 ] ] ]
c0503eb43e1f6313ef06aee199ba63087f0788b1
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/NetWheelDirector/src/TableComponentKey.cpp
50eddd16d7410552078a5892c466d9fac2b1c91e
[]
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
807
cpp
#include "NetWheelDirectorStableHeaders.h" #include "TableComponentKey.h" #include "F5TableInterface.h" #include "F5Table.h" #include "F6Table.h" using namespace Orz; TableComponentKey::~TableComponentKey(void) { Orz::IInputManager::getSingleton().removeKeyListener(this); } bool TableComponentKey::onKeyPressed(const KeyEvent & evt) { //switch(evt.getKey()) //{ //case Orz::KC_P: // F5Table::getInstancePtr()->pushCoin(F5TableInterface::_1,1); // break; //case Orz::KC_L: // F5Table::getInstancePtr()->popCoin(F5TableInterface::_1,1); // break; //} return false; } bool TableComponentKey::onKeyReleased(const KeyEvent & evt) { return false; } TableComponentKey::TableComponentKey(void) { Orz::IInputManager::getSingleton().addKeyListener(this); }
[ [ [ 1, 38 ] ] ]
8758c047b88fbfe1b65235b7591d8873d6c610b5
942b88e59417352fbbb1a37d266fdb3f0f839d27
/src/windowui.hxx
0789d9539a1b921da63bcfb3cc54347122309847
[ "BSD-2-Clause" ]
permissive
take-cheeze/ARGSS...
2c1595d924c24730cc714d017edb375cfdbae9ef
2f2830e8cc7e9c4a5f21f7649287cb6a4924573f
refs/heads/master
2016-09-05T15:27:26.319404
2010-12-13T09:07:24
2010-12-13T09:07:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,019
hxx
////////////////////////////////////////////////////////////////////////////////// /// ARGSS - Copyright (c) 2009 - 2010, Alejandro Marzini (vgvgf) /// 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 AUTHOR ''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 AUTHOR 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 _WINDOWUI_HXX_ #define _WINDOWUI_HXX_ //////////////////////////////////////////////////////////// /// Headers //////////////////////////////////////////////////////////// #if defined(ARGSS_WIN32) #include "WIN32/windowui.hxx" #elif defined(ARGSS_Qt) #include "Qt/windowui.hxx" #elif defined(ARGSS_SDL) #include "SDL/windowui.hxx" #elif defined(ARGSS_GLUT) #include "GLUT/windowui.hxx" #endif #endif // _WINDOWUI_HXX_
[ "takeshi@takeshi-laptop.(none)", "[email protected]" ]
[ [ [ 1, 24 ], [ 27, 30 ], [ 40, 40 ] ], [ [ 25, 26 ], [ 31, 39 ], [ 41, 41 ] ] ]
09bc49b157857cd581bc43e739375c19ff7253f7
ef4f4eb0a858bfe7cbc7bd4233522b3f898ef6dc
/entity.h
b73681dd2357f8646fe41231b8aa313825c0ba35
[]
no_license
ryanWIN/Entity-VM
b6d256b81813e950b1170a9be9989597f7617141
efc6b093909f6ead609c3b26044b3f632179074e
refs/heads/master
2016-09-06T15:23:54.235297
2010-05-17T22:50:14
2010-05-17T22:50:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,478
h
#define OPERATE 1 #define VMRAM 65536 #define STACKSIZE 16384 //32BIT PROCESSING DEFINES //Stack #define PUSH 0 #define POP 1 #define CLONE 2 #define CONVERT 3 //Base Math #define ADD 4 #define SUB 5 #define MUL 6 #define DIV 7 //Bitwise Logic #define AND 8 #define OR 9 #define XOR 10 #define NOT 11 //Extended Math and Bitshift #define EXP 16 #define MOD 17 #define SHR 18 #define SHL 19 //Conditional Processing //and branching #define CMP 32 #define JMP 33 #define JME 34 #define JML 35 #define JMG 36 #define JLE 37 #define JGE 38 #define JNE 39 #define FUNCTION 42 #define FRETURN 43 #define DPUSH 44 //Memory routines #define PRESERVE 46 #define RESTORE 47 #define LOAD 48 #define STORE 49 #define LOADB 50 #define STOREB 51 //Goodies #define INCL 52 #define DECL 53 #define RSTORE 54 //API, SYS, and EXIT #define API 61 #define SYS 62 #define EXIT 63 #define ENDPARAMS 0 #define DWORD 1 #define FLOATER 2 #define BYTE 3 #define RETURNADDRESS 4 //FLOATING POINT PROCESSING DEFINES //Stack #define PUSHF 64 #define POPF 65 #define CLONEF 66 #define CONVERTF 67 //Base Math #define ADDF 68 #define SUBF 69 #define DIVF 70 #define MULF 71 //Extended Math #define EXPF 72 #define MODF 73 #define SQRTF 74 #define COSF 75 #define SINF 76 #define TANF 77 //CMP #define CMPF 96 //Memory Routines #define LOADF 97 #define STOREF 98 //Stack swappers //SYS defines #define sys_write 1 #define sys_read 2 #define sys_putchar 3 #define sys_endl 4 #define sys_atoi 16 #define sys_itoa 17 #define sys_atof 18 #define sys_ftoa 19 #define sys_strlen 32 #define sys_sort 33 #define sys_szdouble 64 #define sys_szint 65 #define sys_thread 1337 #define sys_yield 1338 class THREAD { public: union CONVERTDOUBLE { char bytes[sizeof(double)]; double data; }; struct ALLDATA { char type; int address; char byte; int dword; double floater; }; void *owner; THREAD *next; THREAD *parent; CONVERTDOUBLE writedouble; unsigned int writeiterate; //Preserve,Restore int writes; unsigned int address; int functioniterate; int swapper; int preserve; char *ram; int *base; //Used for addressing in 32bit int sizeram; int operational; int yield; int stack[STACKSIZE]; int stackpointer; double fstack[STACKSIZE]; int fstackpointer; ALLDATA pstack[STACKSIZE]; int pstackpointer; int newadd; int codepointer; int workingloc; int done; union evaluation { struct BITEVAL { char equal : 1; char notequal : 1; char lessthan : 1; char greaterthan : 1; char greaterthanequal : 1; char lessthanequal : 1; } cmpbit; int cmpint; }; evaluation bitflags; THREAD(char *ram, int sizeram, int startaddress, void *mymaster); int ExecObj(int cycles); void AddThread(int startpoint); ~THREAD(); }; class VMOBJ { public: struct BINHEADER { char endian; char version[8]; char szint; char szdouble; int numops; int startaddress; }; void *owner; int sizeram; char *ram; int operational; THREAD *processes; VMOBJ(); void setram(char *newram, int newsizeram, void *mymaster); void loadbinary(const char *file); void RemoveProcess(THREAD *pskill); void KillEntries(THREAD *root); int Execute(int cycles); }; typedef void (*APIFUNCTION)(void *); struct APIBLOCK { APIBLOCK *next; char name[128]; APIFUNCTION entrypoint; }; class APIHANDLER { public: APIBLOCK *root; APIHANDLER(); ~APIHANDLER(); void exec(const char *functionname, void *owner); void install(const char *functionname,APIFUNCTION function); }; class ENTITY { //Don't mess with unions, for they are teh powerful. public: #ifdef _MSC_VER #pragma pack(1) #endif struct ATTRIBUTES { //Stick the stuff you want in here! int x; int y; double z; #ifdef __GNUC__ } __attribute__((packed)); #else }; #endif #ifdef _MSC_VER #pragma pack() #endif char ram[65536]; ATTRIBUTES *shared; VMOBJ vm; APIHANDLER api; char name[1337]; int seconds; int execrate; int operational; void Execute(); void SetExecutionRate(int cyclespersecond, int tickrate); ENTITY(const char *myname, const char *binary); ENTITY(); };
[ [ [ 1, 314 ] ] ]
d1b02e818cc6c31135a0598a87b8a82ee1791f4b
e07af5d5401cec17dc0bbf6dea61f6c048f07787
/newsreader.hpp
aafcfc8ddb12d15a757b9bd61ed6bbe7007cfea1
[]
no_license
Mosesofmason/nineo
4189c378026f46441498a021d8571f75579ce55e
c7f774d83a7a1f59fde1ac089fde9aa0b0182d83
refs/heads/master
2016-08-04T16:33:00.101017
2009-12-26T15:25:54
2009-12-26T15:25:54
32,200,899
0
0
null
null
null
null
UTF-8
C++
false
false
799
hpp
#ifndef __NEXT_NINEO_NEWSREADERS_DEFINE__ #define __NEXT_NINEO_NEWSREADERS_DEFINE__ //////////////////////////////////////////////////////////////////////////////// ////////// Author: newblue <[email protected]> ////////// Copyright by newblue, 2008. //////////////////////////////////////////////////////////////////////////////// #include <wx/wx.h> #include "config.hpp" #include <wx/panel.h> #include <wx/splitter.h> #include "groupview.hpp" #include "summaryview.hpp" class NiNewsReader : public wxSplitterWindow { DECLARE_EVENT_TABLE () public: NiNewsReader ( wxWindow *parent, wxWindowID id, const wxString& name = wxT("NewsReaders") ); ~NiNewsReader (); private: enum { ID_SPLIT = wxID_HIGHEST + 1, }; }; #endif //
[ [ [ 1, 29 ] ] ]
e7e40fc3b1d9008bf9bfd13bdd01a7375853d4d3
d20b68a8117dd07fce7e52e28cc5b880ada3469b
/code/base/actorpool.h
9d79724cfb764e9cdf9e111a120939bbdb1ed07a
[]
no_license
zhengqq/uvmoonpatrol
326002e1dab8a85b4cb286db23c7d777b4c9a428
91ba9a6e9407585ff19fed7968188f13bf4157ed
refs/heads/master
2016-09-06T04:34:43.302709
2009-08-21T03:50:45
2009-08-21T03:50:45
42,767,630
0
0
null
null
null
null
UTF-8
C++
false
false
683
h
#pragma once #include <vector> #include "actor.h" class Actor; class Level; class ActorPool{ public: ActorPool(); ~ActorPool(); int createGroup(); void cleanPool(); void addActor(Actor*, int); std::vector<Actor*> * getPool(int); void updatePhysics(Level * lvl, int worldOffset); // update everything in our pool! void checkCollision(int, int); // check collisions between two groups void updateCollisions(); // update anyone who collided void drawPool(); // draw all the contents of the pool! private: std::vector< std::vector<Actor*> > pool; // List of actor pools std::vector<Actor*> collisionPool; };
[ "cthulhu32@591a4e72-d347-0410-ad9e-b354b1ae3366" ]
[ [ [ 1, 24 ] ] ]
877af287403fe71e644892eca00894b94ab8ecb9
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/sys/transm_models/csma_transmission_model.cpp
4814d15500cd2e079a577bfe63f75c88198087ff
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,187
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "sys/transmission_model.h" #include "sys/transm_models/csma_transmission_model.h" #include "sys/edge_model.h" #include "sys/world.h" #include "sys/simulation/simulation_controller.h" #include "sys/simulation/simulation_environment.h" #include <cmath> //#define CSMA_DEBUG #ifdef CSMA_DEBUG #define CSMA_DEBUG_OUT( x ) cout << x << endl << flush; #else #define CSMA_DEBUG_OUT( x ) #endif //Was before 0.00001 since it was not clear whether new_event( now() ) is ok. Well, it is. #define CSMA_SCHED_EPSILON 0.0 using namespace std; namespace shawn { // ---------------------------------------------------------------------- CsmaTransmissionModel:: CsmaTransmissionModel ( double short_inter_frame_spacing, double long_inter_frame_spacing, int max_short_inter_frame_spacing_size, int bandwidth, bool slotted_backoff, double backoff, int max_sending_attempts, int backoff_factor_base, int min_backoff_exponent, int max_backoff_exponent ) : short_inter_frame_spacing_(short_inter_frame_spacing), long_inter_frame_spacing_(long_inter_frame_spacing), max_short_inter_frame_spacing_size_(max_short_inter_frame_spacing_size), slotted_backoff_(slotted_backoff), backOff_(backoff), bandwidth_(bandwidth), max_sending_attempts_(max_sending_attempts), backoff_factor_base_(backoff_factor_base), min_backoff_exponent_(min_backoff_exponent), max_backoff_exponent_(max_backoff_exponent), nodes_(NULL) {} // ---------------------------------------------------------------------- CsmaTransmissionModel:: ~CsmaTransmissionModel() {} // ---------------------------------------------------------------------- void CsmaTransmissionModel:: init() throw() { TransmissionModel::init(); if( nodes_ != NULL ) { delete nodes_; nodes_ = NULL; } //This gives us an Array of Messages for all nodes which can be received in O(1) nodes_ = new DynamicNodeArray<CsmaState>(world_w()); CSMA_DEBUG_OUT("csma: Initialised!"); } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: reset() throw() { TransmissionModel::reset(); if( nodes_ != NULL ) { delete nodes_; nodes_ = NULL; } } // ---------------------------------------------------------------------- bool CsmaTransmissionModel:: supports_mobility( void ) const throw(logic_error) { return world().edge_model().supports_mobility(); } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: send_message( MessageInfo &mi ) throw() { csma_msg* new_msg = new csma_msg(&mi, (double) mi.msg_->size() / bandwidth_); CSMA_DEBUG_OUT("[id: "<<mi.src_->id()<< "]: new msg=" << new_msg << " at node " << mi.src_->id() << ((mi.msg_->is_ack())?(" ack"):(" msg")) ); CsmaState& csma_state = (*nodes_)[*(mi.src_)]; if (mi.msg_->is_ack()) { //acks are treated differently from other message: // - they are scheduled for immediate delivery (ignoring IFS // - They are not queued, i.e. they can "overtake" regular messages in beeing sent csma_state.outgoing_messages_.push_front(new_msg); #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, world().current_time(), new NodeInfo(mi.src_) ); CSMA_DEBUG_OUT("[id: "<<mi.src_->id()<< "]: " << eh << " sched in send message at "<< eh->time() << " for ack"); } else { csma_state.outgoing_messages_.push_back(new_msg); if (!csma_state.busy_) { csma_state.busy_= true; #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, world().current_time() + CSMA_SCHED_EPSILON, new NodeInfo(mi.src_) ); CSMA_DEBUG_OUT("[id: "<<mi.src_->id()<< "]: " << eh << " sched in send message at " << eh->time() << " for next msg"); } } } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: timeout(EventScheduler & event_scheduler, EventScheduler::EventHandle event_handle, double time, EventScheduler::EventTagHandle & event_tag_handle) throw() { NodeInfo* ni = dynamic_cast<NodeInfo* >(event_tag_handle.get()); if (ni != NULL) // This means that a new message must be scheduled { CsmaState& csma_state = (*nodes_)[*(ni->n_)]; CSMA_DEBUG_OUT("[id: "<<ni->n_->id()<< "]: " << event_handle << " fired (handle next message) at " << event_handle->time() << " at node " << ni->n_->id() ); if (!csma_state.outgoing_messages_.empty()) // get next outgoing message { csma_msg *new_msg = csma_state.outgoing_messages_.front(); csma_state.outgoing_messages_.pop_front(); handle_next_message(new_msg); } else { //no more messages to be sent csma_state.busy_ = false; } } else { csma_msg* msg = dynamic_cast<csma_msg* >(event_tag_handle.get()); if(msg != NULL) { if(!msg->sending_) { //message not on air yet. We should now check wether the medium is free, and eventually send CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]:" << event_handle << " fired (mac access) at " << event_handle->time() << " msg=" << msg ); CsmaState& csma_state = (*nodes_)[*(msg->pmi_->src_)]; // Soften assert if (csma_state.busy_until_ > ((csma_state.ifs_end_)+(0.001))) cout << "csma_transmission_model::timeout (MAC access): busy_until_>ifs_end_! (" << csma_state.busy_until_ << " > " << csma_state.ifs_end_ << ") This must never happen" << endl; assert((csma_state.busy_until_ <= ((csma_state.ifs_end_)+(0.001)))); while( (!msg->pmi_->msg_->is_ack()) && (csma_state.ifs_end_ > msg->deliver_time_) && (msg->sending_attempts_< max_sending_attempts_)) { double wait_periods = shawn::uniform_random_0i_1i()* (int)(pow((float)(backoff_factor_base_),min(min_backoff_exponent_+msg->sending_attempts_, max_backoff_exponent_))-1); if (slotted_backoff_) wait_periods = int(wait_periods + 0.5); msg->deliver_time_ += (backOff_ * wait_periods); //New Event to now + backoff ++msg->sending_attempts_; CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]: Waiting in timeout (src: " << msg->pmi_->src_->id() << ") " << wait_periods << ", send attempts: "<< msg->sending_attempts_); } if (msg->deliver_time_ <= world().current_time() && msg->sending_attempts_< max_sending_attempts_) { start_send(msg); // If the message has not been sent yet. } else { // Reschedule for next media acess if (msg->sending_attempts_< max_sending_attempts_) { #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, msg->deliver_time_ ,msg); CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]:" << eh << " sched for new mac access at " << eh->time() << " msg=" << msg ); } else // media access finally failed { const Message* m = msg->pmi_->msg_.get(); if (m->has_sender_proc()) { (m->sender_proc_w()).process_sent_indication( ConstMessageHandle(msg->pmi_->msg_), shawn::Processor::SHAWN_TX_STATE_CHANNEL_ACCESS_FAILURE, msg->sending_attempts_ ); } #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, world().current_time() + CSMA_SCHED_EPSILON, new NodeInfo(msg->pmi_->src_)); CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]:" << eh<<" sched in media access at "<< eh->time()<<" for next msg" ); } } } else { //Otherwise the transmission has terminated CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]" << event_handle<<" fired (end_send) at "<< event_handle->time()<<" msg="<<msg ); end_send(msg); } } } } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: deliver_messages() throw() {} // ---------------------------------------------------------------------- void CsmaTransmissionModel:: start_send(csma_msg* msg) throw() { CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]: start sending at " << world().current_time() << " deliver_time_="<< msg->deliver_time_ ); CsmaState& csma_state = (*nodes_)[*(msg->pmi_->src_)]; //csma_state.current_message_ = msg; if (csma_state.current_message_!=NULL) { cout << "csma_transmission_model::start_send: current msg was not NULL --> start send though currently receiving.. This must never happen" << endl; cout << "csma_transmission_model::start_send: msg->pmi_->src_->id() = "<< msg->pmi_->src_->id() << endl; cout << "csma_transmission_model::start_send: csma_state.busy_until_ = " << csma_state.busy_until_ << endl; cout << "csma_transmission_model::start_send: csma_state.ifs_end_ = " << csma_state.ifs_end_ << endl; cout << "csma_transmission_model::start_send: csma_state.busy_ = " << csma_state.busy_ << endl; cout << "csma_transmission_model::start_send: csma_state.current_message_::pmi_->src_->id() = " << csma_state.current_message_->pmi_->src_->id() << endl; cout << "csma_transmission_model::start_send: csma_state.current_message_::pmi_->time_ = " << csma_state.current_message_->pmi_->time_ << endl; cout << "csma_transmission_model::start_send: csma_state.current_message_::deliver_time_ = " << csma_state.current_message_->deliver_time_<< endl; cout << "csma_transmission_model::start_send: csma_state.current_message_::duration_ = " << csma_state.current_message_->duration_<< endl; cout << "csma_transmission_model::start_send: csma_state.current_message_::sending_ = " << csma_state.current_message_->sending_<< endl; cout << "csma_transmission_model::start_send: csma_state.current_message_::sending_attempts_ = " << csma_state.current_message_->sending_attempts_ << endl; cout << "csma_transmission_model::start_send: csma_state.size(outgoing_messages_) = " << csma_state.outgoing_messages_.size() << endl; for(set<Node*>::iterator it = csma_state.destinations_.begin(), end = csma_state.destinations_.end(); it!=end; ++it) cout << "csma_transmission_model::start_send: csma_state::dest = " << (**it).id() << endl; } assert(csma_state.current_message_ == NULL); csma_state.busy_until_ = msg->deliver_time_ + msg->duration_; if(!msg->pmi_->msg_->is_ack()) //ack is not followed by its own IFS, but "defers" the IFS of messages it belongs to { double ifs_time = (msg->pmi_->msg_->size() <=max_short_inter_frame_spacing_size_) ? short_inter_frame_spacing_ : long_inter_frame_spacing_; csma_state.ifs_end_ = max(msg->deliver_time_ + msg->duration_ + ifs_time, csma_state.ifs_end_); CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]: msg clean_busy=" << msg->deliver_time_ + msg->duration_<<" IFS_time " << ifs_time <<" IFS_end " << (*nodes_)[*(msg->pmi_->src_)].ifs_end_ ); } else { csma_state.ifs_end_ += msg->duration_; CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]: ack IFS_end " << csma_state.ifs_end_); } msg->sending_ = true; //int count = 0; for(EdgeModel::adjacency_iterator it = world_w().begin_adjacent_nodes_w( *msg->pmi_->src_ , EdgeModel::CD_OUT), endit = world_w().end_adjacent_nodes_w( *msg->pmi_->src_ ); it != endit; ++it) { if (*it != *(msg->pmi_->src_)) { Node *cur_dst = &(*it); if(transmission_in_range(msg->pmi_->src_, cur_dst, msg->pmi_)) { csma_state.destinations_.insert(&(*it)); start_receive(&(*it), msg); } // count++; } } //if (count==0) // cout << "start send empty receiver set" << endl; CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]: deliver time: "<< msg->deliver_time_ << " , duration " << msg->duration_ << "sched at "<< msg->deliver_time_ + msg->duration_ << " msg=" << msg); #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, msg->deliver_time_ + msg->duration_, msg); CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]:" << eh << " sched in start send at " << eh->time() << " msg=" << msg ); } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: end_send(csma_msg* msg) throw() { CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]: end sending at " << world().current_time() <<" deliver time: "<< msg->deliver_time_ << " , duration " << msg->duration_ << " endtime="<< msg->deliver_time_ + msg->duration_<< " msg="<<msg); assert( world().current_time() + 0.00001 >= msg->deliver_time_ + msg->duration_); CsmaState& csma_state = (*nodes_)[*(msg->pmi_->src_)]; //int c = 0; //if (csma_state.current_message_ == msg) { csma_state.current_message_ = NULL; for(set<Node*>::iterator it = csma_state.destinations_.begin(), endit = csma_state.destinations_.end(); it != endit; ++it ) { end_receive(*it, msg); // c++; } csma_state.destinations_.clear(); } //if (c==0) // cout << "end send empty receiver set" << endl; const Message* m = msg->pmi_->msg_.get(); if (m->has_sender_proc()) (m->sender_proc_w()).process_sent_indication( ConstMessageHandle(msg->pmi_->msg_), shawn::Processor::SHAWN_TX_STATE_SUCCESS, msg->sending_attempts_ ); // Acks are scheduled separately, so do not schedule next message if this one was an ack if (!msg->pmi_->msg_->is_ack()) { #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, world().current_time() + CSMA_SCHED_EPSILON, new NodeInfo(msg->pmi_->src_)); CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]:" << eh<<" sched in end send at "<< eh->time() << " for next msg"); } else { CSMA_DEBUG_OUT("[id: "<< msg->pmi_->src_->id() << "]:" << "no sched in end send, was ack"); } } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: start_receive(Node* target, csma_msg* msg) throw() { CSMA_DEBUG_OUT("[id: "<< target->id() << "]: start receive " << target->id() << " at " << world().current_time() << " delivertime_=" << msg->deliver_time_); CsmaState& csma_state = (*nodes_)[*target]; // If target is not busy --> no collision (so far) if ( csma_state.busy_until_ <= msg->deliver_time_ ) { csma_state.current_message_ = msg; if(!msg->pmi_->msg_->is_ack()) // calc end of inter frame spacing { double ifs_time = (msg->pmi_->msg_->size() <=max_short_inter_frame_spacing_size_) ? short_inter_frame_spacing_ : long_inter_frame_spacing_; csma_state.ifs_end_ = max( msg->deliver_time_ + msg->duration_ + ifs_time, csma_state.ifs_end_ ); CSMA_DEBUG_OUT("[id: "<< target->id() << "]: msg clean_busy=" << msg->deliver_time_ + msg->duration_ << " IFS_time " << ifs_time << " IFS_end " << csma_state.ifs_end_ ); } else { //Ack is not followed by its own IFS, but "defers" the IFS of messages it belongs to csma_state.ifs_end_ = max(csma_state.ifs_end_ + msg->duration_, msg->deliver_time_ + msg->duration_); CSMA_DEBUG_OUT("[id: "<< target->id() << "]: ack IFS_end " << csma_state.ifs_end_ ); } } else { // this is collision --> always long interframe spacing csma_state.ifs_end_ = max( msg->deliver_time_ + msg->duration_ + long_inter_frame_spacing_, csma_state.ifs_end_ ); CSMA_DEBUG_OUT("[id: "<< target->id() << "] COLLISION: msg clean_busy=" << msg->deliver_time_ + msg->duration_ << " IFS_time " << long_inter_frame_spacing_ << " IFS_end " << csma_state.ifs_end_ ); csma_state.current_message_ = NULL; } // busy until latest packet is delivered if (csma_state.busy_until_ < msg->deliver_time_ + msg->duration_) csma_state.busy_until_ = msg->deliver_time_ + msg->duration_; } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: end_receive(Node* target, csma_msg* msg) throw() { CsmaState& csma_state = (*nodes_)[*target]; if (csma_state.current_message_ == msg) // original message is still set --> no collision { csma_state.current_message_ = NULL; CSMA_DEBUG_OUT("[id: "<< target->id() << "]:" << target->id() << " receives msg from " << msg->pmi_->src_->id() << " at " << world().current_time() << " IFS_end " << csma_state.ifs_end_ ); target->receive(ConstMessageHandle(msg->pmi_->msg_)); } else // collision { CSMA_DEBUG_OUT("[id: "<< target->id() << "]:" << "---- COLLISION at "<< target->id()<< " of msg from " << msg->pmi_->src_->id() << " at " << world().current_time() ); target->receive_dropped(ConstMessageHandle(msg->pmi_->msg_)); } } // ---------------------------------------------------------------------- void CsmaTransmissionModel:: handle_next_message(csma_msg *new_msg) throw() { CsmaState& csma_state = (*nodes_)[*(new_msg->pmi_->src_)]; if(new_msg->pmi_->msg_->is_ack()) { //send ack without csma #ifdef CSMA_DEBUG if ( csma_state.ifs_end_ <= world().current_time() ) { CSMA_DEBUG_OUT("[id: "<< new_msg->pmi_->src_->id() << "]: curtime=" << world().current_time() << " ifs_end="<< csma_state.ifs_end_ << " at " << new_msg->pmi_->src_->id() ); } #endif assert(csma_state.ifs_end_ > world().current_time()); assert(csma_state.ifs_end_ > world().current_time() + new_msg->duration_); new_msg->pmi_->time_ = world().current_time(); new_msg->deliver_time_ = new_msg->pmi_->time_; start_send(new_msg); } else { new_msg->pmi_->time_ = max(csma_state.ifs_end_, world().current_time()); //New Event to now + backoff double wait_periods = shawn::uniform_random_0i_1i()* (int)(pow((float)(backoff_factor_base_),min_backoff_exponent_)-1); if (slotted_backoff_) wait_periods = int(wait_periods + 0.5); new_msg->pmi_->time_ += backOff_ * wait_periods; ++new_msg->sending_attempts_; CSMA_DEBUG_OUT("[id: "<< new_msg->pmi_->src_->id() << "]: Waiting in handle_next_message (src: " << new_msg->pmi_->src_->id() << ") " << wait_periods << ", send attempts: "<< new_msg->sending_attempts_ ); new_msg->deliver_time_ = new_msg->pmi_->time_; // Create a new Event. Important is the MessageTag (new_msg). It defines which message will be send assert(!new_msg->sending_); #ifdef CSMA_DEBUG EventScheduler::EventHandle eh = #endif world_w().scheduler_w().new_event(*this, new_msg->pmi_->time_,new_msg); CSMA_DEBUG_OUT("[id: "<< new_msg->pmi_->src_->id() << "]: " <<eh << " sched in handle next (2) at " << eh->time() << " msg=" << new_msg ); } } } /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/sys/transm_models/csma_transmission_model.cpp,v $ * Version $Revision: 38 $ * Date $Date: 2007-06-08 14:30:12 +0200 (Fr, 08 Jun 2007) $ *----------------------------------------------------------------------- * $Log: csma_transmission_model.cpp,v $ *-----------------------------------------------------------------------*/
[ [ [ 1, 7 ], [ 9, 15 ], [ 29, 29 ], [ 33, 33 ], [ 52, 54 ], [ 60, 63 ], [ 65, 66 ], [ 70, 70 ], [ 72, 72 ], [ 80, 80 ], [ 84, 85 ], [ 89, 89 ], [ 91, 91 ], [ 99, 102 ], [ 105, 105 ], [ 107, 108 ], [ 150, 150 ], [ 246, 247 ], [ 251, 252 ], [ 318, 318 ], [ 352, 352 ], [ 434, 434 ], [ 453, 453 ], [ 495, 495 ], [ 500, 506 ] ], [ [ 8, 8 ], [ 16, 16 ], [ 18, 28 ], [ 30, 32 ], [ 34, 35 ], [ 39, 39 ], [ 41, 41 ], [ 45, 47 ], [ 59, 59 ], [ 64, 64 ], [ 67, 69 ], [ 73, 73 ], [ 79, 79 ], [ 82, 82 ], [ 86, 88 ], [ 98, 98 ], [ 103, 104 ], [ 106, 106 ], [ 109, 109 ], [ 112, 112 ], [ 115, 118 ], [ 124, 126 ], [ 128, 128 ], [ 130, 137 ], [ 139, 146 ], [ 152, 152 ], [ 154, 155 ], [ 157, 157 ], [ 159, 159 ], [ 161, 164 ], [ 166, 167 ], [ 169, 173 ], [ 175, 178 ], [ 180, 189 ], [ 191, 191 ], [ 194, 196 ], [ 198, 199 ], [ 203, 203 ], [ 205, 210 ], [ 212, 214 ], [ 216, 220 ], [ 226, 226 ], [ 228, 235 ], [ 237, 237 ], [ 239, 239 ], [ 241, 243 ], [ 249, 249 ], [ 253, 258 ], [ 260, 265 ], [ 267, 269 ], [ 272, 304 ], [ 306, 308 ], [ 320, 330 ], [ 332, 340 ], [ 344, 346 ], [ 348, 348 ], [ 351, 351 ], [ 353, 353 ], [ 355, 362 ], [ 364, 382 ], [ 384, 392 ], [ 394, 402 ], [ 404, 404 ], [ 406, 418 ], [ 422, 428 ], [ 431, 433 ], [ 436, 442 ], [ 445, 448 ], [ 450, 452 ], [ 454, 457 ], [ 459, 459 ], [ 462, 472 ], [ 476, 477 ], [ 479, 480 ], [ 482, 484 ], [ 486, 486 ], [ 489, 494 ], [ 497, 497 ], [ 499, 499 ] ], [ [ 17, 17 ], [ 36, 38 ], [ 40, 40 ], [ 42, 44 ], [ 48, 51 ], [ 55, 56 ], [ 114, 114 ], [ 119, 119 ], [ 121, 123 ], [ 127, 127 ], [ 129, 129 ], [ 138, 138 ], [ 147, 148 ], [ 151, 151 ], [ 153, 153 ], [ 158, 158 ], [ 160, 160 ], [ 168, 168 ], [ 174, 174 ], [ 179, 179 ], [ 192, 192 ], [ 200, 202 ], [ 204, 204 ], [ 211, 211 ], [ 221, 225 ], [ 227, 227 ], [ 240, 240 ], [ 245, 245 ], [ 248, 248 ], [ 259, 259 ], [ 266, 266 ], [ 270, 271 ], [ 305, 305 ], [ 316, 316 ], [ 319, 319 ], [ 331, 331 ], [ 341, 342 ], [ 347, 347 ], [ 349, 350 ], [ 354, 354 ], [ 383, 383 ], [ 420, 421 ], [ 429, 429 ], [ 435, 435 ], [ 443, 444 ], [ 458, 458 ], [ 460, 461 ], [ 473, 475 ], [ 481, 481 ], [ 485, 485 ], [ 487, 488 ], [ 496, 496 ], [ 498, 498 ] ], [ [ 57, 58 ], [ 190, 190 ] ], [ [ 71, 71 ], [ 78, 78 ], [ 83, 83 ], [ 90, 90 ], [ 97, 97 ], [ 110, 111 ], [ 113, 113 ], [ 149, 149 ], [ 156, 156 ], [ 250, 250 ] ], [ [ 74, 77 ], [ 81, 81 ], [ 92, 96 ], [ 120, 120 ], [ 165, 165 ], [ 193, 193 ], [ 215, 215 ], [ 236, 236 ], [ 238, 238 ], [ 244, 244 ], [ 309, 309 ], [ 317, 317 ], [ 343, 343 ], [ 363, 363 ], [ 393, 393 ], [ 403, 403 ], [ 405, 405 ], [ 419, 419 ], [ 430, 430 ], [ 449, 449 ] ], [ [ 197, 197 ], [ 478, 478 ] ], [ [ 310, 315 ] ] ]
1d66b4e3b4d6ae4cbc81bf4c8fb0d9630fde419d
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleAffectors/ParticleUniverseParticleFollower.h
29ddfe40838be38ea6bddb8eca3228587d81f886
[]
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
2,110
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_PARTICLE_FOLLOWER_H__ #define __PU_PARTICLE_FOLLOWER_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseAffector.h" namespace ParticleUniverse { /** This affector makes particles follow its predecessor. */ class _ParticleUniverseExport ParticleFollower : public ParticleAffector { public: ParticleFollower(void) : ParticleAffector(), mMinDistance(10.0f), mMaxDistance(Ogre::Math::POS_INFINITY), mPositionPreviousParticle(Ogre::Vector3::ZERO), mFirst(false) { mAffectorType = "Follower"; }; virtual ~ParticleFollower(void) {}; /** @copydoc ParticleAffector::copyAttributesTo */ virtual void copyAttributesTo (ParticleAffector* affector); /** Validate if first particle. */ virtual void _firstParticle(ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed); /** */ virtual void _affect(ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed); /** */ Ogre::Real getMaxDistance(void) const; void setMaxDistance(Ogre::Real maxDistance); /** */ Ogre::Real getMinDistance(void) const; void setMinDistance(Ogre::Real minDistance); protected: Ogre::Real mMinDistance; Ogre::Real mMaxDistance; Ogre::Vector3 mPositionPreviousParticle; bool mFirst; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 72 ] ] ]
394125f148440bddb19762469f32c7d127cd0c6a
12d2d19ae9e12973a7d25b97b5bc530b82dd9519
/rclib/include/TinyXMLPP/tinyxml.cpp
b3cd11b59a41c0c5ef70aa43f7cf947aca20c1f8
[ "Zlib" ]
permissive
gaoxiaojun/delicacymap
fe82b228e89d3fad48262e03bd097a9041c2a252
aceabb664bbd6f7b87b0c9b8ffdad55bc6310c68
refs/heads/master
2021-01-10T11:11:51.412815
2010-05-05T02:36:14
2010-05-05T02:36:14
47,736,729
0
0
null
null
null
null
UTF-8
C++
false
false
40,814
cpp
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "tinyxml.h" #include <ctype.h> #ifdef TIXML_USE_STL #include <sstream> #include <iostream> #endif bool TiXmlBase::condenseWhiteSpace = true; // Microsoft compiler security FILE* TiXmlFOpen( const char* filename, const char* mode ) { #if defined(TIXML_SAFE) && defined(_MSC_VER) && (_MSC_VER >= 1400 ) FILE* fp = 0; errno_t err = fopen_s( &fp, filename, mode ); if ( !err && fp ) return fp; return 0; #else return fopen( filename, mode ); #endif } void TiXmlBase::EncodeString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // &#xA9; -- copyright symbol, for example. // // The -1 is a bug fix from Rob Laveaux. It keeps // an overflow from happening if there is no ';'. // There are actually 2 ways to exit this loop - // while fails (error case) and break (semicolon found). // However, there is no mechanism (currently) for // this function to return an error. while ( i<(int)str.length()-1 ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "&#x%02X;", (unsigned) ( c & 0xff ) ); #else sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); #endif //*ME: warning C4267: convert 'size_t' to 'int' //*ME: Int-Cast to make compiler happy ... outString->append( buf, (int)strlen( buf ) ); ++i; } else { //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } } TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } } void TiXmlNode::CopyTo( TiXmlNode* target ) const { target->SetValue (value.c_str() ); target->userData = userData; } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { assert( node->parent == 0 || node->parent == this ); assert( node->GetDocument() == 0 || node->GetDocument() == this->GetDocument() ); if ( node->Type() == TiXmlNode::DOCUMENT ) { delete node; if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) { return 0; } if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; if ( beforeThis->prev ) { beforeThis->prev->next = node; } else { assert( firstChild == beforeThis ); firstChild = node; } beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) { return 0; } if ( addThis.Type() == TiXmlNode::DOCUMENT ) { if ( GetDocument() ) GetDocument()->SetError( TIXML_ERROR_DOCUMENT_TOP_ONLY, 0, 0, TIXML_ENCODING_UNKNOWN ); return 0; } TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; if ( afterThis->next ) { afterThis->next->prev = node; } else { assert( lastChild == afterThis ); lastChild = node; } afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; delete replaceThis; node->parent = this; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; delete removeThis; return true; } const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { const TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { const TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::IterateChildren( const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } const TiXmlNode* TiXmlNode::IterateChildren( const char * val, const TiXmlNode* previous ) const { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { const TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { const TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( strcmp( node->Value(), _value ) == 0 ) return node; } return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { #ifdef TIXML_USE_STL TIXML_STRING str( name ); TiXmlAttribute* node = attributeSet.Find( str ); #else TiXmlAttribute* node = attributeSet.Find( name ); #endif if ( node ) { attributeSet.Remove( node ); delete node; } } const TiXmlElement* TiXmlNode::FirstChildElement() const { const TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { const TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement() const { const TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { const TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #ifdef TIXML_USE_STL TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; copy.CopyTo( this ); } void TiXmlElement::operator=( const TiXmlElement& base ) { ClearThis(); base.CopyTo( this ); } TiXmlElement::~TiXmlElement() { ClearThis(); } void TiXmlElement::ClearThis() { Clear(); while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); delete node; } } const char* TiXmlElement::Attribute( const char* name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); return 0; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return &node->ValueStr(); return 0; } #endif const char* TiXmlElement::Attribute( const char* name, int* i ) const { const char* s = Attribute( name ); if ( i ) { if ( s ) { *i = atoi( s ); } else { *i = 0; } } return s; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { const std::string* s = Attribute( name ); if ( i ) { if ( s ) { *i = atoi( s->c_str() ); } else { *i = 0; } } return s; } #endif const char* TiXmlElement::Attribute( const char* name, double* d ) const { const char* s = Attribute( name ); if ( d ) { if ( s ) { *d = atof( s ); } else { *d = 0; } } return s; } #ifdef TIXML_USE_STL const std::string* TiXmlElement::Attribute( const std::string& name, double* d ) const { const std::string* s = Attribute( name ); if ( d ) { if ( s ) { *d = atof( s->c_str() ); } else { *d = 0; } } return s; } #endif int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryIntAttribute( const std::string& name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } #endif int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } #ifdef TIXML_USE_STL int TiXmlElement::QueryDoubleAttribute( const std::string& name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } #endif void TiXmlElement::SetAttribute( const char * name, int val ) { char buf[64]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%d", val ); #else sprintf( buf, "%d", val ); #endif SetAttribute( name, buf ); } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, int val ) { std::ostringstream oss; oss << val; SetAttribute( name, oss.str() ); } #endif void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { char buf[256]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%f", val ); #else sprintf( buf, "%f", val ); #endif SetAttribute( name, buf ); } void TiXmlElement::SetAttribute( const char * cname, const char * cvalue ) { #ifdef TIXML_USE_STL TIXML_STRING _name( cname ); TIXML_STRING _value( cvalue ); #else const char* _name = cname; const char* _value = cvalue; #endif TiXmlAttribute* node = attributeSet.Find( _name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( cname, cvalue ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } #ifdef TIXML_USE_STL void TiXmlElement::SetAttribute( const std::string& name, const std::string& _value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( name, _value ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } #endif void TiXmlElement::Print( FILE* cfile, int depth ) const { int i; assert( cfile ); for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<%s", value.c_str() ); const TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { fprintf( cfile, " " ); attrib->Print( cfile, depth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. TiXmlNode* node; if ( !firstChild ) { fprintf( cfile, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf( cfile, ">" ); firstChild->Print( cfile, depth + 1 ); fprintf( cfile, "</%s>", value.c_str() ); } else { fprintf( cfile, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf( cfile, "\n" ); } node->Print( cfile, depth+1 ); } fprintf( cfile, "\n" ); for( i=0; i<depth; ++i ) { fprintf( cfile, " " ); } fprintf( cfile, "</%s>", value.c_str() ); } } void TiXmlElement::CopyTo( TiXmlElement* target ) const { // superclass: TiXmlNode::CopyTo( target ); // Element class: // Clone the attributes, then clone the children. const TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { target->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } bool TiXmlElement::Accept( TiXmlVisitor* visitor ) const { if ( visitor->VisitEnter( *this, attributeSet.First() ) ) { for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) break; } } return visitor->VisitExit( *this ); } TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) return 0; CopyTo( clone ); return clone; } const char* TiXmlElement::GetText() const { const TiXmlNode* child = this->FirstChild(); if ( child ) { const TiXmlText* childText = child->ToText(); if ( childText ) { return childText->Value(); } } return 0; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; value = documentName; ClearError(); } #ifdef TIXML_USE_STL TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; useMicrosoftBOM = false; value = documentName; ClearError(); } #endif TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT ) { copy.CopyTo( this ); } void TiXmlDocument::operator=( const TiXmlDocument& copy ) { Clear(); copy.CopyTo( this ); } bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { // See STL_STRING_BUG below. //StringToBuffer buf( value ); return LoadFile( Value(), encoding ); } bool TiXmlDocument::SaveFile() const { // See STL_STRING_BUG below. // StringToBuffer buf( value ); // // if ( buf.buffer && SaveFile( buf.buffer ) ) // return true; // // return false; return SaveFile( Value() ); } bool TiXmlDocument::LoadFile( const char* _filename, TiXmlEncoding encoding ) { // There was a really terrifying little bug here. The code: // value = filename // in the STL case, cause the assignment method of the std::string to // be called. What is strange, is that the std::string had the same // address as it's c_str() method, and so bad things happen. Looks // like a bug in the Microsoft STL implementation. // Add an extra string to avoid the crash. TIXML_STRING filename( _filename ); value = filename; // reading in binary mode so that tinyxml can normalize the EOL FILE* file = TiXmlFOpen( value.c_str (), "rb" ); if ( file ) { bool result = LoadFile( file, encoding ); fclose( file ); return result; } else { SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } } bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding ) { if ( !file ) { SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // Delete the existing data: Clear(); location.Clear(); // Get the file size, so we can pre-allocate the string. HUGE speed impact. long length = 0; fseek( file, 0, SEEK_END ); length = ftell( file ); fseek( file, 0, SEEK_SET ); // Strange case, but good to handle up front. if ( length <= 0 ) { SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); // Subtle bug here. TinyXml did use fgets. But from the XML spec: // 2.11 End-of-Line Handling // <snip> // <quote> // ...the XML processor MUST behave as if it normalized all line breaks in external // parsed entities (including the document entity) on input, before parsing, by translating // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to // a single #xA character. // </quote> // // It is not clear fgets does that, and certainly isn't clear it works cross platform. // Generally, you expect fgets to translate from the convention of the OS to the c/unix // convention, and not work generally. /* while( fgets( buf, sizeof(buf), file ) ) { data += buf; } */ char* buf = new char[ length+1 ]; buf[0] = 0; if ( fread( buf, length, 1, file ) != 1 ) { delete [] buf; SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } const char* lastPos = buf; const char* p = buf; buf[length] = 0; while( *p ) { assert( p < (buf+length) ); if ( *p == 0xa ) { // Newline character. No special rules for this. Append all the characters // since the last string, and include the newline. data.append( lastPos, (p-lastPos+1) ); // append, include the newline ++p; // move past the newline lastPos = p; // and point to the new buffer (may be 0) assert( p <= (buf+length) ); } else if ( *p == 0xd ) { // Carriage return. Append what we have so far, then // handle moving forward in the buffer. if ( (p-lastPos) > 0 ) { data.append( lastPos, p-lastPos ); // do not add the CR } data += (char)0xa; // a proper newline if ( *(p+1) == 0xa ) { // Carriage return - new line sequence p += 2; lastPos = p; assert( p <= (buf+length) ); } else { // it was followed by something else...that is presumably characters again. ++p; lastPos = p; assert( p <= (buf+length) ); } } else { ++p; } } // Handle any left over characters. if ( p-lastPos ) { data.append( lastPos, p-lastPos ); } delete [] buf; buf = 0; Parse( data.c_str(), 0, encoding ); if ( Error() ) return false; else return true; } bool TiXmlDocument::SaveFile( const char * filename ) const { // The old c stuff lives on... FILE* fp = TiXmlFOpen( filename, "w" ); if ( fp ) { bool result = SaveFile( fp ); fclose( fp ); return result; } return false; } bool TiXmlDocument::SaveFile( FILE* fp ) const { if ( useMicrosoftBOM ) { const unsigned char TIXML_UTF_LEAD_0 = 0xefU; const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; fputc( TIXML_UTF_LEAD_0, fp ); fputc( TIXML_UTF_LEAD_1, fp ); fputc( TIXML_UTF_LEAD_2, fp ); } Print( fp, 0 ); return (ferror(fp) == 0); } void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { TiXmlNode::CopyTo( target ); target->error = error; target->errorId = errorId; target->errorDesc = errorDesc; target->tabsize = tabsize; target->errorLocation = errorLocation; target->useMicrosoftBOM = useMicrosoftBOM; TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { assert( cfile ); for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { node->Print( cfile, depth ); fprintf( cfile, "\n" ); } } bool TiXmlDocument::Accept( TiXmlVisitor* visitor ) const { if ( visitor->VisitEnter( *this ) ) { for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) break; } } return visitor->VisitExit( *this ); } const TiXmlAttribute* TiXmlAttribute::Next() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } /* TiXmlAttribute* TiXmlAttribute::Next() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } */ const TiXmlAttribute* TiXmlAttribute::Previous() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } /* TiXmlAttribute* TiXmlAttribute::Previous() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } */ void TiXmlAttribute::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { TIXML_STRING n, v; EncodeString( name, &n ); EncodeString( value, &v ); if (value.find ('\"') == TIXML_STRING::npos) { if ( cfile ) { fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); } if ( str ) { (*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\""; } } else { if ( cfile ) { fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); } if ( str ) { (*str) += n; (*str) += "='"; (*str) += v; (*str) += "'"; } } } int TiXmlAttribute::QueryIntValue( int* ival ) const { if ( TIXML_SSCANF( value.c_str(), "%d", ival ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { if ( TIXML_SSCANF( value.c_str(), "%lf", dval ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { char buf [64]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF(buf, sizeof(buf), "%d", _value); #else sprintf (buf, "%d", _value); #endif SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { char buf [256]; #if defined(TIXML_SNPRINTF) TIXML_SNPRINTF( buf, sizeof(buf), "%lf", _value); #else sprintf (buf, "%lf", _value); #endif SetValue (buf); } int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT ) { copy.CopyTo( this ); } void TiXmlComment::operator=( const TiXmlComment& base ) { Clear(); base.CopyTo( this ); } void TiXmlComment::Print( FILE* cfile, int depth ) const { assert( cfile ); for ( int i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<!--%s-->", value.c_str() ); } void TiXmlComment::CopyTo( TiXmlComment* target ) const { TiXmlNode::CopyTo( target ); } bool TiXmlComment::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlComment::Clone() const { TiXmlComment* clone = new TiXmlComment(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlText::Print( FILE* cfile, int depth ) const { assert( cfile ); if ( cdata ) { int i; fprintf( cfile, "\n" ); for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<![CDATA[%s]]>\n", value.c_str() ); // unformatted output } else { TIXML_STRING buffer; EncodeString( value, &buffer ); fprintf( cfile, "%s", buffer.c_str() ); } } void TiXmlText::CopyTo( TiXmlText* target ) const { TiXmlNode::CopyTo( target ); target->cdata = cdata; } bool TiXmlText::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; clone = new TiXmlText( "" ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, const char * _encoding, const char * _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) : TiXmlNode( TiXmlNode::DECLARATION ) { copy.CopyTo( this ); } void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { if ( cfile ) fprintf( cfile, "<?xml " ); if ( str ) (*str) += "<?xml "; if ( !version.empty() ) { if ( cfile ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); if ( str ) { (*str) += "version=\""; (*str) += version; (*str) += "\" "; } } if ( !encoding.empty() ) { if ( cfile ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); if ( str ) { (*str) += "encoding=\""; (*str) += encoding; (*str) += "\" "; } } if ( !standalone.empty() ) { if ( cfile ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); if ( str ) { (*str) += "standalone=\""; (*str) += standalone; (*str) += "\" "; } } if ( cfile ) fprintf( cfile, "?>" ); if ( str ) (*str) += "?>"; } void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { TiXmlNode::CopyTo( target ); target->version = version; target->encoding = encoding; target->standalone = standalone; } bool TiXmlDeclaration::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlDeclaration::Clone() const { TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlStylesheetReference::TiXmlStylesheetReference( const char * _type, const char * _href ) : TiXmlNode( TiXmlNode::STYLESHEETREFERENCE ) { type = _type; href = _href; } #ifdef TIXML_USE_STL TiXmlStylesheetReference::TiXmlStylesheetReference( const std::string& _type, const std::string& _href ) : TiXmlNode( TiXmlNode::STYLESHEETREFERENCE ) { type = _type; href = _href; } #endif TiXmlStylesheetReference::TiXmlStylesheetReference( const TiXmlStylesheetReference& copy ) : TiXmlNode( TiXmlNode::STYLESHEETREFERENCE ) { copy.CopyTo( this ); } void TiXmlStylesheetReference::operator=( const TiXmlStylesheetReference& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlStylesheetReference::Print( FILE* cfile, int /*depth*/, TIXML_STRING* str ) const { if ( cfile ) fprintf( cfile, "<?xml-stylesheet " ); if ( str ) (*str) += "<?xml-stylesheet "; if ( !type.empty() ) { if ( cfile ) fprintf (cfile, "type=\"%s\" ", type.c_str ()); if ( str ) { (*str) += "type=\""; (*str) += type; (*str) += "\" "; } } if ( !href.empty() ) { if ( cfile ) fprintf (cfile, "href=\"%s\" ", href.c_str ()); if ( str ) { (*str) += "href=\""; (*str) += href; (*str) += "\" "; } } if ( cfile ) fprintf (cfile, "?>"); if ( str ) (*str) += "?>"; } void TiXmlStylesheetReference::CopyTo( TiXmlStylesheetReference* target ) const { TiXmlNode::CopyTo( target ); target->type = type; target->href = href; } bool TiXmlStylesheetReference::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlStylesheetReference::Clone() const { TiXmlStylesheetReference* clone = new TiXmlStylesheetReference(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) fprintf( cfile, " " ); fprintf( cfile, "<%s>", value.c_str() ); } void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { TiXmlNode::CopyTo( target ); } bool TiXmlUnknown::Accept( TiXmlVisitor* visitor ) const { return visitor->Visit( *this ); } TiXmlNode* TiXmlUnknown::Clone() const { TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { #ifdef TIXML_USE_STL assert( !Find( TIXML_STRING( addMe->Name() ) ) ); // Shouldn't be multiply adding to the set. #else assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. #endif addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } #ifdef TIXML_USE_STL const TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const { for( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } /* TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) { for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } */ #endif const TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) const { for( const TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } return 0; } /* TiXmlAttribute* TiXmlAttributeSet::Find( const char* name ) { for( TiXmlAttribute* node = sentinel.next; node != &sentinel; node = node->next ) { if ( strcmp( node->name.c_str(), name ) == 0 ) return node; } return 0; } */ #ifdef TIXML_USE_STL std::istream& operator>> (std::istream & in, TiXmlNode & base) { TIXML_STRING tag; tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); return in; } #endif #ifdef TIXML_USE_STL std::ostream& operator<< (std::ostream & out, const TiXmlNode & base) { TiXmlPrinter printer; printer.SetStreamPrinting(); base.Accept( &printer ); out << printer.Str(); return out; } std::string& operator<< (std::string& out, const TiXmlNode& base ) { TiXmlPrinter printer; printer.SetStreamPrinting(); base.Accept( &printer ); out.append( printer.Str() ); return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { if ( node ) { TiXmlNode* child = node->FirstChild(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { if ( node ) { TiXmlNode* child = node->FirstChild( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { if ( node ) { TiXmlElement* child = node->FirstChildElement(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { if ( node ) { TiXmlElement* child = node->FirstChildElement( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild(); for ( i=0; child && i<count; child = child->NextSibling(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild( value ); for ( i=0; child && i<count; child = child->NextSibling( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement(); for ( i=0; child && i<count; child = child->NextSiblingElement(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement( value ); for ( i=0; child && i<count; child = child->NextSiblingElement( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } bool TiXmlPrinter::VisitEnter( const TiXmlDocument& ) { return true; } bool TiXmlPrinter::VisitExit( const TiXmlDocument& ) { return true; } bool TiXmlPrinter::VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ) { DoIndent(); buffer += "<"; buffer += element.Value(); for( const TiXmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->Next() ) { buffer += " "; attrib->Print( 0, 0, &buffer ); } if ( !element.FirstChild() ) { buffer += " />"; DoLineBreak(); } else { buffer += ">"; if ( element.FirstChild()->ToText() && element.LastChild() == element.FirstChild() && element.FirstChild()->ToText()->CDATA() == false ) { simpleTextPrint = true; // no DoLineBreak()! } else { DoLineBreak(); } } ++depth; return true; } bool TiXmlPrinter::VisitExit( const TiXmlElement& element ) { --depth; if ( !element.FirstChild() ) { // nothing. } else { if ( simpleTextPrint ) { simpleTextPrint = false; } else { DoIndent(); } buffer += "</"; buffer += element.Value(); buffer += ">"; DoLineBreak(); } return true; } bool TiXmlPrinter::Visit( const TiXmlText& text ) { if ( text.CDATA() ) { DoIndent(); buffer += "<![CDATA["; buffer += text.Value(); buffer += "]]>"; DoLineBreak(); } else if ( simpleTextPrint ) { TIXML_STRING str; TiXmlBase::EncodeString( text.ValueTStr(), &str ); buffer += str; } else { DoIndent(); TIXML_STRING str; TiXmlBase::EncodeString( text.ValueTStr(), &str ); buffer += str; DoLineBreak(); } return true; } bool TiXmlPrinter::Visit( const TiXmlDeclaration& declaration ) { DoIndent(); declaration.Print( 0, 0, &buffer ); DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlComment& comment ) { DoIndent(); buffer += "<!--"; buffer += comment.Value(); buffer += "-->"; DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlUnknown& unknown ) { DoIndent(); buffer += "<"; buffer += unknown.Value(); buffer += ">"; DoLineBreak(); return true; } bool TiXmlPrinter::Visit( const TiXmlStylesheetReference& stylesheet ) { DoIndent(); stylesheet.Print( 0, 0, &buffer ); DoLineBreak(); return true; }
[ "colprog@d4fe8cd8-f54c-11dd-8c4e-4bbb75a408b7" ]
[ [ [ 1, 1969 ] ] ]
48d0b1576b81b48bd39736dbc0b2b7e3f21251ed
3387244856041685a94b72264d41a80ae35c3f80
/include/TowerBarrier.h
9665ada87ecdba38cf5e00d259e9e14283f0dcd9
[]
no_license
kinfung0602/ogre-tower-defense
768c9ae0c0972379cfbddf91361cf343b8c76dfb
ce950d36b49ea46e294d936f3cd363bcc73c8468
refs/heads/master
2021-01-10T08:22:05.424893
2011-07-11T01:32:05
2011-07-11T01:32:05
53,152,007
0
0
null
null
null
null
UTF-8
C++
false
false
292
h
#pragma once #include "Tower.h" class TowerBase; class TowerBarrier : public Tower { public: TowerBarrier(TowerBase* parent); ~TowerBarrier(void); // Inherited from Tower void upgrade(void); void sell(void); bool createGraphics(void); void update(float t); };
[ [ [ 1, 17 ] ] ]
4054d00bfb33816e4b60333de2d640ab4e212a75
0f973718202109e95fc25240d1cec2d952225732
/Source/Important/Signals.cpp
3d3c7ce0d31e7f0dc13bcd8a8fa2be231cc94be5
[]
no_license
RadicalZephyr/fast-ai
eeb9a7bb2357680f63f06c5d49361e274772b456
4f8b9847f6d59f0ec0fcbbdaef8b2c7291be338f
refs/heads/master
2021-01-01T19:47:08.047409
2011-09-28T01:14:48
2011-09-28T01:14:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,359
cpp
#include "Signals.h" namespace Signal { //Register a start callback. //Only called once, so no need for return value boost::signal<void ()> &onStart(void) { static boost::signal<void ()> onStart; return onStart; } //Register an end callback. //Only called once, so no need for return value //1 = isWinner boost::signal<void (bool)> &onEnd() { static boost::signal<void (bool)> onEnd; return onEnd; } //Register a frame callback. boost::signal<void ()> &onFrame(void) { static boost::signal<void ()> onFrame; return onFrame; } //Register a sending_text callback. //1 = text boost::signal<void (std::string)> &onSendText(void) { static boost::signal<void (std::string)> onSendText; return onSendText; } //Register a receiving_text callback. //1 = player //2 = text boost::signal<void (BWAPI::Player* player, std::string)> &onReceiveText(void) { static boost::signal<void (BWAPI::Player* player, std::string)> onReceiveText; return onReceiveText; } //Register a player_left callback. //1 = player boost::signal<void (BWAPI::Player* player)> &onPlayerLeft(void) { static boost::signal<void (BWAPI::Player* player)> onPlayerLeft; return onPlayerLeft; } //Register a nuke_detect callback. //1 = posistion boost::signal<void (BWAPI::Position target)> &onNukeDetect(void) { static boost::signal<void (BWAPI::Position target)> onNukeDetect; return onNukeDetect; } //Register a unit discover callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onUnitDiscover(void) { static boost::signal<void (BWAPI::Unit*)> onUnitDiscover; return onUnitDiscover; } //Register a unit evade callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onUnitEvade(void) { static boost::signal<void (BWAPI::Unit*)> onUnitEvade; return onUnitEvade; } //Register a unit show callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onUnitShow(void) { static boost::signal<void (BWAPI::Unit*)> onUnitShow; return onUnitShow; } //Register a unit hide callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onUnitHide(void) { static boost::signal<void (BWAPI::Unit*)> onUnitHide; return onUnitHide; } //Register a friendly unit create callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onFriendlyUnitCreate(void) { static boost::signal<void (BWAPI::Unit*)> onFriendlyUnitCreate; return onFriendlyUnitCreate; } //Register an enemy unit create callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onEnemyUnitCreate(void) { static boost::signal<void (BWAPI::Unit*)> onEnemyUnitCreate; return onEnemyUnitCreate; } //Register a frienldy unit destroy callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onFriendlyUnitDestroy(void) { static boost::signal<void (BWAPI::Unit*)> onFriendlyUnitDestroy; return onFriendlyUnitDestroy; } //Register an enemy unit destroy callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onEnemyUnitDestroy(void) { static boost::signal<void (BWAPI::Unit*)> onEnemyUnitDestroy; return onEnemyUnitDestroy; } //Register a neutral unit destroy callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onNeutralUnitDestroy(void) { static boost::signal<void (BWAPI::Unit*)> onNeutralUnitDestroy; return onNeutralUnitDestroy; } //Register a unit morph callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onUnitMorph(void) { static boost::signal<void (BWAPI::Unit*)> onUnitMorph; return onUnitMorph; } //Register a unit renegade callback. //1 = unit boost::signal<void (BWAPI::Unit*)> &onUnitRenegade(void) { static boost::signal<void (BWAPI::Unit*)> onUnitRenegade; return onUnitRenegade; } //Register a on save game callback. //1 = gamename boost::signal<void (std::string)> &onSaveGame(void) { static boost::signal<void (std::string)> onSaveGame; return onSaveGame; } }
[ [ [ 1, 140 ] ] ]
3e8d1daac127cc6978dccd7222c0c782a116ef99
9a5db9951432056bb5cd4cf3c32362a4e17008b7
/FacesCapture/trunkl/frontalFaceDetect/stdafx.cpp
b28c81b3e8f94d32079a32d492d423f45a696922
[]
no_license
miaozhendaoren/appcollection
65b0ede264e74e60b68ca74cf70fb24222543278
f8b85af93f787fa897af90e8361569a36ff65d35
refs/heads/master
2021-05-30T19:27:21.142158
2011-06-27T03:49:22
2011-06-27T03:49:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
// stdafx.cpp : source file that includes just the standard includes // frontalFaceDetect.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "[email protected]@cbf8b9f2-3a65-11de-be05-5f7a86268029" ]
[ [ [ 1, 8 ] ] ]
9961a1af0f8d4b4a711de7a1bbccc46318becb5e
9566086d262936000a914c5dc31cb4e8aa8c461c
/EnigmaClient-Console/Application.cpp
c142ec10101aa5ffe8b63c3f43784e87d1b8bed8
[]
no_license
pazuzu156/Enigma
9a0aaf0cd426607bb981eb46f5baa7f05b66c21f
b8a4dfbd0df206e48072259dbbfcc85845caad76
refs/heads/master
2020-06-06T07:33:46.385396
2011-12-19T03:14:15
2011-12-19T03:14:15
3,023,618
1
0
null
null
null
null
UTF-8
C++
false
false
8,424
cpp
/* Copyright © 2011 Christopher Joseph Dean Schaefer (disks86) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Application.hpp" namespace Enigma { Application::Application() : mSoundManager(mClientTransmissionManager) { this->PreInit(); } Application::~Application() { this->Unload(); } void Application::PreInit() { this->mIsStopped=true; this->mIsUnloaded=true; this->mGameMode = 0; } void Application::Init(int argc, Enigma::c8** argv) { //initialize sub servers. this->mSoundManager.Init(argc,argv); this->mClientTransmissionManager.Init(); this->mClientTransmissionManager.GetClientSessionManager().RegisterApplicationEventListener(this); this->mClientTransmissionManager.GetClientSessionManager().RegisterChatEventListener(this); } void Application::Load() { try { this->LoadUnsafely(); } catch (Enigma::HardwareException&) { throw; //nothing to do but bailout. } catch (std::overflow_error&) { throw; //may need to pop some calls off the stack. } catch(Enigma::EnigmaException& e) { std::cout << "Enigma Exception: " << e.what() << std::endl; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } } void Application::LoadUnsafely() { this->mIsUnloaded=false; this->mSoundManager.Load(); //another thread is not yet needed. //start sub servers. this->mClientTransmissionManager.Start(); //make connection to server. while(!this->mClientTransmissionManager.GetIsLoaded()) { boost::posix_time::seconds workTime(1); boost::this_thread::sleep(workTime); } ServerConnectionInformation info = this->mClientTransmissionManager.GetClientSessionManager().GetClientConfigurationManager().GetDefaultServer(); this->mClientTransmissionManager.Connect(info.Host,info.Port); } void Application::Unload() { if(!this->mIsUnloaded) { this->mIsUnloaded=true; //stop sub servers. this->mClientTransmissionManager.Stop(); } } void Application::Poll() { DoApplicationEvents(); //make sure initial messages are posted before requesting user input. char command[2048]; std::cin.getline(command, 2048); this->mClientTransmissionManager.GetClientSessionManager().ProcessCommand(std::string(command)); DoApplicationEvents(); DoChatEvents(); //DoSceneEvents(); //May make this another thread later. DoAudioEvents(); this->mSoundManager.Poll(); } bool Application::PollSafe() { bool success=false; try { this->Poll(); success=true; } catch (Enigma::HardwareException&) { throw; } catch (std::overflow_error&) { throw; //may need to pop some calls off the stack. } catch(Enigma::EnigmaException& e) { std::cout << "Enigma Exception: " << e.what() << std::endl; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } return success; } //Calls poll until stopped. void Application::EnterLoop(int argc, Enigma::c8** argv) { this->Init(argc,argv); this->Load(); while(!this->mIsStopped) { this->PollSafe(); } this->Unload(); } void Application::Start(int argc, Enigma::c8** argv) { this->mIsStopped=false; this->EnterLoop(argc,argv); } void Application::Stop() { if(!this->mIsStopped) { this->mIsStopped=true; } } void Application::DoApplicationEvents() { this->mClientTransmissionManager.GetClientSessionManager().DoApplicationEvents(); } void Application::DoAudioEvents() { this->mClientTransmissionManager.GetClientSessionManager().DoAudioEvents(); } void Application::DoChatEvents() { this->mClientTransmissionManager.GetClientSessionManager().DoChatEvents(); } void Application::DoSceneEvents() { this->mClientTransmissionManager.GetClientSessionManager().DoSceneEvents(); } void Application::onExit() { this->mIsStopped=true; //should cause program to halt. } void Application::onChangeGameMode(size_t gameMode) { this->mGameMode = gameMode; //console client doesn't need much here no scenes to load or ui to change. } void Application::onLog(const std::string& message) { std::cout << "Log: " << message << std::endl; } void Application::onInvited(size_t chatType, size_t inviteId, const std::string& organizationName) { char anwser='n'; switch(chatType) { case CHAT_TYPE_GUILD: std::cout << "You have been invited to the " << organizationName << " guild. Would you like to join? (y/n)" << std::endl; std::cin >> anwser; if(anwser=='y' || anwser=='Y') { this->mClientTransmissionManager.GetClientSessionManager().RespondToGuildInvite(true,inviteId); } else { this->mClientTransmissionManager.GetClientSessionManager().RespondToGuildInvite(false,inviteId); } break; case CHAT_TYPE_PARTY: std::cout << "You have been invited to " << organizationName << "'s party. Would you like to join? (y/n)" << std::endl; std::cin >> anwser; if(anwser=='y' || anwser=='Y') { this->mClientTransmissionManager.GetClientSessionManager().RespondToPartyInvite(true,inviteId); } else { this->mClientTransmissionManager.GetClientSessionManager().RespondToPartyInvite(false,inviteId); } break; default: break; } } void Application::onJoined(size_t chatType, const std::string& organizationName) { switch(chatType) { case CHAT_TYPE_GUILD: std::cout << "You have joined the " << organizationName << " guild." << std::endl; break; case CHAT_TYPE_PARTY: std::cout << "You have joined " << organizationName << "'s party." << std::endl; break; default: break; } } void Application::onRankModified(size_t chatType, const std::string& rankName, size_t permissions) { } void Application::onModified(size_t chatType, const std::string& playerName, const std::string& rankName) { } void Application::onExpelled(size_t chatType, const std::string& organizationName, const std::string& reason) { switch(chatType) { case CHAT_TYPE_GUILD: std::cout << "You have been expelled from the " << organizationName << " guild." << std::endl; break; case CHAT_TYPE_PARTY: std::cout << "You have been expelled from " << organizationName << "'s party." << std::endl; break; default: break; } } void Application::onReceivedMessage(size_t chatType, const std::string& message, const std::string& sender) { switch(chatType) { case CHAT_TYPE_BROADCAST: std::cout << sender << " broadcast: " << message << std::endl; break; case CHAT_TYPE_GUILD: std::cout << sender << " from your guild said: " << message << std::endl; break; case CHAT_TYPE_MAP: std::cout << sender << " shouted: " << message << std::endl; break; case CHAT_TYPE_PARTY: std::cout << sender << " from your party said: " << message << std::endl; break; case CHAT_TYPE_SYSTEM: std::cout << message << std::endl; break; case CHAT_TYPE_WHISPER: std::cout << sender << " whispered: " << message << std::endl; break; default: std::cout << sender << " spoke strangely: " << message << std::endl; //this shouldn't happen. break; } } void Application::onNpcResponse(size_t npcId, const std::string& response, const std::vector<std::string>& playerResponses) { } }
[ [ [ 1, 315 ] ] ]
957c5f0566384c69f115317c6c3ef04d6f4c11a7
ce10be13a62b6ed6e3ccdd0780fe98e08573166e
/include/creature.h
fe0e66f884c93d4c2cf6311cf68411273b50888c
[]
no_license
pfeyssaguet/afrods
b2d63fd501a60a5c40d2d128bc03820f389c4d59
df2e85990bac4a2107bba5ad7ba9232753cf7725
refs/heads/master
2016-09-06T02:13:26.546098
2010-02-07T13:07:01
2010-02-07T13:07:01
32,130,697
0
0
null
null
null
null
UTF-8
C++
false
false
5,138
h
#ifndef __CREATURE_H__ #define __CREATURE_H__ #include "item.h" #include "itemweapon.h" #include "itemarmor.h" #include "types.h" #include <string> #include <map> #include <vector> #define StatModifier(stat) (((stat) / 2) - 5) namespace AfroDS { /** * Les différents slots d'équipement * - Tête : casque ou chapeau * - Dos : cape * - Corps : armure * - Main droite : arme * - Main gauche : bouclier ou indispo si arme à 2 mains * - Pieds : bottes * - Mains : gants * - Doigt droit : anneau * - Doigt gauche : anneau * - Cou : amulette * - Taille : ceinture * le dernier élément SLOT_SIZE sert à connaître le nombre de slots * ou à indiquer un item sans slot (non équipable) */ enum EquipmentSlot { SLOT_HELMET, SLOT_CLOAK, SLOT_ARMOR, SLOT_RIGHT_WEAPON, SLOT_LEFT_WEAPON, SLOT_BOOTS, SLOT_GLOVES, SLOT_RIGHT_RING, SLOT_LEFT_RING, SLOT_NECKLACE, SLOT_BELT, SLOT_SIZE // un faux slot qui permet de compter le nombre de slots, et aussi d'indiquer qu'un item ne s'équipe pas }; /** * Représente un personnage */ class Creature { public: virtual ~Creature(); /** * Renvoie le nom du personnage * @return std::string nom du personnage */ std::string getName() const; /** * Définit le nom du personnage * @param std::string sName nom du personnage */ void setName(const std::string sName); /** * Renvoie les stats de base du personnage, sans bonus * @return Stats stats de base du perso */ Stats getBaseStats() const; long getCurrentHp() const; void setCurrentHp(const int hp); long getCurrentMp() const; void setCurrentMp(const int mp); long getMaxHp() const; long getMaxMp() const; void addMoney(const long money); void subMoney(const long money); long getMoney() const; /** * Ajoute un item dans l'équipement * @param EquipmentSlot slot slot dans lequel équiper l'item * @param Item * item item à équiper (pointeur) */ void addItemToEquipment(const EquipmentSlot slot, Item * item); /** * Renvoie l'item d'équipement correspondant au slot demandé * @param EquipmentSlot slot slot demandé * @return Item * item d'équipement (pointeur) */ Item * getEquipmentItem(const EquipmentSlot slot) const; int attack(Creature * target); int getBonusAttack() const; int getArmorClass() const; /** * Ajoute un item dans l'inventaire * @param Item item l'item à ajouter */ void addItemToInventory(Item * item); /** * Renvoie l'item n° N de l'inventaire * @param int iNumItem numéro de l'item à récupérer * @return Item item récupéré */ Item * getInventoryItem(const int iNumItem); Item * getInventoryItem(const int iNumItem, bool extract); void deleteInventoryItem(const int iNumItem); /** * Renvoie le nombre d'items dans l'inventaire * @return int nombre d'items */ unsigned int getInventorySize() const; /** * Equipe un item de l'inventaire si possible, et renvoie true en cas de succès * @param unsigned int iNumItem numéro de l'item d'inventaire * @return bool false en cas d'échec */ bool equipItem(const unsigned int iNumItem); /** * Retire un item d'équipement et le remet dans l'inventaire * @param EquipmentSlot slot slot d'équipement à vider * @return bool false en cas d'échec */ bool unequipItem(const EquipmentSlot slot); void activateInventoryItem(const unsigned int iNumItem); bool activateItem(Item * item); /** * Renvoie les stats du personnage, avec les bonus et modificateurs appliqués * @return Stats stats du personnage */ virtual Stats getStats() const = 0; virtual int rollAttack() const; /** * Méthode statique utilitaire permettant de traduire un slot * en string pour l'afficher dans le menu (comme un toString() pour * l'enum EquipmentSlot) * @param EquipmentSlot slot à traduire * @return std::string chaîne de caractères */ static std::string translateSlot(const EquipmentSlot slot, const bool shortName); static std::string translateSlot(const EquipmentSlot slot); static int XpToLevel(const long xp); static long XpForNextLevel(const long xp); protected: /** * Constructeur initialisant le nom * @param std::string sName nom du personnage */ Creature(const std::string sName = ""); /** Nom du personnage */ std::string m_sName; /** Stats de base */ Stats m_baseStats; /** Pts de vie max */ long m_maxHp; /** Pts de vie courants */ long m_currentHp; /** Pts de mana max */ long m_maxMp; /** Pts de mana courants */ long m_currentMp; /** Argent */ long m_money; /** Inventaire */ std::vector<Item *> m_inventory; /** Equipement */ std::map<EquipmentSlot, Item *> m_equipment; }; } #endif
[ "deuspi@fce96c3e-db3a-11de-b64b-7d26b27941e2" ]
[ [ [ 1, 204 ] ] ]
57837b264ac1953dc871bc5e2b7ed1472446fc2e
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_core/text/juce_LocalisedStrings.cpp
d38cb3273a5f531e71340190d81fb312e9fd7bb8
[]
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
5,992
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 //============================================================================== LocalisedStrings::LocalisedStrings (const String& fileContents) { loadFromText (fileContents); } LocalisedStrings::LocalisedStrings (const File& fileToLoad) { loadFromText (fileToLoad.loadFileAsString()); } LocalisedStrings::~LocalisedStrings() { } //============================================================================== String LocalisedStrings::translate (const String& text) const { return translations.getValue (text, text); } String LocalisedStrings::translate (const String& text, const String& resultIfNotFound) const { return translations.getValue (text, resultIfNotFound); } namespace { #if JUCE_CHECK_MEMORY_LEAKS // By using this object to force a LocalisedStrings object to be created // before the currentMappings object, we can force the static order-of-destruction to // delete the currentMappings object first, which avoids a bogus leak warning. // (Oddly, just creating a LocalisedStrings on the stack doesn't work in gcc, it // has to be created with 'new' for this to work..) struct LeakAvoidanceTrick { LeakAvoidanceTrick() { const ScopedPointer<LocalisedStrings> dummy (new LocalisedStrings (String())); } }; LeakAvoidanceTrick leakAvoidanceTrick; #endif SpinLock currentMappingsLock; ScopedPointer<LocalisedStrings> currentMappings; int findCloseQuote (const String& text, int startPos) { juce_wchar lastChar = 0; String::CharPointerType t (text.getCharPointer() + startPos); for (;;) { const juce_wchar c = t.getAndAdvance(); if (c == 0 || (c == '"' && lastChar != '\\')) break; lastChar = c; ++startPos; } return startPos; } String unescapeString (const String& s) { return s.replace ("\\\"", "\"") .replace ("\\\'", "\'") .replace ("\\t", "\t") .replace ("\\r", "\r") .replace ("\\n", "\n"); } } void LocalisedStrings::loadFromText (const String& fileContents) { StringArray lines; lines.addLines (fileContents); for (int i = 0; i < lines.size(); ++i) { String line (lines[i].trim()); if (line.startsWithChar ('"')) { int closeQuote = findCloseQuote (line, 1); const String originalText (unescapeString (line.substring (1, closeQuote))); if (originalText.isNotEmpty()) { const int openingQuote = findCloseQuote (line, closeQuote + 1); closeQuote = findCloseQuote (line, openingQuote + 1); const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote))); if (newText.isNotEmpty()) translations.set (originalText, newText); } } else if (line.startsWithIgnoreCase ("language:")) { languageName = line.substring (9).trim(); } else if (line.startsWithIgnoreCase ("countries:")) { countryCodes.addTokens (line.substring (10).trim(), true); countryCodes.trim(); countryCodes.removeEmptyStrings(); } } } void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) { translations.setIgnoresCase (shouldIgnoreCase); } //============================================================================== void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) { const SpinLock::ScopedLockType sl (currentMappingsLock); currentMappings = newTranslations; } LocalisedStrings* LocalisedStrings::getCurrentMappings() { return currentMappings; } String LocalisedStrings::translateWithCurrentMappings (const String& text) { return juce::translate (text); } String LocalisedStrings::translateWithCurrentMappings (const char* text) { return juce::translate (String (text)); } String translate (const String& text) { return translate (text, text); } String translate (const char* const literal) { const String text (literal); return translate (text, text); } String translate (const String& text, const String& resultIfNotFound) { const SpinLock::ScopedLockType sl (currentMappingsLock); const LocalisedStrings* const currentMappings = LocalisedStrings::getCurrentMappings(); if (currentMappings != nullptr) return currentMappings->translate (text, resultIfNotFound); return resultIfNotFound; } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 194 ] ] ]
d105978904c0d23101f2372c772a4a0a6fb50bff
3977ae61b891f7e8ae7d75b8e22bcb63dedc3c1c
/Protected/Models/Department.h
ebdab9fb6e35e86dd61e8c3c4ba721a9b13801be
[]
no_license
jayrulez/ourprs
9734915b69207e7c3382412ca8647b051a787bb1
9d10f7a6edb06483015ed11dcfc9785f63b7204b
refs/heads/master
2020-05-17T11:40:55.001049
2010-03-25T05:20:04
2010-03-25T05:20:04
40,554,502
0
0
null
null
null
null
UTF-8
C++
false
false
2,160
h
/* @Group: BSC2D @Group Members: <ul> <li>Robert Campbell: 0701334</li> <li>Audley Gordon: 0802218</li> <li>Dale McFarlane: 0801042</li> <li>Dyonne Duberry: 0802189</li> </ul> @ */ #ifndef _DEPARTMENT_H #define _DEPARTMENT_H #ifndef _BASEMODEL_H #include "../../Base/BaseModel.h" #endif #ifdef _WIN32 #include "../../Base/Gui/Win32/Core/Console.h" #endif #include "../../Base/Gui/Source/Tools/Frame.h" #include <string> class Department: public BaseModel { private: int deptCode; int oldDeptCode; string deptName; float regularRate; float overtimeRate; Department * next; Department * prev; public: Department(); ~Department(); Department(int, string, float, float); int getDeptCode(); string getDeptName(); float getRegularRate(); float getOvertimeRate(); void setDeptCode(int); void setDeptName(string); void setRegularRate(float); void setOvertimeRate(float); void setNext(Department*); Department* getNext(); static Department* model(); Department* find(int); void show(int); bool recordExists(int); bool recordExists(int, int); void setOldDeptCode(int); int getOldDeptCode(); Department * findByCode(int); void save(Department*); void save(Department*, Department*); void setPrev(Department*); Department* getPrev(); string getFileHeaderFromFile(); void setColumnHeaders(); Department & Department::operator=(const Department &department) { if(this != &department) { this->deptCode = department.deptCode; this->deptName = department.deptName; this->regularRate = department.regularRate; this->overtimeRate = department.overtimeRate; } return *this; } bool Department::operator==(const Department &department) const { return this->deptCode == department.deptCode && this->deptName == department.deptName && this->regularRate == department.regularRate && this->overtimeRate == department.overtimeRate; } bool Department::operator!=(const Department &department) const { return !(*this == department); } }; #endif
[ "[email protected]", "portmore.representa@c48e7a12-1f02-11df-8982-67e453f37615" ]
[ [ [ 1, 12 ], [ 16, 16 ], [ 22, 22 ], [ 26, 33 ], [ 37, 49 ], [ 51, 83 ], [ 85, 85 ] ], [ [ 13, 15 ], [ 17, 21 ], [ 23, 25 ], [ 34, 36 ], [ 50, 50 ], [ 84, 84 ] ] ]
0b4f178723bd274c23445dcd9467b1d278d27e8b
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Framework/Camera.cpp
4d79598e45cb23f9623491ceff6a49a6abdd6b93
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,192
cpp
#include "Camera.h" #include "MouseHandler.h" #include "KeyboardHandler.h" #include "Globals.h" using namespace Helpers; Camera::Camera(){ position = D3DXVECTOR3(-52.0432f, 19.3221f, -34.1443f); initialForward = D3DXVECTOR3(0.0f, 0.0f, 1.0f); D3DXVec3Normalize(&initialForward, &initialForward); forward = D3DXVECTOR3(0.776472f, -0.283583f, 0.562735f); deltaMovement = 10.0f; deltaRotation = 1.0f; yaw = 0.94366282f; pitch = 0.28752902f; near_plane = 0.001f; far_plane = 1000.0f; D3DXMATRIX rot; D3DXMatrixRotationY(&rot, (float)D3DX_PI/2.0f); initialRight = D3DXVECTOR3(1.0f, 0.0f, 0.0f); D3DXVec3TransformCoord(&right, &forward, &rot); D3DXVec3Normalize(&right, &right); right = initialRight; up = D3DXVECTOR3(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtLH(&view, &position, &(position + forward), &up); D3DXMatrixInverse(&invView, NULL, &(view)); viewProjection = view * projection; Reset(); } void Camera::Reset(){ this->fov = Globals::HALF_PI * ((float)Globals::ClientHeight/ (float)Globals::ClientWidth); nearHeight = near_plane * tan(fov*0.5f); nearWidth = near_plane * tan(fov*0.5f) * ((float)Globals::ClientWidth/ (float)Globals::ClientHeight); D3DXMatrixPerspectiveFovLH(&projection, fov, (float)Globals::ClientWidth/ (float)Globals::ClientHeight, near_plane, far_plane); viewPortWidth = projection(0, 0); viewPortHeight = projection(1, 1); } void Camera::Update(float dt){ bool changed = false; if(!Helpers::Globals::MOVE_WRECKINGBALL){ if(Helpers::KeyboardHandler::IsKeyDown(DIK_W)){ changed = true; position += forward * dt * deltaMovement; } else if(Helpers::KeyboardHandler::IsKeyDown(DIK_S)){ changed = true; position -= forward * dt * deltaMovement; } if(Helpers::KeyboardHandler::IsKeyDown(DIK_A)){ changed = true; position -= right * dt * deltaMovement; } else if(Helpers::KeyboardHandler::IsKeyDown(DIK_D)){ changed = true; position += right * dt * deltaMovement; } } // look around, the MouseState object comes from the MouseHandler if(MouseHandler::MouseState.lX != 0 || MouseHandler::MouseState.lY != 0){ changed = true; yaw += dt*deltaRotation*((float)MouseHandler::MouseState.lX) * ((float)Helpers::Globals::ClientHeight / (float)Helpers::Globals::ClientWidth); pitch += dt*deltaRotation*((float)MouseHandler::MouseState.lY) * ((float)Helpers::Globals::ClientHeight / (float)Helpers::Globals::ClientWidth ); if(yaw < 0.0f) yaw += Globals::TWO_PI; else if(yaw > Globals::TWO_PI) yaw -= Globals::TWO_PI; if(pitch < -Globals::HALF_PI+0.1f) pitch = -Globals::HALF_PI+0.1f; else if(pitch > Globals::HALF_PI-0.1f) pitch = Globals::HALF_PI-0.1f; } if(changed){ D3DXMATRIX rotation; D3DXMatrixRotationYawPitchRoll(&rotation, yaw, pitch, 0.0f); D3DXVec3TransformCoord(&forward, &initialForward, &rotation); D3DXVec3TransformCoord(&right, &initialRight, &rotation); D3DXMatrixLookAtLH(&view, &position, &(position + forward), &up); D3DXMatrixInverse(&invView, NULL, &(view)); viewProjection = view * projection; } }
[ [ [ 1, 109 ] ] ]
604a4ac78414719a8179bcc33f6180684409782a
c4001da8f012dfbc46fef0d9c11f8412f4ad9c6f
/allegro/examples/ex_ogre3d.cpp
50ac058eb78594264b5ae35570ef156b50222aa2
[ "Zlib", "BSD-3-Clause" ]
permissive
sesc4mt/mvcdecoder
4602fdfe42ab39706cfa3c749282782ca9da73c9
742a5c0d9cad43f0b01aa6e9169d96a286458e72
refs/heads/master
2021-01-01T17:56:47.666505
2010-11-02T12:36:52
2010-11-02T12:36:52
40,896,775
1
0
null
null
null
null
UTF-8
C++
false
false
12,063
cpp
/* * Example program for the Allegro library, by Peter Wang. * * This is a test program to see if Allegro can be used alongside the OGRE * graphics library. It currently only works on Linux/GLX. To run, you * will need to have OGRE plugins.cfg and resources.cfg files in the * current directory. * * Inputs: W A S D, mouse * * This code is based on the samples in the OGRE distribution. */ #include <Ogre.h> #include <allegro5/allegro.h> #include <allegro5/allegro_opengl.h> /* * Ogre 1.7 (and, optionally, earlier versions) uses the FreeImage library to * handle image loading. FreeImage bundles its own copies of common libraries * like libjpeg and libpng, which can conflict with the system copies of those * libraries that allegro_image uses. That means we can't use allegro_image * safely, nor any of the addons which depend on it. * * One solution would be to write a codec for Ogre that avoids FreeImage, or * write allegro_image handlers using FreeImage. The latter would probably be * easier and useful for other reasons. */ using namespace Ogre; const int WIDTH = 640; const int HEIGHT = 480; const float MOVE_SPEED = 1500.0; class Application { protected: Root *mRoot; RenderWindow *mWindow; SceneManager *mSceneMgr; Camera *mCamera; public: void setup() { createRoot(); defineResources(); setupRenderSystem(); createRenderWindow(); initializeResourceGroups(); chooseSceneManager(); createCamera(); createViewports(); createScene(); } ~Application() { delete mRoot; } private: void createRoot() { mRoot = new Root(); } void defineResources() { String secName, typeName, archName; ConfigFile cf; cf.load("resources.cfg"); ConfigFile::SectionIterator seci = cf.getSectionIterator(); while (seci.hasMoreElements()) { secName = seci.peekNextKey(); ConfigFile::SettingsMultiMap *settings = seci.getNext(); ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); } } } void setupRenderSystem() { if (!mRoot->restoreConfig() && !mRoot->showConfigDialog()) { throw Exception(52, "User canceled the config dialog!", "Application::setupRenderSystem()"); } } void createRenderWindow() { // Initialise Ogre without creating a window. mRoot->initialise(false); Ogre::NameValuePairList misc; // Tell Ogre to use the current GL context. This works on Linux/GLX but // you *will* need something different on Windows or Mac. misc["currentGLContext"] = String("True"); int w = al_get_display_width(); int h = al_get_display_height(); mWindow = mRoot->createRenderWindow("MainRenderWindow", w, h, false, &misc); mWindow->setVisible(true); } void initializeResourceGroups() { TextureManager::getSingleton().setDefaultNumMipmaps(5); ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } virtual void chooseSceneManager() { mSceneMgr = mRoot->createSceneManager(ST_GENERIC, "Default SceneManager"); } virtual void createCamera() { mCamera = mSceneMgr->createCamera("PlayerCam"); mCamera->setPosition(Vector3(-300, 300, -300)); mCamera->lookAt(Vector3(0, 0, 0)); mCamera->setNearClipDistance(5); } virtual void createViewports() { // Create one viewport, entire window. Viewport *vp = mWindow->addViewport(mCamera); vp->setBackgroundColour(ColourValue(0, 0.25, 0.5)); // Alter the camera aspect ratio to match the viewport. mCamera->setAspectRatio( Real(vp->getActualWidth()) / Real(vp->getActualHeight())); } virtual void createScene() = 0; public: void render() { const bool swap_buffers = false; mWindow->update(swap_buffers); mRoot->renderOneFrame(); al_flip_display(); } }; class Example : public Application { private: ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_TIMER *timer; double startTime; double lastRenderTime; double lastMoveTime; bool lmb; bool rmb; bool forward; bool back; bool left; bool right; float current_speed; Vector3 last_translate; public: Example(); ~Example(); void setup(); void mainLoop(); private: void createScene(); void moveCamera(double timestamp, Radian rot_x, Radian rot_y, Vector3 & translate); void animate(double now); void nextFrame(); }; Example::Example() : queue(NULL), timer(NULL), startTime(0.0), lastRenderTime(0.0), lastMoveTime(0.0), lmb(false), rmb(false), forward(false), back(false), left(false), right(false), current_speed(0), last_translate(Vector3::ZERO) { } Example::~Example() { al_uninstall_timer(timer); al_destroy_event_queue(queue); } void Example::createScene() { // Enable shadows. mSceneMgr->setAmbientLight(ColourValue(0.5, 0.25, 0.0)); //mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); // slower mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); // faster // Create the character. Entity *ent1 = mSceneMgr->createEntity("Ninja", "ninja.mesh"); ent1->setCastShadows(true); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent1); AnimationState *anim1 = ent1->getAnimationState("Walk"); anim1->setLoop(true); anim1->setEnabled(true); // Create the ground. Plane plane(Vector3::UNIT_Y, 0); MeshManager::getSingleton().createPlane("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, 1500, 1500, 20, 20, true, 1, 5, 5, Vector3::UNIT_Z); Entity *ent2 = mSceneMgr->createEntity("GroundEntity", "ground"); ent2->setMaterialName("Examples/Rockwall"); ent2->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent2); // Create a light. Light *light = mSceneMgr->createLight("Light1"); light->setType(Light::LT_POINT); light->setPosition(Vector3(0, 150, 250)); light->setDiffuseColour(1.0, 1.0, 1.0); light->setSpecularColour(1.0, 0.0, 0.0); } void Example::setup() { Application::setup(); const double BPS = 60.0; timer = al_install_timer(1.0 / BPS); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_mouse_event_source()); al_register_event_source(queue, al_get_timer_event_source(timer)); al_register_event_source(queue, al_get_display_event_source(al_get_current_display())); } void Example::mainLoop() { bool redraw = true; startTime = lastMoveTime = al_current_time(); al_start_timer(timer); for (;;) { ALLEGRO_EVENT event; if (al_event_queue_is_empty(queue) && redraw) { nextFrame(); redraw = false; } al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_KEY_DOWN && event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } Radian rot_x(0); Radian rot_y(0); Vector3 translate(Vector3::ZERO); switch (event.type) { case ALLEGRO_EVENT_TIMER: redraw = true; break; case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: if (event.mouse.button == 1) lmb = true; if (event.mouse.button == 2) rmb = true; break; case ALLEGRO_EVENT_MOUSE_BUTTON_UP: if (event.mouse.button == 1) lmb = false; if (event.mouse.button == 2) rmb = false; if (!lmb && !rmb) al_show_mouse_cursor(); break; case ALLEGRO_EVENT_MOUSE_AXES: if (lmb) { rot_x = Degree(-event.mouse.dx * 0.13); rot_y = Degree(-event.mouse.dy * 0.13); } if (rmb) { translate.x = event.mouse.dx * 0.5; translate.y = event.mouse.dy * -0.5; } if (lmb || rmb) { al_hide_mouse_cursor(); al_set_mouse_xy(al_get_display_width()/2, al_get_display_height()/2); } break; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_UP: { const bool is_down = (event.type == ALLEGRO_EVENT_KEY_DOWN); if (event.keyboard.keycode == ALLEGRO_KEY_W) forward = is_down; if (event.keyboard.keycode == ALLEGRO_KEY_S) back = is_down; if (event.keyboard.keycode == ALLEGRO_KEY_A) left = is_down; if (event.keyboard.keycode == ALLEGRO_KEY_D) right = is_down; break; } case ALLEGRO_EVENT_DISPLAY_RESIZE: { al_acknowledge_resize(event.display.source); int w = al_get_display_width(); int h = al_get_display_height(); mWindow->resize(w, h); mCamera->setAspectRatio(Real(w) / Real(h)); redraw = true; break; } } moveCamera(event.any.timestamp, rot_x, rot_y, translate); } } void Example::moveCamera(double timestamp, Radian rot_x, Radian rot_y, Vector3 & translate) { const double time_since_move = timestamp - lastMoveTime; const float move_scale = MOVE_SPEED * time_since_move; if (forward) { translate.z = -move_scale; } if (back) { translate.z = move_scale; } if (left) { translate.x = -move_scale; } if (right) { translate.x = move_scale; } if (translate == Vector3::ZERO) { // Continue previous motion but dampen. translate = last_translate; current_speed -= time_since_move * 0.3; } else { // Ramp up. current_speed += time_since_move; } if (current_speed > 1.0) current_speed = 1.0; if (current_speed < 0.0) current_speed = 0.0; translate *= current_speed; mCamera->yaw(rot_x); mCamera->pitch(rot_y); mCamera->moveRelative(translate); last_translate = translate; lastMoveTime = timestamp; } void Example::animate(double now) { const double dt0 = now - startTime; const double dt = now - lastRenderTime; // Animate the character. Entity *ent = mSceneMgr->getEntity("Ninja"); AnimationState *anim = ent->getAnimationState("Walk"); anim->addTime(dt); // Move the light around. Light *light = mSceneMgr->getLight("Light1"); light->setPosition(Vector3(300 * cos(dt0), 300, 300 * sin(dt0))); } void Example::nextFrame() { const double now = al_current_time(); animate(now); render(); lastRenderTime = now; } int main(int argc, char *argv[]) { (void)argc; (void)argv; if (!al_init()) { return 1; } al_install_keyboard(); al_install_mouse(); al_set_new_display_flags(ALLEGRO_OPENGL | ALLEGRO_RESIZABLE); if (!al_create_display(WIDTH, HEIGHT)) { return 1; } al_set_window_title("My window"); { Example app; app.setup(); app.mainLoop(); } al_uninstall_system(); return 0; } /* vim: set sts=3 sw=3 et: */
[ "edwardtoday@34199c9c-95aa-5eba-f35a-9ba8a8a04cd7" ]
[ [ [ 1, 449 ] ] ]
1ca40b138739a6cc4a910dacaad337ff8f1ab741
515e917815568d213e75bfcbd3fb9f0e08cf2677
/datamanager/dataserializer.cpp
47f0fcf6f90bcfd5bf4e670d0784daf2881b64a1
[ "BSD-2-Clause" ]
permissive
dfk789/CodenameInfinite
bd183aec6b9e60e20dda6764d99f4e8d8a945add
aeb88b954b65f6beca3fb221fe49459b75e7c15f
refs/heads/master
2020-05-30T15:46:20.450963
2011-10-15T00:21:38
2011-10-15T00:21:38
5,652,791
2
0
null
null
null
null
UTF-8
C++
false
false
1,899
cpp
#include "dataserializer.h" #include <strutils.h> #include "data.h" void CDataSerializer::Read(std::basic_istream<tchar>& sStream, CData* pData) { if (!sStream) return; if (!pData) return; tchar szLine[1024]; tstring sLine; CData* pCurrentData = pData; CData* pLastData = NULL; while (sStream.getline(szLine, 1024)) { sLine = tstring(szLine); size_t iComment = sLine.find(_T("//")); if (iComment != eastl::string::npos) sLine = sLine.substr(0, iComment); sLine = trim(sLine); if (sLine.length() == 0) continue; if (sLine[0] == '{') { pCurrentData = pLastData; continue; } if (sLine[0] == '}') { pCurrentData = pCurrentData->GetParent(); continue; } eastl::vector<tstring> asTokens; tstrtok(sLine, asTokens, _T(":")); if (asTokens.size() == 1) pLastData = pCurrentData->AddChild(trim(sLine)); else if (asTokens.size() >= 2) pLastData = pCurrentData->AddChild(trim(asTokens[0]), trim(sLine.substr(sLine.find(_T(':'))+1))); } } static void SaveData(std::basic_ostream<tchar>& sStream, CData* pData, size_t iLevel) { tstring sTabs; for (size_t i = 0; i < iLevel; i++) sTabs += _T("\t"); for (size_t i = 0; i < pData->GetNumChildren(); i++) { CData* pChild = pData->GetChild(i); if (pChild->GetValueTString().length()) sStream << (sTabs + pChild->GetKey() + _T(": ") + pChild->GetValueTString() + _T("\n")).c_str(); else sStream << (sTabs + pChild->GetKey() + _T("\n")).c_str(); if (pChild->GetNumChildren()) { sStream << (sTabs + _T("{\n")).c_str(); SaveData(sStream, pChild, iLevel+1); sStream << (sTabs + _T("}\n")).c_str(); } } } void CDataSerializer::Save(std::basic_ostream<tchar>& sStream, CData* pData) { if (!sStream) return; if (!pData) return; SaveData(sStream, pData, 0); }
[ [ [ 1, 6 ], [ 8, 14 ], [ 17, 22 ], [ 24, 24 ], [ 26, 45 ], [ 48, 50 ], [ 53, 54 ] ], [ [ 7, 7 ], [ 15, 16 ], [ 23, 23 ], [ 25, 25 ], [ 46, 47 ], [ 51, 52 ], [ 55, 89 ] ] ]
310c90359fa53499d6bb791a91438331c83ac8f3
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/test/TestFilterSetting/stdafx.cpp
3cb81cfe322a9948f241337ab462c47c0f25b918
[]
no_license
weimingtom/httpcontentparser
4d5ed678f2b38812e05328b01bc6b0c161690991
54554f163b16a7c56e8350a148b1bd29461300a0
refs/heads/master
2021-01-09T21:58:30.326476
2009-09-23T08:05:31
2009-09-23T08:05:31
48,733,304
3
0
null
null
null
null
GB18030
C++
false
false
276
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // TestFilterSetting.pch 将成为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 //引用任何所需的附加头文件,而不是在此文件中引用
[ "ynkhpp@1a8edc88-4151-0410-b40c-1915dda2b29b" ]
[ [ [ 1, 8 ] ] ]
a782b907ef11b87ff9acb0c244691118f9b31bbc
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_media_util/CLinuxFileLog.cpp
3676d2f9ad80cffdc6d87d3d3861c5c6dcde1120
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
885
cpp
#ifdef _LINUX #include "compat.h" #include <sstream> #include "CLinuxFileLog.h" #include "global_error.h" CLinuxFileLog g_FileLog(DBG_FILENAME); ULONG CLinuxFileLog::SetLog(LPCSTR _szString) { ULONG ret; m_Semaph.Wait(); if ( (ret = Open() ) == RET_OK) { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); char * pszDate = asctime (timeinfo); char * pszTemp = new char[strlen(pszDate)-1]; if (pszTemp) { strncpy(pszTemp, pszDate, strlen(pszDate) -1); pszTemp[strlen(pszDate) -1] = '\0'; if (fprintf (m_pFile, "[%s] %s\n", pszTemp, _szString) < 0) ret = RET_ERROR; delete pszTemp; } else ret = RET_LOW_MEMORY; } Close(); m_Semaph.Signal(); return ret; } #endif
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 49 ] ] ]
364733a1f12c8e899b8eca3c5833ea7a88c63cec
daef491056b6a9e227eef3e3b820e7ee7b0af6b6
/Tags/0.2.6/code/toolkit/graphics/gl/gl_indexbuffer.cpp
c989a7cc6c34a29f0431f99e37cde0482b80c325
[ "BSD-3-Clause" ]
permissive
BackupTheBerlios/gut-svn
de9952b8b3e62cedbcfeb7ccba0b4d267771dd95
0981d3b37ccfc1ff36cd79000f6c6be481ea4546
refs/heads/master
2021-03-12T22:40:32.685049
2006-07-07T02:18:38
2006-07-07T02:18:38
40,725,529
0
0
null
null
null
null
UTF-8
C++
false
false
1,752
cpp
/********************************************************************** * GameGut - graphics/gl/gl_indexbuffer.cpp * Copyright (c) 1999-2005 Jason Perkins. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the BSD-style license that is * included with this library in the file LICENSE.txt. * * 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 * files LICENSE.txt for more details. **********************************************************************/ #include "core/core.h" #include "gl_graphics.h" /* Keep track of all open buffers so I can close them at exit */ static utxArray<utIndexBuffer> my_buffers; utIndexBuffer utCreateIndexBuffer(int size, utBufferFlags flags) { utIndexBuffer buffer = utNEW utxIndexBuffer(); buffer->data = (int*)utALLOC(sizeof(int) * size); buffer->size = size; /* Add the buffer to the master list */ buffer->reference(); my_buffers.push_back(buffer); return buffer; } utxIndexBuffer::~utxIndexBuffer() { utFREE(data); } int utReleaseIndexBuffer(utIndexBuffer buffer) { if (my_buffers.remove(buffer)) buffer->release(); return true; } void utxReleaseAllIndexBuffers() { for (int i = 0; i < my_buffers.size(); ++i) my_buffers[i]->release(); my_buffers.clear(); } int utCopyIndexData(utIndexBuffer buffer, const int* data, int size) { if (size > buffer->size) { utLog("utCopyIndices: data size is greater than buffer size\n"); return false; } memcpy(buffer->data, data, size * sizeof(int)); return true; }
[ "starkos@5eb1f239-c603-0410-9f17-9cbfe04d0a06" ]
[ [ [ 1, 68 ] ] ]
d076c34fde85c83e5843e45658ebe92d68be369c
3eae1d8c99d08bca129aceb7c2269bd70e106ff0
/trunk/Codes/DeviceCode/Targets/Native/MC9328/DeviceCode/MC9328MXL_i2c/MC9328MXL_i2c_functions.cpp
808886898448901435c0767c36a08ec8b66e4e0f
[]
no_license
yuaom/miniclr
9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082
4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1
refs/heads/master
2023-06-07T09:10:33.703929
2010-12-27T14:41:18
2010-12-27T14:41:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <cores\arm\include\cpu.h> BOOL I2C_Internal_Initialize() { NATIVE_PROFILE_HAL_PROCESSOR_I2C(); return MC9328MXL_I2C_Driver::Initialize(); } BOOL I2C_Internal_Uninitialize() { NATIVE_PROFILE_HAL_PROCESSOR_I2C(); return MC9328MXL_I2C_Driver::Uninitialize(); } void I2C_Internal_XActionStart( I2C_HAL_XACTION* xAction, bool repeatedStart ) { NATIVE_PROFILE_HAL_PROCESSOR_I2C(); MC9328MXL_I2C_Driver::MasterXAction_Start( xAction, repeatedStart ); } void I2C_Internal_XActionStop() { NATIVE_PROFILE_HAL_PROCESSOR_I2C(); MC9328MXL_I2C_Driver::MasterXAction_Stop(); } UINT8 I2C_Internal_GetClockRate( UINT32 rateKhz ) { NATIVE_PROFILE_HAL_PROCESSOR_I2C(); return MC9328MXL_I2C_Driver::GetClockRate( rateKhz ); } void I2C_Internal_GetPins(GPIO_PIN& scl, GPIO_PIN& sda) { MC9328MXL_I2C_Driver::GetPins( scl, sda); return; }
[ [ [ 1, 43 ] ] ]
35327b2b532b3205c2ef36faa94862829c79215f
4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4
/src/nvimage/openexr/src/IlmThread/IlmThreadSemaphore.cpp
568d97711ed0d6ad520ef9560d5adb2dcc9245d8
[]
no_license
saggita/nvidia-mesh-tools
9df27d41b65b9742a9d45dc67af5f6835709f0c2
a9b7fdd808e6719be88520e14bc60d58ea57e0bd
refs/heads/master
2020-12-24T21:37:11.053752
2010-09-03T01:39:02
2010-09-03T01:39:02
56,893,300
0
1
null
null
null
null
UTF-8
C++
false
false
2,502
cpp
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2005, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class Semaphore -- dummy implementation for // for platforms that do not support threading // //----------------------------------------------------------------------------- #include "IlmBaseConfig.h" #if !defined (_WIN32) && !(_WIN64) && !(HAVE_PTHREAD) #include "IlmThreadSemaphore.h" namespace IlmThread { Semaphore::Semaphore (unsigned int value) {} Semaphore::~Semaphore () {} void Semaphore::wait () {} bool Semaphore::tryWait () {return true;} void Semaphore::post () {} int Semaphore::value () const {return 0;} } // namespace IlmThread #endif
[ "castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c" ]
[ [ [ 1, 60 ] ] ]
c6fe5492bfcb45bc18833215ec2d0eae90561580
dd3f4d317a0e363a866fa06e8a8fd4bc29d86805
/vaultmpdll/vaultmp.cpp
5879347c1fa051acbc18e5b08f1c8974bc575e1e
[]
no_license
Xaretius/vaultmp
23c0b3a5a5e623d5ac7ab70eab11a0142ff9edad
28f83a7068441a4120b086a1355462d2f26eaa3a
refs/heads/master
2021-01-10T14:40:34.980883
2011-05-18T13:09:30
2011-05-18T13:09:30
50,698,651
0
0
null
null
null
null
UTF-8
C++
false
false
25,697
cpp
#include <windows.h> #include <stdio.h> #include <string> #include "vaultmp.h" using namespace std; using namespace pipe; HANDLE hProc; PipeServer pipeServer; PipeClient pipeClient; unsigned Fallout3opTrigger = 0x00; // 0x00 = trigger disabled. 0x0A = trigger enabled. unsigned Fallout3refid = 0x00; // RefID storage char Fallout3output[MAX_OUTPUT_LENGTH]; // Command output storage char Fallout3input[MAX_INPUT_LENGTH]; // Command input storage bool Fallout3mutex = false; // Command queue mutex typedef HANDLE (*fDLLjump)(void); typedef void (*fDLLend)(void); typedef void (*fMessage)(string); void seDebugPrivilege() { TOKEN_PRIVILEGES priv; HANDLE hThis, hToken; LUID luid; hThis = GetCurrentProcess(); OpenProcessToken(hThis, TOKEN_ADJUST_PRIVILEGES, &hToken); LookupPrivilegeValue(0, "seDebugPrivilege", &luid); priv.PrivilegeCount = 1; priv.Privileges[0].Luid = luid; priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, false, &priv, 0, 0, 0); CloseHandle(hToken); CloseHandle(hThis); } unsigned offset(unsigned src, unsigned dest, unsigned jmpbytes) { unsigned way; src += jmpbytes; way = dest - src; return way; } void Fallout3toggleTrigger(bool toggle) { Fallout3opTrigger = toggle ? 0x0A : 0x00; } void Fallout3sendOp(string op) { while (Fallout3mutex) Sleep(2); Fallout3mutex = true; strcpy(Fallout3input, op.c_str()); } void Fallout3commandNotify() { char format[MAX_OUTPUT_LENGTH + 3]; strcat(format, "op:"); strcat(format, Fallout3output); string output(format); pipeClient.Send(&output); } void Fallout3refidNotify() { char format[16]; char refid[16]; sprintf(refid, "%x", Fallout3refid); strcat(format, "re:"); strcat(format, refid); string output(format); pipeClient.Send(&output); } DWORD WINAPI Fallout3pipe(LPVOID data) { HINSTANCE vaultgui = (HINSTANCE) data; fDLLend GUI_end; fMessage GUI_msg; if (vaultgui != NULL) { GUI_end = (fDLLend) GetProcAddress(vaultgui, "DLLend"); GUI_msg = (fMessage) GetProcAddress(vaultgui, "Message"); } pipeClient.SetPipeAttributes("Fallout3client", 4096); while (!pipeClient.ConnectToServer()); pipeServer.SetPipeAttributes("Fallout3server", 4096); pipeServer.CreateServer(); pipeServer.ConnectToServer(); string send; string recv; string low; string high; send = "up:"; pipeClient.Send(&send); Fallout3toggleTrigger(true); do { recv.clear(); low.clear(); high.clear(); recv = pipeServer.Recv(); low = recv.substr(0, 3); high = recv.substr(3); if (low.compare("op:") == 0) Fallout3sendOp(high); else if (low.compare("ce:") == 0) { if (vaultgui != NULL) GUI_msg(high); } } while (low.compare("ca:") != 0); if (vaultgui != NULL) GUI_end(); return ((DWORD) data); } extern "C" void __declspec(dllexport) DLLjump() { seDebugPrivilege(); hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); DWORD rw = 0; unsigned bytes = 0; unsigned tmp = 0; char bytestream[16]; /* Patching key event and console */ /* 0062B663 83FB 0A CMP EBX,A * 0062B666 90 NOP * * 0062B66B 0F85 BE150000 JNZ Fallout3.0062CC2F * 00627A84 EB 6E JMP SHORT Fallout3.00627AF4 * 0062B67E EB 1B JMP SHORT Fallout3.0062B69B * * 00627AFF E9 990D0000 JMP Fallout3.0062889D * 00627B04 90 NOP * 0062B69B 90 NOP * 0062B69C 90 NOP * 0062B69D 90 NOP * 0062B69E 90 NOP * 0062B69F 90 NOP * 0062B6A0 90 NOP * 0062B6A1 90 NOP * * 0062B744 83FB 0A CMP EBX,A * 0062B747 90 NOP * 0062B748 90 NOP * 0062B749 90 NOP * * 006195E8 90 NOP * 006195E9 90 NOP * 006195EA 90 NOP * 006195EB 90 NOP * 006195EC 90 NOP * 006195ED 90 NOP * 006195EE 90 NOP * 006195EF 90 NOP * 006195F0 90 NOP * 006195F1 90 NOP * 006195F2 90 NOP * 006195F3 90 NOP * 006195F4 90 NOP * 006195F5 90 NOP * 006195F6 90 NOP */ bytestream[0] = 0x83; bytestream[1] = 0xFB; bytestream[2] = 0x0A; bytestream[3] = 0x90; for (int i = 0; i < 4; i++) WriteProcessMemory(hProc, (LPVOID) (0x0062B663 + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0x0F; bytestream[1] = 0x85; bytestream[2] = 0xBE; bytestream[3] = 0x15; bytestream[4] = 0x00; bytestream[5] = 0x00; for (int i = 0; i < 6; i++) WriteProcessMemory(hProc, (LPVOID) (0x0062B66B + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0xEB; bytestream[1] = 0x6E; for (int i = 0; i < 2; i++) WriteProcessMemory(hProc, (LPVOID) (0x00627A84 + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0xEB; bytestream[1] = 0x1B; for (int i = 0; i < 2; i++) WriteProcessMemory(hProc, (LPVOID) (0x0062B67E + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0xE9; bytestream[1] = 0x99; bytestream[2] = 0x0D; bytestream[3] = 0x00; bytestream[4] = 0x00; bytestream[5] = 0x90; for (int i = 0; i < 6; i++) WriteProcessMemory(hProc, (LPVOID) (0x00627AFF + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0x90; bytestream[1] = 0x90; bytestream[2] = 0x90; bytestream[3] = 0x90; bytestream[4] = 0x90; bytestream[5] = 0x90; bytestream[6] = 0x90; for (int i = 0; i < 7; i++) WriteProcessMemory(hProc, (LPVOID) (0x0062B69B + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0x83; bytestream[1] = 0xFB; bytestream[2] = 0x0A; bytestream[3] = 0x90; bytestream[4] = 0x90; bytestream[5] = 0x90; for (int i = 0; i < 6; i++) WriteProcessMemory(hProc, (LPVOID) (0x0062B744 + i), &bytestream[i], sizeof(bytestream[i]), &rw); bytestream[0] = 0x90; bytestream[1] = 0x90; bytestream[2] = 0x90; bytestream[3] = 0x90; bytestream[4] = 0x90; bytestream[5] = 0x90; bytestream[6] = 0x90; bytestream[7] = 0x90; bytestream[8] = 0x90; bytestream[9] = 0x90; bytestream[10] = 0x90; bytestream[11] = 0x90; bytestream[12] = 0x90; bytestream[13] = 0x90; bytestream[14] = 0x90; for (int i = 0; i < 15; i++) WriteProcessMemory(hProc, (LPVOID) (0x006195E8 + i), &bytestream[i], sizeof(bytestream[i]), &rw); /* Writing Fallout3 command trigger TOTAL BYTES TO RESERVE: 20 */ /* XXXXXXXX 8B1D XXXXXXXX MOV EBX,[XXXXXXXX] * XXXXXXXX 83FB 0A CMP EBX,A * XXXXXXXX -0F84 XXXXXXXX JE Fallout3.006288CA * XXXXXXXX -E9 XXXXXXXX JMP Fallout3.0062897A * * 006288C4 -E9 XXXXXXXX JMP XXXXXXXX * 006288C9 90 NOP */ bytes = 0; rw = 0; LPVOID Fallout3triggerASM = VirtualAllocEx(hProc, 0, 20, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); tmp = (unsigned) &Fallout3opTrigger; bytestream[0] = 0x8B; bytestream[1] = 0x1D; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; bytestream[0] = 0x83; bytestream[1] = 0xFB; bytestream[2] = 0x0A; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = offset((((unsigned) Fallout3triggerASM) + bytes), (unsigned) 0x006288CA, 6); bytestream[0] = 0x0F; bytestream[1] = 0x84; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((((unsigned) Fallout3triggerASM) + bytes), (unsigned) 0x0062897A, 5); bytestream[0] = 0xE9; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3triggerASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((unsigned) 0x006288C4, (unsigned) Fallout3triggerASM, 5); bytestream[0] = 0xE9; bytes = 0; WriteProcessMemory(hProc, (LPVOID) (0x006288C4 + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (0x006288C4 + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; bytestream[0] = 0x90; WriteProcessMemory(hProc, (LPVOID) (0x006288C4 + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; /* Writing Fallout3 command INPUT detour TOTAL BYTES TO RESERVE: 61 */ /* XXXXXXXX 50 PUSH EAX * XXXXXXXX 51 PUSH ECX * XXXXXXXX 56 PUSH ESI * XXXXXXXX 8A06 MOV AL,BYTE PTR DS:[ESI] * XXXXXXXX 3C 00 CMP AL,0 * XXXXXXXX 74 0D JE SHORT XXXXXXXX * XXXXXXXX 5E POP ESI * XXXXXXXX 59 POP ECX * XXXXXXXX 58 POP EAX * XXXXXXXX BA FFFEFE7E MOV EDX,7EFEFEFF * XXXXXXXX -E9 XXXXXXXX JMP Fallout3.00C075B4 * XXXXXXXX B9 XXXXXXXX MOV ECX,XXXXXXXX * XXXXXXXX 8A01 MOV AL,BYTE PTR DS:[ECX] * XXXXXXXX 3C 00 CMP AL,0 * XXXXXXXX ^74 E8 JE SHORT XXXXXXXX * XXXXXXXX 8806 MOV BYTE PTR DS:[ESI],AL * XXXXXXXX C601 00 MOV BYTE PTR DS:[ECX],0 * XXXXXXXX 83C1 01 ADD ECX,1 * XXXXXXXX 83C6 01 ADD ESI,1 * XXXXXXXX 8A01 MOV AL,BYTE PTR DS:[ECX] * XXXXXXXX 3C 00 CMP AL,0 * XXXXXXXX 74 02 JE SHORT XXXXXXXX * XXXXXXXX ^EB ED JMP SHORT XXXXXXXX * XXXXXXXX C605 XXXXXXXX 00 MOV BYTE PTR DS:[XXXXXXXX],0 * XXXXXXXX ^EB CC JMP SHORT XXXXXXXX * * 00C075AF -E9 XXXXXXXX JMP XXXXXXXX */ bytes = 0; rw = 0; LPVOID Fallout3inputASM = VirtualAllocEx(hProc, 0, 61, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); bytestream[0] = 0x50; bytestream[1] = 0x51; bytestream[2] = 0x56; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x8A; bytestream[1] = 0x06; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x3C; bytestream[1] = 0x00; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x74; bytestream[1] = 0x0D; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x5E; bytestream[1] = 0x59; bytestream[2] = 0x58; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0xBA; bytestream[1] = 0xFF; bytestream[2] = 0xFE; bytestream[3] = 0xFE; bytestream[4] = 0x7E; for (int i = 0; i < 5; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = offset((((unsigned) Fallout3inputASM) + bytes), (unsigned) 0x00C075B4, 5); bytestream[0] = 0xE9; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = (unsigned) &Fallout3input; bytestream[0] = 0xB9; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; bytestream[0] = 0x8A; bytestream[1] = 0x01; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x3C; bytestream[1] = 0x00; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x74; bytestream[1] = 0xE8; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x88; bytestream[1] = 0x06; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0xC6; bytestream[1] = 0x01; bytestream[2] = 0x00; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x83; bytestream[1] = 0xC1; bytestream[2] = 0x01; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x83; bytestream[1] = 0xC6; bytestream[2] = 0x01; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x8A; bytestream[1] = 0x01; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x3C; bytestream[1] = 0x00; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x74; bytestream[1] = 0x02; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0xEB; bytestream[1] = 0xED; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = (unsigned) &Fallout3mutex; bytestream[0] = 0xC6; bytestream[1] = 0x05; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; bytestream[0] = 0x00; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; bytestream[0] = 0xEB; bytestream[1] = 0xCC; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3inputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = offset((unsigned) 0x00C075AF, ((unsigned) Fallout3inputASM), 5); bytestream[0] = 0xE9; bytes = 0; WriteProcessMemory(hProc, (LPVOID) ((unsigned) 0x00C075AF + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) ((unsigned) 0x00C075AF + bytes), &tmp, sizeof(tmp), &rw); /* Writing Fallout3 command OUTPUT detour TOTAL BYTES TO RESERVE: 46 */ /* XXXXXXXX 50 PUSH EAX * XXXXXXXX 51 PUSH ECX * XXXXXXXX 52 PUSH EDX * XXXXXXXX B9 XXXXXXXX MOV ECX,XXXXXXXX * XXXXXXXX 8A10 MOV DL,BYTE PTR DS:[EAX] * XXXXXXXX 80FA 00 CMP DL,0 * XXXXXXXX 74 0A JE SHORT XXXXXXXX * XXXXXXXX 8811 MOV BYTE PTR DS:[ECX],DL * XXXXXXXX 83C0 01 ADD EAX,1 * XXXXXXXX 83C1 01 ADD ECX,1 * XXXXXXXX ^EB EF JMP SHORT XXXXXXXX * XXXXXXXX C601 00 MOV BYTE PTR DS:[ECX],0 * XXXXXXXX E8 XXXXXXXX CALL vaultmp.XXXXXXXX * XXXXXXXX 5A POP EDX * XXXXXXXX 59 POP ECX * XXXXXXXX 58 POP EAX * XXXXXXXX E8 XXXXXXXX CALL Fallout3.0062A800 * XXXXXXXX -E9 XXXXXXXX JMP Fallout3.0062B230 * * 0062B22B -E9 XXXXXXXX JMP XXXXXXXX */ bytes = 0; rw = 0; LPVOID Fallout3outputASM = VirtualAllocEx(hProc, 0, 46, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); bytestream[0] = 0x50; bytestream[1] = 0x51; bytestream[2] = 0x52; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = (unsigned) &Fallout3output; bytestream[0] = 0xB9; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; bytestream[0] = 0x8A; bytestream[1] = 0x10; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x80; bytestream[1] = 0xFA; bytestream[2] = 0x00; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x74; bytestream[1] = 0x0A; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x88; bytestream[1] = 0x11; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x83; bytestream[1] = 0xC0; bytestream[2] = 0x01; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0x83; bytestream[1] = 0xC1; bytestream[2] = 0x01; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0xEB; bytestream[1] = 0xEF; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } bytestream[0] = 0xC6; bytestream[1] = 0x01; bytestream[2] = 0x00; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = offset((((unsigned) Fallout3outputASM) + bytes), ((unsigned) &Fallout3commandNotify), 5); bytestream[0] = 0xE8; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; bytestream[0] = 0x5A; bytestream[1] = 0x59; bytestream[2] = 0x58; for (int i = 0; i < 3; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } tmp = offset((((unsigned) Fallout3outputASM) + bytes), (unsigned) 0x0062A800, 5); bytestream[0] = 0xE8; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((((unsigned) Fallout3outputASM) + bytes), (unsigned) 0x0062B230, 5); bytestream[0] = 0xE9; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3outputASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((unsigned) 0x0062B22B, ((unsigned) Fallout3outputASM), 5); bytestream[0] = 0xE9; bytes = 0; WriteProcessMemory(hProc, (LPVOID) ((unsigned) 0x0062B22B + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) ((unsigned) 0x0062B22B + bytes), &tmp, sizeof(tmp), &rw); /* Writing Fallout3 RefID detour TOTAL BYTES TO RESERVE: 21 */ /* XXXXXXXX 8915 XXXXXXXX MOV DWORD PTR DS:[XXXXXXXX],EDX * XXXXXXXX E8 XXXXXXXX CALL vaultmp.XXXXXXXX * XXXXXXXX E8 XXXXXXXX CALL Fallout3.00516790 * XXXXXXXX -E9 XXXXXXXX JMP Fallout3.0053CACF * * 0053CAC6 -E9 XXXXXXXX JMP XXXXXXXX */ bytes = 0; rw = 0; LPVOID Fallout3refidASM = VirtualAllocEx(hProc, 0, 21, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); tmp = (unsigned) &Fallout3refid; bytestream[0] = 0x89; bytestream[1] = 0x15; for (int i = 0; i < 2; i++) { WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &bytestream[i], sizeof(bytestream[i]), &rw); bytes += rw; } WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((((unsigned) Fallout3refidASM) + bytes), (unsigned) &Fallout3refidNotify, 5); bytestream[0] = 0xE8; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((((unsigned) Fallout3refidASM) + bytes), (unsigned) 0x00516790, 5); bytestream[0] = 0xE8; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((((unsigned) Fallout3refidASM) + bytes), (unsigned) 0x0053CACF, 5); bytestream[0] = 0xE9; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) (((unsigned) Fallout3refidASM) + bytes), &tmp, sizeof(tmp), &rw); bytes += rw; tmp = offset((unsigned) 0x0053CAC6, ((unsigned) Fallout3refidASM), 5); bytestream[0] = 0xE9; bytes = 0; WriteProcessMemory(hProc, (LPVOID) ((unsigned) 0x0053CAC6 + bytes), &bytestream[0], sizeof(bytestream[0]), &rw); bytes += rw; WriteProcessMemory(hProc, (LPVOID) ((unsigned) 0x0053CAC6 + bytes), &tmp, sizeof(tmp), &rw); CloseHandle(hProc); /* Loading and initalizing vaultgui.dll */ HINSTANCE vaultgui = NULL; HANDLE guiThread; vaultgui = LoadLibrary("vaultgui.dll"); if (vaultgui != NULL) { fDLLjump init; init = (fDLLjump) GetProcAddress(vaultgui, "DLLjump"); guiThread = init(); } /* Initalizing vaultmp.exe <-> Fallout3.exe pipe */ HANDLE PipeThread; DWORD Fallout3pipeID; PipeThread = CreateThread(NULL, 0, Fallout3pipe, (LPVOID) vaultgui, 0, &Fallout3pipeID); if (guiThread != NULL) { HANDLE threads[2]; threads[0] = PipeThread; threads[1] = guiThread; WaitForMultipleObjects(2, threads, TRUE, INFINITE); } else WaitForSingleObject(PipeThread, INFINITE); if (vaultgui != NULL) FreeLibrary(vaultgui); if (guiThread != NULL) CloseHandle(guiThread); CloseHandle(PipeThread); } BOOL APIENTRY DllMain(HINSTANCE hInst, DWORD reason, LPVOID reserved) { return TRUE; }
[ [ [ 1, 514 ] ] ]
bc7369659db56131494a9d046aa032f50a60d9d8
f2b4a9d938244916aa4377d4d15e0e2a6f65a345
/Game/player.cpp
7b2b60ea8c19676fd8437e02ecffcbcaa43482a9
[ "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
14,502
cpp
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. #include "stdafx.h" #include "ai.h" #include "Dlg_NewWeek.h" /* * Player */ iPlayer::iPlayer(PLAYER_TYPE_MASK playerTypeMask, PLAYER_ID playerId, NATION_TYPE nation, const iSize& map_siz) : m_playerTypeMask(playerTypeMask) , m_PlayerId(playerId) , m_Nation(nation) , m_pCurHero(NULL) , m_pCurCastle(NULL) , m_bDirtPassMap(true) , m_pTavernVisitor(NULL) { m_Minerals.Reset(); m_FogMap.InitFogMap(map_siz.w,map_siz.h, gSettings.FogOfWar()); // //m_FogMap.OpenWholeMap(); // m_passMap.Init(gGame.Map().m_PassMap.GetWidth(),gGame.Map().m_PassMap.GetHeight()); } iPlayer::~iPlayer() { // Cleanup tavern visitor if (m_pTavernVisitor) { gGame.ItemMgr().HeroesMgr().Put(m_pTavernVisitor); m_pTavernVisitor = NULL; } } iHero* iPlayer::AddHero(iHero* pHero, bool bUpdateFog) { m_Heroes.Add(pHero); if (!m_pCurHero) m_pCurHero = pHero; if (bUpdateFog) UpdateFogMap(); gGame.OnAddHero(pHero); return pHero; } iHero* iPlayer::RemoveHero(iHero* pHero) { iHLIt nhit = m_Heroes.Remove(pHero); if (pHero == m_pCurHero) { if (m_Heroes.Count()) { SetCurHero(*m_Heroes.First()); } else { m_pCurHero = NULL; } } UpdateFogMap(); gGame.OnDelHero(pHero); return pHero; } uint32 iPlayer::CurHeroIdx() const { uint32 idx = 0; for (iHeroList::ConstIterator hit = m_Heroes.First(); hit != m_Heroes.End(); ++hit, ++idx) if ( *hit == m_pCurHero) break; return idx; } iOwnCnst* iPlayer::AddCnst(iOwnCnst* pCnst, bool bUpdateFog) { m_Cnsts.Add(pCnst); if (bUpdateFog) UpdateFogMap(); return pCnst; } iCastle* iPlayer::AddCastle(iCastle* pCastle, bool bUpdateFog) { m_Castles.Add(pCastle); if (!m_pCurCastle) m_pCurCastle = pCastle; if (bUpdateFog) UpdateFogMap(); gGame.OnAddCastle(pCastle); return pCastle; } iCastle* iPlayer::RemoveCastle(iCastle* pCastle) { iCtLIt ctit = m_Castles.Remove(pCastle); if (pCastle == m_pCurCastle) { if (m_Castles.Count()) m_pCurCastle = *m_Castles.First(); else m_pCurCastle = NULL; } UpdateFogMap(); gGame.OnDelCastle(pCastle); return pCastle; } uint32 iPlayer::CurCastleIdx() const { uint32 idx = 0; bool bFound = false; for (iCastleList::ConstIterator ctit = m_Castles.First(); ctit != m_Castles.End(); ++ctit, ++idx) if ( *ctit == m_pCurCastle) { bFound = true; break; } check(bFound); return idx; } sint32 iPlayer::AddMineral(MINERAL_TYPE mtype, sint32 count, bool bShowMessage) { return m_Minerals.quant[mtype] = iMAX<sint32>(m_Minerals.quant[mtype]+count,0); } void iPlayer::NewDay() { for (iHLIt hit = m_Heroes.First(); hit != m_Heroes.End(); ++hit) (*hit)->NewDay(); for (iCLIt cit = m_Cnsts.First(); cit != m_Cnsts.End(); ++cit) (*cit)->NewDay(); for (iCtLIt ctit = m_Castles.First(); ctit != m_Castles.End(); ++ctit) (*ctit)->NewDay(); // Process player's minerals income for (uint32 xx=0; xx<MINERAL_COUNT; ++xx) m_Minerals.quant[xx] += m_furtSkills.Value((FURTHER_SKILLS)(FSK_MIN_GOLD+xx)); UpdateFogMap(); } void iPlayer::NewWeek(const iWeekDesc& weekDesk) { // Update tavern visitor UpdateTavernVisitor(); // for (iHLIt hit = m_Heroes.First(); hit != m_Heroes.End(); ++hit) (*hit)->NewWeek(weekDesk); for (iCLIt cit = m_Cnsts.First(); cit != m_Cnsts.End(); ++cit) (*cit)->NewWeek(weekDesk); for (iCtLIt ctit = m_Castles.First(); ctit != m_Castles.End(); ++ctit) (*ctit)->NewWeek(weekDesk); } void iPlayer::OnSelect(bool bNewWeek, bool bAfterLoad) { check(PlayerType() == PT_HUMAN); // Show new week dialog if (bNewWeek) { iDlg_NewWeek dlg(&gApp.ViewMgr(), m_PlayerId, gGame.Map().WeekDesc()); dlg.DoModal(); } // show current day uint32 days = gGame.Map().m_CurDay-1; gGame.AddMsg(iFormat(_T("#F4B4%s: #F9F9%d #F4B4%s: #F9F9%d #F4B4%s: #F9F9%d"),gTextMgr[TRID_MONTH], days/28+1,gTextMgr[TRID_WEEK], (days%28)/7+1,gTextMgr[TRID_DAY],days%7+1)); // update fog map UpdateFogMap(); // Select current hero and castle if (!m_pCurHero && m_Heroes.Count()){ m_pCurHero = *m_Heroes.First(); } if (m_pCurHero) m_pCurHero->OnSelect(); else if (m_pCurCastle) m_pCurCastle->OnSelect(); // Process time events if (!bAfterLoad) gGame.Map().ProcessTimeEvents(this); } void iPlayer::OnCaptureCastle(iCastle* pNewCastle) { SetCurCastle(pNewCastle); } iHero* iPlayer::NextHero() { if (!m_pCurHero && !m_Heroes.Count()) return NULL; iHLIt hit(m_pCurHero); if (++hit == m_Heroes.End()) hit = m_Heroes.First(); m_pCurHero = *hit; m_bDirtPassMap = true; m_pCurHero->OnSelect(); return m_pCurHero; } iHero* iPlayer::PrevHero() { if (!m_pCurHero && !m_Heroes.Count()) return NULL; iHLIt hit(m_pCurHero); if (hit == m_Heroes.First()) hit = m_Heroes.Last(); else --hit; m_pCurHero = *hit; m_pCurHero->OnSelect(); m_bDirtPassMap = true; return m_pCurHero; } void iPlayer::PrvSetCurHero(uint16 hid) { check(hid != 0xFFFF); iHero* pHero = NULL; for (iHLIt hit = m_Heroes.First(); hit != m_Heroes.End(); ++hit) { if ( (*hit)->Proto()->m_protoId == hid ) { m_pCurHero = *hit; return; } } check(0); } void iPlayer::SetCurHero(iHero* pHero) { m_pCurHero = pHero; m_pCurHero->OnSelect(); m_bDirtPassMap = true; } iCastle* iPlayer::NextCastle() { if (!m_pCurCastle && !m_Castles.Count()) return NULL; iCtLIt ctit(m_pCurCastle); if (++ctit == m_Castles.End()) ctit = m_Castles.First(); m_pCurCastle = *ctit; m_pCurCastle->OnSelect(); return m_pCurCastle; } iCastle* iPlayer::PrevCastle() { if (!m_pCurCastle && !m_Castles.Count()) return NULL; iCtLIt ctit(m_pCurCastle); if (ctit == m_Castles.First()) ctit = m_Castles.Last(); else --ctit; m_pCurCastle = *ctit; m_pCurCastle->OnSelect(); return m_pCurCastle; } void iPlayer::SetCurCastle(iCastle* pCastle) { m_pCurCastle = pCastle; m_pCurCastle->OnSelect(); } void iPlayer::Process(fix32 t) { // Process heroes if (m_pCurHero) { m_pCurHero->Process(t); } } ////////////////////////////////////////////////////////////////////////// bool iPlayer::UpdateVisItems() { iVisItemList tmpItems; iGameWorld& map = gGame.Map(); // Map items for (iGameWorld::iMIt mit = map.m_MapItems.First(); mit != map.m_MapItems.End(); ++mit) { iPoint p((*mit)->Pos()); if ( !m_FogMap.IsHidden(p)) { tmpItems.AddItem(*mit); } } // Map guards for (iGameWorld::iGIt git = map.m_MapGuards.First(); git != map.m_MapGuards.End(); ++git) { iPoint p((*git)->Pos()); if (!m_FogMap.IsHidden(p)) { tmpItems.AddItem(*git); } } // Visitables for (iGameWorld::iVCIt vcit = map.m_VisCnsts.First(); vcit != map.m_VisCnsts.End(); ++vcit) { iPoint p((*vcit)->Pos()); if ( !m_FogMap.IsInvisible(p) ) { tmpItems.AddItem(*vcit); } } // Unaccuped constructions and castles { for (iGameWorld::iOCIt ocit = map.m_OwnCnsts.First(); ocit != map.m_OwnCnsts.End(); ++ocit) { iPoint p((*ocit)->Pos()); if ( !m_FogMap.IsInvisible(p) ) { tmpItems.AddItem(*ocit); } } for (iGameWorld::iCtIt ctit = map.m_Castles.First(); ctit != map.m_Castles.End(); ++ctit) { const iCastleT* pProto = (*ctit)->Proto(); for (uint32 cvid=0; cvid<pProto->CoversCount(); ++cvid) { iPoint p((*ctit)->Pos().x + pProto->CoverEntry(cvid).ox, (*ctit)->Pos().y + pProto->CoverEntry(cvid).oy); if (!m_FogMap.IsInvisible(p)){ tmpItems.AddItem(*ctit); break; } } } } // Owned constructions, castles and heroes for (iGameWorld::iPLIt plit = map.m_Players.First(); plit != map.m_Players.End(); ++plit) { for (iCLIt ocit = (*plit)->m_Cnsts.First(); ocit != (*plit)->m_Cnsts.End(); ++ocit) { iPoint p((*ocit)->Pos()); if ( !m_FogMap.IsInvisible(p) ) { tmpItems.AddItem(*ocit); } } for (iCtLIt ctit = (*plit)->m_Castles.First(); ctit !=(*plit)->m_Castles.End(); ++ctit) { const iCastleT* pProto = (*ctit)->Proto(); for (uint32 cvid=0; cvid<pProto->CoversCount(); ++cvid) { iPoint p((*ctit)->Pos().x + pProto->CoverEntry(cvid).ox, (*ctit)->Pos().y + pProto->CoverEntry(cvid).oy); if (!m_FogMap.IsInvisible(p)){ tmpItems.AddItem(*ctit); break; } } } //if ( (*plit)->PlayerId() == PlayerId() ) continue; for (iHLIt hit = (*plit)->m_Heroes.First(); hit != (*plit)->m_Heroes.End(); ++hit) { iPoint p((*hit)->Pos()); if ( !m_FogMap.IsHidden(p) ) { tmpItems.AddItem(*hit); } } } // Find new items m_newVisItems.Cleanup(); m_oldVisItems.Cleanup(); uint32 oCnt = m_visItems.Size(); uint32 tCnt = tmpItems.Size(); uint32 oPos=0; uint32 tPos=0; while (1) { if (tPos == tCnt) { while (oPos < oCnt) m_oldVisItems.AddItem(m_visItems[oPos++].value); break; } if (oPos == oCnt) { while (tPos < tCnt) { m_newVisItems.AddItem(tmpItems[tPos].value); ++tPos; } break; } if (tmpItems[tPos].value == m_visItems[oPos].value && tmpItems[tPos].value->Pos() == m_visItems[oPos].value->Pos()) { ++oPos; ++tPos; } else { if (tmpItems[tPos].idx > m_visItems[oPos].idx){ while (oPos < oCnt && tmpItems[tPos].idx > m_visItems[oPos].idx){ m_oldVisItems.AddItem(m_visItems[oPos].value); ++oPos; } continue; } m_newVisItems.AddItem(tmpItems[tPos].value); ++tPos; } } m_visItems.Init(tmpItems); if (m_newVisItems.Size() || OldVisItems().Size()) m_bDirtPassMap = true; return false; } ////////////////////////////////////////////////////////////////////////// void iPlayer::ResetVistItemChanges() { m_newVisItems.Cleanup(); m_oldVisItems.Cleanup(); } sint32 iPlayer::GetMarketIdx() { sint32 result = 0; for (iCastleList::Iterator ctit=m_Castles.First(); ctit!=m_Castles.End(); ++ctit) { iCtlCnst* pMarket = (*ctit)->FindCnst(CTLCNST_MARKETPLACE); if (pMarket && pMarket->IsBuilt()) result ++; } return result; } ////////////////////////////////////////////////////////////////////////// void iPlayer::UpdateFogMap() { m_FogMap.ResetFog(); if (gSettings.ShowEnemyTurn() && PlayerType() == PT_HUMAN) { for (iGameWorld::iPLIt pit = gGame.Map().m_Players.First(); pit != gGame.Map().m_Players.End(); ++pit) { for (iHLIt hit=(*pit)->m_Heroes.First(); hit!=(*pit)->m_Heroes.End(); ++hit) m_FogMap.DiscoverMap((*hit)->Pos().x,(*hit)->Pos().y,(*hit)->Scouting()); for (iCLIt cit=(*pit)->m_Cnsts.First(); cit!=(*pit)->m_Cnsts.End(); ++cit) m_FogMap.DiscoverMap((*cit)->Pos().x,(*cit)->Pos().y, (*cit)->Proto()->Scouting()); for (iCtLIt ctit=(*pit)->m_Castles.First(); ctit!=(*pit)->m_Castles.End(); ++ctit) m_FogMap.DiscoverMap((*ctit)->Pos().x,(*ctit)->Pos().y, (*ctit)->Scouting()); } } else { for (iHLIt hit=m_Heroes.First(); hit!=m_Heroes.End(); ++hit) m_FogMap.DiscoverMap((*hit)->Pos().x,(*hit)->Pos().y,(*hit)->Scouting()); for (iCLIt cit=m_Cnsts.First(); cit!=m_Cnsts.End(); ++cit) m_FogMap.DiscoverMap((*cit)->Pos().x,(*cit)->Pos().y, (*cit)->Proto()->Scouting()); for (iCtLIt ctit=m_Castles.First(); ctit!=m_Castles.End(); ++ctit) m_FogMap.DiscoverMap((*ctit)->Pos().x,(*ctit)->Pos().y, (*ctit)->Scouting()); } UpdateVisItems(); m_bDirtPassMap = true; if (gSettings.ShowEnemyTurn() && PlayerType() != PT_HUMAN && gGame.Map().ActPlayer()) { gGame.Map().ActPlayer()->UpdateFogMap(); } } ////////////////////////////////////////////////////////////////////////// void iPlayer::UpdatePassMap() { if (!m_bDirtPassMap) return; m_bDirtPassMap=false; bool bConstPass = (PlayerType() == PT_COMPUTER); check(m_pCurHero); sint32 mbonus = m_pCurHero->MoveCostBonus(); m_passMap.CopyFrom(gGame.Map().m_PassMap); for (sint32 yy=0; yy<m_passMap.GetHeight(); ++yy){ for (sint32 xx=0; xx<m_passMap.GetWidth(); ++xx){ sint32 res; if (m_FogMap.IsInvisible(iPoint(xx,yy))) { res = -1; } else { iBaseMapObject* pObj = gGame.Map().m_CoverMap.GetAt(xx,yy); if (pObj && pObj->Pos() == iPoint(xx,yy) && (!pObj->Disap() || bConstPass || !m_FogMap.IsHidden(pObj->Pos()))) { res = -2; } else { res = m_passMap.GetAt(xx,yy); } } if (mbonus && res > SURF_MOVE_COST[STYPE_DIRT]) res -= (res-SURF_MOVE_COST[STYPE_DIRT]) * mbonus / 100; m_passMap.GetAt(xx,yy) = (sint8)res; } } } bool iPlayer::NeedStopHero() const { return (m_newVisItems.Size() || m_oldVisItems.Size()); } void iPlayer::UpdateTavernVisitor(iHero* pNewVisitor) { if (m_pTavernVisitor) { gGame.ItemMgr().HeroesMgr().Put(m_pTavernVisitor); m_pTavernVisitor = NULL; } if (pNewVisitor) { m_pTavernVisitor = pNewVisitor; } else { if (m_Castles.Count()) { uint32 htm = 0; // Prepare list of nations according to owned castles for (iCtLIt ctlit = m_Castles.First(); ctlit != m_Castles.End(); ++ctlit) htm |= CTL_HEROES[(*ctlit)->Proto()->Type()]; uint16 selhid = gGame.ItemMgr().HeroesMgr().Select(htm); if (selhid == iHeroesMgr::INVALID_HERO_ID) selhid = gGame.ItemMgr().HeroesMgr().Select(HTM_ALL); if (selhid != iHeroesMgr::INVALID_HERO_ID) m_pTavernVisitor = gGame.ItemMgr().HeroesMgr().Get(selhid); } } } iHero* iPlayer::RecruitTavernVisitor(iCastle* pTarget) { iHero* pCurVisitor = m_pTavernVisitor; m_pTavernVisitor = NULL; m_Minerals -= pCurVisitor->Proto()->m_Cost; gGame.Map().AddHero(pCurVisitor, this, pTarget->Pos(), HERO_ORIENT[pTarget->Proto()->Orient()]); UpdateTavernVisitor(); SetCurHero(pCurVisitor); return pCurVisitor; } uint16 iPlayer::OpenObelisk( ) { uint16 oldOpened = OpenedPuzzles(); ++m_openedObelisks; return OpenedPuzzles() - oldOpened; } uint8 iPlayer::OpenedPuzzles() const { uint16 ocnt = gGame.Map().ObelisksCount(); if (!ocnt) return 0; return iCLAMP<uint8>(0,TotalPuzzles(),((TotalPuzzles() * m_openedObelisks) / ocnt)); } uint8 iPlayer::PuzzledCard(uint8 idx) const { check(idx<TotalPuzzles()); return m_puzzleCards[idx]; }
[ "palmheroesteam@2c21ad19-eed7-4c86-9350-8a7669309276" ]
[ [ [ 1, 514 ] ] ]
d04b5dcd9729b6e69da233a8b47625243ec84650
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestscrollerbar/src/bctestscrollercontainer.cpp
0114f49851c2c58e722e976e8df67255bc9679ca
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
3,586
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: container * */ #include "bctestScrollercontainer.h" #define KAknAtListGray TRgb(0xaaaaaa) // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // C++ default Constructor // --------------------------------------------------------------------------- // CBCTestScrollerContainer::CBCTestScrollerContainer() { } // --------------------------------------------------------------------------- // Destructor // --------------------------------------------------------------------------- // CBCTestScrollerContainer::~CBCTestScrollerContainer() { ResetControl(); } // --------------------------------------------------------------------------- // Symbian 2nd Constructor // --------------------------------------------------------------------------- // void CBCTestScrollerContainer::ConstructL( const TRect& aRect ) { CreateWindowL(); SetRect( aRect ); ActivateL(); } // ---------------------------------------------------------------------------- // CBCTestScrollerContainer::Draw // Fills the window's rectangle. // ---------------------------------------------------------------------------- // void CBCTestScrollerContainer::Draw( const TRect& aRect ) const { CWindowGc& gc = SystemGc(); gc.SetPenStyle( CGraphicsContext::ENullPen ); gc.SetBrushColor( KAknAtListGray ); gc.SetBrushStyle( CGraphicsContext::ESolidBrush ); gc.DrawRect( aRect ); } // --------------------------------------------------------------------------- // CBCTestScrollerContainer::CountComponentControls // --------------------------------------------------------------------------- // TInt CBCTestScrollerContainer::CountComponentControls() const { if ( iControl ) { return 1; } else { return 0; } } // --------------------------------------------------------------------------- // CBCTestScrollerContainer::ComponentControl // --------------------------------------------------------------------------- // CCoeControl* CBCTestScrollerContainer::ComponentControl( TInt ) const { return iControl; } // --------------------------------------------------------------------------- // CBCTestScrollerContainer::SetControl // --------------------------------------------------------------------------- // void CBCTestScrollerContainer::SetControl( CCoeControl* aControl ) { iControl = aControl; if ( iControl ) { // You can change the position and size iControl->SetExtent( Rect().iTl, Rect().Size() ); iControl->ActivateL(); DrawNow(); } } // --------------------------------------------------------------------------- // CBCTestScrollerContainer::ResetControl // --------------------------------------------------------------------------- // void CBCTestScrollerContainer::ResetControl() { delete iControl; iControl = NULL; }
[ "none@none" ]
[ [ [ 1, 116 ] ] ]
1321ab2f596efb0c6a3f2372d2d3287f90a92380
65da00cc6f20a83dd89098bb22f8f93c2ff7419b
/HabuMath/Library/Include/Point.hpp
d1d500d88442c0ebb321a4b75dcd950f3abd25ce
[]
no_license
skevy/CSC-350-Assignment-5
8b7c42257972d71e3d0cd3e9566e88a1fdcce73c
8091a56694f4b5b8de7e278b64448d4f491aaef5
refs/heads/master
2021-01-23T11:49:35.653361
2011-04-20T02:20:06
2011-04-20T02:20:06
1,638,578
0
0
null
null
null
null
UTF-8
C++
false
false
5,672
hpp
//***************************************************************************// // Point Class Interface // // Created: April 6, 2007 // By: Jeremy M Miller // // Copyright (c) 2007 Jeremy M Miller. All rights reserved. // This source code module, and all information, data, and algorithms // associated with it, are part of BlueHabu technology (tm). // // Usage of HabuMath is subject to the appropriate license agreement. // A proprietary/commercial licenses are available. ([email protected]) // // HabuMath 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. // // HabuMath 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 HabuThreads. If not, see <http://www.gnu.org/licenses/>. //***************************************************************************// #ifndef HABU_MATH_POINT_HPP #define HABU_MATH_POINT_HPP #include <assert.h> #include <memory.h> //***************************************************************************// namespace HabuTech { //*************************************************************************// // Point class. NOTE the lack of virtual methods including the non-virtual // destructor. This because I want to be able to have many Point objects // without wasting 4 bytes on the vtable pointer. Therefore, object derived // from this object must call Point's destructor explicitly. template <class T, unsigned char D> class Point { private: //***********************************************************************// //***********************************************************************// protected: //***********************************************************************// // This array stores information about the current position of the point // mtaComponent[0] => X // mtaComponent[1] => Y // mtaComponent[2] => Z // mtaComponent[3] => W T mtaComponent[D]; //***********************************************************************// public: //***********************************************************************// //-----------------------------------------------------------------------// // Contructor sets all the coordinates to zero or the orgin Point() { memset(&mtaComponent, 0L, sizeof(T) * D); } // TODO Bounds check Point(float fX, float fY, float fZ, float fW) { mtaComponent[0] = fX; mtaComponent[1] = fY; mtaComponent[2] = fZ; mtaComponent[3] = fW; } ~Point() {} // NOTE: non-virtual. See the comment on top of this class declaration. //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// void Get(T& Xout, T& Yout, T& Zout) { Xout = mtaComponent[0]; Yout = mtaComponent[1]; if(D > 2) Zout = mtaComponent[2]; } void Set(T Xin, T Yin, T Zin) { mtaComponent[0] = Xin; mtaComponent[1] = Yin; if(D > 2) mtaComponent[2] = Zin; } //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// // These methods return the coordinates of the current position T& rX() {return mtaComponent[0];} // Returns X T& rY() {return mtaComponent[1];} // Returns Y T& rZ() {return mtaComponent[2];} // Returns Z T X() const {return mtaComponent[0];} // Returns X T Y() const {return mtaComponent[1];} // Returns Y T Z() const {return mtaComponent[2];} // Returns Z //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// // These methods set the coordinates of the point void rX(T& Xin) {mtaComponent[0] = Xin;} // Sets X void rY(T& Yin) {mtaComponent[1] = Yin;} // Sets Y void rZ(T& Zin) {mtaComponent[2] = Zin;} // Sets Z void X(T Xin) {mtaComponent[0] = Xin;} // Sets X void Y(T Yin) {mtaComponent[1] = Yin;} // Sets Y void Z(T Zin) {mtaComponent[2] = Zin;} // Sets Z //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// T& operator[](unsigned char ucIndex) { assert(ucIndex < D); if(ucIndex < D) return mtaComponent[ucIndex]; return mtaComponent[D - 1]; } //-----------------------------------------------------------------------// //-----------------------------------------------------------------------// Point<T, D>& operator=(const Point<T, D>& rhs) { memcpy(&mtaComponent, &rhs.mtaComponent, D * sizeof(T)); return *this; } //-----------------------------------------------------------------------// //***********************************************************************// }; //*************************************************************************// } //***************************************************************************// #endif HABU_MATH_POINT_HPP
[ [ [ 1, 130 ] ] ]
8f2066ba1819e276e1809da379bff27fa55873f6
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Animation/Ragdoll/Utils/hkaRagdollUtils.h
7dded46afba05c25c007df1836e22c87e27fa7ea
[]
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,611
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 INC_HKRAGDOLL_UTILS_H #define INC_HKRAGDOLL_UTILS_H #include <Common/Base/hkBase.h> class hkpRigidBody; class hkpConstraintInstance; class hkaSkeleton; class hkaRagdollInstance; /// The static methods in this utility class provide functionality in order to create and manipulate ragdoll instances class hkaRagdollUtils { public: /// Reorders the rigid bodies (parent first) and the constaints static hkResult HK_CALL reorderForRagdoll (hkArray<hkpRigidBody*> &rigidBodiesInOut, hkArray<hkpConstraintInstance*> &constraintsInOut); /// Reorders the rigid bodies (parent first) and aligns their pivots to the constraints spaces /// The requirements for this to succeed are:. /// a - There is n rigid bodies and n-1 constraints /// b - Constraints are properly parented (rigid body a -> child bone, rigid body b -> parent bone). /// c - Constraints are properly placed at the joints. /// If you give a skeleton it will make sure that the bodies are in the same order as the skeleton bones /// If warnOnAlignment is set to true, a warning will be raised whenever a rigid body had to be re-aligned static hkResult HK_CALL reorderAndAlignForRagdoll (hkArray<hkpRigidBody*>& rigidBodiesInOut, hkArray<hkpConstraintInstance*>& constraintsInOut, hkBool warnOnAlignment = false); /// Given a physics system representing a ragdoll, constructs an hkaSkeleton describing its structure. /// It assumes the physics system has been properly set up using "reorderAndAlignForRagdoll". /// Note that in the creation of a skeleton some memory gets allocated and needs to be deallocated properly by calling the /// utility method "destroySkeleton". static hkaSkeleton* HK_CALL constructSkeletonForRagdoll (const hkArray<hkpRigidBody*> &rigidBodies, const hkArray<hkpConstraintInstance*> &constraints); /// Deallocates any memory allocated by constructSkeletonForagdoll(). static void HK_CALL destroySkeleton (hkaSkeleton* skeleton); /// Constructs a ragdoll instance based on the given skeleton. /// It takes the rigid bodies and constraints from the "candidate" lists passed as a parameter. /// Returns HK_NULL on failure. static class hkaRagdollInstance* createRagdollInstanceFromSkeleton (const hkaSkeleton* skeleton, const hkArray<hkpRigidBody*>& candidateRBs, const hkArray<hkpConstraintInstance*>& candidateConstraints); }; #endif //INC_HKRAGDOLL_UTILS_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, 68 ] ] ]
6bba6b1c4b705ea1fe77572b6caeefc86b77d6ac
0c62a303659646fa06db4d5d09c44ecb53ce619a
/Kickapoo/Game.cpp
d3e16c60c12d3b5a0e6243558879d093b3014c4a
[]
no_license
gosuwachu/igk-game
60dcdd8cebf7a25faf60a5cc0f5acd6f698c1c25
faf2e6f3ec6cfe8ddc7cb1f3284f81753f9745f5
refs/heads/master
2020-05-17T21:51:18.433505
2010-04-12T12:42:01
2010-04-12T12:42:01
32,650,596
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
14,961
cpp
#include "Common.h" #include "Game.h" Sound* g_fireSound = NULL; Sound* g_wallSound = NULL; static float _introTime = 0.0f; static float _fake; static float _selectionAlpha = 0.0f; static float _splashZeroElementY = 0.0f; static float _splashOneElementY = 600.0f; Audio g_AudioSystem; string _introText = "W roku 2010 na konferencji IGK wyciekł kod pluginu do firefoxa\ndający możliwość podróżowania w czasie.\nNic od tamtego momentu nie było już takie samo.\n... a mówili, że na wojnie nie ma God Mode."; RECT _introRect; RECT _screenMiddleRect; const float MaxRelativeTime = 10.0f; Game::Game(void) : state_(EGameState::Intro) , kryzys_("kryzys_logo.jpg") , crysis_("crysis.jpg") , selection_("gfx/wave.png") , gameScreen_("gfx/splash_main.png") , zero_("gfx/splash_0.png") , one_("gfx/splash_1.png") , clockTexture("gfx/circle.png") , activePlayer(NULL) { relativeTime = 0; activePlayer = NULL; changeState(EGameState::Intro); map = NULL; g_AudioSystem.create(); clockSound = g_AudioSystem.loadSound("sfx/clock.mp3"); explosionSound = g_AudioSystem.loadSound("sfx/explosion.wav"); g_fireSound = g_AudioSystem.loadSound("sfx/fire.wav"); pickSound = g_AudioSystem.loadSound("sfx/pick.wav"); g_wallSound = g_AudioSystem.loadSound("sfx/wall.wav"); background = g_AudioSystem.loadSound("sfx/background.mp3", true); backgroundMusicStarted = false; typingSound = g_AudioSystem.loadSound("sfx/typing.wav"); } void Game::loadLevel() { AnimationSequence::releaseAll(); delete map; map = NULL; towers.clear(); playerList.clear(); activePlayer = NULL; char buffer[100]; sprintf(buffer, "map%i.bmp", level_); map = Map::load(buffer); map->loadContent(playerList, towers); towersAlive_ = towers.size(); replayCount_ = 0; if(level_==0) changeState(EGameState::Tutorial); else changeState(EGameState::Selection); } Game::~Game(void) { delete introFont_; g_AudioSystem.release(); } void Game::changeState(EGameState::TYPE state) { state_ = state; //! TODO: implement tutorial if(state == EGameState::Tutorial) { changeState(EGameState::Selection); } else if(state == EGameState::Running) { relativeTime = 0; towersAlive_ = towers.size(); for(int i = 0; i < playerList.size(); ++i) { playerList[i].reset(); } // reset all towers state for(int i = 0; i < towers.size(); ++i) { Tower* tower = &towers[i]; tower->state = ETS_ALIVE; } g_ParticleSystem()->clear(); } else //! TODO: implement selection if(state == EGameState::Selection) { //relativeTime = 0; activePlayer = NULL; AnimationSequence::releaseAll(); for(int i = 0; i < playerList.size(); ++i) { playerList[i].dead = false; } // reset all towers state for(int i = 0; i < towers.size(); ++i) { //Tower* tower = &towers[i]; //tower->state = ETS_ALIVE; } // hack off // changeState(EGameState::Running); g_ParticleSystem()->clear(); } if(state == EGameState::LevelFinished) { } } void Game::startGame() { loadLevel(); changeState(EGameState::Tutorial); } void Game::killTower(Tower* tower) { tower->state = ETS_DYING; //! kill tower AnimationSequenceActivator* kill = new AnimationSequenceActivator(MakeDelegate(tower, &Tower::kill)); //! add particle wait 1 sec and hide tower AnimationSequenceActivator1Param* spawnParticle = new AnimationSequenceActivator1Param(MakeDelegate(this, &Game::explodeTower), tower); AnimationSequenceScalar* wait1Sec = new AnimationSequenceScalar(_fake, 0, 1, 1.0f); AnimationSequenceActivator* hide = new AnimationSequenceActivator(MakeDelegate(tower, &Tower::hide)); //! set seq kill->setNext(spawnParticle); spawnParticle->setNext(wait1Sec); wait1Sec->setNext(hide); //! add to system AnimationSequence::add(kill); onTowerKilled(); } void Game::onTowerKilled() { towersAlive_--; for(unsigned i = 0; i < towers.size(); ++i) { if(towers[i].state == ETS_ALIVE) return; } //! Change level if(++level_ < maxLevels_) { //! level finished change state and wait 1 sec changeState(EGameState::LevelFinished); AnimationSequenceScalar* wait3sec = new AnimationSequenceScalar(_fake, 0, 1, 3); AnimationSequenceActivator* changeLevel = new AnimationSequenceActivator(MakeDelegate(this, &Game::loadLevel)); wait3sec->setNext(changeLevel); AnimationSequence::add(wait3sec); } else { changeState(EGameState::GameFinished); } } void Game:: explodeTower(void* t) { Tower* tower = (Tower*)t; ParticleSystem * ps = ParticleSystem::getSingletonPtr(); ps->spawnExplosion(D3DXVECTOR2(tower->getX(), tower->getY())); g_AudioSystem.play(explosionSound); } void Game::create() { //! Create intro //! Fade In [0.0f - 1.0f] //! Wave it and FadeOut [1.0f - 2.0f] //! Fade In Game Screen [2.0f - 3.0f] //! Type text [3.0f - 3.0f + textLength * 0.1f] if(state_ == EGameState::Intro) { float totalTime = 3 + _introText.size() * 0.1f + 3; AnimationSequenceScalar* introTimeLine = new AnimationSequenceScalar(_introTime, 0.0f, totalTime, totalTime); AnimationSequenceActivator* startGame = new AnimationSequenceActivator( MakeDelegate(this, &Game::startGame) ); introTimeLine->setNext(startGame); AnimationSequence::add(introTimeLine); } //! intro font RECT tmp={80, 530, g_Window()->getWidth(), g_Window()->getHeight()}; _introRect = tmp; introFont_ = new Font(); introFont_->create("Comic Sans MS", 40, 0, false, &_introRect); introFont_->setTextColor(D3DCOLOR_RGBA(127, 100, 0, 255)); RECT screenMiddle ={g_Window()->getWidth() * 0.25f, g_Window()->getHeight()*0.5f, g_Window()->getWidth() * 0.25f + g_Window()->getWidth(), g_Window()->getHeight() * 0.25f + g_Window()->getHeight()}; _screenMiddleRect = screenMiddle; scoreFont = new Font(); scoreFont->create("Comic Sans MS", 40, 0, false, &_screenMiddleRect); scoreFont->setTextColor(D3DCOLOR_RGBA(255, 0, 0, 255)); RECT rect2 = {665, 64, g_Window()->getWidth(), g_Window()->getHeight()}; clockFont = new Font(); clockFont->create("Verdana", 20, 0, false, &rect2); clockFont->setTextColor(D3DCOLOR_RGBA(255, 0, 0, 255)); level_ = 0; replayCount_ = 0; } void Game::update() { float dt = g_Timer()->getFrameTime(); if(state_ != EGameState::Intro) { map->update(); } if(state_ == EGameState::Intro) { } else if(state_ == EGameState::Running) { if(GetKeyState(VK_RETURN) & 0x80) { changeState(EGameState::Selection); return; } for(int i = 0; i < maxLevels_; ++i) { if(GetKeyState('1' + i) & 0x80) { level_ = i; loadLevel(); return; } } g_ParticleSystem()->updateParticles(map, relativeTime); g_ParticleSystem()->checkParticlesAgainstMap(*map, ParticleShot, *this); g_ParticleSystem()->checkParticlesAgainstPlayer(&playerList, ParticleHarmful, MakeDelegate(this, &Game::onPlayerKilled), relativeTime); if(state_ != EGameState::Running) return; ParticleSystem * ps = ParticleSystem::getSingletonPtr(); relativeTime += dt; if(relativeTime > MaxRelativeTime) { changeState(EGameState::Selection); } else if(activePlayer) { activePlayer->record(dt, relativeTime, map, leftMouseDown); } if(state_ == EGameState::Running) { for(int i = 0; i < playerList.size(); ++i) playerList[i].update(relativeTime); for(int i = 0 ; i < towers.size() ; ++i) towers[i].ai(&playerList, relativeTime); } else { g_AudioSystem.stopSoud(clockSound); } } leftMouseClick = false; g_AudioSystem.update(); } void Game::drawDynamicObjects() { for(unsigned i = 0; i < playerList.size(); ++i) { playerList[i].draw(true, state_ >= EGameState::Running, relativeTime, &playerList[i] == activePlayer); } for(unsigned i = 0; i < towers.size(); ++i) { Tower& tower = towers[i]; tower.draw(); } } void Game::draw() { if(state_ == EGameState::Intro) { if(_introTime < 1.0f) { getDevice()->SetTexture(0, crysis_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)(_introTime * 255.0f),255,255,255)); } else //! Wave it and FadeOut [1.0f - 2.0f] if(_introTime < 2.0f) { getDevice()->SetTexture(0, crysis_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)((2.0f - _introTime) * 255.0f),255,255,255)); getDevice()->SetTexture(0, kryzys_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)((_introTime - 1.0f ) * 255.0f),255,255,255)); } else //! Fade In Game Screen [2.0f - 3.0f] if(_introTime < 3.0f) { getDevice()->SetTexture(0, gameScreen_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB((int)((_introTime - 2.0f) * 255.0f),255,255,255)); getDevice()->SetTexture(0, zero_.getTexture()); g_Renderer()->drawRect(0, _splashZeroElementY, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); } else //! Type text [3.0f - 3.0f + textLength * 0.1f] //! and change 2010 into 2110 { static int typeChar = 0; getDevice()->SetTexture(0, gameScreen_.getTexture()); g_Renderer()->drawRect(0, 0, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); string typedText; int currentLength = (int)((_introTime - 3.0f) * 10.0f); typedText.assign(_introText.c_str(), currentLength); introFont_->write(typedText.c_str()); float totalTime = 3 + _introText.size() * 0.1f; if(currentLength > typeChar && _introTime <= totalTime) { typeChar = currentLength; if(typedText[typedText.length() - 1] != ' ') g_AudioSystem.play(typingSound); } if(_splashOneElementY > 0.0f) { float speed = 600.0f / 1.5f; _splashZeroElementY -= speed * g_Timer()->getFrameTime(); _splashOneElementY -= speed * g_Timer()->getFrameTime(); }; getDevice()->SetTexture(0, zero_.getTexture()); g_Renderer()->drawRect(0, _splashZeroElementY, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); getDevice()->SetTexture(0, one_.getTexture()); g_Renderer()->drawRect(0, _splashOneElementY, g_Window()->getWidth(), g_Window()->getHeight(), D3DCOLOR_ARGB(255,255,255,255)); } } else { if(!backgroundMusicStarted) { backgroundMusicStarted = true; g_AudioSystem.play(background); } map->draw(); g_ParticleSystem()->renderParticles(); drawDynamicObjects(); updateClock(); //! draw selection if(_selectionAlpha > 0.0f && activePlayer) { float ssize = 1.5f * BLOCK_SIZE * (- _selectionAlpha + 3); getDevice()->SetTexture(0, selection_.getTexture()); g_Renderer()->drawRect( activePlayer->getX()- ssize * 0.5f, activePlayer->getY() - ssize * 0.5f, ssize, ssize, D3DCOLOR_ARGB((int)(_selectionAlpha*255), 120, 255,0)); } if(state_ == EGameState::LevelFinished) { getDevice()->SetTexture(0, NULL); g_Renderer()->drawRect(g_Window()->getWidth() / 4 - 30, g_Window()->getHeight() / 4, g_Window()->getWidth() / 2 + 60, g_Window()->getHeight() / 2, D3DCOLOR_ARGB(127,255,255,255)); scoreFont->write("Gratulacje! Udało Ci się w czasie: %0.2f", relativeTime); } else if(state_ == EGameState::GameFinished) { getDevice()->SetTexture(0, NULL); g_Renderer()->drawRect(g_Window()->getWidth() / 4 - 60, g_Window()->getHeight() / 4, g_Window()->getWidth() / 2 + 200, g_Window()->getHeight() / 2, D3DCOLOR_ARGB(127,255,255,255)); scoreFont->write("Gratulacje! Gra ukończona ostatni czas: %0.2f", relativeTime); } } } void Game::onLeftClick() { leftMouseClick = true; if(state_ == EGameState::Selection) { for(int i=0; i < (int) playerList.size(); ++i) { if(playerList[i].contains(g_Mouse()->getX(), g_Mouse()->getY())) { g_AudioSystem.play(pickSound); activePlayer = &playerList[i]; activePlayer->StateList.clear(); activePlayer->Velocity = D3DXVECTOR2(0, 0); //! draw selection AnimationSequenceScalar* sel = new AnimationSequenceScalar(_selectionAlpha, 1.0f, 0.0f, 1.0f); AnimationSequence::add(sel); changeState(EGameState::Running); return; } } } } void Game::updateClock() { float radius = BLOCK_SIZE * 2; D3DXVECTOR3 position = D3DXVECTOR3(g_Window()->getWidth()-radius, g_Window()->getHeight()-radius, 0); D3DCOLOR color = D3DCOLOR_ARGB(127,0,255,0); int vertexCount = 36; float rotAngle = 0; float angle = 3.14f * 2 / vertexCount; rotAngle -= 3.14f * 90.0f / 180.0f; float timeStep = 360.0f / 10.0f; const int steps = 60; int k = 0; //! generate vertices static std::vector<vertex> vertices; vertices.resize((steps+1) * 3); D3DXVECTOR3 last = position + D3DXVECTOR3(0, 1, 0) * radius; for(int i=1; i <= steps; ++i) { float angle = (float) i / steps * D3DX_PI * 2; float cf = cosf(angle); float sf = sinf(angle); float t = (float) i / steps * MaxRelativeTime; D3DCOLOR color2 = t < relativeTime ? D3DCOLOR_ARGB(192+i*64/steps,(255-90+i*90/steps),64,0): D3DCOLOR_ARGB(160,0,255,0); vertices[k].pos = position; vertices[k].tu = vertices[k].tv = 0.5f; vertices[k++].color = color2; vertices[k].pos = last; vertices[k].tu = vertices[k].tv = 0.5f; vertices[k++].color = color2; vertices[k].pos = position + D3DXVECTOR3(sf, cf, 0) * radius; vertices[k].tu = vertices[k].tv = 0.5f; vertices[k++].color = color2; last = position + D3DXVECTOR3(sf, cf, 0) * radius; } //g_AudioSystem.play(clockSound); getDevice()->SetTexture(0, NULL); getDevice()->SetFVF(FVF_TEX); getDevice()->DrawPrimitiveUP(D3DPT_TRIANGLELIST, k/3, &vertices[0], sizeof(vertex)); /* static float circleAngle = 0; static bool isLooping = false; SLine line; line.x1 = 684.0f; line.y1 = 484.0f; line.x2 = line.x1+sin(circleAngle*DEG2RAD)*66; line.y2 = line.y1+cos(circleAngle*DEG2RAD)*66; circleAngle = relativeTime*360.0f/10; if((int)circleAngle >= clockLines.size()) clockLines.push_back(line); if(relativeTime >= 9.9f) { circleAngle = 0; clockLines.clear(); } if(!isLooping) { g_AudioSystem.play(clockSound); isLooping = true; }*/ } void Game::onPlayerKilled(Player* player) { //if(activePlayer == player) // changeState(EGameState::Selection); // if(player != NULL) player->dead = true; if(player == activePlayer) activePlayer = NULL; }
[ "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d", "konrad.rodzik@d16c65a5-d515-2969-3ec5-0ec16041161d", "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d", "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d", "[email protected]@d16c65a5-d515-2969-3ec5-0ec16041161d" ]
[ [ [ 1, 3 ], [ 20, 20 ], [ 29, 30 ], [ 48, 49 ], [ 74, 75 ], [ 79, 80 ], [ 208, 209 ], [ 245, 248 ], [ 250, 250 ], [ 367, 369 ] ], [ [ 4, 5 ], [ 11, 11 ], [ 28, 28 ], [ 33, 33 ], [ 35, 47 ], [ 68, 71 ], [ 77, 78 ], [ 116, 116 ], [ 122, 124 ], [ 127, 128 ], [ 143, 143 ], [ 204, 204 ], [ 225, 225 ], [ 237, 241 ], [ 244, 244 ], [ 259, 259 ], [ 289, 290 ], [ 295, 295 ], [ 298, 298 ], [ 301, 304 ], [ 308, 309 ], [ 317, 322 ], [ 354, 354 ], [ 359, 360 ], [ 365, 366 ], [ 370, 370 ], [ 385, 390 ], [ 408, 408 ], [ 414, 414 ], [ 421, 422 ], [ 431, 431 ], [ 435, 435 ], [ 439, 439 ], [ 448, 448 ], [ 450, 454 ], [ 459, 459 ], [ 464, 464 ], [ 470, 470 ], [ 477, 477 ], [ 500, 501 ], [ 505, 530 ] ], [ [ 6, 10 ], [ 13, 15 ], [ 18, 19 ], [ 21, 27 ], [ 34, 34 ], [ 50, 51 ], [ 64, 66 ], [ 72, 73 ], [ 76, 76 ], [ 81, 89 ], [ 108, 110 ], [ 129, 130 ], [ 133, 142 ], [ 144, 148 ], [ 152, 166 ], [ 171, 174 ], [ 176, 176 ], [ 195, 195 ], [ 197, 203 ], [ 205, 207 ], [ 210, 214 ], [ 222, 223 ], [ 226, 226 ], [ 228, 230 ], [ 232, 233 ], [ 236, 236 ], [ 243, 243 ], [ 249, 249 ], [ 255, 256 ], [ 279, 279 ], [ 299, 299 ], [ 323, 346 ], [ 350, 353 ], [ 355, 356 ], [ 358, 358 ], [ 361, 361 ], [ 371, 384 ], [ 391, 392 ], [ 394, 398 ], [ 400, 405 ], [ 419, 420 ], [ 423, 424 ], [ 426, 430 ], [ 432, 434 ], [ 436, 437 ], [ 440, 447 ], [ 449, 449 ], [ 458, 458 ], [ 460, 463 ], [ 499, 499 ], [ 502, 503 ], [ 531, 531 ] ], [ [ 12, 12 ], [ 106, 107 ], [ 175, 175 ], [ 216, 216 ], [ 224, 224 ], [ 227, 227 ], [ 231, 231 ], [ 234, 235 ], [ 276, 277 ], [ 280, 280 ], [ 296, 296 ], [ 347, 349 ], [ 357, 357 ], [ 362, 364 ], [ 409, 410 ], [ 415, 416 ], [ 532, 532 ], [ 534, 534 ], [ 544, 544 ] ], [ [ 16, 17 ], [ 31, 32 ], [ 52, 63 ], [ 67, 67 ], [ 90, 105 ], [ 111, 115 ], [ 117, 121 ], [ 125, 126 ], [ 131, 132 ], [ 149, 151 ], [ 167, 170 ], [ 177, 194 ], [ 196, 196 ], [ 215, 215 ], [ 217, 221 ], [ 242, 242 ], [ 251, 254 ], [ 257, 258 ], [ 260, 275 ], [ 278, 278 ], [ 281, 288 ], [ 291, 294 ], [ 297, 297 ], [ 300, 300 ], [ 305, 307 ], [ 310, 316 ], [ 393, 393 ], [ 399, 399 ], [ 406, 407 ], [ 411, 413 ], [ 417, 418 ], [ 425, 425 ], [ 438, 438 ], [ 455, 457 ], [ 465, 469 ], [ 471, 476 ], [ 478, 498 ], [ 504, 504 ], [ 533, 533 ], [ 535, 543 ] ] ]
2f8d7199220aebfbb9e2c81ed35e79368be0fcdb
1741474383f0b3bc3518d7935a904f7903f40506
/A6/ram/ram.h
ee94b02c917753cb65c5b7282d7682590c51e3da
[]
no_license
osecki/drexelgroupwork
739df86f361e00528a6b03032985288d64b464aa
7c3bde253a50cab42c22d286c80cad72348b4fcf
refs/heads/master
2020-05-31T02:25:57.734312
2009-06-03T18:34:59
2009-06-03T18:34:59
32,121,248
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
// Definition of RAM (random access machine) class #include "inst.h" class RAM { public: // Constructors RAM(); RAM(int pSize, int mSize); // Initialize RAM with hardwired program and memory // pc is set to 1 and ac is set to 0 void init(); // Initialize RAM with program in file with the name pInput // and initial memory configuration in the file with name mInput // pc is set to 1 and ac is set to 0. programSize is set to the number // of instructions read. void init(const char *pFile, const char *mFile); // simulate execution of RAM with given program and memory configuration. // 1. Program may not terminate (if HLT is not executed) // 2. Currently no error checking is performed. Checks for valid program // and memory addresses and illegal opcodes should be provided. void execute(); // Dump memory contents void dump(); private: int *memory; Instruction *program; int memorySize; int programSize; int pc; int ac; };
[ "jordan.osecki@c6e0ff0a-2120-11de-a108-cd2f117ce590" ]
[ [ [ 1, 38 ] ] ]
46e7a4cfc9df459690bf711127c31fd14118e556
48c6de8cb63cf11147049ce07b2bd7e020d0d12b
/gcc/opencollada/include/COLLADAFramework/include/COLLADAFWUniqueId.h
fb6a70f2c1b12ac3f4d225f6a4b9d2c5dcc90757
[]
no_license
ngbinh/libBlenderWindows
73effaa1aab8d9d1745908f5528ded88eca21ce3
23fbaaaad973603509b23f789a903959f6ebb560
refs/heads/master
2020-06-08T00:41:55.437544
2011-03-25T05:13:25
2011-03-25T05:13:25
1,516,625
1
1
null
null
null
null
UTF-8
C++
false
false
3,536
h
/* Copyright (c) 2008-2009 NetAllied Systems GmbH This file is part of COLLADAFramework. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADAFW_UNIQUEID_H__ #define __COLLADAFW_UNIQUEID_H__ #include "COLLADAFWPrerequisites.h" #include "COLLADAFWTypes.h" #include "COLLADAFWArray.h" namespace COLLADAFW { /** Class that uniquely identifies each object in the model. It consists of a ClassId that uniquely identifies the class an object is instantiated from and of an ObjectId that uniquely identifies the object in the set of all objects of the same Type.*/ class UniqueId { public: /** An invalid UniqueId.*/ static const UniqueId INVALID; private: /** The class id of the class the object is instantiated from.*/ ClassId mClassId; /** The object id that uniquely identifies the object in the set of all objects of the same Type.*/ ObjectId mObjectId; /** The id of the COLLADA file that contains the object.*/ FileId mFileId; public: /** Default constructor. Creates a UniqueId with ClassId COLALDA_TYPES::No_TYPE, which is an invalid ClassId. Therefore the UniqueId is considered to be invalid.*/ UniqueId() : mClassId(COLLADA_TYPE::NO_TYPE), mObjectId(0), mFileId(0){} /** Constructor. Creates UniqueId with ClassId @a classId an ObjectId @a objectId.*/ UniqueId(ClassId classId, ObjectId objectId, FileId fileId) : mClassId(classId), mObjectId(objectId), mFileId(fileId){} /** Constructor. Creates UniqueId from string @a ascii. This text representation is used in formula to reference parameters.*/ UniqueId(const String& ascii); ~UniqueId(); /** Returns the class id of the class the object is instantiated from.*/ ClassId getClassId() const { return mClassId; } /** Returns the object id that uniquely identifies the object in the set of all objects of the same Type.*/ ObjectId getObjectId() const { return mObjectId; } /** Returns the id of the COLLADA file that contains the object.*/ FileId getFileId() const { return mFileId; } /** Returns true if the unique id is valid, false otherwise.*/ bool isValid() const { return mClassId != COLLADA_TYPE::NO_TYPE; } /** Creates an ascii representation of the unique id.*/ String toAscii() const; /** Parses the ascii representation and sets this values according to @a ascii. To ensure parsing always succeeds, only parse string created by toAscii(). @return True on success, false if parsing failed.*/ bool fromAscii( const String& ascii); bool operator<(const UniqueId& rhs) const; bool operator>(const UniqueId& rhs) const; bool operator==(const UniqueId& uid) const; bool operator!=(const UniqueId& uid) const; operator size_t()const; private: /** Parses the ascii representation and sets this values according to @a ascii. To ensure parsing always succeeds, only parse string created by toAscii(). @return True on success, false if parsing failed.*/ bool fromAscii_intern( const String& ascii); }; typedef Array<UniqueId> UniqueIdArray; } // namespace COLLADAFW #if defined(__MINGW32__) # include "COLLADABUhash_map.h" namespace __gnu_cxx { template<> struct hash<COLLADAFW::UniqueId> { size_t operator()(const COLLADAFW::UniqueId& id) const { return id; } }; } #endif #endif // __COLLADAFW_UNIQUEID_H__
[ [ [ 1, 107 ] ] ]
3380582859203b4d6b7a2a3a1f2efc4c71bbd6f2
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/properties/vis_properties_init.cpp
0e8f258335926ef7e59f82141abcc053f60ddc74
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,826
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/properties/vis_properties_init.h" #include "sys/simulation/simulation_controller.h" #include "sys/simulation/simulation_task_keeper.h" #include "apps/vis/properties/vec/vis_properties_vec_init.h" #include "apps/vis/properties/double/vis_properties_double_init.h" #include "apps/vis/properties/int/vis_properties_int_init.h" #include "apps/vis/properties/bool/vis_properties_bool_init.h" namespace vis { void init_vis_properties( shawn::SimulationController& sc ) { init_vis_vec_properties(sc); init_vis_double_properties(sc); init_vis_int_properties(sc); init_vis_bool_properties(sc); } } #endif /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/tubsapps/vis/properties/vis_properties_init.cpp,v $ * Version $Revision: 1.2 $ * Date $Date: 2006/01/31 12:44:00 $ *----------------------------------------------------------------------- * $Log: vis_properties_init.cpp,v $ * Revision 1.2 2006/01/31 12:44:00 ali * *** empty log message *** * * Revision 1.1 2006/01/29 21:02:01 ali * began vis * *-----------------------------------------------------------------------*/
[ [ [ 1, 46 ] ] ]
ea22ff574b5fab8e981c01100c2a73c12506cc8b
2e5fd1fc05c0d3b28f64abc99f358145c3ddd658
/deps/quickfix/src/C++/test/MySQLStoreTestCase.cpp
3289745cd5553c2bd1c369093a59a86d0cd35a17
[ "BSD-2-Clause" ]
permissive
indraj/fixfeed
9365c51e2b622eaff4ce5fac5b86bea86415c1e4
5ea71aab502c459da61862eaea2b78859b0c3ab3
refs/heads/master
2020-12-25T10:41:39.427032
2011-02-15T13:38:34
2011-02-15T20:50:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,486
cpp
/**************************************************************************** ** Copyright (c) quickfixengine.org All rights reserved. ** ** This file is part of the QuickFIX FIX Engine ** ** This file may be distributed under the terms of the quickfixengine.org ** license as defined by quickfixengine.org and appearing in the file ** LICENSE included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.quickfixengine.org/LICENSE for licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** ****************************************************************************/ #ifdef _MSC_VER #pragma warning( disable : 4503 4355 4786 ) #include "stdafx.h" #else #include "config.h" #endif #ifdef HAVE_MYSQL #include <UnitTest++.h> #include <TestHelper.h> #include <MySQLStore.h> #include "MessageStoreTestCase.h" using namespace FIX; SUITE(MySQLStoreTests) { struct mySQLStoreFixture { mySQLStoreFixture( bool reset ) : factory( TestSettings::sessionSettings.get() ) { SessionID sessionID( BeginString( "FIX.4.2" ), SenderCompID( "SETGET" ), TargetCompID( "TEST" ) ); try { object = factory.create( sessionID ); } catch( std::exception& e ) { std::cerr << e.what() << std::endl; throw; } if( reset ) object->reset(); this->resetAfter = resetAfter; } ~mySQLStoreFixture() { factory.destroy( object ); } MySQLStoreFactory factory; MessageStore* object; bool resetAfter; }; struct noResetMySQLStoreFixture : mySQLStoreFixture { noResetMySQLStoreFixture() : mySQLStoreFixture( false ) {} }; struct resetMySQLStoreFixture : mySQLStoreFixture { resetMySQLStoreFixture() : mySQLStoreFixture( true ) {} }; TEST_FIXTURE(resetMySQLStoreFixture, setGet) { CHECK_MESSAGE_STORE_SET_GET; } TEST_FIXTURE(resetMySQLStoreFixture, setGetWithQuote) { CHECK_MESSAGE_STORE_SET_GET_WITH_QUOTE; } TEST_FIXTURE(resetMySQLStoreFixture, other) { CHECK_MESSAGE_STORE_OTHER } TEST_FIXTURE(noResetMySQLStoreFixture, reload) { CHECK_MESSAGE_STORE_RELOAD } TEST_FIXTURE(noResetMySQLStoreFixture, refresh) { CHECK_MESSAGE_STORE_REFRESH } } #endif
[ [ [ 1, 110 ] ] ]
8e15b53df179ef60439fa1fbe4916e807ebbb631
bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2
/Open GL Basic Engine/source/glutFramework/glutFramework/mapTile.h
9e7568f35d73ba3144ba073344599ff232d86950
[]
no_license
CorwinJV/rvbgame
0f2723ed3a4c1a368fc3bac69052091d2d87de77
a4fc13ed95bd3e5a03e3c6ecff633fe37718314b
refs/heads/master
2021-01-01T06:49:33.445550
2009-11-03T23:14:39
2009-11-03T23:14:39
32,131,378
0
0
null
null
null
null
UTF-8
C++
false
false
609
h
#ifndef MAPTILE_H #define MAPTILE_H #include "oglUtility.h" //#include "pixmap.h" #include <cstring> #include <iostream> #include "tileEnums.h" class mapTile { protected: tileTypeEnum tileType; bool isActive; bool resetActiveStatus; // pointer to whoever is standing on me public: mapTile(); mapTile(tileTypeEnum nType, bool nisActive); ~mapTile(); tileTypeEnum getType(); bool setType(tileTypeEnum nType); bool getIsActive(); bool setActive(bool nactive); bool toggleActive(); bool update(); void resetActive(); void setResetActive(bool newActive); }; #endif
[ "corwin.j@5457d560-9b84-11de-b17c-2fd642447241" ]
[ [ [ 1, 32 ] ] ]
0222d7fb4ad65ab95d49c3979e3e0df004fddfd7
22b6d8a368ecfa96cb182437b7b391e408ba8730
/engine samples/01_Sample/source/sdcQuitCommand.cpp
1be141729a3e8584959def67bb9b4593b5e9484b
[ "MIT" ]
permissive
drr00t/quanticvortex
2d69a3e62d1850b8d3074ec97232e08c349e23c2
b780b0f547cf19bd48198dc43329588d023a9ad9
refs/heads/master
2021-01-22T22:16:50.370688
2010-12-18T12:06:33
2010-12-18T12:06:33
85,525,059
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
#include "sdcQuitCommand.h" #include "qvEventArgs.h" namespace sdc { namespace controller { // QuitCommand::QuitCommand(qv::IEngineManager *engine) // :ICommandEvent(qv::CI_COMMAND_GAME_QUIT), mEngine(engine) // { // mEventTypes.push_back(qv::events::ET_GAME_QUIT); // } // // QuitCommand::~QuitCommand() // { // mEventTypes.set_free_when_destroyed(false); // mEventTypes.clear(); // } // // void QuitCommand::executeCommand(const qv::events::IEventArgs *args) // { // mEngine->setQuit(true); // mEngine->getDevice()->getLogger()->log("quit event generated"); // } //----------------------------------------------------------------------------- } }
[ [ [ 1, 30 ] ] ]
c3756f4a162cacce764ac181ae38e77b9b3ff490
3276915b349aec4d26b466d48d9c8022a909ec16
/c++/模板/模版函数参数匹配 .cpp
6bd71582adab7f248bd865c5699bbb9f1d28ac1e
[]
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
630
cpp
#include<iostream> //模版函数参数匹配 using namespace std; class zhong { int a; public: zhong() {} }; template<class T,class U> T disp(U a) { cout<<"调用1"<<endl; return a; } template<class U> U disp(U a) { cout<<"调用2"<<endl; return a; } int main() { int i=0; disp(i); disp<double>(i); //通过显示说明参数的类型来区别 disp<double,int>(i); //disp<int>(i); //产生二义性 //disp<zhong>(zhong()); //disp<zhong>(i); system("pause"); return 0; }
[ [ [ 1, 52 ] ] ]
f21003b5819f32b636c7efcbcf8c012e4a30f49b
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.2/bctestpreviewpopup/inc/bctestpreviewpopupview.h
e9a79ae2a82060b7cbc840e571f9020abdd865a9
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,188
h
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Test BC for PreviewPopup control API. * */ #ifndef BCTEST_PREVIEWPOPUP_VIEW_H #define BCTEST_PREVIEWPOPUP_VIEW_H #include <aknview.h> const TUid KBCTestPreviewPopupViewId = { 1 }; class CBCTestPreviewPopupContainer; class CBCTestUtil; /** * Application UI class * * @lib bctestutil.lib */ class CBCTestPreviewPopupView : public CAknView { public: // Constructors and destructor /** * Symbian static 2nd constructor */ static CBCTestPreviewPopupView* NewL(CBCTestUtil* aUtil); /** * dtor */ virtual ~CBCTestPreviewPopupView(); public: // from CAknView /** * Return view Id. */ TUid Id() const; /** * From CAknView, HandleCommandL. * @param aCommand Command to be handled. */ void HandleCommandL( TInt aCommand ); /** * getter of Container */ CBCTestPreviewPopupContainer* Container(); protected: // from CAknView /** * When view is activated, do something */ void DoActivateL( const TVwsViewId&, TUid, const TDesC8& ); /** * When view is deactivated, do something */ void DoDeactivate(); private: // constructor /** * C++ default constructor */ CBCTestPreviewPopupView(); /** * symbian 2nd ctor */ void ConstructL(CBCTestUtil* aUtil); private: // data /** * pointor to the BC Test framework utility. * not own just refer to */ CBCTestUtil* iTestUtil; /** * pointor to the container. * own */ CBCTestPreviewPopupContainer* iContainer; }; #endif // BCTEST_PREVIEWPOPUP_VIEW_H // End of File
[ "none@none" ]
[ [ [ 1, 108 ] ] ]
03c77f19afd8c58b323792416cc9b3254d4a0e49
4c0c3b9539a84860b1ecec87e0cc89da5a2b8579
/src/exerb/exerb.cpp
76bc4fa9fd9b163ff11e26a13fe9f4a006920624
[ "DOC" ]
permissive
snaury/exerb-mingw
8ec9f4f39aead177c91dec3671b49315d300d923
577683046e021785e6ac47cf2bd6fe6a8e6951f7
refs/heads/master
2016-09-05T11:59:54.922776
2009-11-02T14:31:25
2009-11-02T14:31:25
348,470
5
1
null
null
null
null
SHIFT_JIS
C++
false
false
30,854
cpp
// $Id: exerb.cpp,v 1.198 2009/09/08 12:25:47 arton Exp $ #include <ruby.h> #include <crtdbg.h> #include "exerb.h" #include "module.h" #include "utility.h" #include "resource.h" #ifdef RUBY19 extern "C" { #include <yarvcore.h> } #endif //////////////////////////////////////////////////////////////////////////////// typedef struct { char *filepath; HMODULE handle; } LOADED_LIBRARY_ENTRY; typedef struct { DWORD base_of_file; IMAGE_DOS_HEADER *dos_header; IMAGE_NT_HEADERS *nt_headers; IMAGE_SECTION_HEADER *section; DWORD base_of_import_table; DWORD delta_of_import_table; DWORD base_of_name_pool; DWORD size_of_name_pool; } IMPORT_TABLE_INFO; //////////////////////////////////////////////////////////////////////////////// VALUE rb_mExerbRuntime = 0; VALUE rb_eExerbRuntimeError = 0; ARCHIVE_HEADER *g_archive_header = NULL; NAME_TABLE_HEADER *g_name_table_header = NULL; FILE_TABLE_HEADER *g_file_table_header = NULL; int g_loaded_library_count = 0; LOADED_LIBRARY_ENTRY g_loaded_library_table[32] = {0}; LOADED_LIBRARY_ENTRY g_pre_loaded_library_table[8] = {0}; int g_loaded_resource_count = 0; HMODULE g_loaded_resource_table[4] = {0}; extern "C" VALUE rb_load_path; extern "C" VALUE rb_argv0; extern "C" VALUE rb_progname; //////////////////////////////////////////////////////////////////////////////// int exerb_main(int argc, char** argv, void (*on_init)(VALUE, VALUE, VALUE), void (*on_fail)(VALUE)); static VALUE exerb_main_in_protect(VALUE replace_io); static void exerb_mapping(); static void exerb_set_script_name(char* name); static void exerb_setup_kcode(); static void exerb_setup_resource_library(); static void exerb_execute(); static void exerb_cleanup(); extern "C" VALUE exerb_require(VALUE fname); static bool exerb_find_ruby_pre_loaded(const VALUE filename); static bool exerb_find_file_pre_loaded(const VALUE filename, VALUE *feature, LOADED_LIBRARY_ENTRY **loaded_library_entry); static bool exerb_find_file_inside(const VALUE filename, WORD *id, VALUE *feature, VALUE *realname); static bool exerb_find_file_outside(const VALUE filename, VALUE *feature, VALUE *realname); static VALUE exerb_load_ruby_script(const FILE_ENTRY_HEADER *file_entry); static VALUE exerb_load_ruby_script(const char *filepath); #ifdef RUBY19 static VALUE exerb_load_compiled_script(const FILE_ENTRY_HEADER *file_entry); #endif static void exerb_load_extension_library(const FILE_ENTRY_HEADER *file_entry); static void exerb_load_extension_library(const char *filepath); static HMODULE exerb_load_library(const FILE_ENTRY_HEADER *file_entry); static HMODULE exerb_load_library(const char *base_of_file, const int size_of_file, const char* filepath, bool no_replace_function); static HMODULE exerb_preload_library(const FILE_ENTRY_HEADER *file_entry); static bool exerb_replace_import_dll(const char *base_of_file); static void exerb_replace_import_dll_name(IMPORT_TABLE_INFO *info, const char *src_name, const char* new_name); static bool exerb_get_import_table_info(const char *base_of_file, IMPORT_TABLE_INFO *info); static IMAGE_SECTION_HEADER* exerb_get_enclosing_section_header(const IMAGE_NT_HEADERS *nt_headers, const DWORD rva); static void exerb_call_initialize_function(const HMODULE handle, const char *filepath); static bool exerb_find_resource(const DWORD base_of_image, const int type, const int id, DWORD *base_of_item, DWORD *size_of_item); static void exerb_replace_import_function(const HMODULE module); static bool exerb_replace_import_function_thunk(const HMODULE module, const FARPROC src_proc, const FARPROC new_proc); static HMODULE WINAPI exerb_hook_load_library(LPCTSTR filename); static HMODULE WINAPI exerb_hook_load_library_ex(LPCTSTR filename, HANDLE file, DWORD flags); static HMODULE WINAPI exerb_hook_get_module_handle(LPCTSTR filename); static FARPROC WINAPI exerb_hook_get_proc_address(HMODULE module, LPCTSTR procname); //////////////////////////////////////////////////////////////////////////////// int exerb_main(int argc, char** argv, void (*on_init)(VALUE, VALUE, VALUE), void (*on_fail)(VALUE)) { ::NtInitialize(&argc, &argv); ::ruby_init(); argc = ::rb_w32_cmdvector(::GetCommandLine(), &argv); ::ruby_set_argv(argc - 1, argv + 1); ::exerb_set_script_name("exerb"); ::rb_ary_push(rb_load_path, ::rb_str_new2(".")); int state = 0, result_code = 0; ::rb_protect(exerb_main_in_protect, UINT2NUM((DWORD)on_init), &state); if ( state ) { #ifdef RUBY19 VALUE errinfo = GET_THREAD()->errinfo; #else VALUE errinfo = ruby_errinfo; #endif if ( ::rb_obj_is_kind_of(errinfo, rb_eSystemExit) ) { result_code = FIX2INT(::rb_iv_get(errinfo, "status")); } else { on_fail(errinfo); result_code = 1; } } ::ruby_finalize(); ::exerb_cleanup(); return result_code; } static VALUE exerb_main_in_protect(VALUE on_init_proc) { ::Init_ExerbRuntime(); void (*on_init)(VALUE, VALUE, VALUE) = (void(*)(VALUE, VALUE, VALUE))NUM2UINT(on_init_proc); if ( on_init ) on_init(rb_stdin, rb_stdout, rb_stderr); ::exerb_mapping(); ::exerb_setup_kcode(); ::exerb_setup_resource_library(); ::exerb_execute(); return Qnil; } static void exerb_mapping() { const DWORD base_of_image = (DWORD)::GetModuleHandle(NULL); DWORD base_of_archive = 0, size_of_archive = 0; if ( !::exerb_find_resource(base_of_image, RT_EXERB, ID_EXERB, &base_of_archive, &size_of_archive) ) { ::rb_raise(rb_eExerbRuntimeError, "The executable hasn't an archive."); } g_archive_header = (ARCHIVE_HEADER*)base_of_archive; if ( g_archive_header->signature1 != ARCHIVE_HEADER_SIGNATURE1 || g_archive_header->signature2 != ARCHIVE_HEADER_SIGNATURE2 ) { ::rb_raise(rb_eExerbRuntimeError, "The executable has invalid signature of archive header."); } if ( g_archive_header->offset_of_name_table == 0 || g_archive_header->offset_of_file_table == 0 ) { ::rb_raise(rb_eExerbRuntimeError, "The executable has invalid archive header."); } g_name_table_header = (NAME_TABLE_HEADER*)(base_of_archive + g_archive_header->offset_of_name_table); g_file_table_header = (FILE_TABLE_HEADER*)(base_of_archive + g_archive_header->offset_of_file_table); if ( g_name_table_header->signature != NAME_TABLE_HEADER_SIGNATURE ) { ::rb_raise(rb_eExerbRuntimeError, "The executable has invalid signature of the name table header."); } if ( g_file_table_header->signature != FILE_TABLE_HEADER_SIGNATURE ) { ::rb_raise(rb_eExerbRuntimeError, "The executable has invalid signature of the file table header."); } } static void exerb_set_script_name(char* name) { ::ruby_script(name); rb_argv0 = rb_progname; } static void exerb_setup_kcode() { switch ( g_archive_header->kcode ) { case ARCHIVE_HEADER_OPTIONS_KCODE_NONE: ::rb_set_kcode("n"); break; case ARCHIVE_HEADER_OPTIONS_KCODE_EUC: ::rb_set_kcode("e"); break; case ARCHIVE_HEADER_OPTIONS_KCODE_SJIS: ::rb_set_kcode("s"); break; case ARCHIVE_HEADER_OPTIONS_KCODE_UTF8: ::rb_set_kcode("u"); break; } } static void exerb_setup_resource_library() { FILE_ENTRY_HEADER *file_entry = ::exerb_get_first_file_entry(); for ( int i = 0; i < g_file_table_header->number_of_headers; i++, file_entry++ ) { if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_RESOURCE_LIBRARY ) { if ( g_loaded_resource_count > sizeof(g_loaded_resource_table) / sizeof(HMODULE) ) { ::rb_raise(rb_eExerbRuntimeError, "the loaded recourse table is too big."); } g_loaded_resource_table[g_loaded_resource_count] = ::exerb_load_library(file_entry); g_loaded_resource_count++; } } } static void exerb_execute() { FILE_ENTRY_HEADER *file_entry = ::exerb_get_first_file_entry(); for ( int i = 0; i < g_file_table_header->number_of_headers; i++, file_entry++ ) { if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_RUBY_SCRIPT ) { ::exerb_set_script_name(::exerb_get_name_from_entry(::exerb_find_name_entry(file_entry->id))); ::exerb_load_ruby_script(file_entry); return; #ifdef RUBY19 } else if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_COMPILED_SCRIPT ) { ::exerb_set_script_name(::exerb_get_name_from_entry(::exerb_find_name_entry(file_entry->id))); ::exerb_load_compiled_script(file_entry); return; #endif } } ::rb_raise(rb_eExerbRuntimeError, "The startup script was not found."); } static void exerb_cleanup() { for ( int i = g_loaded_library_count; i > 0; i-- ) { const LOADED_LIBRARY_ENTRY *entry = &g_loaded_library_table[i - 1]; char filepath[MAX_PATH] = ""; ::GetModuleFileName(entry->handle, filepath, sizeof(filepath)); ::FreeLibrary(entry->handle); ::DeleteFile(filepath); delete[] entry->filepath; } } extern "C" VALUE exerb_require(VALUE fname) { ::Check_SafeStr(fname); LOADED_LIBRARY_ENTRY *loaded_library_entry = NULL; WORD id = 0; VALUE feature = Qnil, realname = Qnil; if ( ::exerb_find_ruby_pre_loaded(fname) ) { return Qfalse; } if ( ::exerb_find_file_pre_loaded(fname, &feature, &loaded_library_entry) ) { ::rb_provide(RSTRING_PTR(feature)); ::exerb_call_initialize_function(loaded_library_entry->handle, loaded_library_entry->filepath); delete[] loaded_library_entry->filepath; loaded_library_entry->filepath = NULL; loaded_library_entry->handle = NULL; return Qtrue; } else if ( ::exerb_find_file_inside(fname, &id, &feature, &realname) ) { if ( ::rb_provided(RSTRING_PTR(feature)) ) return Qfalse; FILE_ENTRY_HEADER *file_entry = ::exerb_find_file_entry(id); switch ( file_entry->type_of_file ) { case FILE_ENTRY_HEADER_TYPE_RUBY_SCRIPT: ::rb_provide(RSTRING_PTR(feature)); ::exerb_load_ruby_script(file_entry); return Qtrue; #ifdef RUBY19 case FILE_ENTRY_HEADER_TYPE_COMPILED_SCRIPT: ::rb_provide(RSTRING_PTR(feature)); ::exerb_load_compiled_script(file_entry); return Qtrue; #endif case FILE_ENTRY_HEADER_TYPE_EXTENSION_LIBRARY: ::rb_provide(RSTRING_PTR(feature)); ::exerb_load_extension_library(file_entry); return Qtrue; } } else if ( ::exerb_find_file_outside(fname, &feature, &realname) ) { if ( ::rb_provided(RSTRING_PTR(feature)) ) return Qfalse; const char *ext = ::strrchr(RSTRING_PTR(feature), '.'); if ( ::stricmp(ext, ".rb") == 0 ) { ::rb_provide(RSTRING_PTR(feature)); ::exerb_load_ruby_script(RSTRING_PTR(realname)); return Qtrue; } else if ( ::stricmp(ext, ".so") == 0 ) { ::rb_provide(RSTRING_PTR(feature)); ::exerb_load_extension_library(RSTRING_PTR(realname)); return Qtrue; } } ::rb_raise(rb_eLoadError, "No such file to load -- %s", RSTRING_PTR(fname)); return Qfalse; } static char* EXTTBL[] = { "rb", "so", "dll" }; static bool exerb_find_ruby_pre_loaded(const VALUE filename) { const char* fname = RSTRING_PTR(filename); if (strchr(fname, '.')) { return ::rb_provided(fname) != Qfalse; } else { char* p = (char*)_alloca(strlen(fname) + 8); for (int i = 0; i < sizeof(EXTTBL)/sizeof(EXTTBL[0]); i++) { sprintf(p, "%s.%s", fname, EXTTBL[i]); if (::rb_provided(p)) { return true; } } } return false; } static bool exerb_find_file_pre_loaded(const VALUE filename, VALUE *feature, LOADED_LIBRARY_ENTRY **loaded_library_entry) { const char *fname = RSTRING_PTR(filename); for ( int i = 0; i < sizeof(g_pre_loaded_library_table) / sizeof(LOADED_LIBRARY_ENTRY); i++ ) { const char *name = g_pre_loaded_library_table[i].filepath; if ( !name ) continue; if ( ::stricmp(name, fname) == 0 ) { *feature = ::rb_str_new2(name); *loaded_library_entry = &g_pre_loaded_library_table[i]; return true; } else if ( ::exerb_cmp_filename_with_ext(name, fname, "so") ) { *feature = ::rb_str_new2(name); *loaded_library_entry = &g_pre_loaded_library_table[i]; return true; } else if ( ::exerb_cmp_filename_with_ext(name, fname, "dll") ) { *feature = ::rb_str_concat(::rb_str_new2(fname), ::rb_str_new2(".so")); *loaded_library_entry = &g_pre_loaded_library_table[i]; return true; } } return false; } static bool exerb_find_file_inside(const VALUE filename, WORD *id, VALUE *feature, VALUE *realname) { const char *fname = STR2CSTR(filename); NAME_ENTRY_HEADER *name_entry = ::exerb_get_first_name_entry(); for ( int i = 0; i < g_name_table_header->number_of_headers; i++, name_entry++ ) { const char *name = ::exerb_get_name_from_entry(name_entry); if ( ::strcmp(name, fname) == 0 ) { *id = name_entry->id; *feature = ::rb_str_new2(name); *realname = ::rb_str_new2(name); return true; } else if ( ::exerb_cmp_filename_with_ext(name, fname, "rb") ) { *id = name_entry->id; *feature = ::rb_str_new2(name); *realname = ::rb_str_new2(name); return true; } else if ( ::exerb_cmp_filename_with_ext(name, fname, "so") ) { *id = name_entry->id; *feature = ::rb_str_new2(name); *realname = ::rb_str_new2(name); return true; } else if ( ::exerb_cmp_filename_with_ext(name, fname, "dll") ) { *id = name_entry->id; *feature = ::rb_str_concat(::rb_str_new2(fname), ::rb_str_new2(".so")); *realname = ::rb_str_new2(name); return true; } } *id = 0; *feature = Qnil; *realname = Qnil; return false; } static bool exerb_find_file_outside(const VALUE filename, VALUE *feature, VALUE *realname) { const VALUE filename_rb = ::rb_str_concat(::rb_str_dup(filename), ::rb_str_new2(".rb")); const VALUE filename_so = ::rb_str_concat(::rb_str_dup(filename), ::rb_str_new2(".so")); const VALUE filename_dll = ::rb_str_concat(::rb_str_dup(filename), ::rb_str_new2(".dll")); if ( *realname = ::rb_find_file(*feature = filename) ) return true; if ( *realname = ::rb_find_file(*feature = filename_rb) ) return true; if ( *realname = ::rb_find_file(*feature = filename_so) ) return true; if ( *realname = ::rb_find_file(filename_dll) ) { *feature = filename_so; return true; } *feature = Qnil; *realname = Qnil; return false; } static VALUE exerb_load_ruby_script(const FILE_ENTRY_HEADER *file_entry) { static const ID id_eval = ::rb_intern("eval"); static const VALUE binding = ::rb_const_get(rb_mKernel, ::rb_intern("TOPLEVEL_BINDING")); static const VALUE lineno = INT2FIX(1); const VALUE code = ::rb_str_new(::exerb_get_file_from_entry(file_entry), file_entry->size_of_file); const VALUE name = ::rb_str_new2(::exerb_get_name_from_entry(::exerb_find_name_entry(file_entry->id))); return ::rb_funcall(rb_mKernel, id_eval, 4, code, binding, name, lineno); } static VALUE exerb_load_ruby_script(const char *filepath) { ::rb_load(::rb_str_new2(filepath), 0); return Qnil; } #ifdef RUBY19 static VALUE exerb_load_compiled_script(const FILE_ENTRY_HEADER *file_entry) { static const ID id_load = ::rb_intern("load"); static const ID id_eval = ::rb_intern("eval"); const VALUE code = ::rb_str_new(::exerb_get_file_from_entry(file_entry), file_entry->size_of_file); const VALUE iseq_ary = ::rb_marshal_load(code); const VALUE iseq = ::rb_funcall(rb_cISeq, id_load, 1, iseq_ary); return ::rb_funcall(iseq, id_eval, 0); } #endif static void exerb_load_extension_library(const FILE_ENTRY_HEADER *file_entry) { const HMODULE handle = ::exerb_load_library(file_entry); const char *filepath = ::exerb_get_name_from_entry(::exerb_find_name_entry(file_entry->id)); ::exerb_call_initialize_function(handle, filepath); } static void exerb_load_extension_library(const char *filepath) { const HANDLE file = ::exerb_fopen_for_read(filepath); const DWORD size = ::exerb_fsize(file); char *buffer = new char[size]; ::exerb_fread(file, buffer, size); ::exerb_fclose(file); const HMODULE handle = ::exerb_load_library(buffer, size, filepath, false); ::exerb_call_initialize_function(handle, filepath); delete[] buffer; } static HMODULE exerb_load_library(const FILE_ENTRY_HEADER *file_entry) { const char *base_of_file = ::exerb_get_file_from_entry(file_entry); const char *filepath = ::exerb_get_name_from_entry(::exerb_find_name_entry(file_entry->id)); return ::exerb_load_library(base_of_file, file_entry->size_of_file, filepath, (bool)file_entry->flag_no_replace_function); } static HMODULE exerb_load_library(const char *base_of_file, const int size_of_file, const char* filepath, bool no_replace_function) { if ( g_loaded_library_count > sizeof(g_loaded_library_table) / sizeof(LOADED_LIBRARY_ENTRY) ) { ::rb_raise(rb_eExerbRuntimeError, "the loaded library table is too big."); } DWORD protect = 0, dummy = 0; ::VirtualProtect((void*)base_of_file, size_of_file, PAGE_READWRITE, &protect); ::exerb_replace_import_dll(base_of_file); ::VirtualProtect((void*)base_of_file, size_of_file, protect, &dummy); char tmp_filepath[MAX_PATH] = ""; ::exerb_create_tmpfile("exerb", tmp_filepath, base_of_file, size_of_file); const HMODULE handle = ::LoadLibraryEx(tmp_filepath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if ( !handle ) { DWORD error = ::GetLastError(); ::DeleteFile(tmp_filepath); ::exerb_raise_runtime_error(error); } g_loaded_library_table[g_loaded_library_count].filepath = ::exerb_strdup(filepath); g_loaded_library_table[g_loaded_library_count].handle = handle; g_loaded_library_count++; if ( !no_replace_function ) ::exerb_replace_import_function(handle); return handle; } static HMODULE exerb_preload_library(const FILE_ENTRY_HEADER *file_entry) { NAME_ENTRY_HEADER *name_entry = ::exerb_find_name_entry(file_entry->id); const char *name = ::exerb_get_name_from_entry(name_entry); for ( int i = 0; i < g_loaded_library_count; i++ ) { if ( g_loaded_library_table[i].filepath && ::stricmp(g_loaded_library_table[i].filepath, name) == 0 ) { return g_loaded_library_table[i].handle; } } HMODULE module = ::exerb_load_library(file_entry); if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_EXTENSION_LIBRARY ) { for ( int i = 0; i < sizeof(g_pre_loaded_library_table) / sizeof(LOADED_LIBRARY_ENTRY); i++ ) { if ( !g_pre_loaded_library_table[i].handle ) { g_pre_loaded_library_table[i].filepath = ::exerb_strdup(name); g_pre_loaded_library_table[i].handle = module; break; } } } return module; } static bool exerb_replace_import_dll(const char *base_of_file) { IMPORT_TABLE_INFO info = {0}; if ( !::exerb_get_import_table_info(base_of_file, &info) ) return false; char self_filepath[MAX_PATH] = ""; const char *self_filename = ::exerb_get_self_filepath(self_filepath, sizeof(self_filepath)); // FIXME: msvcrt-ruby19.dll に対応させる // FIXME: msvcrt-ruby??.dll 以外のRubyライブラリにリンクされていた場合は、例外とする // FIXME: ランタイム版コアを使用している場合は、exerb??.dllにリンクする ::exerb_replace_import_dll_name(&info, "exerb_dummy_module.dll", self_filename); // for an exerb plug-in ::exerb_replace_import_dll_name(&info, "ruby.exe", self_filename); // for an extension library on static linked ruby #ifdef RUBY19 ::exerb_replace_import_dll_name(&info, "msvcrt-ruby19.dll", self_filename); // for an extension library on dynamic linked ruby #else ::exerb_replace_import_dll_name(&info, "msvcrt-ruby18.dll", self_filename); // for an extension library on dynamic linked ruby ::exerb_replace_import_dll_name(&info, "cygwin-ruby18.dll", self_filename); // for experiment ::exerb_replace_import_dll_name(&info, "cygruby18.dll", self_filename); // for experiment #endif return true; } static void exerb_replace_import_dll_name(IMPORT_TABLE_INFO *info, const char *src_name, const char* new_name) { const DWORD base_of_name = info->base_of_file - info->delta_of_import_table; const DWORD size_of_new_name = ::strlen(new_name); IMAGE_IMPORT_DESCRIPTOR *first_descriptor = (IMAGE_IMPORT_DESCRIPTOR*)(info->base_of_file + info->base_of_import_table); for ( IMAGE_IMPORT_DESCRIPTOR *descriptor = first_descriptor; descriptor->Name; descriptor++ ) { char *name = (char*)(base_of_name + descriptor->Name); if ( ::stricmp(name, src_name) == 0 ) { bool found = false; for ( IMAGE_IMPORT_DESCRIPTOR *desc = first_descriptor; desc->Name; desc++ ) { if ( ::strcmp((char*)(base_of_name + desc->Name), new_name) == 0 ) { descriptor->Name = desc->Name; found = true; break; } } if ( found ) continue; if ( ::strlen(name) >= size_of_new_name ) { ::strcpy(name, new_name); } else if ( size_of_new_name + 1 <= info->size_of_name_pool ) { DWORD address_of_new_name = info->base_of_name_pool - (size_of_new_name + 1); ::strcpy((char*)(info->base_of_file + address_of_new_name), new_name); descriptor->Name = address_of_new_name + info->delta_of_import_table; info->base_of_name_pool -= size_of_new_name + 1; info->size_of_name_pool -= size_of_new_name + 1; } else { ::rb_raise(rb_eLoadError, "Couldn't modify DLL's name in the import table. The name of the executable file is too long."); } } else if ( FILE_ENTRY_HEADER *file_entry = ::exerb_find_file_entry(name) ) { if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_EXTENSION_LIBRARY || file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_DYNAMIC_LIBRARY ) { HMODULE module = ::exerb_preload_library(file_entry); char filepath[MAX_PATH] = ""; const char *filename = ::exerb_get_module_filepath(module, filepath, sizeof(filepath)); ::exerb_replace_import_dll_name(info, name, filename); } } } } static bool exerb_get_import_table_info(const char *base_of_file, IMPORT_TABLE_INFO *info) { info->base_of_file = (DWORD)base_of_file; info->dos_header = (IMAGE_DOS_HEADER*)info->base_of_file; info->nt_headers = (IMAGE_NT_HEADERS*)(info->base_of_file + info->dos_header->e_lfanew); const DWORD rva_of_import_table = info->nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; info->section = ::exerb_get_enclosing_section_header(info->nt_headers, rva_of_import_table); if ( !info->section ) return false; info->delta_of_import_table = info->section->VirtualAddress - info->section->PointerToRawData; info->base_of_import_table = rva_of_import_table - info->delta_of_import_table; if ( ::strnicmp((char*)info->section->Name, ".idata", 8) == 0 || // for Boland's Compiler ::strnicmp((char*)info->section->Name, ".rdata", 8) == 0 ) { // for Microsoft's Compiler info->base_of_name_pool = info->section->PointerToRawData + info->section->SizeOfRawData; info->size_of_name_pool = info->section->SizeOfRawData - info->section->Misc.VirtualSize; } else { info->base_of_name_pool = 0; info->size_of_name_pool = 0; } return true; } static IMAGE_SECTION_HEADER* exerb_get_enclosing_section_header(const IMAGE_NT_HEADERS *nt_headers, const DWORD rva) { IMAGE_SECTION_HEADER *section = IMAGE_FIRST_SECTION(nt_headers); for ( int i = 0; i < nt_headers->FileHeader.NumberOfSections; i++, section++ ) { if ( (rva >= section->VirtualAddress) && (rva < (section->VirtualAddress + section->Misc.VirtualSize)) ) { return section; } } return NULL; } static void exerb_call_initialize_function(const HMODULE handle, const char *filepath) { const char *filename = ::exerb_get_filename(filepath); char funcname[128] = "Init_"; ::strncat(funcname, filename, sizeof(funcname) - ::strlen(funcname) - 1); char *ext = ::strrchr(funcname, '.'); if ( ext && (::stricmp(ext, ".so") == 0 || ::stricmp(ext, ".dll") == 0) ) { *ext = '\0'; } void (*init_proc)(void) = (void (*)(void))::GetProcAddress(handle, funcname); if ( !init_proc ) ::rb_raise(rb_eExerbRuntimeError, "Couldn't call the initialize function in the extension library. --- %s(%s)", filepath, funcname); (*init_proc)(); } static bool exerb_find_resource(const DWORD base_of_image, const int type, const int id, DWORD *base_of_item, DWORD *size_of_item) { const IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER*)base_of_image; const IMAGE_NT_HEADERS *nt_headers = (IMAGE_NT_HEADERS*)(base_of_image + dos_header->e_lfanew); const DWORD base_of_resource = base_of_image + nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress; if ( base_of_resource == base_of_image ) return false; const IMAGE_RESOURCE_DIRECTORY *root_dir = (IMAGE_RESOURCE_DIRECTORY*)base_of_resource; const IMAGE_RESOURCE_DIRECTORY_ENTRY *root_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root_dir + 1); for ( WORD i = 0; i < root_dir->NumberOfNamedEntries + root_dir->NumberOfIdEntries; i++ ) { if ( !root_entries[i].NameIsString && root_entries[i].Id == type ) { const IMAGE_RESOURCE_DIRECTORY *type_dir = (IMAGE_RESOURCE_DIRECTORY*)(base_of_resource + root_entries[i].OffsetToDirectory); const IMAGE_RESOURCE_DIRECTORY_ENTRY *type_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(type_dir + 1); for ( WORD j = 0; j < type_dir->NumberOfNamedEntries + type_dir->NumberOfIdEntries; j++ ) { if ( !type_entries[j].NameIsString && type_entries[j].Id == id ) { const IMAGE_RESOURCE_DIRECTORY *item_dir = (IMAGE_RESOURCE_DIRECTORY*)(base_of_resource + type_entries[j].OffsetToDirectory); const IMAGE_RESOURCE_DIRECTORY_ENTRY *item_entries = (IMAGE_RESOURCE_DIRECTORY_ENTRY*)(item_dir + 1); const IMAGE_RESOURCE_DATA_ENTRY *data_entry = (IMAGE_RESOURCE_DATA_ENTRY*)(base_of_resource + item_entries[0].OffsetToData); if ( base_of_item ) *base_of_item = base_of_image + data_entry->OffsetToData; if ( size_of_item ) *size_of_item = data_entry->Size; return true; } } } } return false; } //////////////////////////////////////////////////////////////////////////////// static void exerb_replace_import_function(const HMODULE module) { static const HMODULE kernel32 = ::GetModuleHandle("kernel32.dll"); static const FARPROC load_library_proc = ::GetProcAddress(kernel32, "LoadLibraryA"); static const FARPROC load_library_ex_proc = ::GetProcAddress(kernel32, "LoadLibraryExA"); static const FARPROC get_module_handle = ::GetProcAddress(kernel32, "GetModuleHandleA"); static const FARPROC get_proc_address_proc = ::GetProcAddress(kernel32, "GetProcAddress"); ::exerb_replace_import_function_thunk(module, load_library_proc, (FARPROC)::exerb_hook_load_library); ::exerb_replace_import_function_thunk(module, load_library_ex_proc, (FARPROC)::exerb_hook_load_library_ex); ::exerb_replace_import_function_thunk(module, get_module_handle, (FARPROC)::exerb_hook_get_module_handle); ::exerb_replace_import_function_thunk(module, get_proc_address_proc, (FARPROC)::exerb_hook_get_proc_address); } static bool exerb_replace_import_function_thunk(const HMODULE module, const FARPROC src_proc, const FARPROC new_proc) { const DWORD base_of_image = (DWORD)module; const IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER*)base_of_image; const IMAGE_NT_HEADERS *nt_headers = (IMAGE_NT_HEADERS*)(base_of_image + dos_header->e_lfanew); const DWORD base_of_import = base_of_image + nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; if ( base_of_import == base_of_image ) return false; for ( IMAGE_IMPORT_DESCRIPTOR *desc = (IMAGE_IMPORT_DESCRIPTOR*)base_of_import; desc->Name; desc++ ) { for ( DWORD *thunk = (DWORD*)(base_of_image + desc->FirstThunk); *thunk; thunk++ ) { if ( *thunk == (DWORD)src_proc ) { DWORD protect = 0, dummy = 0; ::VirtualProtect(thunk, sizeof(DWORD), PAGE_READWRITE, &protect); *thunk = (DWORD)new_proc; ::VirtualProtect(thunk, sizeof(DWORD), protect, &dummy); return true; } } } return false; } static HMODULE WINAPI exerb_hook_load_library(LPCTSTR filename) { _RPT1(_CRT_WARN, "exerb_hook_load_library('%s')\n", filename); if ( filename ) { if ( ::stricmp(filename, "msvcrt-ruby18") == 0 || ::stricmp(filename, "msvcrt-ruby18.dll") == 0 ) { return ::GetModuleHandle(NULL); } else if ( FILE_ENTRY_HEADER *file_entry = ::exerb_find_file_entry(filename, "dll") ) { if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_EXTENSION_LIBRARY || file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_DYNAMIC_LIBRARY ) { return ::exerb_preload_library(file_entry); } } } return ::LoadLibrary(filename); } static HMODULE WINAPI exerb_hook_load_library_ex(LPCTSTR filename, HANDLE file, DWORD flags) { _RPT3(_CRT_WARN, "exerb_hook_load_library_ex('%s', %i, %i)\n", filename, file, flags); if ( filename ) { if ( ::stricmp(filename, "msvcrt-ruby18") == 0 || ::stricmp(filename, "msvcrt-ruby18.dll") == 0 ) { return ::GetModuleHandle(NULL); } else if ( FILE_ENTRY_HEADER *file_entry = ::exerb_find_file_entry(filename, "dll") ) { if ( file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_EXTENSION_LIBRARY || file_entry->type_of_file == FILE_ENTRY_HEADER_TYPE_DYNAMIC_LIBRARY ) { return ::exerb_preload_library(file_entry); } } } return ::LoadLibraryEx(filename, file, flags); } static HMODULE WINAPI exerb_hook_get_module_handle(LPCTSTR filename) { _RPT1(_CRT_WARN, "exerb_hook_get_module_handle('%s')\n", filename); if ( filename && (::stricmp(filename, "msvcrt-ruby18") == 0 || ::stricmp(filename, "msvcrt-ruby18.dll") == 0) ) { return ::GetModuleHandle(NULL); } return ::GetModuleHandle(filename); } static FARPROC WINAPI exerb_hook_get_proc_address(HMODULE module, LPCTSTR procname) { _RPT2(_CRT_WARN, "exerb_hook_get_proc_address(0x%08X, '%s')\n", module, procname); static HMODULE kernel32 = ::GetModuleHandle("kernel32.dll"); // FIXME: 序数によるインポートに対応する if ( module == kernel32 ) { if ( ::strcmp(procname, "LoadLibraryA") == 0 ) return (FARPROC)::exerb_hook_load_library; else if ( ::strcmp(procname, "LoadLibraryExA") == 0 ) return (FARPROC)::exerb_hook_load_library_ex; else if ( ::strcmp(procname, "GetModuleHandleA") == 0 ) return (FARPROC)::exerb_hook_get_module_handle; else if ( ::strcmp(procname, "GetProcAddress") == 0 ) return (FARPROC)::exerb_hook_get_proc_address; } return ::GetProcAddress(module, procname); } ////////////////////////////////////////////////////////////////////////////////
[ [ [ 1, 813 ] ] ]
8e89283bfdf7ed40f368e3e6ad03be744b6091d6
119ba245bea18df8d27b84ee06e152b35c707da1
/unreal/branches/robots/qrgui/thirdparty/qextserialport-1.2win-alpha/win_qextserialport.cpp
2c1881f3310b2a5094f6d178730537c07aeb327f
[]
no_license
nfrey/qreal
05cd4f9b9d3193531eb68ff238d8a447babcb3d2
71641e6c5f8dc87eef9ec3a01cabfb9dd7b0e164
refs/heads/master
2020-04-06T06:43:41.910531
2011-05-30T19:30:09
2011-05-30T19:30:09
1,634,768
0
0
null
null
null
null
UTF-8
C++
false
false
34,860
cpp
//#include <stdio.h> //#include <Process.h> //#include <QCoreApplication> //#include <QEvent> #include <QReadWriteLock> #include "win_qextserialport.h" /*! \fn Win_QextSerialPort::Win_QextSerialPort() Default constructor. Note that the name of the device used by a Win_QextSerialPort constructed with this constructor will be determined by #defined constants, or lack thereof - the default behavior is the same as _TTY_LINUX_. Possible naming conventions and their associated constants are: \verbatim Constant Used By Naming Convention ---------- ------------- ------------------------ _TTY_WIN_ Windows COM1, COM2 _TTY_IRIX_ SGI/IRIX /dev/ttyf1, /dev/ttyf2 _TTY_HPUX_ HP-UX /dev/tty1p0, /dev/tty2p0 _TTY_SUN_ SunOS/Solaris /dev/ttya, /dev/ttyb _TTY_DIGITAL_ Digital UNIX /dev/tty01, /dev/tty02 _TTY_FREEBSD_ FreeBSD /dev/ttyd0, /dev/ttyd1 _TTY_LINUX_ Linux /dev/ttyS0, /dev/ttyS1 <none> Linux /dev/ttyS0, /dev/ttyS1 \endverbatim This constructor associates the object with the first port on the system, e.g. COM1 for Windows platforms. See the other constructor if you need a port other than the first. */ Win_QextSerialPort::Win_QextSerialPort(): QextSerialBase() { Win_Handle=INVALID_HANDLE_VALUE; init(); } /*!Win_QextSerialPort::Win_QextSerialPort(const Win_QextSerialPort&) Copy constructor. */ Win_QextSerialPort::Win_QextSerialPort(const Win_QextSerialPort& s): QextSerialBase(s.port) { Win_Handle=INVALID_HANDLE_VALUE; _queryMode = s._queryMode; _bytesToWrite = s._bytesToWrite; bytesToWriteLock = new QReadWriteLock; overlapThread = new Win_QextSerialThread(this); memcpy(& overlap, & s.overlap, sizeof(OVERLAPPED)); memcpy(& overlapWrite, & s.overlapWrite, sizeof(OVERLAPPED)); setOpenMode(s.openMode()); lastErr=s.lastErr; port = s.port; Settings.FlowControl=s.Settings.FlowControl; Settings.Parity=s.Settings.Parity; Settings.DataBits=s.Settings.DataBits; Settings.StopBits=s.Settings.StopBits; Settings.BaudRate=s.Settings.BaudRate; Win_Handle=s.Win_Handle; memcpy(&Win_CommConfig, &s.Win_CommConfig, sizeof(COMMCONFIG)); memcpy(&Win_CommTimeouts, &s.Win_CommTimeouts, sizeof(COMMTIMEOUTS)); if (s.overlapThread->isRunning()) overlapThread->start(); } /*! \fn Win_QextSerialPort::Win_QextSerialPort(const QString & name) Constructs a serial port attached to the port specified by devName. devName is the name of the device, which is windowsystem-specific, e.g."COM2" or "/dev/ttyS0". */ Win_QextSerialPort::Win_QextSerialPort(const QString & name, QextSerialBase::QueryMode mode): QextSerialBase(name) { Win_Handle=INVALID_HANDLE_VALUE; setQueryMode(mode); init(); } /*! \fn Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings) Constructs a port with default name and specified settings. */ Win_QextSerialPort::Win_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode) { Win_Handle=INVALID_HANDLE_VALUE; setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setStopBits(settings.StopBits); setParity(settings.Parity); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); init(); } /*! \fn Win_QextSerialPort::Win_QextSerialPort(const QString & name, const PortSettings& settings) Constructs a port with specified name and settings. */ Win_QextSerialPort::Win_QextSerialPort(const QString & name, const PortSettings& settings, QextSerialBase::QueryMode mode) { Win_Handle=INVALID_HANDLE_VALUE; setPortName(name); setBaudRate(settings.BaudRate); setDataBits(settings.DataBits); setStopBits(settings.StopBits); setParity(settings.Parity); setFlowControl(settings.FlowControl); setTimeout(settings.Timeout_Millisec); setQueryMode(mode); init(); } void Win_QextSerialPort::init() { _bytesToWrite = 0; overlap.Internal = 0; overlap.InternalHigh = 0; overlap.Offset = 0; overlap.OffsetHigh = 0; overlap.hEvent = CreateEvent(NULL, true, false, NULL); overlapThread = new Win_QextSerialThread(this); bytesToWriteLock = new QReadWriteLock; } /*! \fn Win_QextSerialPort::~Win_QextSerialPort() Standard destructor. */ Win_QextSerialPort::~Win_QextSerialPort() { if (isOpen()) { close(); } CloseHandle(overlap.hEvent); delete overlapThread; delete bytesToWriteLock; } /*! \fn Win_QextSerialPort& Win_QextSerialPort::operator=(const Win_QextSerialPort& s) overrides the = operator */ Win_QextSerialPort& Win_QextSerialPort::operator=(const Win_QextSerialPort& s) { setOpenMode(s.openMode()); _queryMode = s._queryMode; _bytesToWrite = s._bytesToWrite; bytesToWriteLock = new QReadWriteLock; overlapThread = new Win_QextSerialThread(this); memcpy(& overlap, & s.overlap, sizeof(OVERLAPPED)); memcpy(& overlapWrite, & s.overlapWrite, sizeof(OVERLAPPED)); lastErr=s.lastErr; port = s.port; Settings.FlowControl=s.Settings.FlowControl; Settings.Parity=s.Settings.Parity; Settings.DataBits=s.Settings.DataBits; Settings.StopBits=s.Settings.StopBits; Settings.BaudRate=s.Settings.BaudRate; Win_Handle=s.Win_Handle; memcpy(&Win_CommConfig, &s.Win_CommConfig, sizeof(COMMCONFIG)); memcpy(&Win_CommTimeouts, &s.Win_CommTimeouts, sizeof(COMMTIMEOUTS)); if (s.overlapThread->isRunning()) overlapThread->start(); return *this; } /*! \fn bool Win_QextSerialPort::open(OpenMode mode) Opens a serial port. Note that this function does not specify which device to open. If you need to open a device by name, see Win_QextSerialPort::open(const char*). This function has no effect if the port associated with the class is already open. The port is also configured to the current settings, as stored in the Settings structure. */ bool Win_QextSerialPort::open(OpenMode mode) { unsigned long confSize = sizeof(COMMCONFIG); Win_CommConfig.dwSize = confSize; DWORD dwFlagsAndAttributes = 0; if (queryMode() == QextSerialBase::EventDriven) dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED; LOCK_MUTEX(); if (mode == QIODevice::NotOpen) return isOpen(); if (!isOpen()) { /*open the port*/ Win_Handle=CreateFileA("\\\\.\\" + port.toAscii(), GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL); if (Win_Handle!=INVALID_HANDLE_VALUE) { /*configure port settings*/ GetCommConfig(Win_Handle, &Win_CommConfig, &confSize); GetCommState(Win_Handle, &(Win_CommConfig.dcb)); /*set up parameters*/ Win_CommConfig.dcb.fBinary=TRUE; Win_CommConfig.dcb.fInX=FALSE; Win_CommConfig.dcb.fOutX=FALSE; Win_CommConfig.dcb.fAbortOnError=FALSE; Win_CommConfig.dcb.fNull=FALSE; setBaudRate(Settings.BaudRate); setDataBits(Settings.DataBits); setStopBits(Settings.StopBits); setParity(Settings.Parity); setFlowControl(Settings.FlowControl); setTimeout(Settings.Timeout_Millisec); SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); //init event driven approach if (queryMode() == QextSerialBase::EventDriven) { Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD; Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0; Win_CommTimeouts.ReadTotalTimeoutConstant = 0; Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0; Win_CommTimeouts.WriteTotalTimeoutConstant = 0; SetCommTimeouts(Win_Handle, &Win_CommTimeouts); if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) { qWarning("Failed to set Comm Mask. Error code: %ld", GetLastError()); UNLOCK_MUTEX(); return false; } overlapThread->start(); } QIODevice::open(mode); } } else { UNLOCK_MUTEX(); return false; } UNLOCK_MUTEX(); return isOpen(); } /*! \fn void Win_QextSerialPort::close() Closes a serial port. This function has no effect if the serial port associated with the class is not currently open. */ void Win_QextSerialPort::close() { LOCK_MUTEX(); if (isOpen()) { flush(); if (overlapThread->isRunning()) { overlapThread->stop(); if (QThread::currentThread() != overlapThread) overlapThread->wait(); } if (CloseHandle(Win_Handle)) Win_Handle = INVALID_HANDLE_VALUE; _bytesToWrite = 0; QIODevice::close(); } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::flush() Flushes all pending I/O to the serial port. This function has no effect if the serial port associated with the class is not currently open. */ void Win_QextSerialPort::flush() { LOCK_MUTEX(); if (isOpen()) { FlushFileBuffers(Win_Handle); } UNLOCK_MUTEX(); } /*! \fn qint64 Win_QextSerialPort::size() const This function will return the number of bytes waiting in the receive queue of the serial port. It is included primarily to provide a complete QIODevice interface, and will not record errors in the lastErr member (because it is const). This function is also not thread-safe - in multithreading situations, use Win_QextSerialPort::bytesAvailable() instead. */ qint64 Win_QextSerialPort::size() const { int availBytes; COMSTAT Win_ComStat; DWORD Win_ErrorMask=0; ClearCommError(Win_Handle, &Win_ErrorMask, &Win_ComStat); availBytes = Win_ComStat.cbInQue; return (qint64)availBytes; } /*! \fn qint64 Win_QextSerialPort::bytesAvailable() Returns the number of bytes waiting in the port's receive queue. This function will return 0 if the port is not currently open, or -1 on error. Error information can be retrieved by calling Win_QextSerialPort::getLastError(). */ qint64 Win_QextSerialPort::bytesAvailable() { LOCK_MUTEX(); if (isOpen()) { DWORD Errors; COMSTAT Status; bool success=ClearCommError(Win_Handle, &Errors, &Status); translateError(Errors); if (success) { lastErr=E_NO_ERROR; UNLOCK_MUTEX(); return Status.cbInQue + QIODevice::bytesAvailable(); } UNLOCK_MUTEX(); return (unsigned int)-1; } UNLOCK_MUTEX(); return 0; } /*! \fn void Win_QextSerialPort::translateError(ulong error) Translates a system-specific error code to a QextSerialPort error code. Used internally. */ void Win_QextSerialPort::translateError(ulong error) { if (error&CE_BREAK) { lastErr=E_BREAK_CONDITION; } else if (error&CE_FRAME) { lastErr=E_FRAMING_ERROR; } else if (error&CE_IOE) { lastErr=E_IO_ERROR; } else if (error&CE_MODE) { lastErr=E_INVALID_FD; } else if (error&CE_OVERRUN) { lastErr=E_BUFFER_OVERRUN; } else if (error&CE_RXPARITY) { lastErr=E_RECEIVE_PARITY_ERROR; } else if (error&CE_RXOVER) { lastErr=E_RECEIVE_OVERFLOW; } else if (error&CE_TXFULL) { lastErr=E_TRANSMIT_OVERFLOW; } } /*! \fn qint64 Win_QextSerialPort::readData(char *data, qint64 maxSize) Reads a block of data from the serial port. This function will read at most maxlen bytes from the serial port and place them in the buffer pointed to by data. Return value is the number of bytes actually read, or -1 on error. \warning before calling this function ensure that serial port associated with this class is currently open (use isOpen() function to check if port is open). */ qint64 Win_QextSerialPort::readData(char *data, qint64 maxSize) { DWORD retVal; LOCK_MUTEX(); retVal = 0; if (queryMode() == QextSerialBase::EventDriven) { OVERLAPPED overlapRead; overlapRead.Internal = 0; overlapRead.InternalHigh = 0; overlapRead.Offset = 0; overlapRead.OffsetHigh = 0; overlapRead.hEvent = CreateEvent(NULL, true, false, NULL); if (!ReadFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, & overlapRead)) { if (GetLastError() == ERROR_IO_PENDING) GetOverlappedResult(Win_Handle, & overlapRead, & retVal, true); else { lastErr = E_READ_FAILED; retVal = (DWORD)-1; } } CloseHandle(overlapRead.hEvent); } else if (!ReadFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, NULL)) { lastErr = E_READ_FAILED; retVal = (DWORD)-1; } UNLOCK_MUTEX(); return (qint64)retVal; } /*! \fn qint64 Win_QextSerialPort::writeData(const char *data, qint64 maxSize) Writes a block of data to the serial port. This function will write len bytes from the buffer pointed to by data to the serial port. Return value is the number of bytes actually written, or -1 on error. \warning before calling this function ensure that serial port associated with this class is currently open (use isOpen() function to check if port is open). */ qint64 Win_QextSerialPort::writeData(const char *data, qint64 maxSize) { DWORD retVal; LOCK_MUTEX(); retVal = 0; if (queryMode() == QextSerialBase::EventDriven) { bytesToWriteLock->lockForWrite(); _bytesToWrite += maxSize; bytesToWriteLock->unlock(); overlapWrite.Internal = 0; overlapWrite.InternalHigh = 0; overlapWrite.Offset = 0; overlapWrite.OffsetHigh = 0; overlapWrite.hEvent = CreateEvent(NULL, true, false, NULL); if (!WriteFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, & overlapWrite)) { lastErr = E_WRITE_FAILED; retVal = (DWORD)-1; } else retVal = maxSize; } else if (!WriteFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, NULL)) { lastErr = E_WRITE_FAILED; retVal = (DWORD)-1; } UNLOCK_MUTEX(); return (qint64)retVal; } /*! \fn void Win_QextSerialPort::ungetChar(char c) This function is included to implement the full QIODevice interface, and currently has no purpose within this class. This function is meaningless on an unbuffered device and currently only prints a warning message to that effect. */ void Win_QextSerialPort::ungetChar(char c) { /*meaningless on unbuffered sequential device - return error and print a warning*/ TTY_WARNING("Win_QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless"); } /*! \fn void Win_QextSerialPort::setFlowControl(FlowType flow) Sets the flow control used by the port. Possible values of flow are: \verbatim FLOW_OFF No flow control FLOW_HARDWARE Hardware (RTS/CTS) flow control FLOW_XONXOFF Software (XON/XOFF) flow control \endverbatim */ void Win_QextSerialPort::setFlowControl(FlowType flow) { LOCK_MUTEX(); if (Settings.FlowControl!=flow) { Settings.FlowControl=flow; } if (isOpen()) { switch(flow) { /*no flow control*/ case FLOW_OFF: Win_CommConfig.dcb.fOutxCtsFlow=FALSE; Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_DISABLE; Win_CommConfig.dcb.fInX=FALSE; Win_CommConfig.dcb.fOutX=FALSE; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); break; /*software (XON/XOFF) flow control*/ case FLOW_XONXOFF: Win_CommConfig.dcb.fOutxCtsFlow=FALSE; Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_DISABLE; Win_CommConfig.dcb.fInX=TRUE; Win_CommConfig.dcb.fOutX=TRUE; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); break; case FLOW_HARDWARE: Win_CommConfig.dcb.fOutxCtsFlow=TRUE; Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_HANDSHAKE; Win_CommConfig.dcb.fInX=FALSE; Win_CommConfig.dcb.fOutX=FALSE; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); break; } } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::setParity(ParityType parity) Sets the parity associated with the serial port. The possible values of parity are: \verbatim PAR_SPACE Space Parity PAR_MARK Mark Parity PAR_NONE No Parity PAR_EVEN Even Parity PAR_ODD Odd Parity \endverbatim */ void Win_QextSerialPort::setParity(ParityType parity) { LOCK_MUTEX(); if (Settings.Parity!=parity) { Settings.Parity=parity; } if (isOpen()) { Win_CommConfig.dcb.Parity=(unsigned char)parity; switch (parity) { /*space parity*/ case PAR_SPACE: if (Settings.DataBits==DATA_8) { TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: Space parity with 8 data bits is not supported by POSIX systems."); } Win_CommConfig.dcb.fParity=TRUE; break; /*mark parity - WINDOWS ONLY*/ case PAR_MARK: TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: Mark parity is not supported by POSIX systems"); Win_CommConfig.dcb.fParity=TRUE; break; /*no parity*/ case PAR_NONE: Win_CommConfig.dcb.fParity=FALSE; break; /*even parity*/ case PAR_EVEN: Win_CommConfig.dcb.fParity=TRUE; break; /*odd parity*/ case PAR_ODD: Win_CommConfig.dcb.fParity=TRUE; break; } SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::setDataBits(DataBitsType dataBits) Sets the number of data bits used by the serial port. Possible values of dataBits are: \verbatim DATA_5 5 data bits DATA_6 6 data bits DATA_7 7 data bits DATA_8 8 data bits \endverbatim \note This function is subject to the following restrictions: \par 5 data bits cannot be used with 2 stop bits. \par 1.5 stop bits can only be used with 5 data bits. \par 8 data bits cannot be used with space parity on POSIX systems. */ void Win_QextSerialPort::setDataBits(DataBitsType dataBits) { LOCK_MUTEX(); if (Settings.DataBits!=dataBits) { if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) || (Settings.StopBits==STOP_1_5 && dataBits!=DATA_5)) { } else { Settings.DataBits=dataBits; } } if (isOpen()) { switch(dataBits) { /*5 data bits*/ case DATA_5: if (Settings.StopBits==STOP_2) { TTY_WARNING("Win_QextSerialPort: 5 Data bits cannot be used with 2 stop bits."); } else { Win_CommConfig.dcb.ByteSize=5; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } break; /*6 data bits*/ case DATA_6: if (Settings.StopBits==STOP_1_5) { TTY_WARNING("Win_QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits."); } else { Win_CommConfig.dcb.ByteSize=6; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } break; /*7 data bits*/ case DATA_7: if (Settings.StopBits==STOP_1_5) { TTY_WARNING("Win_QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits."); } else { Win_CommConfig.dcb.ByteSize=7; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } break; /*8 data bits*/ case DATA_8: if (Settings.StopBits==STOP_1_5) { TTY_WARNING("Win_QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits."); } else { Win_CommConfig.dcb.ByteSize=8; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } break; } } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::setStopBits(StopBitsType stopBits) Sets the number of stop bits used by the serial port. Possible values of stopBits are: \verbatim STOP_1 1 stop bit STOP_1_5 1.5 stop bits STOP_2 2 stop bits \endverbatim \note This function is subject to the following restrictions: \par 2 stop bits cannot be used with 5 data bits. \par 1.5 stop bits cannot be used with 6 or more data bits. \par POSIX does not support 1.5 stop bits. */ void Win_QextSerialPort::setStopBits(StopBitsType stopBits) { LOCK_MUTEX(); if (Settings.StopBits!=stopBits) { if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) || (stopBits==STOP_1_5 && Settings.DataBits!=DATA_5)) { } else { Settings.StopBits=stopBits; } } if (isOpen()) { switch (stopBits) { /*one stop bit*/ case STOP_1: Win_CommConfig.dcb.StopBits=ONESTOPBIT; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); break; /*1.5 stop bits*/ case STOP_1_5: TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: 1.5 stop bit operation is not supported by POSIX."); if (Settings.DataBits!=DATA_5) { TTY_WARNING("Win_QextSerialPort: 1.5 stop bits can only be used with 5 data bits"); } else { Win_CommConfig.dcb.StopBits=ONE5STOPBITS; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } break; /*two stop bits*/ case STOP_2: if (Settings.DataBits==DATA_5) { TTY_WARNING("Win_QextSerialPort: 2 stop bits cannot be used with 5 data bits"); } else { Win_CommConfig.dcb.StopBits=TWOSTOPBITS; SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } break; } } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::setBaudRate(BaudRateType baudRate) Sets the baud rate of the serial port. Note that not all rates are applicable on all platforms. The following table shows translations of the various baud rate constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an * are speeds that are usable on both Windows and POSIX. \verbatim RATE Windows Speed POSIX Speed ----------- ------------- ----------- BAUD50 110 50 BAUD75 110 75 *BAUD110 110 110 BAUD134 110 134.5 BAUD150 110 150 BAUD200 110 200 *BAUD300 300 300 *BAUD600 600 600 *BAUD1200 1200 1200 BAUD1800 1200 1800 *BAUD2400 2400 2400 *BAUD4800 4800 4800 *BAUD9600 9600 9600 BAUD14400 14400 9600 *BAUD19200 19200 19200 *BAUD38400 38400 38400 BAUD56000 56000 38400 *BAUD57600 57600 57600 BAUD76800 57600 76800 *BAUD115200 115200 115200 BAUD128000 128000 115200 BAUD256000 256000 115200 \endverbatim */ void Win_QextSerialPort::setBaudRate(BaudRateType baudRate) { LOCK_MUTEX(); if (Settings.BaudRate!=baudRate) { switch (baudRate) { case BAUD50: case BAUD75: case BAUD134: case BAUD150: case BAUD200: Settings.BaudRate=BAUD110; break; case BAUD1800: Settings.BaudRate=BAUD1200; break; case BAUD76800: Settings.BaudRate=BAUD57600; break; default: Settings.BaudRate=baudRate; break; } } if (isOpen()) { switch (baudRate) { /*50 baud*/ case BAUD50: TTY_WARNING("Win_QextSerialPort: Windows does not support 50 baud operation. Switching to 110 baud."); Win_CommConfig.dcb.BaudRate=CBR_110; break; /*75 baud*/ case BAUD75: TTY_WARNING("Win_QextSerialPort: Windows does not support 75 baud operation. Switching to 110 baud."); Win_CommConfig.dcb.BaudRate=CBR_110; break; /*110 baud*/ case BAUD110: Win_CommConfig.dcb.BaudRate=CBR_110; break; /*134.5 baud*/ case BAUD134: TTY_WARNING("Win_QextSerialPort: Windows does not support 134.5 baud operation. Switching to 110 baud."); Win_CommConfig.dcb.BaudRate=CBR_110; break; /*150 baud*/ case BAUD150: TTY_WARNING("Win_QextSerialPort: Windows does not support 150 baud operation. Switching to 110 baud."); Win_CommConfig.dcb.BaudRate=CBR_110; break; /*200 baud*/ case BAUD200: TTY_WARNING("Win_QextSerialPort: Windows does not support 200 baud operation. Switching to 110 baud."); Win_CommConfig.dcb.BaudRate=CBR_110; break; /*300 baud*/ case BAUD300: Win_CommConfig.dcb.BaudRate=CBR_300; break; /*600 baud*/ case BAUD600: Win_CommConfig.dcb.BaudRate=CBR_600; break; /*1200 baud*/ case BAUD1200: Win_CommConfig.dcb.BaudRate=CBR_1200; break; /*1800 baud*/ case BAUD1800: TTY_WARNING("Win_QextSerialPort: Windows does not support 1800 baud operation. Switching to 1200 baud."); Win_CommConfig.dcb.BaudRate=CBR_1200; break; /*2400 baud*/ case BAUD2400: Win_CommConfig.dcb.BaudRate=CBR_2400; break; /*4800 baud*/ case BAUD4800: Win_CommConfig.dcb.BaudRate=CBR_4800; break; /*9600 baud*/ case BAUD9600: Win_CommConfig.dcb.BaudRate=CBR_9600; break; /*14400 baud*/ case BAUD14400: TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: POSIX does not support 14400 baud operation."); Win_CommConfig.dcb.BaudRate=CBR_14400; break; /*19200 baud*/ case BAUD19200: Win_CommConfig.dcb.BaudRate=CBR_19200; break; /*38400 baud*/ case BAUD38400: Win_CommConfig.dcb.BaudRate=CBR_38400; break; /*56000 baud*/ case BAUD56000: TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: POSIX does not support 56000 baud operation."); Win_CommConfig.dcb.BaudRate=CBR_56000; break; /*57600 baud*/ case BAUD57600: Win_CommConfig.dcb.BaudRate=CBR_57600; break; /*76800 baud*/ case BAUD76800: TTY_WARNING("Win_QextSerialPort: Windows does not support 76800 baud operation. Switching to 57600 baud."); Win_CommConfig.dcb.BaudRate=CBR_57600; break; /*115200 baud*/ case BAUD115200: Win_CommConfig.dcb.BaudRate=CBR_115200; break; /*128000 baud*/ case BAUD128000: TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: POSIX does not support 128000 baud operation."); Win_CommConfig.dcb.BaudRate=CBR_128000; break; /*256000 baud*/ case BAUD256000: TTY_PORTABILITY_WARNING("Win_QextSerialPort Portability Warning: POSIX does not support 256000 baud operation."); Win_CommConfig.dcb.BaudRate=CBR_256000; break; } SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG)); } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::setDtr(bool set) Sets DTR line to the requested state (high by default). This function will have no effect if the port associated with the class is not currently open. */ void Win_QextSerialPort::setDtr(bool set) { LOCK_MUTEX(); if (isOpen()) { if (set) { EscapeCommFunction(Win_Handle, SETDTR); } else { EscapeCommFunction(Win_Handle, CLRDTR); } } UNLOCK_MUTEX(); } /*! \fn void Win_QextSerialPort::setRts(bool set) Sets RTS line to the requested state (high by default). This function will have no effect if the port associated with the class is not currently open. */ void Win_QextSerialPort::setRts(bool set) { LOCK_MUTEX(); if (isOpen()) { if (set) { EscapeCommFunction(Win_Handle, SETRTS); } else { EscapeCommFunction(Win_Handle, CLRRTS); } } UNLOCK_MUTEX(); } /*! \fn ulong Win_QextSerialPort::lineStatus(void) returns the line status as stored by the port function. This function will retrieve the states of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned long with specific bits indicating which lines are high. The following constants should be used to examine the states of individual lines: \verbatim Mask Line ------ ---- LS_CTS CTS LS_DSR DSR LS_DCD DCD LS_RI RI \endverbatim This function will return 0 if the port associated with the class is not currently open. */ ulong Win_QextSerialPort::lineStatus(void) { unsigned long Status=0, Temp=0; LOCK_MUTEX(); if (isOpen()) { GetCommModemStatus(Win_Handle, &Temp); if (Temp&MS_CTS_ON) { Status|=LS_CTS; } if (Temp&MS_DSR_ON) { Status|=LS_DSR; } if (Temp&MS_RING_ON) { Status|=LS_RI; } if (Temp&MS_RLSD_ON) { Status|=LS_DCD; } } UNLOCK_MUTEX(); return Status; } bool Win_QextSerialPort::waitForReadyRead(int msecs) { //@todo implement return false; } qint64 Win_QextSerialPort::bytesToWrite() const { return _bytesToWrite; } void Win_QextSerialPort::monitorCommEvent() { DWORD eventMask = 0; ResetEvent(overlap.hEvent); if (!WaitCommEvent(Win_Handle, & eventMask, & overlap)) if (GetLastError() != ERROR_IO_PENDING) qCritical("WaitCommEvent error %ld\n", GetLastError()); if (WaitForSingleObject(overlap.hEvent, INFINITE) == WAIT_OBJECT_0) { //overlap event occured DWORD undefined; if (!GetOverlappedResult(Win_Handle, & overlap, & undefined, false)) { qWarning("Comm event overlapped error %ld", GetLastError()); return; } if (eventMask & EV_RXCHAR) { if (sender() != this) emit readyRead(); } if (eventMask & EV_TXEMPTY) { DWORD numBytes; GetOverlappedResult(Win_Handle, & overlapWrite, & numBytes, true); bytesToWriteLock->lockForWrite(); if (sender() != this) emit bytesWritten(bytesToWrite()); _bytesToWrite = 0; bytesToWriteLock->unlock(); } if (eventMask & EV_DSR) if (lineStatus() & LS_DSR) emit dsrChanged(true); else emit dsrChanged(false); } } void Win_QextSerialPort::terminateCommWait() { SetCommMask(Win_Handle, 0); } /*! \fn void Win_QextSerialPort::setTimeout(ulong millisec); Sets the read and write timeouts for the port to millisec milliseconds. Setting 0 for both sec and millisec indicates that timeouts are not used for read nor write operations. Setting -1 indicates that read and write should return immediately. \note this function does nothing in event driven mode. */ void Win_QextSerialPort::setTimeout(long millisec) { LOCK_MUTEX(); Settings.Timeout_Millisec = millisec; if (millisec == -1) { Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD; Win_CommTimeouts.ReadTotalTimeoutConstant = 0; } else { Win_CommTimeouts.ReadIntervalTimeout = millisec; Win_CommTimeouts.ReadTotalTimeoutConstant = millisec; } Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0; Win_CommTimeouts.WriteTotalTimeoutMultiplier = millisec; Win_CommTimeouts.WriteTotalTimeoutConstant = 0; if (queryMode() != QextSerialBase::EventDriven) SetCommTimeouts(Win_Handle, &Win_CommTimeouts); UNLOCK_MUTEX(); } Win_QextSerialThread::Win_QextSerialThread(Win_QextSerialPort * qesp): QThread() { this->qesp = qesp; terminate = false; } void Win_QextSerialThread::stop() { terminate = true; qesp->terminateCommWait(); } void Win_QextSerialThread::run() { while (!terminate) qesp->monitorCommEvent(); terminate = false; }
[ [ [ 1, 1049 ] ] ]
7bf9c1773048762b69fdd3736e8d1a271ea0c618
1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50
/bumblebee_driver_test.exe/main.cpp
29a2a76687901873b4ed955e1baca7273d336f86
[]
no_license
llvllrbreeze/alcorapp
dfe2551f36d346d73d998f59d602c5de46ef60f7
3ad24edd52c19f0896228f55539aa8bbbb011aac
refs/heads/master
2021-01-10T07:36:01.058011
2008-12-16T12:51:50
2008-12-16T12:51:50
47,865,136
0
0
null
null
null
null
UTF-8
C++
false
false
1,680
cpp
#include "alcor/sense/bumblebee_ipc_recv_t.h" #include "alcor.extern/CImg/CImg.h" using namespace all; using namespace cimg_library; int main () { sense::bumblebee_ipc_recv_t beeA; if (beeA.open("config/bumblebeeB.ini")) { //printf("Tout bien!\n"); printf("Height: %d Width: %d\n",beeA.height(),beeA.width()); printf("Channels %d\n", beeA.channels() ); printf("Focal %f\n",beeA.focal()); } CImgDisplay displ(beeA.width(), beeA.height(), "Bumblebee Left"); CImgDisplay dispr(beeA.width(), beeA.height(), "Bumblebee Right"); CImg<core::uint8_t> left; CImg<core::uint8_t> right; while( dispr.key != cimg::keyESC && displ.key != cimg::keyESC && !dispr.is_closed && !displ.is_closed) { //beeA.lock(); core::uint8_sarr imgl = beeA.get_color_buffer(core::left_img); core::uint8_sarr imgr = beeA.get_color_buffer(core::right_img); if(!imgr || !imgl) printf("What?\n"); else { left.assign(imgl.get(), beeA.width(), beeA.height(),1,3); right.assign(imgr.get(), beeA.width(), beeA.height(),1,3); left.display(displ); right.display(dispr); } //beeA.unlock(); if( dispr.button&1 && dispr.mouse_y >= 0) { dispr.button&=~1; printf(" Left Button clicked "); printf("x: %d y: %d\n",dispr.mouse_x, dispr.mouse_y); } if( dispr.button&2 && dispr.mouse_y >= 0) { dispr.button&=~2; printf(" Right Button clicked"); printf("x: %d y: %d\n",dispr.mouse_x, dispr.mouse_y); } cimg::wait(50); } }
[ "andrea.carbone@1ffd000b-a628-0410-9a29-793f135cad17" ]
[ [ [ 1, 63 ] ] ]
f73f8eaa8714dcc7c0e43728bf91bd9fabb20b1f
01c236af2890d74ca5b7c25cec5e7b1686283c48
/Src/PlayersCard.h
77f03d2bd3e3986dfe93ddb6e50db679c49acc89
[ "MIT" ]
permissive
muffinista/palm-pitch
80c5900d4f623204d3b837172eefa09c4efbe5e3
aa09c857b1ccc14672b3eb038a419bd13abc0925
refs/heads/master
2021-01-19T05:43:04.740676
2010-07-08T14:42:18
2010-07-08T14:42:18
763,958
1
0
null
null
null
null
UTF-8
C++
false
false
250
h
#ifndef PLAYERSCARD_H #define PLAYERSCARD_H #include "Player.h" #include "Card.h" class Player; class Card; class PlayersCard { public: PlayersCard(Player *, Card *); ~PlayersCard(); Player *p; Card *c; }; #endif
[ [ [ 1, 21 ] ] ]
d0bbe836a9bebf627a3dc55461ef7d220a9ff043
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/win/WebFrame.h
04171465c054b5a8ea5358c0803abb6e0fbd7925
[ "BSD-2-Clause" ]
permissive
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,386
h
/* * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 WebFrame_H #define WebFrame_H #include "WebFrameLoaderClient.h" #include "WebKit.h" #include "WebDataSource.h" #include "AccessibleDocument.h" #pragma warning(push, 0) #include <WebCore/FrameWin.h> #include <WebCore/GraphicsContext.h> #include <WebCore/KURL.h> #include <WebCore/PlatformString.h> #include <WebCore/ResourceHandleClient.h> #pragma warning(pop) #include <WTF/RefPtr.h> #include <WTF/HashMap.h> #include <WTF/OwnPtr.h> namespace WebCore { class AuthenticationChallenge; class DocumentLoader; class Element; class Frame; class GraphicsContext; class HTMLFrameOwnerElement; class IntRect; class Page; class ResourceError; class SharedBuffer; } typedef const struct OpaqueJSContext* JSContextRef; typedef struct OpaqueJSValue* JSObjectRef; #if PLATFORM(CG) typedef struct CGContext PlatformGraphicsContext; #elif PLATFORM(CAIRO) typedef struct _cairo PlatformGraphicsContext; #endif class WebFrame; class WebFramePolicyListener; class WebHistory; class WebView; interface IWebHistoryItemPrivate; WebFrame* kit(WebCore::Frame*); WebCore::Frame* core(WebFrame*); class DECLSPEC_UUID("{A3676398-4485-4a9d-87DC-CB5A40E6351D}") WebFrame : public IWebFrame, IWebFramePrivate, IWebDocumentText , public WebFrameLoaderClient { public: static WebFrame* createInstance(); protected: WebFrame(); ~WebFrame(); public: // IUnknown virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef(void); virtual ULONG STDMETHODCALLTYPE Release(void); //IWebFrame virtual HRESULT STDMETHODCALLTYPE name( /* [retval][out] */ BSTR *frameName); virtual HRESULT STDMETHODCALLTYPE webView( /* [retval][out] */ IWebView **view); virtual HRESULT STDMETHODCALLTYPE frameView( /* [retval][out] */ IWebFrameView **view); virtual HRESULT STDMETHODCALLTYPE DOMDocument( /* [retval][out] */ IDOMDocument** document); virtual HRESULT STDMETHODCALLTYPE frameElement( /* [retval][out] */ IDOMHTMLElement **frameElement); virtual HRESULT STDMETHODCALLTYPE loadRequest( /* [in] */ IWebURLRequest *request); virtual HRESULT STDMETHODCALLTYPE loadData( /* [in] */ IStream *data, /* [in] */ BSTR mimeType, /* [in] */ BSTR textEncodingName, /* [in] */ BSTR url); virtual HRESULT STDMETHODCALLTYPE loadHTMLString( /* [in] */ BSTR string, /* [in] */ BSTR baseURL); virtual HRESULT STDMETHODCALLTYPE loadAlternateHTMLString( /* [in] */ BSTR str, /* [in] */ BSTR baseURL, /* [in] */ BSTR unreachableURL); virtual HRESULT STDMETHODCALLTYPE loadArchive( /* [in] */ IWebArchive *archive); virtual HRESULT STDMETHODCALLTYPE dataSource( /* [retval][out] */ IWebDataSource **source); virtual HRESULT STDMETHODCALLTYPE provisionalDataSource( /* [retval][out] */ IWebDataSource **source); virtual HRESULT STDMETHODCALLTYPE stopLoading( void); virtual HRESULT STDMETHODCALLTYPE reload( void); virtual HRESULT STDMETHODCALLTYPE findFrameNamed( /* [in] */ BSTR name, /* [retval][out] */ IWebFrame **frame); virtual HRESULT STDMETHODCALLTYPE parentFrame( /* [retval][out] */ IWebFrame **frame); virtual HRESULT STDMETHODCALLTYPE childFrames( /* [retval][out] */ IEnumVARIANT **enumFrames); virtual HRESULT STDMETHODCALLTYPE currentForm( /* [retval][out] */ IDOMElement **formElement); virtual /* [local] */ JSGlobalContextRef STDMETHODCALLTYPE globalContext(); // IWebFramePrivate virtual HRESULT STDMETHODCALLTYPE unused1(BSTR*) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE renderTreeAsExternalRepresentation(BOOL forPrinting, BSTR *result); virtual HRESULT STDMETHODCALLTYPE counterValueForElementById( /* [in] */ BSTR id, /* [retval][out] */ BSTR *result); virtual HRESULT STDMETHODCALLTYPE pageNumberForElementById( /* [in] */ BSTR id, /* [in] */ float pageWidthInPixels, /* [in] */ float pageHeightInPixels, /* [retval][out] */ int* result); virtual HRESULT STDMETHODCALLTYPE numberOfPages( /* [in] */ float pageWidthInPixels, /* [in] */ float pageHeightInPixels, /* [retval][out] */ int* result); virtual HRESULT STDMETHODCALLTYPE scrollOffset( /* [retval][out] */ SIZE* offset); virtual HRESULT STDMETHODCALLTYPE layout(); virtual HRESULT STDMETHODCALLTYPE firstLayoutDone( /* [retval][out] */ BOOL* result); virtual HRESULT STDMETHODCALLTYPE loadType( /* [retval][out] */ WebFrameLoadType* type); virtual HRESULT STDMETHODCALLTYPE pendingFrameUnloadEventCount( /* [retval][out] */ UINT* result); virtual HRESULT STDMETHODCALLTYPE fetchApplicationIcon( /* [in] */ IWebIconFetcherDelegate *delegate, /* [retval][out] */ IWebIconFetcher **result); virtual HRESULT STDMETHODCALLTYPE setInPrintingMode( /* [in] */ BOOL value, /* [in] */ HDC printDC); virtual HRESULT STDMETHODCALLTYPE getPrintedPageCount( /* [in] */ HDC printDC, /* [retval][out] */ UINT *pageCount); virtual HRESULT STDMETHODCALLTYPE spoolPages( /* [in] */ HDC printDC, /* [in] */ UINT startPage, /* [in] */ UINT endPage, /* [retval][out] */ void* ctx); virtual HRESULT STDMETHODCALLTYPE isFrameSet( /* [retval][out] */ BOOL* result); virtual HRESULT STDMETHODCALLTYPE string( /* [retval][out] */ BSTR* result); virtual HRESULT STDMETHODCALLTYPE size( /* [retval][out] */ SIZE *size); virtual HRESULT STDMETHODCALLTYPE hasScrollBars( /* [retval][out] */ BOOL *result); virtual HRESULT STDMETHODCALLTYPE contentBounds( /* [retval][out] */ RECT *result); virtual HRESULT STDMETHODCALLTYPE frameBounds( /* [retval][out] */ RECT *result); virtual HRESULT STDMETHODCALLTYPE isDescendantOfFrame( /* [in] */ IWebFrame *ancestor, /* [retval][out] */ BOOL *result); virtual HRESULT STDMETHODCALLTYPE setAllowsScrolling( /* [in] */ BOOL flag); virtual HRESULT STDMETHODCALLTYPE allowsScrolling( /* [retval][out] */ BOOL *flag); virtual HRESULT STDMETHODCALLTYPE setIsDisconnected( /* [in] */ BOOL flag); virtual HRESULT STDMETHODCALLTYPE setExcludeFromTextSearch( /* [in] */ BOOL flag); virtual HRESULT STDMETHODCALLTYPE reloadFromOrigin(); virtual HRESULT STDMETHODCALLTYPE paintDocumentRectToContext( /* [in] */ RECT rect, /* [in] */ OLE_HANDLE deviceContext); virtual HRESULT STDMETHODCALLTYPE paintScrollViewRectToContextAtPoint( /* [in] */ RECT rect, /* [in] */ POINT pt, /* [in] */ OLE_HANDLE deviceContext); virtual HRESULT STDMETHODCALLTYPE elementDoesAutoComplete( /* [in] */ IDOMElement* element, /* [retval][out] */ BOOL* result); virtual HRESULT STDMETHODCALLTYPE pauseAnimation(BSTR animationName, IDOMNode*, double secondsFromNow, BOOL* animationWasRunning); virtual HRESULT STDMETHODCALLTYPE pauseTransition(BSTR propertyName, IDOMNode*, double secondsFromNow, BOOL* transitionWasRunning); virtual HRESULT STDMETHODCALLTYPE pauseSVGAnimation(BSTR elementId, IDOMNode*, double secondsFromNow, BOOL* animationWasRunning); virtual HRESULT STDMETHODCALLTYPE numberOfActiveAnimations(UINT*); virtual HRESULT STDMETHODCALLTYPE suspendAnimations(); virtual HRESULT STDMETHODCALLTYPE resumeAnimations(); virtual HRESULT STDMETHODCALLTYPE isDisplayingStandaloneImage(BOOL*); virtual HRESULT STDMETHODCALLTYPE allowsFollowingLink( /* [in] */ BSTR url, /* [retval][out] */ BOOL* result); virtual HRESULT STDMETHODCALLTYPE stringByEvaluatingJavaScriptInScriptWorld(IWebScriptWorld*, JSObjectRef globalObjectRef, BSTR script, BSTR* evaluationResult); virtual JSGlobalContextRef STDMETHODCALLTYPE globalContextForScriptWorld(IWebScriptWorld*); virtual HRESULT STDMETHODCALLTYPE visibleContentRect(RECT*); virtual HRESULT STDMETHODCALLTYPE layerTreeAsText(BSTR*); // IWebDocumentText virtual HRESULT STDMETHODCALLTYPE supportsTextEncoding( /* [retval][out] */ BOOL* result); virtual HRESULT STDMETHODCALLTYPE selectedString( /* [retval][out] */ BSTR* result); virtual HRESULT STDMETHODCALLTYPE selectAll(); virtual HRESULT STDMETHODCALLTYPE deselectAll(); // FrameLoaderClient virtual void frameLoaderDestroyed(); virtual void makeRepresentation(WebCore::DocumentLoader*); virtual void forceLayoutForNonHTML(); virtual void setCopiesOnScroll(); virtual void detachedFromParent2(); virtual void detachedFromParent3(); virtual void cancelPolicyCheck(); virtual void dispatchWillSendSubmitEvent(WebCore::HTMLFormElement*) { } virtual void dispatchWillSubmitForm(WebCore::FramePolicyFunction, PassRefPtr<WebCore::FormState>); virtual void revertToProvisionalState(WebCore::DocumentLoader*); virtual void setMainFrameDocumentReady(bool); virtual void willChangeTitle(WebCore::DocumentLoader*); virtual void didChangeTitle(WebCore::DocumentLoader*); virtual void didChangeIcons(WebCore::DocumentLoader*); virtual bool canHandleRequest(const WebCore::ResourceRequest&) const; virtual bool canShowMIMEType(const WTF::String& MIMEType) const; virtual bool canShowMIMETypeAsHTML(const WTF::String& MIMEType) const; virtual bool representationExistsForURLScheme(const WTF::String& URLScheme) const; virtual WTF::String generatedMIMETypeForURLScheme(const WTF::String& URLScheme) const; virtual void frameLoadCompleted(); virtual void restoreViewState(); virtual void provisionalLoadStarted(); virtual bool shouldTreatURLAsSameAsCurrent(const WebCore::KURL&) const; virtual void addHistoryItemForFragmentScroll(); virtual void didFinishLoad(); virtual void prepareForDataSourceReplacement(); virtual WTF::String userAgent(const WebCore::KURL&); virtual void saveViewStateToItem(WebCore::HistoryItem *); virtual WebCore::ResourceError cancelledError(const WebCore::ResourceRequest&); virtual WebCore::ResourceError blockedError(const WebCore::ResourceRequest&); virtual WebCore::ResourceError cannotShowURLError(const WebCore::ResourceRequest&); virtual WebCore::ResourceError interruptForPolicyChangeError(const WebCore::ResourceRequest&); virtual WebCore::ResourceError cannotShowMIMETypeError(const WebCore::ResourceResponse&); virtual WebCore::ResourceError fileDoesNotExistError(const WebCore::ResourceResponse&); virtual WebCore::ResourceError pluginWillHandleLoadError(const WebCore::ResourceResponse&); virtual bool shouldFallBack(const WebCore::ResourceError&); virtual void dispatchDecidePolicyForMIMEType(WebCore::FramePolicyFunction, const WTF::String& MIMEType, const WebCore::ResourceRequest&); virtual void dispatchDecidePolicyForNewWindowAction(WebCore::FramePolicyFunction, const WebCore::NavigationAction&, const WebCore::ResourceRequest&, PassRefPtr<WebCore::FormState>, const WTF::String& frameName); virtual void dispatchDecidePolicyForNavigationAction(WebCore::FramePolicyFunction, const WebCore::NavigationAction&, const WebCore::ResourceRequest&, PassRefPtr<WebCore::FormState>); virtual void dispatchUnableToImplementPolicy(const WebCore::ResourceError&); virtual void download(WebCore::ResourceHandle*, const WebCore::ResourceRequest&, const WebCore::ResourceRequest&, const WebCore::ResourceResponse&); virtual bool dispatchDidLoadResourceFromMemoryCache(WebCore::DocumentLoader*, const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, int length); virtual void dispatchDidFailProvisionalLoad(const WebCore::ResourceError&); virtual void dispatchDidFailLoad(const WebCore::ResourceError&); virtual void startDownload(const WebCore::ResourceRequest&); virtual PassRefPtr<WebCore::Widget> createJavaAppletWidget(const WebCore::IntSize&, WebCore::HTMLAppletElement*, const WebCore::KURL& baseURL, const Vector<WTF::String>& paramNames, const Vector<WTF::String>& paramValues); virtual WebCore::ObjectContentType objectContentType(const WebCore::KURL& url, const WTF::String& mimeType); virtual WTF::String overrideMediaType() const; virtual void dispatchDidClearWindowObjectInWorld(WebCore::DOMWrapperWorld*); virtual void documentElementAvailable(); virtual void didPerformFirstNavigation() const; virtual void registerForIconNotification(bool listen); virtual PassRefPtr<WebCore::FrameNetworkingContext> createNetworkingContext(); // WebFrame PassRefPtr<WebCore::Frame> init(IWebView*, WebCore::Page*, WebCore::HTMLFrameOwnerElement*); WebCore::Frame* impl(); void invalidate(); void unmarkAllMisspellings(); void unmarkAllBadGrammar(); void updateBackground(); // WebFrame (matching WebCoreFrameBridge) HRESULT inViewSourceMode(BOOL *flag); HRESULT setInViewSourceMode(BOOL flag); HRESULT elementWithName(BSTR name, IDOMElement* form, IDOMElement** element); HRESULT formForElement(IDOMElement* element, IDOMElement** form); HRESULT controlsInForm(IDOMElement* form, IDOMElement** controls, int* cControls); HRESULT elementIsPassword(IDOMElement* element, bool* result); HRESULT searchForLabelsBeforeElement(const BSTR* labels, unsigned cLabels, IDOMElement* beforeElement, unsigned* resultDistance, BOOL* resultIsInCellAbove, BSTR* result); HRESULT matchLabelsAgainstElement(const BSTR* labels, int cLabels, IDOMElement* againstElement, BSTR* result); HRESULT canProvideDocumentSource(bool* result); COMPtr<WebFramePolicyListener> setUpPolicyListener(WebCore::FramePolicyFunction function); void receivedPolicyDecision(WebCore::PolicyAction); WebCore::KURL url() const; WebView* webView() const; COMPtr<IAccessible> accessible() const; protected: void loadHTMLString(BSTR string, BSTR baseURL, BSTR unreachableURL); void loadData(PassRefPtr<WebCore::SharedBuffer>, BSTR mimeType, BSTR textEncodingName, BSTR baseURL, BSTR failingURL); const Vector<WebCore::IntRect>& computePageRects(HDC printDC); void setPrinting(bool printing, float minPageWidth, float maxPageWidth, bool adjustViewSize); void headerAndFooterHeights(float*, float*); WebCore::IntRect printerMarginRect(HDC); void spoolPage (PlatformGraphicsContext* pctx, WebCore::GraphicsContext* spoolCtx, HDC printDC, IWebUIDelegate*, float headerHeight, float footerHeight, UINT page, UINT pageCount); void drawHeader(PlatformGraphicsContext* pctx, IWebUIDelegate*, const WebCore::IntRect& pageRect, float headerHeight); void drawFooter(PlatformGraphicsContext* pctx, IWebUIDelegate*, const WebCore::IntRect& pageRect, UINT page, UINT pageCount, float headerHeight, float footerHeight); protected: ULONG m_refCount; class WebFramePrivate; WebFramePrivate* d; bool m_quickRedirectComing; WebCore::KURL m_originalRequestURL; bool m_inPrintingMode; Vector<WebCore::IntRect> m_pageRects; int m_pageHeight; // height of the page adjusted by margins mutable COMPtr<AccessibleDocument> m_accessible; }; #endif
[ [ [ 1, 401 ] ] ]
f025371e2ce286a7702be50fd9aa76ad6a618454
a2ba072a87ab830f5343022ed11b4ac365f58ef0
/ urt-bumpy-q3map2 --username [email protected]/libs/jpeg6/jdapimin.cpp
9086b490163624f29ac6ae061223071517318806
[]
no_license
Garey27/urt-bumpy-q3map2
7d0849fc8eb333d9007213b641138e8517aa092a
fcc567a04facada74f60306c01e68f410cb5a111
refs/heads/master
2021-01-10T17:24:51.991794
2010-06-22T13:19:24
2010-06-22T13:19:24
43,057,943
0
0
null
null
null
null
UTF-8
C++
false
false
13,644
cpp
/* * jdapimin.c * * Copyright (C) 1994-1995, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface code for the decompression half * of the JPEG library. These are the "minimum" API routines that may be * needed in either the normal full-decompression case or the * transcoding-only case. * * Most of the routines intended to be called directly by an application * are in this file or in jdapistd.c. But also see jcomapi.c for routines * shared by compression and decompression, and jdtrans.c for the transcoding * case. */ #define JPEG_INTERNALS #include "jinclude.h" #include "radiant_jpeglib.h" /* * Initialization of a JPEG decompression object. * The error manager must already be set up (in case memory manager fails). */ GLOBAL void jpeg_create_decompress (j_decompress_ptr cinfo) { int i; /* For debugging purposes, zero the whole master structure. * But error manager pointer is already there, so save and restore it. */ { struct jpeg_error_mgr * err = cinfo->err; i = sizeof(struct jpeg_decompress_struct); i = SIZEOF(struct jpeg_decompress_struct); MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct)); cinfo->err = err; } cinfo->is_decompressor = TRUE; /* Initialize a memory manager instance for this object */ jinit_memory_mgr((j_common_ptr) cinfo); /* Zero out pointers to permanent structures. */ cinfo->progress = NULL; cinfo->src = NULL; for (i = 0; i < NUM_QUANT_TBLS; i++) cinfo->quant_tbl_ptrs[i] = NULL; for (i = 0; i < NUM_HUFF_TBLS; i++) { cinfo->dc_huff_tbl_ptrs[i] = NULL; cinfo->ac_huff_tbl_ptrs[i] = NULL; } /* Initialize marker processor so application can override methods * for COM, APPn markers before calling jpeg_read_header. */ jinit_marker_reader(cinfo); /* And initialize the overall input controller. */ jinit_input_controller(cinfo); /* OK, I'm ready */ cinfo->global_state = DSTATE_START; } /* * Destruction of a JPEG decompression object */ GLOBAL void jpeg_destroy_decompress (j_decompress_ptr cinfo) { jpeg_destroy((j_common_ptr) cinfo); /* use common routine */ } /* * Abort processing of a JPEG decompression operation, * but don't destroy the object itself. */ GLOBAL void jpeg_abort_decompress (j_decompress_ptr cinfo) { jpeg_abort((j_common_ptr) cinfo); /* use common routine */ } /* * Install a special processing method for COM or APPn markers. */ GLOBAL void jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code, jpeg_marker_parser_method routine) { if (marker_code == JPEG_COM) cinfo->marker->process_COM = routine; else if (marker_code >= JPEG_APP0 && marker_code <= JPEG_APP0+15) cinfo->marker->process_APPn[marker_code-JPEG_APP0] = routine; else ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code); } /* * Set default decompression parameters. */ LOCAL void default_decompress_parms (j_decompress_ptr cinfo) { /* Guess the input colorspace, and set output colorspace accordingly. */ /* (Wish JPEG committee had provided a real way to specify this...) */ /* Note application may override our guesses. */ switch (cinfo->num_components) { case 1: cinfo->jpeg_color_space = JCS_GRAYSCALE; cinfo->out_color_space = JCS_GRAYSCALE; break; case 3: if (cinfo->saw_JFIF_marker) { cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */ } else if (cinfo->saw_Adobe_marker) { switch (cinfo->Adobe_transform) { case 0: cinfo->jpeg_color_space = JCS_RGB; break; case 1: cinfo->jpeg_color_space = JCS_YCbCr; break; default: WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform); cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ break; } } else { /* Saw no special markers, try to guess from the component IDs */ int cid0 = cinfo->comp_info[0].component_id; int cid1 = cinfo->comp_info[1].component_id; int cid2 = cinfo->comp_info[2].component_id; if (cid0 == 1 && cid1 == 2 && cid2 == 3) cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */ else if (cid0 == 82 && cid1 == 71 && cid2 == 66) cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */ else { TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2); cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */ } } /* Always guess RGB is proper output colorspace. */ cinfo->out_color_space = JCS_RGB; break; case 4: if (cinfo->saw_Adobe_marker) { switch (cinfo->Adobe_transform) { case 0: cinfo->jpeg_color_space = JCS_CMYK; break; case 2: cinfo->jpeg_color_space = JCS_YCCK; break; default: WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform); cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */ break; } } else { /* No special markers, assume straight CMYK. */ cinfo->jpeg_color_space = JCS_CMYK; } cinfo->out_color_space = JCS_CMYK; break; default: cinfo->jpeg_color_space = JCS_UNKNOWN; cinfo->out_color_space = JCS_UNKNOWN; break; } /* Set defaults for other decompression parameters. */ cinfo->scale_num = 1; /* 1:1 scaling */ cinfo->scale_denom = 1; cinfo->output_gamma = 1.0; cinfo->buffered_image = FALSE; cinfo->raw_data_out = FALSE; cinfo->dct_method = JDCT_DEFAULT; cinfo->do_fancy_upsampling = TRUE; cinfo->do_block_smoothing = TRUE; cinfo->quantize_colors = FALSE; /* We set these in case application only sets quantize_colors. */ cinfo->dither_mode = JDITHER_FS; #ifdef QUANT_2PASS_SUPPORTED cinfo->two_pass_quantize = TRUE; #else cinfo->two_pass_quantize = FALSE; #endif cinfo->desired_number_of_colors = 256; cinfo->colormap = NULL; /* Initialize for no mode change in buffered-image mode. */ cinfo->enable_1pass_quant = FALSE; cinfo->enable_external_quant = FALSE; cinfo->enable_2pass_quant = FALSE; } /* * Decompression startup: read start of JPEG datastream to see what's there. * Need only initialize JPEG object and supply a data source before calling. * * This routine will read as far as the first SOS marker (ie, actual start of * compressed data), and will save all tables and parameters in the JPEG * object. It will also initialize the decompression parameters to default * values, and finally return JPEG_HEADER_OK. On return, the application may * adjust the decompression parameters and then call jpeg_start_decompress. * (Or, if the application only wanted to determine the image parameters, * the data need not be decompressed. In that case, call jpeg_abort or * jpeg_destroy to release any temporary space.) * If an abbreviated (tables only) datastream is presented, the routine will * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then * re-use the JPEG object to read the abbreviated image datastream(s). * It is unnecessary (but OK) to call jpeg_abort in this case. * The JPEG_SUSPENDED return code only occurs if the data source module * requests suspension of the decompressor. In this case the application * should load more source data and then re-call jpeg_read_header to resume * processing. * If a non-suspending data source is used and require_image is TRUE, then the * return code need not be inspected since only JPEG_HEADER_OK is possible. * * This routine is now just a front end to jpeg_consume_input, with some * extra error checking. */ GLOBAL int jpeg_read_header (j_decompress_ptr cinfo, boolean require_image) { int retcode; if (cinfo->global_state != DSTATE_START && cinfo->global_state != DSTATE_INHEADER) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); retcode = jpeg_consume_input(cinfo); switch (retcode) { case JPEG_REACHED_SOS: retcode = JPEG_HEADER_OK; break; case JPEG_REACHED_EOI: if (require_image) /* Complain if application wanted an image */ ERREXIT(cinfo, JERR_NO_IMAGE); /* Reset to start state; it would be safer to require the application to * call jpeg_abort, but we can't change it now for compatibility reasons. * A side effect is to free any temporary memory (there shouldn't be any). */ jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */ retcode = JPEG_HEADER_TABLES_ONLY; break; case JPEG_SUSPENDED: /* no work */ break; } return retcode; } /* * Consume data in advance of what the decompressor requires. * This can be called at any time once the decompressor object has * been created and a data source has been set up. * * This routine is essentially a state machine that handles a couple * of critical state-transition actions, namely initial setup and * transition from header scanning to ready-for-start_decompress. * All the actual input is done via the input controller's consume_input * method. */ GLOBAL int jpeg_consume_input (j_decompress_ptr cinfo) { int retcode = JPEG_SUSPENDED; /* NB: every possible DSTATE value should be listed in this switch */ switch (cinfo->global_state) { case DSTATE_START: /* Start-of-datastream actions: reset appropriate modules */ (*cinfo->inputctl->reset_input_controller) (cinfo); /* Initialize application's data source module */ (*cinfo->src->init_source) (cinfo); cinfo->global_state = DSTATE_INHEADER; /*FALLTHROUGH*/ case DSTATE_INHEADER: retcode = (*cinfo->inputctl->consume_input) (cinfo); if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */ /* Set up default parameters based on header data */ default_decompress_parms(cinfo); /* Set global state: ready for start_decompress */ cinfo->global_state = DSTATE_READY; } break; case DSTATE_READY: /* Can't advance past first SOS until start_decompress is called */ retcode = JPEG_REACHED_SOS; break; case DSTATE_PRELOAD: case DSTATE_PRESCAN: case DSTATE_SCANNING: case DSTATE_RAW_OK: case DSTATE_BUFIMAGE: case DSTATE_BUFPOST: case DSTATE_STOPPING: retcode = (*cinfo->inputctl->consume_input) (cinfo); break; default: ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); } return retcode; } /* * Have we finished reading the input file? */ GLOBAL boolean jpeg_input_complete (j_decompress_ptr cinfo) { /* Check for valid jpeg object */ if (cinfo->global_state < DSTATE_START || cinfo->global_state > DSTATE_STOPPING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); return cinfo->inputctl->eoi_reached; } /* * Is there more than one scan? */ GLOBAL boolean jpeg_has_multiple_scans (j_decompress_ptr cinfo) { /* Only valid after jpeg_read_header completes */ if (cinfo->global_state < DSTATE_READY || cinfo->global_state > DSTATE_STOPPING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); return cinfo->inputctl->has_multiple_scans; } /* * Finish JPEG decompression. * * This will normally just verify the file trailer and release temp storage. * * Returns FALSE if suspended. The return value need be inspected only if * a suspending data source is used. */ GLOBAL boolean jpeg_finish_decompress (j_decompress_ptr cinfo) { if ((cinfo->global_state == DSTATE_SCANNING || cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) { /* Terminate final pass of non-buffered mode */ if (cinfo->output_scanline < cinfo->output_height) ERREXIT(cinfo, JERR_TOO_LITTLE_DATA); (*cinfo->master->finish_output_pass) (cinfo); cinfo->global_state = DSTATE_STOPPING; } else if (cinfo->global_state == DSTATE_BUFIMAGE) { /* Finishing after a buffered-image operation */ cinfo->global_state = DSTATE_STOPPING; } else if (cinfo->global_state != DSTATE_STOPPING) { /* STOPPING = repeat call after a suspension, anything else is error */ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); } /* Read until EOI */ while (! cinfo->inputctl->eoi_reached) { if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) return FALSE; /* Suspend, come back later */ } /* Do final cleanup */ (*cinfo->src->term_source) (cinfo); /* We can use jpeg_abort to release memory and reset global_state */ jpeg_abort((j_common_ptr) cinfo); return TRUE; }
[ [ [ 1, 800 ] ] ]