blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d974f337220db0e6a5a1f827e42096c6ace2df9f | 4497c10f3b01b7ff259f3eb45d0c094c81337db6 | /VideoMontage/Norm.h | e5cb9a4ebfd5d5675753cd7d3579bad4b2e6a338 | []
| no_license | liuguoyou/retarget-toolkit | ebda70ad13ab03a003b52bddce0313f0feb4b0d6 | d2d94653b66ea3d4fa4861e1bd8313b93cf4877a | refs/heads/master | 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | h | #pragma once
#include <Math.h>
#include <cv.h>
#include "Point.h"
// to calculate all kinds of norm
class Norm
{
public:
Norm(void);
~Norm(void);
// return 0 by default so child does not have to implement anything
virtual double CalculateNorm(Point3D point1, Point3D point2);
// return 0 by default so child does not have to implement anything
virtual double CalculateNorm(CvScalar value1, CvScalar value2);
// return 0 by default so child does not have to implement anything
virtual double CalculateNorm(CvMat matrix1, CvMat matrix2);
}; | [
"kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a"
]
| [
[
[
1,
21
]
]
]
|
954a6cc142590420733f1219373c4fe09af5f296 | d00be105055225808a242cd6bd8411b376c4f4e1 | /src/native/windows/directshow/ds_capture_device.h | a49859ed01418a79f56eefd6e236525711ab7df1 | []
| no_license | zhiji6/sip-comm-jn | bae7d463353de91a5e95bfb4ea5bb85e42c7609c | 8259cf641bd4d868481c0ef4785a5ce75aac098d | refs/heads/master | 2020-04-29T02:52:02.743960 | 2010-11-08T19:48:29 | 2010-11-08T19:48:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,159 | h | /*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
/**
* \file ds_capture_device.h
* \brief DirectShow capture device.
* \author Sebastien Vincent
* \date 2010
*/
#ifndef DS_CAPTURE_DEVICE_H
#define DS_CAPTURE_DEVICE_H
#include <list>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <dshow.h>
#include "qedit.h"
#include "video_format.h"
/**
* \class DSGrabberCallback
* \brief Callback when DirectShow device capture frames.
*/
class DSGrabberCallback : public ISampleGrabberCB
{
public:
/**
* \brief Constructor.
*/
DSGrabberCallback();
/**
* \brief Destructor.
*/
~DSGrabberCallback();
/**
* \brief Method callback when device capture a frame.
* \param time time when frame was received
* \param sample media sample
* \see ISampleGrabberCB
*/
virtual STDMETHODIMP SampleCB(double time, IMediaSample* sample);
/**
* \brief Method callback when device buffer a frame.
* \param time time when frame was received
* \param buffer raw buffer
* \param len length of buffer
* \see ISampleGrabberCB
*/
virtual STDMETHODIMP BufferCB(double time, BYTE* buffer, long len);
/**
* \brief Query if this COM object has the interface iid.
* \param iid interface requested
* \param ptr if method succeed, an object corresponding
* to the interface requested will be copied in this pointer
*/
virtual HRESULT STDMETHODCALLTYPE QueryInterface(const IID& iid, void** ptr);
/**
* \brief Adding a reference.
* \return number of reference hold
*/
STDMETHODIMP_(ULONG) AddRef();
/**
* \brief Release a reference.
* \return number of reference hold
*/
STDMETHODIMP_(ULONG) Release();
};
/**
* \class DSCaptureDevice
* \brief DirectShow capture device.
*
* Once a DSCapture has been obtained by DSManager, do not
* forget to build the graph and optionally set a format.
*/
class DSCaptureDevice
{
public:
/**
* \brief Constructor.
* \param name name of the capture device
*/
DSCaptureDevice(const WCHAR* name);
/**
* \brief Destructor.
*/
~DSCaptureDevice();
/**
* \brief Get name of the capture device.
* \return name of the capture device
*/
const WCHAR* getName() const;
/**
* \brief Initialize the device.
* \param moniker moniker of the capture device
* \return true if initialization succeed, false otherwise (in this
* case the capture device have to be deleted)
*/
bool initDevice(IMoniker* moniker);
/**
* \brief Set video format.
* \param format video format
* \return true if change is successful, false otherwise (format unsupported, ...)
* \note This method stop stream so you have to call start() after.
*/
bool setFormat(const VideoFormat& format);
/**
* \brief Get list of supported formats.
* \return list of supported formats.
*/
std::list<VideoFormat> getSupportedFormats() const;
/**
* \brief Build the filter graph for this capture device.
* \return true if success, false otherwise
* \note Call this method before start().
*/
bool buildGraph();
/**
* \brief get callback object.
* \return callback
*/
DSGrabberCallback* getCallback();
/**
* \brief Set callback object when receiving new frames.
* \param callback callback object to set
*/
void setCallback(DSGrabberCallback* callback);
/**
* \brief Start capture device.
* \return false if problem, true otherwise
*/
bool start();
/**
* \brief Stop capture device.
* \return false if problem, true otherwise
*/
bool stop();
/**
* \brief Get current format.
* \return current format
*/
VideoFormat getFormat() const;
/**
* \brief Get current bit per pixel.
* \return bit per pixel of images
*/
size_t getBitPerPixel();
private:
/**
* \brief Initialize list of supported size.
*/
void initSupportedFormats();
/**
* \brief Name of the capture device.
*/
WCHAR* m_name;
/**
* \brief Callback.
*/
DSGrabberCallback* m_callback;
/**
* \brief List of VideoFormat.
*/
std::list<VideoFormat> m_formats;
/**
* \brief Reference of the filter graph.
*/
IFilterGraph2* m_filterGraph;
/**
* \brief Reference of the capture graph builder.
*/
ICaptureGraphBuilder2* m_captureGraphBuilder;
/**
* \brief Controller of the graph.
*/
IMediaControl* m_graphController;
/**
* \brief Source filter.
*/
IBaseFilter* m_srcFilter;
/**
* \brief Sample grabber filter.
*/
IBaseFilter* m_sampleGrabberFilter;
/**
* \brief The null renderer.
*/
IBaseFilter* m_renderer;
/**
* \brief The sample grabber.
*/
ISampleGrabber* m_sampleGrabber;
/**
* \brief Current format.
*/
VideoFormat m_format;
/**
* \brief Current bit per pixel.
*/
size_t m_bitPerPixel;
};
#endif /* DS_CAPTURE_DEVICE_H */
| [
"[email protected]"
]
| [
[
[
1,
242
]
]
]
|
817c4f79353f0cacfc7ab9ac73266130074ae858 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /tools/common/wxCommonHelper.cpp | a66e136014a57411e4954e9ee5ad7d27ee1382e3 | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,563 | cpp | /*!
* \file wxCommonHelper.cpp
* \date 3-3-2010 15:39:20
*
*
* \author zjhlogo ([email protected])
*/
#include "wxCommonHelper.h"
#include <wx/app.h>
#include <wx/fs_mem.h>
#include <wx/xrc/xmlres.h>
bool wxCommonHelper::Initialize()
{
if (!wxInitialize()) return false;
if (!InitializeXrc()) return false;
return true;
}
void wxCommonHelper::Terminate()
{
wxUninitialize();
}
bool wxCommonHelper::InitializeXrc()
{
wxXmlResource::Get()->InitAllHandlers();
// add memory file system
wxFileSystem::AddHandler(new wxMemoryFSHandler());
return true;
}
bool wxCommonHelper::AddMemoryXrc(const tstring& strResType, uint nResID, const tstring& strMemoryFileName, HINSTANCE hInstance /* = NULL */)
{
// load the resource
HRSRC hRes = FindResource(hInstance, MAKEINTRESOURCE(nResID), strResType.c_str());
HGLOBAL hResData = LoadResource(hInstance, hRes);
void* pResBuffer = LockResource(hResData);
if (!pResBuffer) return false;
int nResSize = SizeofResource(hInstance, hRes);
// add resource into memory file system
wxMemoryFSHandler::AddFile(strMemoryFileName.c_str(), pResBuffer, nResSize);
// unload the resource
UnlockResource(hResData);
//// MSDN: For 32-bit Windows applications, it is not necessary to free the resources loaded using function LoadResource
//FreeResource(hResData);
// add xrc file
wxString strMemoryPath = wxT("memory:");
strMemoryPath += strMemoryFileName.c_str();
if (!wxXmlResource::Get()->Load(strMemoryPath)) return false;
return true;
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
60
]
]
]
|
7f2d5b5c0ad6519277224d33112318e55ac02b13 | 6b83c731acb331c4f7ddd167ab5bb562b450d0f2 | /ScriptEngine/src/GM_Demo.cpp | ad88c4dd66884bb1dec35187a537e7da43114972 | []
| no_license | weimingtom/toheart2p | fbfb96f6ca8d3102b462ba53d3c9cff16ca509e7 | 560e99c42fdff23e65f16df6d14df9a9f1868d8e | refs/heads/master | 2021-01-10T01:36:31.515707 | 2007-12-20T15:13:51 | 2007-12-20T15:13:51 | 44,464,730 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 14,602 | cpp |
#include <mm_std.h>
#include "main.h"
#include "bmp.h"
#include "draw.h"
#include "drawprim.h"
#include "math.h"
#include "text.h"
#include "disp.h"
#include "GM_demo.h"
#include "GM_avg.h"
#include "font.h"
#include "dispSprite.h"
enum
{
DEMO_INIT = 0,
DEMO_LOAD,
DEMO_MAIN,
DEMO_TERM,
};
static int DemoStep[5] ={ 0, 0, 0, 0, 0 };
static int NextDemoStep[5]={ 0, 0, 0, 0, 0 };
static int DemoCounter[5] ={ 0, 0, 0, 0, 0 };
static int DemoCounter2[5] ={ 0, 0, 0, 0, 0 };
static void DEM_ChangeSetp( int index, int step )
{
NextDemoStep[index] = step;
}
static void DEM_RenewSetp( void )
{
int index, j;
for( index=0; index<5 ;index++ )
{
if( DemoStep[index] != NextDemoStep[index] )
{
for( j=index; j<5 ;j++ )
{
DemoCounter[j] = 0;
DemoCounter2[j]= 0;
if(j!=index)
DemoStep[j] = NextDemoStep[j]=0;
}
DemoStep[index] = NextDemoStep[index];
break;
}
else
{
DemoCounter[index]++;
DemoCounter2[index]++;
}
}
}
void DEM_Init( void )
{
MAIN_SetScriptFlag( OFF );
}
void DEM_Load( void )
{
int bmp_bpp = BPP(MainWindow.draw_mode2);
int anti_bpp = (MainWindow.draw_mode2==16)? BMP_HIGH: BMP_TRUE;
DSP_LoadBmp( 0, bmp_bpp, "v00020.bmp" );
DSP_LoadBmp( 10, BMP_256P, "smple0000.bmp" );
DSP_LoadBmp( 11, BMP_256P, "smple0001.bmp" );
DSP_LoadBmp( 12, BMP_256P, "smple0002.bmp" );
DSP_LoadBmp( 13, BMP_256P, "smple0003.bmp" );
FNT_LoadFont( 28, 0 );
FrameFormat = 1;
}
void DEM_Term( void )
{
}
void ChangeSetpCounter( int index, int step, int counter )
{
if( DemoCounter[index] >= counter )
DEM_ChangeSetp( index, step );
}
#include "movie.h"
#include "keybord.h"
#include "mouse.h"
#include <soundDS.h>
void SetRipple( int go )
{
short *depth = DRW_GetRippleTableAddr();
int x,y;
static int wsctr = 0;
if(wsctr<100)
{
if(wsctr%10==0)
{
for( y = -10; y<=10; y++ )
{
if( (DRW_GetRippleTableNwf()+y+150)%2 )
{
for( x = -10; x<=10; x++ )
{
if( sqrt( (double)(x*x+y*y) ) <80 )
{
}
}
}
}
}
}
if(wsctr%256==8)
{
for( y = -10; y<=10; y++ )
{
for( x = -10; x<=10; x++ )
{
if( sqrt( (double)(x*x+y*y) ) < 4 )
{
*(depth+(100+y)*400+150+x) = -LIM(256-(x*x+y*y),0,256);
}
}
}
}
if(wsctr%256==16)
{
for( y = -10; y<=10; y++ )
{
for( x = -10; x<=10; x++ )
{
if( sqrt( (double)(x*x+y*y) ) < 6 )
{
*(depth+(160+y)*400+300+x) = -LIM(256-(x*x+y*y),0,256);
}
}
}
}
if(wsctr%256==20)
{
for( y = -32; y<=32; y++ )
{
for( x = -32; x<=32; x++ )
{
}
}
}
wsctr++;
}
static int NetCharX[100];
static int NetCharY[100];
static int NetCharSPD[100];
int RippleGno = 1;
int RippleCount[200];
int RippleMax[200];
int RippleX[200];
int RippleY[200];
void DEM_Ripple( int x, int y, int rate, int bld, int angle )
{
DSP_SetGraphPrim( RippleGno, PRM_FLAT, POL_RPLE, 1, ON );
DSP_SetGraphBright( RippleGno, 0,0,32 );
DSP_SetGraphMove( RippleGno, x,y );
DSP_SetGraphParam( RippleGno, DRW_PRM4( bld, rate, 255,angle) );
RippleGno++;
}
BOOL DEM_SystemMain(void )
{
int bmp_bpp = BPP(MainWindow.draw_mode2);
BOOL ret = TRUE;
int dc = (0x1000-DemoCounter[0])%96-16;
int r2 = STD_LimitLoop( GlobalCount2*4, 255 );
int r = timeGetTime();
int lr = STD_LimitLoop( r/8, 255 );
int x = r%DISP_X;
int y = r%DISP_Y;
int i=0,j=0;
static int flag = 0;
char *str = "<Aアクセント>が出せます。\n\\k<s6一次停止、<w30><s4スピード変更>とか>\\k表示中の演出挿入";
static int mh;
int Angle = 0;
static an=0;
int count = DemoCounter[1]*4;
int mx,my;
MUS_GetMousePos( &mx, &my );
MainWindow.draw_flag=1;
Avg.frame=30;
static int wavw_cnt=0;
AVG_GetGameKey();
if(GameKey.click)
wavw_cnt=0;
if(GameKey.cansel)
ChangeSetpCounter( 1, (DemoStep[1]+1)%2, 0 );
if(KeyCond.trg.f1)
{
}
if(KeyCond.trg.f2)
{
}
if(KeyCond.trg.f3)
{
}
if(KeyCond.trg.f4)
{
}
r = SIN( timeGetTime()/10%256 )/2 ;
switch( DemoStep[1] )
{
default:
case 0:
DSP_SetGraphPrim( 0, PRM_FLAT, POL_RECT, 0, ON );
DSP_SetGraphPosRect( 0, 0,0,800,600 );
DSP_SetGraphBright( 0, 255,128,50 );
r = DemoCounter[0]*2%256;
DSP_SetGraph( 1, 10 + (DemoCounter[0]*2/256+0)%4, 1, ON, CHK_NO );
DSP_SetGraph( 2, 10 + (DemoCounter[0]*2/256+1)%4, 1, ON, CHK_NO );
DSP_SetGraph( 3, 10 + (DemoCounter[0]*2/256+2)%4, 1, ON, CHK_NO );
DSP_SetGraph( 4, 10 + (DemoCounter[0]*2/256+3)%4, 1, !!r, CHK_NO );
DSP_SetGraphFade( 1, 64-r/8 );
DSP_SetGraphPosPoly( 1, -r, -r, 200-r*200/256, 150-r*150/256,
-r, 600+r, 200-r*200/256, 150+300+r*150/256,
0, 0, 400, 0, 0, 300, 400, 300 );
DSP_SetGraphFade( 2, 128-r/4 );
DSP_SetGraphPosPoly( 2, 200-r*200/256, 150-r*150/256, 200+400-r*400/256, 150,
200-r*200/256, 300+150+r*150/256, 400+200-r*400/256, 150+300,
0, 0, 400, 0, 0, 300, 400, 300 );
DSP_SetGraphFade( 3, 64+r/4 );
DSP_SetGraphPosPoly( 3, 400+200-r*400/256, 150, 800-r*200/256, 0+r*150/256,
400+200-r*400/256, 300+150, 800-r*200/256, 600-r*150/256,
0, 0, 400, 0, 0, 300, 400, 300 );
DSP_SetGraphFade( 4, 32+r/8 );
DSP_SetGraphPosPoly( 4, 800-r*200/256, r*150/256, 800+256-r, -256+r,
800-r*200/256, 600-r*150/256, 800+256-r, 600+256-r,
0, 0, 400, 0, 0, 300, 400, 300 );
break;
case 1:
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_ResetGraph( 1);
DSP_ResetGraph( 2);
DSP_ResetGraph( 3);
DSP_ResetGraph( 4);
if(0)
{
long xxx[36];
long yyy[36];
long xx[6];
long yy[6];
if(wavw_cnt<256) wavw_cnt+=4;
r = COS( wavw_cnt )*1536/4096;
r = r/32;
xxx[0*6+0] = r*3; yyy[0*6+0] = r*3;
xxx[0*6+1] = r*2; yyy[0*6+1] = r*2;
xxx[0*6+2] = r; yyy[0*6+2] = r;
xxx[0*6+3] = -r; yyy[0*6+3] = r;
xxx[0*6+4] = -r*2; yyy[0*6+4] = r*2;
xxx[0*6+5] = -r*3; yyy[0*6+5] = r*3;
xxx[1*6+0] = r*2; yyy[1*6+0] = r*2;
xxx[1*6+1] = r; yyy[1*6+1] = r;
xxx[1*6+2] = r/2; yyy[1*6+2] = r/2;
xxx[1*6+3] = -r/2; yyy[1*6+3] = r/2;
xxx[1*6+4] = -r; yyy[1*6+4] = r;
xxx[1*6+5] = -r*2; yyy[1*6+5] = r*2;
xxx[2*6+0] = r; yyy[2*6+0] = r;
xxx[2*6+1] = r/2; yyy[2*6+1] = r/2;
xxx[2*6+2] = -r; yyy[2*6+2] = -r;
xxx[2*6+3] = r; yyy[2*6+3] = -r;
xxx[2*6+4] = -r/2; yyy[2*6+4] = r/2;
xxx[2*6+5] = -r; yyy[2*6+5] = r;
xxx[3*6+0] = r; yyy[3*6+0] = -r;
xxx[3*6+1] = r/2; yyy[3*6+1] = -r/2;
xxx[3*6+2] = -r; yyy[3*6+2] = r;
xxx[3*6+3] = r; yyy[3*6+3] = r;
xxx[3*6+4] = -r/2; yyy[3*6+4] = -r/2;
xxx[3*6+5] = -r; yyy[3*6+5] = -r;
xxx[4*6+0] = r*2; yyy[4*6+0] = -r*2;
xxx[4*6+1] = r; yyy[4*6+1] = -r;
xxx[4*6+2] = r/2; yyy[4*6+2] = -r/2;
xxx[4*6+3] = -r/2; yyy[4*6+3] = -r/2;
xxx[4*6+4] = -r; yyy[4*6+4] = -r;
xxx[4*6+5] = -r*2; yyy[4*6+5] = -r*2;
xxx[5*6+0] = r*3; yyy[5*6+0] = -r*3;
xxx[5*6+1] = r*2; yyy[5*6+1] = -r*2;
xxx[5*6+2] = r*1; yyy[5*6+2] = -r*1;
xxx[5*6+3] = -r*1; yyy[5*6+3] = -r*1;
xxx[5*6+4] = -r*2; yyy[5*6+4] = -r*2;
xxx[5*6+5] = -r*3; yyy[5*6+5] = -r*3;
x=mx;
y=my;
xx[0] = -128;
xx[1] = 128+x*1/5-128;
xx[2] = 128+x*4/5-128;
xx[3] = 128+x+(800-x)/5-128;
xx[4] = 128+x+(800-x)*4/5-128;
xx[5] = 800+256-128;
yy[0] = -96;
yy[1] = 96+y*1/5-96;
yy[2] = 96+y*4/5-96;
yy[3] = 96+y+(600-y)/5-96;
yy[4] = 96+y+(600-y)*4/5-96;
yy[5] = 600+192-96;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
DSP_SetGraph( i*5+j, 1, 0, ON, CHK_NO );
DSP_SetGraphPosPoly( i*5+j,
xx[j]+xxx[ i *6+j], yy[i ]+yyy[ i *6+j], xx[j+1]+xxx[ i *6+j+1], yy[i ]+yyy[ i *6+j+1],
xx[j]+xxx[(i+1)*6+j], yy[i+1]+yyy[(i+1)*6+j], xx[j+1]+xxx[(i+1)*6+j+1], yy[i+1]+yyy[(i+1)*6+j+1],
xx[j]+128, yy[i]+96, xx[j+1]+128, yy[i]+96, xx[j]+128, yy[i+1]+96, xx[j+1]+128, yy[i+1]+96 );
}
}
}
break;
case 2:
for( i=0 ; i<RippleGno ; i++ )
DSP_ResetGraph( i );
SetRipple( (DrawCount)%256 );
DRW_RenewRippleTable(1);
DSP_SetGraph( 0, 0, 1, ON, CHK_NO );
DSP_SetGraphPos( 0, 0,0, 0,0, 800, 600 );
DSP_SetGraphParam( 0, DRW_RP2( 255-LIM(r/10%512*4/3,0,255), r/20%256 ) );
DSP_SetGraphFade( 0, 128-LIM(DrawCount%256-128,0,128) );
break;
case 3:
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
DSP_SetGraphBSet2( 1, 2, 3, lr*lr/255 );
break;
case 4:
DSP_SetTextStr( 0, "モザイクワイプ" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraphDisp( 1, OFF );
DSP_SetGraphParam( 0, DRW_MOZ(count*2) );
ChangeSetpCounter( 1, 5, 64 );
break;
case 5:
DSP_SetGraph( 0, 1, 0, ON, CHK_NO );
DSP_SetGraphDisp( 1, OFF );
DSP_SetGraphParam( 0, DRW_MOZ(128-count*2) );
ChangeSetpCounter( 1, 6, 64 );
break;
case 6:
DSP_SetTextStr( 0, "モザイクフェード" );
DSP_SetGraph( 0, 0, 1, ON, CHK_NO );
DSP_SetGraph( 1, 1, 0, ON, CHK_NO );
DSP_SetGraphParam( 0, DRW_BLD(count*4) );
DSP_SetGraphParam( 1, DRW_MOZ(count*4) );
ChangeSetpCounter( 1, 7, 64 );
break;
case 7:
DSP_SetTextStr( 0, "パターンフェード1" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
DSP_SetGraphBSet( 1, 2, count*4 );
ChangeSetpCounter( 1, 8, 64 );
break;
case 8:
DSP_SetTextStr( 0, "パターンフェード2" );
DSP_SetGraph( 0, 0, 1, ON, CHK_NO );
DSP_SetGraph( 1, 1, 0, ON, CHK_NO );
DSP_SetGraphBSet( 0, 3, count*4 );
ChangeSetpCounter( 1, 9, 64 );
break;
case 9:
DSP_SetTextStr( 0, "パターンフェード3" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
DSP_SetGraphBSet( 1, 4, count*4 );
ChangeSetpCounter( 1, 10, 64 );
break;
case 10:
DSP_SetTextStr( 0, "パターンフェード4(放射)" );
DSP_SetGraph( 0, 0, 1, ON, CHK_NO );
DSP_SetGraph( 1, 1, 0, ON, CHK_NO );
DSP_SetGraphBSet( 0, 5, count*4 );
ChangeSetpCounter( 1, 11, 64 );
break;
case 11:
DSP_SetTextStr( 0, "パターンフェード5(文字)" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
DSP_SetGraphBSet( 1, 6, count*4 );
ChangeSetpCounter( 1, 12, 64 );
break;
case 12:
DSP_SetTextStr( 0, "スクロールワイプ(横)" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
r = count*count/64;
x = 800*r/64;
DSP_SetGraphMove( 0, x-800, 0 );
DSP_SetGraphMove( 1, x, 0 );
DSP_SetGraphParam( 0, DRW_BLD(32+r*2) );
DSP_SetGraphParam( 1, DRW_BLD(32) );
ChangeSetpCounter( 1, 13, 64 );
break;
case 13:
DSP_SetTextStr( 0, "スクロールワイプ(縦)" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
r = count*count/64;
y = -600*r/64;
DSP_SetGraphMove( 0, 0, y );
DSP_SetGraphPosRect( 1, 0, y+600, 800, 600 );
DSP_SetGraphParam( 0, DRW_BLD(32) );
DSP_SetGraphParam( 1, DRW_BLD(32+r*2) );
ChangeSetpCounter( 1, 14, 64 );
break;
case 14:
DSP_SetTextStr( 0, "ズームワイプ1" );
DSP_SetGraph( 0, 0, 1, ON, CHK_NO );
DSP_SetGraph( 1, 1, 0, ON, CHK_NO );
r = 64-(64-count)*(64-count)/64;
DSP_SetGraphZoom2( 1, 400, 300, r*4 );
DSP_SetGraphParam( 0, DRW_BLD(r*4) );
ChangeSetpCounter( 1, 15, 64 );
break;
case 15:
DSP_SetTextStr( 0, "ズームワイプ2" );
DSP_SetGraphDisp( 0, OFF );
DSP_SetGraph( 1, 1, 0, ON, CHK_NO );
r = 64-count*count/64;
DSP_SetGraphZoom2( 1, 400, 300, r*4 );
DSP_SetGraphParam( 1, DRW_BLD(16+128-r*2) );
ChangeSetpCounter( 1, 16, 64 );
break;
case 16:
DSP_SetTextStr( 0, "ズームワイプ3" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
r = 64-count;
r = r*r/64;
DSP_SetGraphPos( 1, 0, 0, 0,0, 800, 600 );
DSP_SetGraphZoom2( 1, 400, 300, r*4-256 );
DSP_SetGraphParam( 1, DRW_BLD(r*4) );
ChangeSetpCounter( 1, 17, 64 );
break;
case 17:
DSP_SetTextStr( 0, "ズームワイプ4" );
DSP_SetGraphDisp( 0, OFF );
DSP_SetGraph( 1, 1, 1, ON, CHK_NO );
r = 64-count;
r = 64-r*r/64;
DSP_SetGraphPos( 1, 0, 0, 0,0, 800, 600 );
DSP_SetGraphZoom2( 1, 400, 300, r*4-256 );
DSP_SetGraphParam( 1, DRW_BLD(r*2) );
ChangeSetpCounter( 1, 18, 64 );
break;
case 18:
DSP_SetTextStr( 0, "ノイズワイプ" );
DSP_SetGraph( 0, 0, 1, ON, CHK_NO );
DSP_SetGraph( 1, 1, 0, ON, CHK_NO );
r = count*2;
DSP_SetGraphParam( 0, DRW_NIS(r) );
ChangeSetpCounter( 1, 19, 128 );
break;
case 19:
DSP_SetTextStr( 0, "加算パターンホワイトフェード" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 5, 1, ON, CHK_NO );
r = STD_LimitLoop( count, 64 )*4;
DSP_SetGraphParam( 1, DRW_ADD );
DSP_SetGraphFade( 1, r );
ChangeSetpCounter( 1, 20, 128 );
break;
case 20:
DSP_SetTextStr( 0, "減算パターンフェード" );
DSP_SetGraph( 0, 0, 0, ON, CHK_NO );
DSP_SetGraph( 1, 5, 1, ON, CHK_NO );
r = STD_LimitLoop( count, 64 )*4;
DSP_SetGraphParam( 1, DRW_SUB );
DSP_SetGraphFade( 1, r );
ChangeSetpCounter( 1, 0, 128 );
break;
}
AVG_ControlWeather();
return ret;
}
void DEM_DrawMain( void *dest )
{
}
int DEM_System( void )
{
switch( DemoStep[0] ){
default:
case DEMO_INIT:
DEM_Init( );
DEM_ChangeSetp( 0, DEMO_LOAD );
break;
case DEMO_LOAD:
DEM_Load( );
DEM_ChangeSetp( 0, DEMO_MAIN );
break;
case DEMO_MAIN:
if( !DEM_SystemMain() )
DEM_ChangeSetp( 0, DEMO_TERM );
break;
case DEMO_TERM:
DEM_Term( );
break;
}
DEM_RenewSetp();
return GAME_DEMO;
}
void DEM_Draw( void *dest )
{
switch( DemoStep[0] )
{
default:
case DEMO_INIT:
break;
case DEMO_LOAD:
break;
case DEMO_MAIN:
DEM_DrawMain( dest );
break;
case DEMO_TERM:
break;
}
}
| [
"pspbter@13f3a943-b841-0410-bae6-1b2c8ac2799f"
]
| [
[
[
1,
628
]
]
]
|
79c06995128e3f919d5151669223f251e2444575 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/slon/Physics/Bullet/BulletCommon.h | 93841964f5a781a35100182b40d8f52b03886cc5 | []
| no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,802 | h | #ifndef __SLON_ENGINE_PHYSICS_BULLET_BULLET_COMMON_H__
#define __SLON_ENGINE_PHYSICS_BULLET_BULLET_COMMON_H__
#include "../../Math/RigidTransform.hpp"
#include "../CollisionShape.h"
#include <bullet/btBulletCollisionCommon.h>
#include <bullet/btBulletDynamicsCommon.h>
namespace slon {
namespace physics {
inline btVector3 to_bt_vec(const math::Vector3r& vec)
{
return btVector3(vec.x, vec.y, vec.z);
}
inline btVector4 to_bt_vec(const math::Vector4r& vec)
{
return btVector4(vec.x, vec.y, vec.z, vec.w);
}
inline btMatrix3x3 to_bt_mat(const math::Matrix3r& mat)
{
return btMatrix3x3( mat[0][0], mat[0][1], mat[0][2],
mat[1][0], mat[1][1], mat[1][2],
mat[2][0], mat[2][1], mat[2][2] );
}
inline btTransform to_bt_mat(const math::Matrix4r& mat)
{
btMatrix3x3 basis( mat[0][0], mat[0][1], mat[0][2],
mat[1][0], mat[1][1], mat[1][2],
mat[2][0], mat[2][1], mat[2][2] );
return btTransform( basis, btVector3(mat[0][3], mat[1][3], mat[2][3]) );
}
inline math::Vector3r to_vec(const btVector3& vec)
{
return math::Vector3r( vec.x(), vec.y(), vec.z() );
}
inline math::Vector4r to_vec(const btVector4& vec)
{
return math::Vector4r( vec.x(), vec.y(), vec.z(), vec.w() );
}
inline math::RigidTransformr to_mat(const btTransform& transform)
{
const btMatrix3x3& basis = transform.getBasis();
const btVector3& origin = transform.getOrigin();
return math::RigidTransformr( basis[0].x(), basis[0].y(), basis[0].z(), origin.x(),
basis[1].x(), basis[1].y(), basis[1].z(), origin.y(),
basis[2].x(), basis[2].y(), basis[2].z(), origin.z(),
(real)0.0, (real)0.0, (real)0.0, (real)1.0,
-1.0f );
}
// create bullet collision shape from slon collision shape
inline btCollisionShape* createBtCollisionShape(const CollisionShape& collisionShape, real relativeMargin, real margin)
{
switch ( collisionShape.getShapeType() )
{
case CollisionShape::PLANE:
{
const PlaneShape& planeShape = static_cast<const PlaneShape&>(collisionShape);
btStaticPlaneShape* bulletCollisionShape = new btStaticPlaneShape( to_bt_vec(planeShape.plane.normal), planeShape.plane.distance );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin(margin);
return bulletCollisionShape;
}
case CollisionShape::SPHERE:
{
const SphereShape& sphereShape = static_cast<const SphereShape&>(collisionShape);
btSphereShape* bulletCollisionShape = new btSphereShape(sphereShape.radius);
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin(sphereShape.radius*relativeMargin + margin);
return bulletCollisionShape;
}
case CollisionShape::BOX:
{
const BoxShape& boxShape = static_cast<const BoxShape&>(collisionShape);
btBoxShape* bulletCollisionShape = new btBoxShape( to_bt_vec(boxShape.halfExtent) );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin(2*std::min(boxShape.halfExtent.x, std::min(boxShape.halfExtent.y, boxShape.halfExtent.z))*relativeMargin + margin);
return bulletCollisionShape;
}
case CollisionShape::CAPSULE:
{
const CapsuleShape& capsuleShape = static_cast<const CapsuleShape&>(collisionShape);
btCapsuleShape* bulletCollisionShape = new btCapsuleShape(capsuleShape.radius, capsuleShape.height);
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin( std::min(capsuleShape.height, capsuleShape.radius)*relativeMargin + margin );
return bulletCollisionShape;
}
case CollisionShape::CONE:
{
const ConeShape& coneShape = static_cast<const ConeShape&>(collisionShape);
btConeShape* bulletCollisionShape = new btConeShape(coneShape.radius, coneShape.height);
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin( std::min(coneShape.height, coneShape.radius)*relativeMargin + margin );
return bulletCollisionShape;
}
case CollisionShape::CYLINDER_X:
{
const CylinderXShape& cylShape = static_cast<const CylinderXShape&>(collisionShape);
btCylinderShape* bulletCollisionShape = new btCylinderShapeX( to_bt_vec(cylShape.halfExtent) );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin( 2*std::min(cylShape.halfExtent.x, std::min(cylShape.halfExtent.y, cylShape.halfExtent.z))*relativeMargin + margin );
return bulletCollisionShape;
}
case CollisionShape::CYLINDER_Y:
{
const CylinderYShape& cylShape = static_cast<const CylinderYShape&>(collisionShape);
btCylinderShape* bulletCollisionShape = new btCylinderShape( to_bt_vec(cylShape.halfExtent) );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin( 2*std::min(cylShape.halfExtent.x, std::min(cylShape.halfExtent.y, cylShape.halfExtent.z))*relativeMargin + margin );
return bulletCollisionShape;
}
case CollisionShape::CYLINDER_Z:
{
const CylinderZShape& cylShape = static_cast<const CylinderZShape&>(collisionShape);
btCylinderShape* bulletCollisionShape = new btCylinderShapeZ( to_bt_vec(cylShape.halfExtent) );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin( 2*std::min(cylShape.halfExtent.x, std::min(cylShape.halfExtent.y, cylShape.halfExtent.z))*relativeMargin + margin );
return bulletCollisionShape;
}
case CollisionShape::CONVEX_MESH:
{
const ConvexShape& convexShape = static_cast<const ConvexShape&>(collisionShape);
btConvexHullShape* bulletCollisionShape = new btConvexHullShape( &convexShape.vertices[0].x,
convexShape.vertices.size(),
sizeof(math::Vector3r) );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
// find center
math::Vector3r center(0);
for (size_t i = 0; i<convexShape.vertices.size(); ++i) {
center += convexShape.vertices[i] / convexShape.vertices.size();
}
// find min dimension
float minDimension = std::numeric_limits<real>::max();
for (size_t i = 0; i<convexShape.vertices.size(); ++i) {
minDimension = std::min(minDimension, math::length(convexShape.vertices[i] - center));
}
bulletCollisionShape->setMargin(minDimension*relativeMargin + margin);
return bulletCollisionShape;
}
case CollisionShape::TRIANGLE_MESH:
{
const TriangleMeshShape& triangleMeshShape = static_cast<const TriangleMeshShape&>(collisionShape);
btTriangleIndexVertexArray* indexVertexArray = new btTriangleIndexVertexArray( triangleMeshShape.indices.size() / 3,
(int*)&triangleMeshShape.indices[0],
3 * sizeof(unsigned),
triangleMeshShape.vertices.size(),
(btScalar*)&triangleMeshShape.vertices[0].x,
sizeof(math::Vector3r) );
math::AABBr aabb = compute_aabb<real>( triangleMeshShape.vertices.begin(),
triangleMeshShape.vertices.end() );
float minDimension = std::min(aabb.size().x, std::min(aabb.size().y, aabb.size().z));
btBvhTriangleMeshShape* bulletCollisionShape = new btBvhTriangleMeshShape( indexVertexArray, true, to_bt_vec( xyz(aabb.minVec) ), to_bt_vec( xyz(aabb.maxVec) ) );
bulletCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
bulletCollisionShape->setMargin(minDimension*relativeMargin + margin);
return bulletCollisionShape;
}
case CollisionShape::COMPOUND:
{
const CompoundShape& compoundShape = static_cast<const CompoundShape&>(collisionShape);
// create compound shape from several shapes
btCompoundShape* bulletCompoundCollisionShape = new btCompoundShape();
for( CompoundShape::const_shape_trasnform_iterator shapeIter = compoundShape.shapes.begin();
shapeIter != compoundShape.shapes.end();
++shapeIter )
{
btCollisionShape* btChildCollisionShape = createBtCollisionShape(*shapeIter->shape, relativeMargin, margin);
bulletCompoundCollisionShape->addChildShape( to_bt_mat(shapeIter->transform), btChildCollisionShape );
}
bulletCompoundCollisionShape->setUserPointer( const_cast<CollisionShape*>(&collisionShape) );
return bulletCompoundCollisionShape;
}
default:
assert(!"Can't get here");
}
return 0;
}
// create slon collision shape from bullet collision shape
// TODO: Add shapes
inline CollisionShape* createCollisionShape(const btCollisionShape& collisionShape)
{
if ( const btStaticPlaneShape* btShape = dynamic_cast<const btStaticPlaneShape*>(&collisionShape) )
{
return new PlaneShape( math::Planer( to_vec(btShape->getPlaneNormal()), btShape->getPlaneConstant() ) );
}
else if ( const btSphereShape* btShape = dynamic_cast<const btSphereShape*>(&collisionShape) )
{
return new SphereShape( btShape->getRadius() );
}
else if ( const btBoxShape* btShape = dynamic_cast<const btBoxShape*>(&collisionShape) )
{
return new BoxShape( to_vec( btShape->getHalfExtentsWithoutMargin() ) );
}
else if ( const btConeShape* btShape = dynamic_cast<const btConeShape*>(&collisionShape) )
{
switch ( btShape->getConeUpIndex() )
{
case 0:
return new CompoundShape( math::Matrix4r::rotation_z(math::HALF_PI), new ConeShape(btShape->getRadius(), btShape->getHeight()) );
case 1:
return new ConeShape(btShape->getRadius(), btShape->getHeight());
case 2:
return new CompoundShape( math::Matrix4r::rotation_x(-math::HALF_PI), new ConeShape(btShape->getRadius(), btShape->getHeight()) );
default:
assert(!"can't get here");
}
}
else if ( const btCapsuleShape* btShape = dynamic_cast<const btCapsuleShape*>(&collisionShape) )
{
switch ( btShape->getUpAxis() )
{
case 0:
return new CompoundShape( math::Matrix4r::rotation_z(-math::HALF_PI), new CapsuleShape(btShape->getRadius(), btShape->getHalfHeight() * 2) );
case 1:
return new CapsuleShape(btShape->getRadius(), btShape->getHalfHeight() * 2);
case 2:
return new CompoundShape( math::Matrix4r::rotation_x(-math::HALF_PI), new CapsuleShape(btShape->getRadius(), btShape->getHalfHeight() * 2) );
default:
assert(!"can't get here");
}
}
else if ( const btCylinderShape* btShape = dynamic_cast<const btCylinderShape*>(&collisionShape) )
{
math::Vector3r halfExtent = to_vec(btShape->getHalfExtentsWithoutMargin());
switch ( btShape->getUpAxis() )
{
case 0:
return new CylinderXShape(halfExtent);
case 1:
return new CylinderYShape(halfExtent);
case 2:
return new CylinderZShape(halfExtent);
default:
assert(!"can't get here");
}
}
return 0;
}
} // namespace slon
} // namespace physics
#endif // __SLON_ENGINE_PHYSICS_BULLET_BULLET_COMMON_H__
| [
"devnull@localhost"
]
| [
[
[
1,
282
]
]
]
|
c31afd2914b5d907733606851d88cd4ea8c14c7e | 1eb441701fc977785b13ea70bc590234f4a45705 | /nukak3d/src/nkVolViewer.cpp | eeeca131a572d0fce382dddffbf6c577638cd613 | []
| no_license | svn2github/Nukak3D | 942947dc37c56fc54245bbc489e61923c7623933 | ec461c40431c6f2a04d112b265e184d260f929b8 | refs/heads/master | 2021-01-10T03:13:54.715360 | 2011-01-18T22:16:52 | 2011-01-18T22:16:52 | 47,416,318 | 1 | 2 | null | null | null | null | ISO-8859-1 | C++ | false | false | 37,343 | cpp | /**
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2007-2010 by Bioingenium Research Group.
* Bogota - Colombia
* All rights reserved.
*
* Author(s): Alexander Pinzón Fernández.
*
* ***** END GPL LICENSE BLOCK *****
*/
#include "nkVolViewer.h"
#include "nkLevelSets.h"
#include <vtkInteractorStyleSwitch.h>
#include <vtkRenderWindowInteractor.h>
//*****************************************************************************************
// CONSTRUCTOR
//*****************************************************************************************
nkVolViewer::nkVolViewer(wxWindow* parent,
wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name):
wxPanel(parent, id, pos, size, style, name)
{
prv_auiManager.SetManagedWindow(this);
prv_auiManager.SetFlags(prv_auiManager.GetFlags()|
wxAUI_MGR_ALLOW_ACTIVE_PANE|
wxAUI_MGR_HINT_FADE|
wxAUI_MGR_TRANSPARENT_HINT);
long viewStyle = wxWANTS_CHARS | wxNO_FULL_REPAINT_ON_RESIZE;
prv_wxVtkVistaAxial = new wxVTKRenderWindowInteractor (this, wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
viewStyle,
wxT ("wxVtk Axial view"));
prv_wxVtkVistaCoronal = new wxVTKRenderWindowInteractor (this, wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
viewStyle,
wxT ("wxVtk Coronal view"));
prv_wxVtkVistaSagital = new wxVTKRenderWindowInteractor (this, wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
viewStyle,
wxT ("wxVtk Sagital view"));
prv_wxVtkVista3D = new wxVTKRenderWindowInteractor (this, wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
viewStyle,
wxT ("wxVtk 3D view"));
prv_wxVtkVista3D->GetRenderWindow()->SetStereoCapableWindow(1); //! Init stereo window
prv_vistaAxial = vtkViewImage2DWithTracer::New();
prv_vistaCoronal = vtkViewImage2DWithTracer::New();
prv_vistaSagital = vtkViewImage2DWithTracer::New();
prv_vista3D = vtkViewImage3D::New();
vtkRenderer* mi_renderAxial = vtkRenderer::New();
vtkRenderer* mi_renderCoronal = vtkRenderer::New();
vtkRenderer* mi_renderSagital = vtkRenderer::New();
prv_render3D = vtkRenderer::New();
prv_camera = vtkCamera::New();
prv_render3D->SetActiveCamera(prv_camera);
prv_wxVtkVistaAxial->GetRenderWindow()->AddRenderer (mi_renderAxial);
prv_wxVtkVistaCoronal->GetRenderWindow()->AddRenderer (mi_renderCoronal);
prv_wxVtkVistaSagital->GetRenderWindow()->AddRenderer (mi_renderSagital);
prv_wxVtkVista3D->GetRenderWindow()->AddRenderer (prv_render3D);
prv_vistaAxial->SetRenderWindow (prv_wxVtkVistaAxial->GetRenderWindow());
prv_vistaCoronal->SetRenderWindow (prv_wxVtkVistaCoronal->GetRenderWindow());
prv_vistaSagital->SetRenderWindow (prv_wxVtkVistaSagital->GetRenderWindow());
prv_vista3D->SetRenderWindow (prv_wxVtkVista3D->GetRenderWindow());
prv_vistaAxial->SetRenderer (mi_renderAxial);
prv_vistaCoronal->SetRenderer (mi_renderCoronal);
prv_vistaSagital->SetRenderer (mi_renderSagital);
prv_vista3D->SetRenderer (prv_render3D);
mi_renderAxial->Delete();
mi_renderCoronal->Delete();
mi_renderSagital->Delete();
prv_auiManager.AddPane(prv_wxVtkVistaAxial, wxAuiPaneInfo().
Name(wxT("AXIAL_VIEW")).Caption(_("Axial View")).
Bottom().Position(0).Layer(0).PinButton(true).
MinSize(wxSize(200,200)).PaneBorder(true).
CloseButton(false).MaximizeButton(true));
prv_auiManager.AddPane(prv_wxVtkVistaCoronal, wxAuiPaneInfo().
Name(wxT("CORONAL_VIEW")).Caption(_("Coronal View")).
Bottom().Position(1).Layer(0).PinButton(true).
MinSize(wxSize(200,200)).PaneBorder(true).
CloseButton(false).MaximizeButton(true));
prv_auiManager.AddPane(prv_wxVtkVistaSagital, wxAuiPaneInfo().
Name(wxT("SAGITAL_VIEW")).Caption(_("Sagital View")).
Bottom().Position(2).Layer(0).PinButton(true).
MinSize(wxSize(200,200)).PaneBorder(true).
CloseButton(false).MaximizeButton(true));
prv_auiManager.AddPane(prv_wxVtkVista3D, wxAuiPaneInfo().
Name(wxT("3D_VIEW")).Caption(_("3D View")).
Center().Layer(0).PinButton(true).
MinSize(wxSize(200,200)).PaneBorder(true).
CloseButton(false).MaximizeButton(true));
prv_auiManager.Update();
prv_camtracking=1;
prv_updatePlanes=0;
prv_fpsflag = 0;
}
//*****************************************************************************************
// DESTRUCTOR
//*****************************************************************************************
nkVolViewer::~nkVolViewer(){
prv_vistaAxial->Detach();
prv_vistaCoronal->Detach();
prv_vistaSagital->Detach();
prv_vista3D->Detach();
if (prv_camera != 0) prv_camera->Delete();
if (prv_render3D != 0) prv_render3D->Delete();
prv_vistaAxial->Delete();
prv_vistaCoronal->Delete();
prv_vistaSagital->Delete();
prv_vista3D->Delete();
prv_wxVtkVistaAxial->Delete();
prv_wxVtkVistaCoronal->Delete();
prv_wxVtkVistaSagital->Delete();
prv_wxVtkVista3D->Delete();
prv_auiManager.UnInit();
}
void nkVolViewer::seta_fileName(wxString a_fileName){
this->prv_a_fileName = a_fileName;
}
wxString nkVolViewer::geta_fileName(void){
return this->prv_a_fileName;
}
void nkVolViewer::setImagen(itk::Image<unsigned short,3>::Pointer an_image){
this->prv_imagen = an_image;
}
itk::Image<unsigned short,3>::Pointer nkVolViewer::getImagen(void){
return this->prv_imagen;
}
vtkImageData* nkVolViewer::getVtkImagen(void){
return this->prv_vista3D->GetImage();
}
void nkVolViewer::Configure(void){
prv_vistaAxial->SetInteractionStyle (vtkViewImage2D::SELECT_INTERACTION);
prv_vistaAxial->SetWheelInteractionStyle(vtkViewImage2D::ZOOM_INTERACTION);
prv_vistaAxial->SetMiddleButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION);
prv_vistaAxial->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION);
prv_vistaCoronal->SetInteractionStyle (vtkViewImage2D::SELECT_INTERACTION);
prv_vistaCoronal->SetWheelInteractionStyle(vtkViewImage2D::ZOOM_INTERACTION);
prv_vistaCoronal->SetMiddleButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION);
prv_vistaCoronal->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION);
prv_vistaSagital->SetInteractionStyle (vtkViewImage2D::SELECT_INTERACTION);
prv_vistaSagital->SetWheelInteractionStyle(vtkViewImage2D::ZOOM_INTERACTION);
prv_vistaSagital->SetMiddleButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION);
prv_vistaSagital->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION);
prv_vistaAxial->SetOrientation (vtkViewImage2D::AXIAL_ID);
prv_vistaCoronal->SetOrientation (vtkViewImage2D::CORONAL_ID);
prv_vistaSagital->SetOrientation (vtkViewImage2D::SAGITTAL_ID);
prv_vistaAxial->ScalarBarVisibilityOn();
prv_vistaCoronal->ScalarBarVisibilityOn();
prv_vistaSagital->ScalarBarVisibilityOn();
prv_vista3D->ScalarBarVisibilityOn();
prv_vistaAxial->SetBackgroundColor (0.0,0.0,0.0);
prv_vistaCoronal->SetBackgroundColor (0.0,0.0,0.0);
prv_vistaSagital->SetBackgroundColor (0.0,0.0,0.0);
double color[3] = {0.0,0.0,0.0};
prv_vista3D->SetTextColor (color);
prv_vista3D->SetRenderingModeToPlanar();
prv_vistaAxial->AddChild (prv_vistaCoronal);
prv_vistaAxial->AddChild (prv_vista3D);
prv_vistaCoronal->AddChild (prv_vistaSagital);
prv_vistaSagital->AddChild (prv_vistaAxial);
}
void nkVolViewer::ConfigureITKimage(
wxString un_a_fileName,
itk::Image<unsigned short,3>::Pointer an_image){
this->prv_a_fileName = un_a_fileName;
this->prv_imagen = an_image;
this->prv_vistaAxial->SetITKImage (this->prv_imagen);
this->prv_vistaCoronal->SetITKImage ( this->prv_imagen);
this->prv_vistaSagital->SetITKImage ( this->prv_imagen);
this->prv_vista3D->SetITKImage ( this->prv_imagen);
this->prv_vistaAxial->SyncResetCurrentPoint();
this->prv_vistaAxial->SyncResetWindowLevel();
this->prBoundingBox();
}
void nkVolViewer::prOpenFile(wxString a_fileName){
itk::ImageFileReader<nkVolViewer::ImageType>::Pointer reader;
reader = itk::ImageFileReader<nkVolViewer::ImageType>::New();
itk::AnalyzeImageIOFactory::RegisterOneFactory();
reader->SetFileName (a_fileName.c_str());
try {
reader->Update();
}catch (itk::ExceptionObject & e){
std::cerr << e;
wxMessageDialog* myDialog = new wxMessageDialog(this, _(e.GetDescription()),
wxT ("Error"),
wxOK|wxICON_ERROR);
myDialog->ShowModal();
myDialog->Destroy();
return;
}
this->ConfigureITKimage(a_fileName, reader->GetOutput());
}
void nkVolViewer::prOpenFile_vol(wxString a_fileName){
FILE *fp;
int x[3];
float s[2];
fp = fopen(a_fileName.c_str(),"rb");
seta_fileName(a_fileName);
fread(x,4,3,fp);
#ifndef VTK_WORDS_BIGENDIAN
vtkByteSwap::SwapVoidRange(x,3,4);
#endif
fread(s,4,2,fp);
#ifndef VTK_WORDS_BIGENDIAN
vtkByteSwap::SwapVoidRange(s,2,4);
#endif
fclose(fp);
const int Dimension = 3;
itk::RawImageIO<nkVolViewer::PixelType, Dimension>::Pointer rawImageIO;
rawImageIO = itk::RawImageIO<nkVolViewer::PixelType, Dimension>::New();
rawImageIO->SetHeaderSize(20);
rawImageIO->SetFileDimensionality(Dimension);
rawImageIO->SetByteOrderToBigEndian();
rawImageIO->SetNumberOfComponents(1);
rawImageIO->SetOrigin( 0, 0.0 );
rawImageIO->SetOrigin( 1, 0.0 );
rawImageIO->SetOrigin( 2, 0.0 );
rawImageIO->SetDimensions( 0, x[0]);
rawImageIO->SetDimensions( 1, x[1]);
rawImageIO->SetDimensions( 2, x[2]);
rawImageIO->SetSpacing( 0, s[0] );
rawImageIO->SetSpacing( 1, s[0] );
rawImageIO->SetSpacing( 2, s[1] );
itk::ImageFileReader<nkVolViewer::ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO( rawImageIO );
reader->SetFileName( a_fileName.c_str());
try{
reader->Update();
}catch (itk::ExceptionObject & e){
std::cerr << e;
wxMessageDialog* myDialog = new wxMessageDialog(this, _(e.GetDescription()),
wxT ("Error"),
wxOK|wxICON_ERROR);
myDialog->ShowModal();
myDialog->Destroy();
return;
}
this->ConfigureITKimage(a_fileName, reader->GetOutput());
}
void nkVolViewer::prOpenFile_dicom(wxString a_fileName, wxVtkDICOMImporter* myimporter, int un_index){
#ifdef __WXMAC__
typedef itk::GDCMImporter::FloatImageType DImageType; // vtkInria3D anterior
#else //win and unix
//typedef itk::GDCMImporter2::ImageType DImageType; // vtkInria3D mas reciente
typedef itk::Image<wxVtkDICOMImporter::ImageComponentType, 3> DImageType; // vtkInria3D mas reciente
#endif
itk::RescaleIntensityImageFilter<DImageType, nkVolViewer::ImageType>::Pointer rescaler=
itk::RescaleIntensityImageFilter<DImageType, nkVolViewer::ImageType>::New();
rescaler->SetOutputMinimum ( 0 );
rescaler->SetOutputMaximum ( 65535 );
rescaler->SetInput ( myimporter->GetOutput(un_index) );
try{
rescaler->Update();
}catch (itk::ExceptionObject &e){
std::cerr << e;
return;
}
this->prv_vista3D->SetShift ( rescaler->GetShift() );
this->prv_vista3D->SetScale ( rescaler->GetScale() );
this->ConfigureITKimage(a_fileName, rescaler->GetOutput());
}
void nkVolViewer::cambiarPaletaColor(vtkLookupTable* una_paleta){
if( !una_paleta)
return;
prv_vistaAxial->SyncSetLookupTable (una_paleta);
prv_vistaAxial->Render();
prv_vistaCoronal->Render();
prv_vistaSagital->Render();
prv_vista3D->Render();
}
void nkVolViewer::cambiarFormaDeProcesamiento (int un_modo, int textura_o_mrc){
prv_vista3D->SetRenderingMode(un_modo);
if (un_modo == vtkViewImage3D::VOLUME_RENDERING){
switch(textura_o_mrc ){
case 1:
//prv_vista3D->SetVolumeMapperToTexture();
break;
case 2:
//prv_vista3D->SetVolumeMapperToRayCast();
prv_vista3D->SetVolumeRayCastFunctionToMIP();
break;
case 3:
//prv_vista3D->SetVolumeMapperToRayCast();
prv_vista3D->SetVolumeRayCastFunctionToComposite();
break;
case 4:
//prv_vista3D->SetVolumeMapperToRayCast();
//prv_vista3D->SetVolumeRayCastFunctionToIsosurface();
break;
}
}
prv_vista3D->Render();
}
void nkVolViewer::prSaveFile(wxString a_fileName){
itk::VTKImageToImageFilter<nkVolViewer::ImageType>::Pointer myConverter =
itk::VTKImageToImageFilter<nkVolViewer::ImageType>::New();
vtkImageData* image = vtkImageData::New();
image->DeepCopy(prv_vistaAxial->GetImage());
try {
myConverter->SetInput( image );
myConverter->Update();
}catch (itk::ExceptionObject & e){
std::cerr << e;
return;
}
itk::Matrix<double,3,3> cosines;
cosines[0][0]= 1;
cosines[0][1]= 0;
cosines[0][2]= 0;
cosines[1][0]= 0;
cosines[1][1]=-1;
cosines[1][2]= 0;
cosines[2][0]= 0;
cosines[2][1]= 0;
cosines[2][2]= 1;
ImageType::Pointer itkimage = const_cast<ImageType*>(myConverter->GetOutput());
itkimage->SetDirection(cosines);
itk::ImageFileWriter<ImageType>::Pointer writer
= itk::ImageFileWriter<ImageType>::New();
writer->SetFileName (a_fileName);
writer->SetInput(itkimage);
try{
std::cout << "writing : " << a_fileName << std::endl;
writer->Update();
}catch (itk::ExceptionObject & e){
std::cerr << e;
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(e.GetDescription());
return;
}
image->Delete();
}
void nkVolViewer::prBoundingBox()
{
vtkOutlineFilter *prBoundingBox = vtkOutlineFilter::New(); //! Bounding Box creation
prBoundingBox->SetInput(this->getVtkImagen());
vtkPolyDataMapper *prv_bboxMapper = vtkPolyDataMapper::New(); //! Bounding Box mapper
prv_bboxMapper->SetInput(prBoundingBox->GetOutput());
prv_bboxActor = vtkActor::New(); //! Bounding Box actor
prv_bboxActor->SetMapper(prv_bboxMapper);
prv_bboxActor->GetProperty()->SetColor(1,0.1,0.1); //! Bounding Box color
prv_render3D->AddActor(prv_bboxActor);
prv_bboxActor->VisibilityOff();
}
void nkVolViewer::prBoundingBoxOnOff()
{
if(prv_bboxActor->GetVisibility()==false )
prv_bboxActor->VisibilityOn();
else
prv_bboxActor->VisibilityOff();
prv_render3D->Render();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
void nkVolViewer::BoxWidgetOnOff()
{
/*if( prv_vista3D->GetBoxWidgetVisibility() )
prv_vista3D->BoxWidgetOff();
else
prv_vista3D->BoxWidgetOn();
*/
prv_render3D->Render();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
void nkVolViewer::reiniciarNiveleseDePaleta(void){
prv_vistaAxial->ResetWindowLevel();
prv_vistaCoronal->ResetWindowLevel();
prv_vistaSagital->ResetWindowLevel();
prv_vista3D->ResetWindowLevel();
prv_vistaAxial->Render();
prv_vistaCoronal->Render();
prv_vistaSagital->Render();
prv_vista3D->Render();
}
double nkVolViewer::obtenerValorActualDeContorno(void){
return prv_vistaAxial->GetCurrentPointDoubleValue();
}
//*****************************************************************************************
// Area of axial image
//*****************************************************************************************
void nkVolViewer::Area(void){
//Area calculation
int p_point[3];
prv_vista3D->GetCurrentVoxelCoordinates (p_point);
char temp[100]="";
sprintf(temp,"Coordinate cursor = (%d,%d,%d)\n",p_point[0],p_point[1],p_point[2]);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(temp);
double area=0;
typedef itk::ImageRegionConstIterator< nkVolViewer::ImageType > ConstIteratorType;
ConstIteratorType iterator( prv_imagen, prv_imagen->GetBufferedRegion().GetSize() );
for(iterator.GoToBegin();!iterator.IsAtEnd();++iterator)
{
nkVolViewer::ImageType::IndexType pixelIndex;
pixelIndex = iterator.GetIndex();
if( iterator.Get()>0 && pixelIndex[2]==p_point[2])
area++;
}
nkVolViewer::ImageType::SpacingType spacing;
spacing = prv_imagen->GetSpacing();
sprintf(temp,"\nPixels > 0 = %f\n",area);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(temp);
area*= spacing[0]*spacing[1];
sprintf(temp,"Z =(%d) Area = (%f)\nSpacing=(%f,%f,%f)",p_point[2],area,spacing[0],spacing[1],spacing[2]);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(temp);
}
//*****************************************************************************************
// ACTIVE STEREO
//*****************************************************************************************
void nkVolViewer::prActiveStereo(void){
if(!prv_wxVtkVista3D->GetRenderWindow()->GetStereoRender()) {
prv_wxVtkVista3D->GetRenderWindow()->SetStereoTypeToCrystalEyes();
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOn();
}else
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOff();
prv_wxVtkVista3D->GetRenderWindow()->StereoUpdate();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// PASIVE STEREO
//*****************************************************************************************
void nkVolViewer::prStereoPassive(void){
if(!prv_wxVtkVista3D->GetRenderWindow()->GetStereoRender()) {
prv_wxVtkVista3D->GetRenderWindow()->SetStereoTypeToAnaglyph();
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOn();
}else
prv_wxVtkVista3D->GetRenderWindow()->StereoRenderOff();
prv_wxVtkVista3D->GetRenderWindow()->StereoUpdate();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// STEREO INCREASE - Increase stereo separation
//*****************************************************************************************
void nkVolViewer::prStereoMoreSeparation( void )
{
double sep,
inc=0.1;
sep = prv_camera->GetEyeAngle(); //! Get actual separation
prv_camera->SetEyeAngle(sep+inc); //! Increase separation
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// STEREO DECREASE - Decrease stereo separation
//*****************************************************************************************
void nkVolViewer::prStereoLessSeparation( void )
{
double sep,
inc=0.1;
sep = prv_camera->GetEyeAngle(); //! Get actual separation
prv_camera->SetEyeAngle(sep-inc); //! Decrease separation
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// MENU -> RESET CAMERA
//*****************************************************************************************
void nkVolViewer::prNavResetCamara( void )
{
prv_render3D->ResetCamera();
prv_wxVtkVista3D->Render();
prv_wxVtkVista3D->Refresh();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> TRACKBALL
//*****************************************************************************************
void nkVolViewer::prNavTrackball( )
{
vtkInteractorStyleTrackballCamera *l_style = vtkInteractorStyleTrackballCamera::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> JOYSTICK
//*****************************************************************************************
void nkVolViewer::prNavJoystick( )
{
vtkInteractorStyleJoystickCamera *l_style = vtkInteractorStyleJoystickCamera::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> FLIGHT
//*****************************************************************************************
void nkVolViewer::prNavFlight( )
{
vtkInteractorStyleFlight *l_style = vtkInteractorStyleFlight ::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// MENU -> NAVIGATION -> UNICAM
//*****************************************************************************************
void nkVolViewer::prNavUnicam( )
{
vtkInteractorStyleUnicam *l_style = vtkInteractorStyleUnicam::New();
l_style->SetWorldUpVector(0.0, 0.0, 1.0);
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// FILTER -> GAUSSIAN
//*****************************************************************************************
void nkVolViewer::FilVolGaussian( wxAuiNotebook * p_libro )
{
wxString etiquetas[100];
const int num_datos=2;
etiquetas[0] = _("Variance");
etiquetas[1] = _("Kernel radius");
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
_("Nukak3D: Gauusian filter"),
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
miDlg->cambiarValor(wxT("1.0"),0);
miDlg->cambiarValor(wxT("5"),1);
miDlg->ShowModal();
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
double datos[num_datos];
for(int i=0;i<num_datos;i++)
(miDlg->obtenerValor(i)).ToDouble(&datos[i]);
typedef float InternalPixelType;
typedef itk::Image< InternalPixelType, 3 > InternalImageType;
typedef itk::CastImageFilter<nkVolViewer::ImageType,InternalImageType>
CastFilterInType;
CastFilterInType::Pointer mi_castUnShortToFloat = CastFilterInType::New();
typedef itk::CastImageFilter<InternalImageType, nkVolViewer::ImageType>
CastFilterOutType;
CastFilterOutType::Pointer prv_castOutLevetSet = CastFilterOutType::New();
typedef itk::DiscreteGaussianImageFilter<
InternalImageType,
InternalImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
mi_castUnShortToFloat->SetInput(prv_imagen);
filter->SetVariance( datos[0] );
filter->SetFilterDimensionality(3);
filter->SetMaximumKernelWidth((int)datos[1]);
filter->SetInput(mi_castUnShortToFloat->GetOutput());
prv_castOutLevetSet->SetInput ( filter->GetOutput() );
try
{
prv_castOutLevetSet->Update();
nkVolViewer * mivol = new nkVolViewer(p_libro);
mivol->Configure();
mivol->ConfigureITKimage(_T("Gaussian filter"),prv_castOutLevetSet->GetOutput());
p_libro->AddPage(mivol, _T("Gaussian filter"),true );
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("Exception caught !\n");
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(excep.GetDescription());
}
wxEndBusyCursor();
}
delete miDlg;
}
//*****************************************************************************************
// FILTER -> MEDIAN
//*****************************************************************************************
void nkVolViewer::FilVolMedian( wxAuiNotebook * p_libro )
{
// Captura de parametros
wxString etiquetas[100];
const int num_datos=3;
etiquetas[0] = _("Kernel radius in X");
etiquetas[1] = _("Kernel radius in Y");
etiquetas[2] = _("Kernel radius in Z");
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
_("Nukak3D: Median Filter"),
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
miDlg->cambiarValor(wxT("1"),0);
miDlg->cambiarValor(wxT("1"),1);
miDlg->cambiarValor(wxT("1"),2);
miDlg->ShowModal();
double datos[num_datos];
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
for(int i=0;i<2;i++)
(miDlg->obtenerValor(i)).ToDouble(&datos[i]);
typedef itk::MedianImageFilter<
nkVolViewer::ImageType,
nkVolViewer::ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
ImageType::SizeType indexRadius;
indexRadius[0] = datos[0]; // radius along x
indexRadius[1] = datos[1]; // radius along y
indexRadius[2] = datos[2]; // radius along z
filter->SetRadius( indexRadius );
filter->SetInput(prv_imagen);
try
{
filter->Update();
nkVolViewer * mivol = new nkVolViewer(p_libro);
mivol->Configure();
mivol->ConfigureITKimage(_T("Filtro mediana"),filter->GetOutput());
p_libro->AddPage(mivol, _T("Filtro mediana"),true );
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("Exception caught !\n");
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(excep.GetDescription());
}
wxEndBusyCursor();
}
delete miDlg;
}
//*****************************************************************************************
// Gradient Filter
//*****************************************************************************************
void nkVolViewer::FilVolGradient( )
{
}
//*****************************************************************************************
// Threshold filter
//*****************************************************************************************
void nkVolViewer::FilVolThreshold( )
{
}
//*****************************************************************************************
// Rasterizer window
//*****************************************************************************************
vtkWindowToImageFilter* nkVolViewer::Snapshot( int p_screen )
{
//! Save an window snapshot
vtkWindowToImageFilter* l_w2i = vtkWindowToImageFilter::New();
if(p_screen == 0 )
l_w2i->SetInput(prv_wxVtkVista3D->GetRenderWindow());
else if(p_screen == 1 )
l_w2i->SetInput(prv_wxVtkVistaAxial->GetRenderWindow());
else if(p_screen == 2 )
l_w2i->SetInput(prv_wxVtkVistaCoronal->GetRenderWindow());
else if(p_screen == 3 )
l_w2i->SetInput(prv_wxVtkVistaSagital->GetRenderWindow());
l_w2i->Update();
return l_w2i;
}
//*****************************************************************************************
// VIDEOCARD INFORMATION
//*****************************************************************************************
wxString nkVolViewer::VideoCard( )
{
const char* l_ren = l_ren = prv_wxVtkVista3D->GetRenderWindow()->ReportCapabilities(); //! Capturing Render capabilities from RenderWindow
wxString l_text(l_ren,wxConvUTF8);
return l_text;
}
//*****************************************************************************************
// NUEVO LEVELSETS
//*****************************************************************************************
void nkVolViewer::NuevoLevelSets(wxAuiNotebook * p_libro){
nkLevelSets * miLS = new nkLevelSets(this, p_libro);
miLS->SetInput(prv_imagen);
miLS->Configure();
miLS->CrearAsistente();
miLS->WriteGradientImage();
if(miLS->ConfigureLevelSet()){
miLS->UpdateLevelSets();
}
}
//*****************************************************************************************
// PlanStackChange Execute
//*****************************************************************************************
void nkVolViewer::nkCameraCallback::Execute(vtkObject *p_Caller, unsigned long p_EventId, void *p_CallData)
{
if(!prv_state)
return;
char l_temp[100]="";
double l_camerapos[3];
double l_cameradir[3];
int l_voxel[3];
unsigned short *l_pointer;
unsigned short l_value;
// Check camera position
prv_camera->GetPosition(l_camerapos);
prv_camera->GetDirectionOfProjection(l_cameradir);
//Colisión
if( l_camerapos[0]>=prv_bounds[0] && l_camerapos[0]<prv_bounds[1] &&
l_camerapos[1]>=prv_bounds[2] && l_camerapos[1]<prv_bounds[3] &&
l_camerapos[2]>=prv_bounds[4] && l_camerapos[2]<prv_bounds[5] )
{
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("\nInside volume\n");
//Camera global coordinates in voxel coordinates
l_voxel[0]=(int)( prv_imagesize[0]*l_camerapos[0]/(prv_bounds[1]-prv_bounds[0]) );
l_voxel[1]=(int)( prv_imagesize[1]*l_camerapos[1]/(prv_bounds[3]-prv_bounds[2]) );
l_voxel[2]=(int)( prv_imagesize[2]*l_camerapos[2]/(prv_bounds[5]-prv_bounds[4]) );
//Voxel value
l_pointer = (unsigned short *)prv_imagen->GetScalarPointer(l_voxel[0],l_voxel[1],l_voxel[2]);
l_value = l_pointer[0];
if( l_value>=prv_umbral ) // umbral value detection
{
prv_colision++;
// Colision detection
sprintf(l_temp,"Collision = %d\n",prv_colision);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(l_temp);
// Display camera coordinates
sprintf(l_temp,"Coor( %f | %f | %f ) ",l_camerapos[0],l_camerapos[1],l_camerapos[2]);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(l_temp);
sprintf(l_temp,"Dir( %f | %f | %f )\n",l_cameradir[0],l_cameradir[1],l_cameradir[2]);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(l_temp);
// Display voxel coordinates and value
sprintf(l_temp,"Vox( %d | %d | %d ) = %d \n\n",l_voxel[0],l_voxel[1],l_voxel[2],l_value);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(l_temp);
// IN this point the algorithm must take and action
// stop forward camera movement and return to previous
if(prv_colision)
{
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("Camera stopped");
prv_camera->SetPosition(prv_camerapos);
}
}
else
{
prv_colision=0;
//Store last valid camera position
prv_camerapos[0]=l_camerapos[0];
prv_camerapos[1]=l_camerapos[1];
prv_camerapos[2]=l_camerapos[2];
}
if(prv_updatePlanes)
{
//Set orthogonal planes acording camera position
prv_window->prv_vistaAxial->SetZSlice(l_voxel[2]);
prv_window->prv_vistaCoronal->SetZSlice(l_voxel[1]);
prv_window->prv_vistaSagital->SetZSlice(l_voxel[0]);
}
}
}
//*****************************************************************************************
// Posición de la camara
//*****************************************************************************************
void nkVolViewer::CameraPos()
{
if(prv_camtracking)
{
//Dialogo para solicitar umbral de colisión
wxString etiquetas[100];
const int num_datos=1;
etiquetas[0] = _("Collision threshold");
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
_("Nukak3D: Collision detection"),
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
wxString valor = wxString::Format("%f",this->obtenerValorActualDeContorno());
miDlg->cambiarValor(valor,0);
miDlg->ShowModal(); // Mostrar dialogo
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
long datos; // Arreglo para almacenar los datos
(miDlg->obtenerValor(0)).ToLong(&datos);
//Llamada al callback de la camara para detectar colisiones
prv_cameracallback = nkCameraCallback::New();
prv_cameracallback->SetUmbral((unsigned short)datos);
prv_cameracallback->SetState(prv_camtracking);
prv_cameracallback->SetCameraWindow(prv_camera,prv_camerapos);
prv_cameracallback->SetVista3D(this, prv_vista3D);
prv_cameracallback->SetImage(getVtkImagen(),prv_wxVtkVista3D);
SetCameraEvent(prv_cameracallback);
prv_cameracallback->Delete();
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("Collision activated\n");
// coordenadas del bounding box de la imagen
double bounds[6];
prv_vista3D->GetVolumeActor()->GetBounds(bounds);
char temp[100]="";
sprintf(temp,"Bounding Box %f %f %f\n",bounds[1],bounds[3],bounds[5]);
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(temp);
wxEndBusyCursor();
}
delete miDlg;
prv_camtracking=0; // Camera tracking flag
}
else{
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("Collision deactivated\n");
prv_cameracallback->SetState(prv_camtracking);
prv_camtracking=1; // Camera tracking flag
}
}
//*****************************************************************************************
// Agregar un observador a la cámara para monitorear sus eventos
//*****************************************************************************************
void nkVolViewer::SetCameraEvent(vtkCallbackCommand* p_Event)
{
prv_camera->AddObserver(vtkCommand::AnyEvent ,p_Event);
}
//*****************************************************************************************
// Estilo de navegación tipo endoscopio
//*****************************************************************************************
void nkVolViewer::NavEndoscope( )
{
nkInteractorStyleEndoCamera *l_style = nkInteractorStyleEndoCamera::New();
prv_wxVtkVista3D->SetInteractorStyle(l_style);
l_style->Delete();
}
//*****************************************************************************************
// Actualización de los planos de image
//*****************************************************************************************
void nkVolViewer::NavUpdatePlanes()
{
if(prv_camtracking){
if(prv_updatePlanes)
{
prv_updatePlanes=0;
prv_cameracallback->SetUpdatePlanes(prv_updatePlanes);
}
else{
prv_updatePlanes=1;
prv_cameracallback->SetUpdatePlanes(prv_updatePlanes);
}
}
}
//*****************************************************************************************
// Actualización de los planos de image
//*****************************************************************************************
void nkVolViewer::FPS()
{
if(!prv_fpsflag)
{
prv_fpsEvent=FpsChange::New();
prv_fpsEvent->SetRenderer(prv_render3D);
prv_render3D->AddObserver(vtkCommand::EndEvent,prv_fpsEvent);
prv_fpsEvent->Delete();
prv_fpsflag=1;
}
else
{
prv_render3D->RemoveObserver(vtkCommand::AnyEvent);
prv_fpsflag=0;
}
}
void nkVolViewer::FilterPluginExecute(wxString pluginName, nukak3d::nkKernel &mKernel, wxAuiNotebook * p_libro){
itk::nkImageToImageFilter<nkVolViewer::ImageType, nkVolViewer::ImageType>::Pointer nkFilter;
if(mKernel.getnkITKFilterServer().existITKFilter( std::string( pluginName.c_str())) )
{
unsigned short mtype = 0;
nkFilter = mKernel.getnkITKFilterServer().getkITKFilter(std::string(pluginName.c_str())).createitkFilter(mtype);
unsigned int tamParams = nkFilter->getNumberOfParameter();
wxString etiquetas[100];
const int num_datos=tamParams;
for(int i=0; i<num_datos;i++)
{
char * temp;
nkFilter->getParameterDescription(temp, i);
etiquetas[i] = wxString(temp);
}
nkIODialog * miDlg = new nkIODialog( this,
etiquetas,
num_datos,
-1,
pluginName,
wxDefaultPosition,
wxSize(330,(num_datos+4)*20+40));
miDlg->ShowModal();
if(miDlg->GetReturnCode() == wxID_OK)
{
wxBeginBusyCursor();
double datos[100];
nkFilter->SetInput(getImagen());
for(unsigned int j=0;j<num_datos;j++){
(miDlg->obtenerValor(j)).ToDouble(&datos[j]);
nkFilter->setParameter((void *)(&datos[j]),j);
}
try
{
nkFilter->Update();
nkVolViewer * mivol = new nkVolViewer(p_libro);
mivol->Configure();
mivol->ConfigureITKimage(pluginName,nkFilter->GetOutput());
p_libro->AddPage(mivol, pluginName,true );
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << excep << std::endl;
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText("Exception caught !\n");
if(mensajes) vtkOutputWindow::GetInstance()->DisplayText(excep.GetDescription());
}
wxEndBusyCursor();
}
delete miDlg;
}
} | [
"apinzonf@4b68e429-1748-0410-913f-c2fc311d3372",
"baperezg@4b68e429-1748-0410-913f-c2fc311d3372"
]
| [
[
[
1,
1019
],
[
1022,
1093
]
],
[
[
1020,
1021
]
]
]
|
4c05be3618bf9511b87ac3923ebb27afef849ef9 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/brookbox/src/raytracer.cpp | 347b08101d4df71e570e4c01b3e23265bf814104 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63,054 | cpp |
////////////////////////////////////////////
// Generated by BRCC v0.1
// BRCC Compiled on: Jun 4 2004 15:23:16
////////////////////////////////////////////
#include <brook.hpp>
#include "stdafx.h"
#include "hack.h"
#include "defines.h"
typedef struct t_voxel_t {
float trilist;
} t_voxel;typedef struct __cpustruct_t_voxel_t {
__BrtFloat1 trilist;
}
__cpustruct_t_voxel;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_voxel*) {
static const __BRTStreamType result[] = {__BRTFLOAT, __BRTNONE};
return result;
}
}
typedef struct t_trilist_t {
float triid;
} t_trilist;typedef struct __cpustruct_t_trilist_t {
__BrtFloat1 triid;
}
__cpustruct_t_trilist;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_trilist*) {
static const __BRTStreamType result[] = {__BRTFLOAT, __BRTNONE};
return result;
}
}
typedef struct t_triinfo_t {
float3 v0;
float3 v1;
float3 v2;
float3 n0;
float3 n1;
float3 n2;
float3 color;
float4 mat;
} t_triinfo;typedef struct __cpustruct_t_triinfo_t {
__BrtFloat3 v0;
__BrtFloat3 v1;
__BrtFloat3 v2;
__BrtFloat3 n0;
__BrtFloat3 n1;
__BrtFloat3 n2;
__BrtFloat3 color;
__BrtFloat4 mat;
}
__cpustruct_t_triinfo;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_triinfo*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT4, __BRTNONE};
return result;
}
}
typedef struct t_rayinfo_t {
float4 info;
float3 origin;
float3 direction;
} t_rayinfo;typedef struct __cpustruct_t_rayinfo_t {
__BrtFloat4 info;
__BrtFloat3 origin;
__BrtFloat3 direction;
}
__cpustruct_t_rayinfo;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_rayinfo*) {
static const __BRTStreamType result[] = {__BRTFLOAT4, __BRTFLOAT3, __BRTFLOAT3, __BRTNONE};
return result;
}
}
typedef struct t_raystate_t {
float4 state;
} t_raystate;typedef struct __cpustruct_t_raystate_t {
__BrtFloat4 state;
}
__cpustruct_t_raystate;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_raystate*) {
static const __BRTStreamType result[] = {__BRTFLOAT4, __BRTNONE};
return result;
}
}
typedef struct t_traverserstate_t {
float3 voxel;
float3 tmax;
} t_traverserstate;typedef struct __cpustruct_t_traverserstate_t {
__BrtFloat3 voxel;
__BrtFloat3 tmax;
}
__cpustruct_t_traverserstate;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_traverserstate*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTFLOAT3, __BRTNONE};
return result;
}
}
typedef struct t_intersectorstate_t {
float3 tripos;
} t_intersectorstate;typedef struct __cpustruct_t_intersectorstate_t {
__BrtFloat3 tripos;
}
__cpustruct_t_intersectorstate;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_intersectorstate*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTNONE};
return result;
}
}
typedef struct t_framebufferstate_t {
float3 color;
} t_framebufferstate;typedef struct __cpustruct_t_framebufferstate_t {
__BrtFloat3 color;
}
__cpustruct_t_framebufferstate;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_framebufferstate*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTNONE};
return result;
}
}
typedef struct t_dispatcherstate_t {
float3 phase;
float4 hitinfo;
float3 hitdirection;
float3 hitnormal;
float4 hitmat;
} t_dispatcherstate;typedef struct __cpustruct_t_dispatcherstate_t {
__BrtFloat3 phase;
__BrtFloat4 hitinfo;
__BrtFloat3 hitdirection;
__BrtFloat3 hitnormal;
__BrtFloat4 hitmat;
}
__cpustruct_t_dispatcherstate;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_dispatcherstate*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTFLOAT4, __BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT4, __BRTNONE};
return result;
}
}
typedef struct t_camera_t {
float3 pos;
float3 dir;
float2 fov;
float4 quat;
} t_camera;typedef struct __cpustruct_t_camera_t {
__BrtFloat3 pos;
__BrtFloat3 dir;
__BrtFloat2 fov;
__BrtFloat4 quat;
}
__cpustruct_t_camera;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_camera*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTFLOAT3, __BRTFLOAT2, __BRTFLOAT4, __BRTNONE};
return result;
}
}
typedef struct t_light_t {
float3 pos;
float3 color;
} t_light;typedef struct __cpustruct_t_light_t {
__BrtFloat3 pos;
__BrtFloat3 color;
}
__cpustruct_t_light;
namespace brook {
template<> const __BRTStreamType* getStreamType(t_light*) {
static const __BRTStreamType result[] = {__BRTFLOAT3, __BRTFLOAT3, __BRTNONE};
return result;
}
}
extern t_voxel *scene_voxels;
extern t_trilist *scene_trilist;
extern t_triinfo *scene_triinfos;
extern t_camera *scene_camera;
extern t_light *scene_lights;
extern t_rayinfo *input_rayinfo;
extern t_raystate *input_raystate;
extern t_framebufferstate *input_framebufferstate;
extern t_dispatcherstate *input_dispatcherstate;
extern t_rayinfo *output_rayinfo;
extern t_raystate *output_raystate;
extern t_traverserstate *output_traverserstate;
extern t_intersectorstate *output_intersectorstate;
extern t_framebufferstate *output_framebufferstate;
extern t_dispatcherstate *output_dispatcherstate;
#ifndef STRUCTURES_ONLY
#include "scene.h"
#include "debug.h"
#include "raytracer.h"
static const char *__setup_ps20= NULL;
static const char *__setup_fp30= NULL;
static const char *__setup_arb= NULL;
void __setup_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __BrtArray1d<__cpustruct_t_voxel > &scene_voxels,
__cpustruct_t_raystate &ors,
__cpustruct_t_traverserstate &ots){
__BrtFloat3 boxa = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
__BrtFloat3 boxb = __BrtFloat3 (VOXELSX * VOXELSIZEX,VOXELSY * VOXELSIZEY,VOXELSZ * VOXELSIZEZ);
__BrtFloat3 voxelsize = __BrtFloat3 (VOXELSIZEX,VOXELSIZEY,VOXELSIZEZ);
__BrtFloat3 vboxa = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
__BrtFloat3 vboxb = __BrtFloat3 (VOXELSX,VOXELSY,VOXELSZ);
__BrtFloat3 s = __sign_cpu_inner(iri.direction);
__BrtFloat4 o;
__BrtFloat3 point;
__BrtFloat3 t;
__BrtFloat3 nullray = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
ors = irs;
if (ors.state.swizzle1(maskX) == RAYSTATE_SETUP)
{
if (__point_in_box_cpu_inner(boxa,boxb,iri.origin))
{
ors.state.mask1(RAYSTATE_TRAVERSING,maskX);
point = iri.origin;
}
else
{
__BrtFloat3 ir = __intersect_box_cpu_inner(boxa,boxb,iri.origin,iri.direction);
ors.state.mask1(ir.swizzle1(maskX),maskX);
if (ir.swizzle1(maskX) == RAYSTATE_SHADING)
ors.state.mask1(RAYSTATUS_OUT,maskW);
point = iri.origin + (__BrtFloat1((float)1) + FPHAZARD_ENTERINGRAYSHIFT) * ir.swizzle1(maskY) * iri.direction;
}
ots.voxel = __voxel_addr_cpu_inner(point);
t = __frac_cpu_inner(point);
if (s.swizzle1(maskX) >= __BrtFloat1((float)0))
{
t.mask1(__BrtFloat1((float)1) - t.swizzle1(maskX),maskX);
}
if (s.swizzle1(maskY) >= __BrtFloat1((float)0))
{
t.mask1(__BrtFloat1((float)1) - t.swizzle1(maskY),maskY);
}
if (s.swizzle1(maskZ) >= __BrtFloat1((float)0))
{
t.mask1(__BrtFloat1((float)1) - t.swizzle1(maskZ),maskZ);
}
ots.tmax = t / __abs_cpu_inner(iri.direction);
if ((__BrtFloat1 ) (ors.state.swizzle1(maskX)) == RAYSTATE_TRAVERSING)
{
__cpustruct_t_voxel v;
v = scene_voxels[__VOXELADDR_cpu_inner(ots.voxel.swizzle1(maskX),ots.voxel.swizzle1(maskY),ots.voxel.swizzle1(maskZ))];
if (v.trilist > __BrtFloat1((float)0))
{
ors.state.mask1(RAYSTATE_INTERSECTING,maskX);
ors.state.mask1(v.trilist + __BrtFloat1((float)1),maskY);
}
}
if (iri.direction == nullray)
{
ors.state.mask1(RAYSTATE_DISPATCHING,maskX);
}
}
}
void __setup_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__BrtArray1d<__cpustruct_t_voxel > arg2(
(__cpustruct_t_voxel *)args[2], extents[2]);
__cpustruct_t_raystate*arg3 = (__cpustruct_t_raystate*)args[3];
__cpustruct_t_traverserstate*arg4 = (__cpustruct_t_traverserstate*)args[4];
unsigned int dim=dims[3];
unsigned int newline=extents[3][dim-1];
unsigned int ratio0 = extents[3][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[3][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[3]);
unsigned int ratio1 = extents[3][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[3][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[3]);
arg3+=mapbegin;
unsigned int ratio4 = extents[3][dim-1]/extents[4][dim-1];
unsigned int scale4=extents[4][dim-1]/extents[3][dim-1];
if (scale4<1) scale4 = 1;
unsigned int ratioiter4 = 0;
if (ratio4) ratioiter4 = mapbegin%ratio4;
unsigned int iter4 = getIndexOf(mapbegin,extents[4], dim, extents[3]);
unsigned int i=0;
while (i<mapextent) {
__setup_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
arg2,
*arg3,
*(arg4 + iter4));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
++arg3;
if (++ratioiter4>=ratio4){
ratioiter4=0;
iter4+=scale4;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[3]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[3]);
iter4=getIndexOf(i+mapbegin,extents[4],dim, extents[3]);
}
}
}
void setup (::brook::stream iri,
::brook::stream irs,
::brook::stream scene_voxels,
::brook::stream ors,
::brook::stream ots) {
static const void *__setup_fp[] = {
"fp30", __setup_fp30,
"arb", __setup_arb,
"ps20", __setup_ps20,
"cpu", (void *) __setup_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__setup_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushGatherStream(scene_voxels);
k->PushOutput(ors);
k->PushOutput(ots);
k->Map();
}
static const char *__traverser_ps20= NULL;
static const char *__traverser_fp30= NULL;
static const char *__traverser_arb= NULL;
void __traverser_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __cpustruct_t_traverserstate &its,
const __BrtArray1d<__cpustruct_t_voxel > &scene_voxels,
__cpustruct_t_raystate &ors,
__cpustruct_t_traverserstate &ots){
__BrtFloat3 vboxa = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
__BrtFloat3 vboxb = __BrtFloat3 (VOXELSX,VOXELSY,VOXELSZ);
__BrtFloat3 tmax = its.tmax;
__BrtFloat3 voxel = its.voxel;
ors = irs;
if (irs.state.swizzle1(maskX) == RAYSTATE_TRAVERSING)
{
__BrtFloat3 z = __BrtFloat3 (iri.info.swizzle1(maskZ),iri.info.swizzle1(maskZ),iri.info.swizzle1(maskZ));
__BrtFloat3 c = tmax >= z;
if (__all_cpu_inner(c))
{
ors.state.mask1(RAYSTATE_SHADING,maskX);
ors.state.mask1(RAYSTATUS_MISSED,maskW);
}
else
{
__cpustruct_t_voxel v;
__BrtFloat3 rstep = __sign_cpu_inner(iri.direction);
__BrtFloat3 rdelta = __abs_cpu_inner(__BrtFloat1((float)1) / iri.direction);
__BrtFloat3 c1;
__BrtFloat3 c2;
if (tmax.swizzle1(maskX) < tmax.swizzle1(maskY))
{
if (tmax.swizzle1(maskX) < tmax.swizzle1(maskZ))
{
voxel.mask1(voxel.swizzle1(maskX) + rstep.swizzle1(maskX),maskX);
tmax.mask1(tmax.swizzle1(maskX) + rdelta.swizzle1(maskX),maskX);
}
else
{
voxel.mask1(voxel.swizzle1(maskZ) + rstep.swizzle1(maskZ),maskZ);
tmax.mask1(tmax.swizzle1(maskZ) + rdelta.swizzle1(maskZ),maskZ);
}
}
else
{
if (tmax.swizzle1(maskY) < tmax.swizzle1(maskZ))
{
voxel.mask1(voxel.swizzle1(maskY) + rstep.swizzle1(maskY),maskY);
tmax.mask1(tmax.swizzle1(maskY) + rdelta.swizzle1(maskY),maskY);
}
else
{
voxel.mask1(voxel.swizzle1(maskZ) + rstep.swizzle1(maskZ),maskZ);
tmax.mask1(tmax.swizzle1(maskZ) + rdelta.swizzle1(maskZ),maskZ);
}
}
c1 = voxel >= vboxa;
c2 = voxel <= vboxb;
if (__all_cpu_inner(c1) && __all_cpu_inner(c2))
{
v = scene_voxels[__VOXELADDR_cpu_inner(voxel.swizzle1(maskX),voxel.swizzle1(maskY),voxel.swizzle1(maskZ))];
if (v.trilist > __BrtFloat1((float)0))
{
ors.state.mask1(RAYSTATE_INTERSECTING,maskX);
ors.state.mask1(v.trilist + __BrtFloat1((float)1),maskY);
}
}
else
{
ors.state.mask1(RAYSTATE_SHADING,maskX);
ors.state.mask1(RAYSTATUS_MISSED,maskW);
}
}
}
ots.tmax = tmax;
ots.voxel = voxel;
}
void __traverser_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__cpustruct_t_traverserstate*arg2 = (__cpustruct_t_traverserstate*)args[2];
__BrtArray1d<__cpustruct_t_voxel > arg3(
(__cpustruct_t_voxel *)args[3], extents[3]);
__cpustruct_t_raystate*arg4 = (__cpustruct_t_raystate*)args[4];
__cpustruct_t_traverserstate*arg5 = (__cpustruct_t_traverserstate*)args[5];
unsigned int dim=dims[4];
unsigned int newline=extents[4][dim-1];
unsigned int ratio0 = extents[4][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[4][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[4]);
unsigned int ratio1 = extents[4][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[4][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[4]);
unsigned int ratio2 = extents[4][dim-1]/extents[2][dim-1];
unsigned int scale2=extents[2][dim-1]/extents[4][dim-1];
if (scale2<1) scale2 = 1;
unsigned int ratioiter2 = 0;
if (ratio2) ratioiter2 = mapbegin%ratio2;
unsigned int iter2 = getIndexOf(mapbegin,extents[2], dim, extents[4]);
arg4+=mapbegin;
unsigned int ratio5 = extents[4][dim-1]/extents[5][dim-1];
unsigned int scale5=extents[5][dim-1]/extents[4][dim-1];
if (scale5<1) scale5 = 1;
unsigned int ratioiter5 = 0;
if (ratio5) ratioiter5 = mapbegin%ratio5;
unsigned int iter5 = getIndexOf(mapbegin,extents[5], dim, extents[4]);
unsigned int i=0;
while (i<mapextent) {
__traverser_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
*(arg2 + iter2),
arg3,
*arg4,
*(arg5 + iter5));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
if (++ratioiter2>=ratio2){
ratioiter2=0;
iter2+=scale2;
}
++arg4;
if (++ratioiter5>=ratio5){
ratioiter5=0;
iter5+=scale5;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[4]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[4]);
iter2=getIndexOf(i+mapbegin,extents[2],dim, extents[4]);
iter5=getIndexOf(i+mapbegin,extents[5],dim, extents[4]);
}
}
}
void traverser (::brook::stream iri,
::brook::stream irs,
::brook::stream its,
::brook::stream scene_voxels,
::brook::stream ors,
::brook::stream ots) {
static const void *__traverser_fp[] = {
"fp30", __traverser_fp30,
"arb", __traverser_arb,
"ps20", __traverser_ps20,
"cpu", (void *) __traverser_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__traverser_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushStream(its);
k->PushGatherStream(scene_voxels);
k->PushOutput(ors);
k->PushOutput(ots);
k->Map();
}
static const char *__intersector_ps20= NULL;
static const char *__intersector_fp30= NULL;
static const char *__intersector_arb= NULL;
void __intersector_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __cpustruct_t_intersectorstate &iis,
const __cpustruct_t_traverserstate &its,
const __BrtArray1d<__cpustruct_t_trilist > &scene_trilist,
const __BrtArray1d<__cpustruct_t_triinfo > &scene_triinfos,
__cpustruct_t_raystate &ors,
__cpustruct_t_intersectorstate &ois){
ors = irs;
ois = iis;
if (irs.state.swizzle1(maskX) == RAYSTATE_INTERSECTING && irs.state.swizzle1(maskY) > __BrtFloat1((float)1))
{
ois.tripos.mask1(irs.state.swizzle1(maskY) - __BrtFloat1((float)1),maskX);
ois.tripos.mask1(CG_FLT_MAX,maskY);
ors.state.mask1(__BrtFloat1((float)0),maskY);
ors.state.mask1(__BrtFloat1((float)0),maskW);
}
if (irs.state.swizzle1(maskX) == RAYSTATE_INTERSECTING)
{
__cpustruct_t_trilist tl = scene_trilist[ois.tripos.swizzle1(maskX)];
if (tl.triid >= __BrtFloat1((float)1))
{
__cpustruct_t_triinfo ti = scene_triinfos[tl.triid];
__BrtFloat4 hit = __intersect_triangle_cpu_inner(iri.origin,iri.direction,ti.v0,ti.v1,ti.v2);
if (hit.swizzle1(maskW))
{
__BrtFloat3 hitpoint = iri.origin + iri.direction * hit.swizzle1(maskX);
__BrtFloat3 voxelsize = __BrtFloat3 (VOXELSIZEX,VOXELSIZEY,VOXELSIZEZ);
__BrtFloat3 voxela = its.voxel * voxelsize;
__BrtFloat3 voxelb = voxela + voxelsize;
__BrtFloat3 c1 = voxela <= hitpoint;
__BrtFloat3 c2 = hitpoint <= voxelb;
if (iri.info.swizzle1(maskZ) == CG_FLT_MAX)
{
if (hit.swizzle1(maskX) < ois.tripos.swizzle1(maskY) && __all_cpu_inner(c1) && __all_cpu_inner(c2) && hit.swizzle1(maskX) <= iri.info.swizzle1(maskZ))
{
ors.state.mask1(hit.swizzle1(maskY),maskY);
ors.state.mask1(hit.swizzle1(maskZ),maskZ);
ors.state.mask1(tl.triid,maskW);
ois.tripos.mask1(hit.swizzle1(maskX),maskY);
}
}
else
{
if (__all_cpu_inner(c1) && __all_cpu_inner(c2) && hit.swizzle1(maskX) <= iri.info.swizzle1(maskZ))
{
ors.state.mask1(ors.state.swizzle1(maskZ) * ti.mat.swizzle1(maskZ),maskZ);
if (ors.state.swizzle1(maskZ) < ALMOST_NOLIGHT)
ors.state.mask1(__BrtFloat1((float)1),maskW);
}
}
}
ois.tripos.mask1(ois.tripos.swizzle1(maskX) + __BrtFloat1((float)1),maskX);
}
else
{
if (irs.state.swizzle1(maskW))
{
ors.state.mask1(RAYSTATE_SHADING,maskX);
}
else
{
ors.state.mask1(RAYSTATE_TRAVERSING,maskX);
}
}
}
}
void __intersector_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__cpustruct_t_intersectorstate*arg2 = (__cpustruct_t_intersectorstate*)args[2];
__cpustruct_t_traverserstate*arg3 = (__cpustruct_t_traverserstate*)args[3];
__BrtArray1d<__cpustruct_t_trilist > arg4(
(__cpustruct_t_trilist *)args[4], extents[4]);
__BrtArray1d<__cpustruct_t_triinfo > arg5(
(__cpustruct_t_triinfo *)args[5], extents[5]);
__cpustruct_t_raystate*arg6 = (__cpustruct_t_raystate*)args[6];
__cpustruct_t_intersectorstate*arg7 = (__cpustruct_t_intersectorstate*)args[7];
unsigned int dim=dims[6];
unsigned int newline=extents[6][dim-1];
unsigned int ratio0 = extents[6][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[6][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[6]);
unsigned int ratio1 = extents[6][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[6][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[6]);
unsigned int ratio2 = extents[6][dim-1]/extents[2][dim-1];
unsigned int scale2=extents[2][dim-1]/extents[6][dim-1];
if (scale2<1) scale2 = 1;
unsigned int ratioiter2 = 0;
if (ratio2) ratioiter2 = mapbegin%ratio2;
unsigned int iter2 = getIndexOf(mapbegin,extents[2], dim, extents[6]);
unsigned int ratio3 = extents[6][dim-1]/extents[3][dim-1];
unsigned int scale3=extents[3][dim-1]/extents[6][dim-1];
if (scale3<1) scale3 = 1;
unsigned int ratioiter3 = 0;
if (ratio3) ratioiter3 = mapbegin%ratio3;
unsigned int iter3 = getIndexOf(mapbegin,extents[3], dim, extents[6]);
arg6+=mapbegin;
unsigned int ratio7 = extents[6][dim-1]/extents[7][dim-1];
unsigned int scale7=extents[7][dim-1]/extents[6][dim-1];
if (scale7<1) scale7 = 1;
unsigned int ratioiter7 = 0;
if (ratio7) ratioiter7 = mapbegin%ratio7;
unsigned int iter7 = getIndexOf(mapbegin,extents[7], dim, extents[6]);
unsigned int i=0;
while (i<mapextent) {
__intersector_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
*(arg2 + iter2),
*(arg3 + iter3),
arg4,
arg5,
*arg6,
*(arg7 + iter7));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
if (++ratioiter2>=ratio2){
ratioiter2=0;
iter2+=scale2;
}
if (++ratioiter3>=ratio3){
ratioiter3=0;
iter3+=scale3;
}
++arg6;
if (++ratioiter7>=ratio7){
ratioiter7=0;
iter7+=scale7;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[6]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[6]);
iter2=getIndexOf(i+mapbegin,extents[2],dim, extents[6]);
iter3=getIndexOf(i+mapbegin,extents[3],dim, extents[6]);
iter7=getIndexOf(i+mapbegin,extents[7],dim, extents[6]);
}
}
}
void intersector (::brook::stream iri,
::brook::stream irs,
::brook::stream iis,
::brook::stream its,
::brook::stream scene_trilist,
::brook::stream scene_triinfos,
::brook::stream ors,
::brook::stream ois) {
static const void *__intersector_fp[] = {
"fp30", __intersector_fp30,
"arb", __intersector_arb,
"ps20", __intersector_ps20,
"cpu", (void *) __intersector_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__intersector_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushStream(iis);
k->PushStream(its);
k->PushGatherStream(scene_trilist);
k->PushGatherStream(scene_triinfos);
k->PushOutput(ors);
k->PushOutput(ois);
k->Map();
}
static const char *__dispatcher_ps20= NULL;
static const char *__dispatcher_fp30= NULL;
static const char *__dispatcher_arb= NULL;
void __dispatcher_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __cpustruct_t_dispatcherstate &ids,
const __BrtArray1d<__cpustruct_t_triinfo > &scene_triinfos,
const __BrtArray1d<__cpustruct_t_light > &scene_lights,
__cpustruct_t_rayinfo &ori,
__cpustruct_t_raystate &ors,
__cpustruct_t_dispatcherstate &ods){
ori = iri;
ors = irs;
ods = ids;
if (irs.state.swizzle1(maskX) == RAYSTATE_DISPATCHING)
{
ors.state.mask1(RAYSTATE_SETUP,maskX);
if (ods.phase.swizzle1(maskY) == __BrtFloat1((float)0))
{
if (ors.state.swizzle1(maskW) <= __BrtFloat1((float)0))
{
ods.phase.mask1(NUMLIGHTS,maskY);
}
else
{
if (ods.phase.swizzle1(maskX) == __BrtFloat1((float)0) || ods.phase.swizzle1(maskX) == __BrtFloat1((float)1) || ods.phase.swizzle1(maskX) == __BrtFloat1((float)2))
{
__cpustruct_t_triinfo ti;
__BrtFloat3 hit;
__BrtFloat3 barycoord;
__BrtFloat3 edge1;
__BrtFloat3 edge2;
ods.hitinfo.mask3(ors.state.swizzle3(maskW, maskY, maskZ),maskX,maskY,maskZ);
ods.hitdirection = -iri.direction;
ti = scene_triinfos[ods.hitinfo.swizzle1(maskX)];
ods.hitinfo.mask1(iri.info.swizzle1(maskW),maskW);
ods.hitmat = ti.mat;
edge1 = ti.v1 - ti.v0;
edge2 = ti.v2 - ti.v0;
hit = ti.v0 + ods.hitinfo.swizzle1(maskY) * edge1 + ods.hitinfo.swizzle1(maskZ) * edge2;
barycoord = __BrtFloat3 (ods.hitinfo.swizzle1(maskY),ods.hitinfo.swizzle1(maskZ),__BrtFloat1(1.000000f) - ods.hitinfo.swizzle1(maskY) - ods.hitinfo.swizzle1(maskZ));
ods.hitnormal = __normalize_cpu_inner(barycoord.swizzle1(maskX) * ti.n1 + barycoord.swizzle1(maskY) * ti.n2 + barycoord.swizzle1(maskZ) * ti.n0);
if (__dot_cpu_inner(ods.hitnormal,ods.hitdirection) < __BrtFloat1((float)0))
{
ods.hitnormal = -ods.hitnormal;
}
}
}
}
ods.phase.mask1(ods.phase.swizzle1(maskY) + __BrtFloat1((float)1),maskY);
if (ods.phase.swizzle1(maskY) >= NUMLIGHTS + __BrtFloat1((float)1))
{
ods.phase.mask1(ods.phase.swizzle1(maskX) + __BrtFloat1((float)1),maskX);
ods.phase.mask1(__BrtFloat1((float)0),maskY);
if (ods.phase.swizzle1(maskX) >= NUMSAMPLES)
{
ors.state.mask1(RAYSTATE_DONE,maskX);
}
}
{
__cpustruct_t_triinfo ti = scene_triinfos[ods.hitinfo.swizzle1(maskX)];
__BrtFloat3 edge1 = ti.v1 - ti.v0;
__BrtFloat3 edge2 = ti.v2 - ti.v0;
__BrtFloat3 hit = ti.v0 + ods.hitinfo.swizzle1(maskY) * edge1 + ods.hitinfo.swizzle1(maskZ) * edge2;
if (ods.phase.swizzle1(maskY) == __BrtFloat1((float)0))
{
__BrtFloat3 normal_vec = __normalize_cpu_inner(__cross_cpu_inner(edge1,edge2));
if (__frac_cpu_inner(ods.phase.swizzle1(maskX) / __BrtFloat1(2.000000f)) >= __BrtFloat1(0.500000f))
{
ori.info.mask1(ods.hitinfo.swizzle1(maskW) * ods.hitmat.swizzle1(maskY),maskW);
ori.info.mask1(CG_FLT_MAX,maskZ);
ori.direction = __normalize_cpu_inner(__reflect_cpu_inner(-ods.hitdirection,ods.hitnormal));
ori.origin = hit + FPHAZARD_REFLECTEDRAYSHIFT * ori.direction;
}
else
{
ori.info.mask1(ods.hitinfo.swizzle1(maskW) * ods.hitmat.swizzle1(maskZ),maskW);
ori.info.mask1(CG_FLT_MAX,maskZ);
ori.direction = __normalize_cpu_inner(__refract_cpu_inner(-ods.hitdirection,ods.hitnormal,ti.mat.swizzle1(maskW)));
ori.origin = hit + FPHAZARD_REFLECTEDRAYSHIFT * ori.direction;
}
}
else
{
__cpustruct_t_light light = scene_lights[ods.phase.swizzle1(maskY) - __BrtFloat1((float)1)];
__BrtFloat3 light_vec = light.pos - hit;
__BrtFloat1 side1 = __dot_cpu_inner(ods.hitnormal,ods.hitdirection);
__BrtFloat1 side2 = __dot_cpu_inner(ods.hitnormal,__normalize_cpu_inner(light_vec));
if (__sign_cpu_inner(side1) == __sign_cpu_inner(side2))
{
ori.info.mask1(ods.hitinfo.swizzle1(maskW) * ods.hitmat.swizzle1(maskX),maskW);
ori.info.mask1(__length_cpu_inner(light_vec),maskZ);
ori.direction = __normalize_cpu_inner(light_vec);
ori.origin = hit + FPHAZARD_SHADOWRAYSHIFT * ori.direction;
ors.state.mask1(__BrtFloat1((float)1) / NUMLIGHTS,maskZ);
}
else
{
ors.state.mask1(RAYSTATE_DISPATCHING,maskX);
}
}
}
}
}
void __dispatcher_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__cpustruct_t_dispatcherstate*arg2 = (__cpustruct_t_dispatcherstate*)args[2];
__BrtArray1d<__cpustruct_t_triinfo > arg3(
(__cpustruct_t_triinfo *)args[3], extents[3]);
__BrtArray1d<__cpustruct_t_light > arg4(
(__cpustruct_t_light *)args[4], extents[4]);
__cpustruct_t_rayinfo*arg5 = (__cpustruct_t_rayinfo*)args[5];
__cpustruct_t_raystate*arg6 = (__cpustruct_t_raystate*)args[6];
__cpustruct_t_dispatcherstate*arg7 = (__cpustruct_t_dispatcherstate*)args[7];
unsigned int dim=dims[5];
unsigned int newline=extents[5][dim-1];
unsigned int ratio0 = extents[5][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[5][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[5]);
unsigned int ratio1 = extents[5][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[5][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[5]);
unsigned int ratio2 = extents[5][dim-1]/extents[2][dim-1];
unsigned int scale2=extents[2][dim-1]/extents[5][dim-1];
if (scale2<1) scale2 = 1;
unsigned int ratioiter2 = 0;
if (ratio2) ratioiter2 = mapbegin%ratio2;
unsigned int iter2 = getIndexOf(mapbegin,extents[2], dim, extents[5]);
arg5+=mapbegin;
unsigned int ratio6 = extents[5][dim-1]/extents[6][dim-1];
unsigned int scale6=extents[6][dim-1]/extents[5][dim-1];
if (scale6<1) scale6 = 1;
unsigned int ratioiter6 = 0;
if (ratio6) ratioiter6 = mapbegin%ratio6;
unsigned int iter6 = getIndexOf(mapbegin,extents[6], dim, extents[5]);
unsigned int ratio7 = extents[5][dim-1]/extents[7][dim-1];
unsigned int scale7=extents[7][dim-1]/extents[5][dim-1];
if (scale7<1) scale7 = 1;
unsigned int ratioiter7 = 0;
if (ratio7) ratioiter7 = mapbegin%ratio7;
unsigned int iter7 = getIndexOf(mapbegin,extents[7], dim, extents[5]);
unsigned int i=0;
while (i<mapextent) {
__dispatcher_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
*(arg2 + iter2),
arg3,
arg4,
*arg5,
*(arg6 + iter6),
*(arg7 + iter7));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
if (++ratioiter2>=ratio2){
ratioiter2=0;
iter2+=scale2;
}
++arg5;
if (++ratioiter6>=ratio6){
ratioiter6=0;
iter6+=scale6;
}
if (++ratioiter7>=ratio7){
ratioiter7=0;
iter7+=scale7;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[5]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[5]);
iter2=getIndexOf(i+mapbegin,extents[2],dim, extents[5]);
iter6=getIndexOf(i+mapbegin,extents[6],dim, extents[5]);
iter7=getIndexOf(i+mapbegin,extents[7],dim, extents[5]);
}
}
}
void dispatcher (::brook::stream iri,
::brook::stream irs,
::brook::stream ids,
::brook::stream scene_triinfos,
::brook::stream scene_lights,
::brook::stream ori,
::brook::stream ors,
::brook::stream ods) {
static const void *__dispatcher_fp[] = {
"fp30", __dispatcher_fp30,
"arb", __dispatcher_arb,
"ps20", __dispatcher_ps20,
"cpu", (void *) __dispatcher_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__dispatcher_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushStream(ids);
k->PushGatherStream(scene_triinfos);
k->PushGatherStream(scene_lights);
k->PushOutput(ori);
k->PushOutput(ors);
k->PushOutput(ods);
k->Map();
}
static const char *__shader_simple_ps20= NULL;
static const char *__shader_simple_fp30= NULL;
static const char *__shader_simple_arb= NULL;
void __shader_simple_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __BrtArray1d<__cpustruct_t_triinfo > &scene_triinfos,
__cpustruct_t_raystate &ors,
__cpustruct_t_framebufferstate &ofs){
ors = irs;
if (irs.state.swizzle1(maskX) == RAYSTATE_SHADING)
{
__cpustruct_t_triinfo ti = scene_triinfos[irs.state.swizzle1(maskW)];
ofs.color = ti.color;
ors.state.mask1(RAYSTATE_DONE,maskX);
}
else
{
if (irs.state.swizzle1(maskX) == RAYSTATE_OUT)
{
ofs.color = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
}
else
{
ofs.color = __BrtFloat3 (__BrtFloat1(0.200000f),__BrtFloat1(0.200000f),__BrtFloat1(0.200000f));
}
}
}
void __shader_simple_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__BrtArray1d<__cpustruct_t_triinfo > arg2(
(__cpustruct_t_triinfo *)args[2], extents[2]);
__cpustruct_t_raystate*arg3 = (__cpustruct_t_raystate*)args[3];
__cpustruct_t_framebufferstate*arg4 = (__cpustruct_t_framebufferstate*)args[4];
unsigned int dim=dims[3];
unsigned int newline=extents[3][dim-1];
unsigned int ratio0 = extents[3][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[3][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[3]);
unsigned int ratio1 = extents[3][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[3][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[3]);
arg3+=mapbegin;
unsigned int ratio4 = extents[3][dim-1]/extents[4][dim-1];
unsigned int scale4=extents[4][dim-1]/extents[3][dim-1];
if (scale4<1) scale4 = 1;
unsigned int ratioiter4 = 0;
if (ratio4) ratioiter4 = mapbegin%ratio4;
unsigned int iter4 = getIndexOf(mapbegin,extents[4], dim, extents[3]);
unsigned int i=0;
while (i<mapextent) {
__shader_simple_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
arg2,
*arg3,
*(arg4 + iter4));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
++arg3;
if (++ratioiter4>=ratio4){
ratioiter4=0;
iter4+=scale4;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[3]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[3]);
iter4=getIndexOf(i+mapbegin,extents[4],dim, extents[3]);
}
}
}
void shader_simple (::brook::stream iri,
::brook::stream irs,
::brook::stream scene_triinfos,
::brook::stream ors,
::brook::stream ofs) {
static const void *__shader_simple_fp[] = {
"fp30", __shader_simple_fp30,
"arb", __shader_simple_arb,
"ps20", __shader_simple_ps20,
"cpu", (void *) __shader_simple_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__shader_simple_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushGatherStream(scene_triinfos);
k->PushOutput(ors);
k->PushOutput(ofs);
k->Map();
}
static const char *__shader_flat_ps20= NULL;
static const char *__shader_flat_fp30= NULL;
static const char *__shader_flat_arb= NULL;
void __shader_flat_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __BrtArray1d<__cpustruct_t_triinfo > &scene_triinfos,
const __BrtArray1d<__cpustruct_t_light > &scene_lights,
__cpustruct_t_raystate &ors,
__cpustruct_t_framebufferstate &ofs){
ors = irs;
if (irs.state.swizzle1(maskX) == RAYSTATE_SHADING)
{
__cpustruct_t_triinfo ti = scene_triinfos[irs.state.swizzle1(maskW)];
__cpustruct_t_light light = scene_lights[__BrtFloat1((float)0)];
__BrtFloat3 edge1 = ti.v1 - ti.v0;
__BrtFloat3 edge2 = ti.v2 - ti.v0;
__BrtFloat3 hit = ti.v0 + __BrtFloat1(0.500000f) * edge1 + __BrtFloat1(0.500000f) * edge2;
__BrtFloat3 normal_vec = __normalize_cpu_inner(__cross_cpu_inner(edge1,edge2));
__BrtFloat3 light_vec = __normalize_cpu_inner(light.pos - hit);
__BrtFloat3 eye_vec = __normalize_cpu_inner(iri.origin - hit);
__BrtFloat3 half_vec = __normalize_cpu_inner(light_vec + eye_vec);
__BrtFloat1 diffuse = __dot_cpu_inner(normal_vec,light_vec);
__BrtFloat1 specular = __dot_cpu_inner(normal_vec,half_vec);
__BrtFloat4 lighting = __lit_cpu_inner(diffuse,specular,__BrtFloat1((float)32));
__BrtFloat3 white = __BrtFloat3 (__BrtFloat1((float)1),__BrtFloat1((float)1),__BrtFloat1((float)1));
ofs.color = lighting.swizzle1(maskY) * ti.color + lighting.swizzle1(maskZ) * white;
ors.state.mask1(RAYSTATE_DONE,maskX);
}
else
{
if (irs.state.swizzle1(maskX) == RAYSTATE_OUT)
{
ofs.color = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
}
else
{
ofs.color = __BrtFloat3 (__BrtFloat1(0.200000f),__BrtFloat1(0.200000f),__BrtFloat1(0.200000f));
}
}
}
void __shader_flat_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__BrtArray1d<__cpustruct_t_triinfo > arg2(
(__cpustruct_t_triinfo *)args[2], extents[2]);
__BrtArray1d<__cpustruct_t_light > arg3(
(__cpustruct_t_light *)args[3], extents[3]);
__cpustruct_t_raystate*arg4 = (__cpustruct_t_raystate*)args[4];
__cpustruct_t_framebufferstate*arg5 = (__cpustruct_t_framebufferstate*)args[5];
unsigned int dim=dims[4];
unsigned int newline=extents[4][dim-1];
unsigned int ratio0 = extents[4][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[4][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[4]);
unsigned int ratio1 = extents[4][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[4][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[4]);
arg4+=mapbegin;
unsigned int ratio5 = extents[4][dim-1]/extents[5][dim-1];
unsigned int scale5=extents[5][dim-1]/extents[4][dim-1];
if (scale5<1) scale5 = 1;
unsigned int ratioiter5 = 0;
if (ratio5) ratioiter5 = mapbegin%ratio5;
unsigned int iter5 = getIndexOf(mapbegin,extents[5], dim, extents[4]);
unsigned int i=0;
while (i<mapextent) {
__shader_flat_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
arg2,
arg3,
*arg4,
*(arg5 + iter5));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
++arg4;
if (++ratioiter5>=ratio5){
ratioiter5=0;
iter5+=scale5;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[4]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[4]);
iter5=getIndexOf(i+mapbegin,extents[5],dim, extents[4]);
}
}
}
void shader_flat (::brook::stream iri,
::brook::stream irs,
::brook::stream scene_triinfos,
::brook::stream scene_lights,
::brook::stream ors,
::brook::stream ofs) {
static const void *__shader_flat_fp[] = {
"fp30", __shader_flat_fp30,
"arb", __shader_flat_arb,
"ps20", __shader_flat_ps20,
"cpu", (void *) __shader_flat_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__shader_flat_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushGatherStream(scene_triinfos);
k->PushGatherStream(scene_lights);
k->PushOutput(ors);
k->PushOutput(ofs);
k->Map();
}
static const char *__shader_smooth_ps20= NULL;
static const char *__shader_smooth_fp30= NULL;
static const char *__shader_smooth_arb= NULL;
void __shader_smooth_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __BrtArray1d<__cpustruct_t_triinfo > &scene_triinfos,
const __BrtArray1d<__cpustruct_t_light > &scene_lights,
__cpustruct_t_raystate &ors,
__cpustruct_t_framebufferstate &ofs){
ors = irs;
if (irs.state.swizzle1(maskX) == RAYSTATE_SHADING)
{
__cpustruct_t_triinfo ti = scene_triinfos[irs.state.swizzle1(maskW)];
__cpustruct_t_light light = scene_lights[__BrtFloat1((float)0)];
__BrtFloat3 edge1 = ti.v1 - ti.v0;
__BrtFloat3 edge2 = ti.v2 - ti.v0;
__BrtFloat3 hit = ti.v0 + irs.state.swizzle1(maskY) * edge1 + irs.state.swizzle1(maskZ) * edge2;
__BrtFloat3 barycoord = __BrtFloat3 (irs.state.swizzle1(maskY),irs.state.swizzle1(maskZ),__BrtFloat1(1.000000f) - irs.state.swizzle1(maskY) - irs.state.swizzle1(maskZ));
__BrtFloat3 normal_vec = __normalize_cpu_inner(barycoord.swizzle1(maskX) * ti.n1 + barycoord.swizzle1(maskY) * ti.n2 + barycoord.swizzle1(maskZ) * ti.n0);
__BrtFloat3 light_vec = __normalize_cpu_inner(light.pos - hit);
__BrtFloat3 eye_vec = __normalize_cpu_inner(iri.origin - hit);
__BrtFloat3 half_vec = __normalize_cpu_inner(light_vec + eye_vec);
__BrtFloat1 diffuse = __dot_cpu_inner(normal_vec,light_vec);
__BrtFloat1 specular = __dot_cpu_inner(normal_vec,half_vec);
__BrtFloat4 lighting = __lit_cpu_inner(diffuse,specular,SPECULAR_EXPONENT);
__BrtFloat3 white = __BrtFloat3 (__BrtFloat1((float)1),__BrtFloat1((float)1),__BrtFloat1((float)1));
ofs.color = lighting.swizzle1(maskY) * ti.color + lighting.swizzle1(maskZ) * white;
ors.state.mask1(RAYSTATE_DONE,maskX);
}
else
{
if (irs.state.swizzle1(maskX) == RAYSTATE_OUT)
{
ofs.color = __BrtFloat3 (__BrtFloat1((float)0),__BrtFloat1((float)0),__BrtFloat1((float)0));
}
else
{
ofs.color = __BrtFloat3 (__BrtFloat1(0.200000f),__BrtFloat1(0.200000f),__BrtFloat1(0.200000f));
}
}
}
void __shader_smooth_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__BrtArray1d<__cpustruct_t_triinfo > arg2(
(__cpustruct_t_triinfo *)args[2], extents[2]);
__BrtArray1d<__cpustruct_t_light > arg3(
(__cpustruct_t_light *)args[3], extents[3]);
__cpustruct_t_raystate*arg4 = (__cpustruct_t_raystate*)args[4];
__cpustruct_t_framebufferstate*arg5 = (__cpustruct_t_framebufferstate*)args[5];
unsigned int dim=dims[4];
unsigned int newline=extents[4][dim-1];
unsigned int ratio0 = extents[4][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[4][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[4]);
unsigned int ratio1 = extents[4][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[4][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[4]);
arg4+=mapbegin;
unsigned int ratio5 = extents[4][dim-1]/extents[5][dim-1];
unsigned int scale5=extents[5][dim-1]/extents[4][dim-1];
if (scale5<1) scale5 = 1;
unsigned int ratioiter5 = 0;
if (ratio5) ratioiter5 = mapbegin%ratio5;
unsigned int iter5 = getIndexOf(mapbegin,extents[5], dim, extents[4]);
unsigned int i=0;
while (i<mapextent) {
__shader_smooth_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
arg2,
arg3,
*arg4,
*(arg5 + iter5));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
++arg4;
if (++ratioiter5>=ratio5){
ratioiter5=0;
iter5+=scale5;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[4]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[4]);
iter5=getIndexOf(i+mapbegin,extents[5],dim, extents[4]);
}
}
}
void shader_smooth (::brook::stream iri,
::brook::stream irs,
::brook::stream scene_triinfos,
::brook::stream scene_lights,
::brook::stream ors,
::brook::stream ofs) {
static const void *__shader_smooth_fp[] = {
"fp30", __shader_smooth_fp30,
"arb", __shader_smooth_arb,
"ps20", __shader_smooth_ps20,
"cpu", (void *) __shader_smooth_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__shader_smooth_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushGatherStream(scene_triinfos);
k->PushGatherStream(scene_lights);
k->PushOutput(ors);
k->PushOutput(ofs);
k->Map();
}
static const char *__shader_ps20= NULL;
static const char *__shader_fp30= NULL;
static const char *__shader_arb= NULL;
void __shader_cpu_inner (const __cpustruct_t_rayinfo &iri,
const __cpustruct_t_raystate &irs,
const __cpustruct_t_dispatcherstate &ids,
const __cpustruct_t_framebufferstate &ifs,
const __BrtArray1d<__cpustruct_t_triinfo > &scene_triinfos,
const __BrtArray1d<__cpustruct_t_light > &scene_lights,
__cpustruct_t_raystate &ors,
__cpustruct_t_framebufferstate &ofs){
ors = irs;
ofs = ifs;
if (irs.state.swizzle1(maskX) == RAYSTATE_SHADING)
{
ors.state.mask1(RAYSTATE_DISPATCHING,maskX);
if (ids.phase.swizzle1(maskY) == __BrtFloat1((float)0))
{
if (irs.state.swizzle1(maskW) <= __BrtFloat1((float)0))
{
if (irs.state.swizzle1(maskW) == RAYSTATUS_MISSED && ids.phase.swizzle1(maskX) == __BrtFloat1((float)0))
{
ofs.color = __BrtFloat3 (__BrtFloat1(0.200000f),__BrtFloat1(0.200000f),__BrtFloat1(0.200000f));
}
}
}
else
{
if (irs.state.swizzle1(maskW) <= __BrtFloat1((float)0))
{
__cpustruct_t_triinfo ti = scene_triinfos[ids.hitinfo.swizzle1(maskX)];
__cpustruct_t_light light = scene_lights[ids.phase.swizzle1(maskY) - __BrtFloat1((float)1)];
__BrtFloat3 edge1 = ti.v1 - ti.v0;
__BrtFloat3 edge2 = ti.v2 - ti.v0;
__BrtFloat3 hit = ti.v0 + ids.hitinfo.swizzle1(maskY) * edge1 + ids.hitinfo.swizzle1(maskZ) * edge2;
__BrtFloat3 normal_vec = ids.hitnormal;
__BrtFloat3 light_vec = __normalize_cpu_inner(light.pos - hit);
__BrtFloat3 eye_vec = ids.hitdirection;
__BrtFloat3 half_vec = __normalize_cpu_inner(light_vec + eye_vec);
__BrtFloat3 white = __BrtFloat3 (__BrtFloat1((float)1),__BrtFloat1((float)1),__BrtFloat1((float)1));
__BrtFloat1 diffuse;
__BrtFloat1 specular;
__BrtFloat4 lighting;
diffuse = KD * __dot_cpu_inner(normal_vec,light_vec);
specular = KS * __dot_cpu_inner(normal_vec,half_vec);
lighting = irs.state.swizzle1(maskZ) * iri.info.swizzle1(maskW) * __lit_cpu_inner(diffuse,specular,SPECULAR_EXPONENT);
if (ids.phase.swizzle1(maskX) == __BrtFloat1((float)0))
ofs.color = ofs.color + lighting.swizzle1(maskY) * ti.color + lighting.swizzle1(maskZ) * white;
else
ofs.color = ofs.color + lighting.swizzle1(maskY) * ti.color;
}
}
}
}
void __shader_cpu (const std::vector<void *>&args,
const std::vector<const unsigned int *>&extents,
const std::vector<unsigned int>&dims,
unsigned int mapbegin,
unsigned int mapextent) {
__cpustruct_t_rayinfo*arg0 = (__cpustruct_t_rayinfo*)args[0];
__cpustruct_t_raystate*arg1 = (__cpustruct_t_raystate*)args[1];
__cpustruct_t_dispatcherstate*arg2 = (__cpustruct_t_dispatcherstate*)args[2];
__cpustruct_t_framebufferstate*arg3 = (__cpustruct_t_framebufferstate*)args[3];
__BrtArray1d<__cpustruct_t_triinfo > arg4(
(__cpustruct_t_triinfo *)args[4], extents[4]);
__BrtArray1d<__cpustruct_t_light > arg5(
(__cpustruct_t_light *)args[5], extents[5]);
__cpustruct_t_raystate*arg6 = (__cpustruct_t_raystate*)args[6];
__cpustruct_t_framebufferstate*arg7 = (__cpustruct_t_framebufferstate*)args[7];
unsigned int dim=dims[6];
unsigned int newline=extents[6][dim-1];
unsigned int ratio0 = extents[6][dim-1]/extents[0][dim-1];
unsigned int scale0=extents[0][dim-1]/extents[6][dim-1];
if (scale0<1) scale0 = 1;
unsigned int ratioiter0 = 0;
if (ratio0) ratioiter0 = mapbegin%ratio0;
unsigned int iter0 = getIndexOf(mapbegin,extents[0], dim, extents[6]);
unsigned int ratio1 = extents[6][dim-1]/extents[1][dim-1];
unsigned int scale1=extents[1][dim-1]/extents[6][dim-1];
if (scale1<1) scale1 = 1;
unsigned int ratioiter1 = 0;
if (ratio1) ratioiter1 = mapbegin%ratio1;
unsigned int iter1 = getIndexOf(mapbegin,extents[1], dim, extents[6]);
unsigned int ratio2 = extents[6][dim-1]/extents[2][dim-1];
unsigned int scale2=extents[2][dim-1]/extents[6][dim-1];
if (scale2<1) scale2 = 1;
unsigned int ratioiter2 = 0;
if (ratio2) ratioiter2 = mapbegin%ratio2;
unsigned int iter2 = getIndexOf(mapbegin,extents[2], dim, extents[6]);
unsigned int ratio3 = extents[6][dim-1]/extents[3][dim-1];
unsigned int scale3=extents[3][dim-1]/extents[6][dim-1];
if (scale3<1) scale3 = 1;
unsigned int ratioiter3 = 0;
if (ratio3) ratioiter3 = mapbegin%ratio3;
unsigned int iter3 = getIndexOf(mapbegin,extents[3], dim, extents[6]);
arg6+=mapbegin;
unsigned int ratio7 = extents[6][dim-1]/extents[7][dim-1];
unsigned int scale7=extents[7][dim-1]/extents[6][dim-1];
if (scale7<1) scale7 = 1;
unsigned int ratioiter7 = 0;
if (ratio7) ratioiter7 = mapbegin%ratio7;
unsigned int iter7 = getIndexOf(mapbegin,extents[7], dim, extents[6]);
unsigned int i=0;
while (i<mapextent) {
__shader_cpu_inner (
*(arg0 + iter0),
*(arg1 + iter1),
*(arg2 + iter2),
*(arg3 + iter3),
arg4,
arg5,
*arg6,
*(arg7 + iter7));
i++;
if (++ratioiter0>=ratio0){
ratioiter0=0;
iter0+=scale0;
}
if (++ratioiter1>=ratio1){
ratioiter1=0;
iter1+=scale1;
}
if (++ratioiter2>=ratio2){
ratioiter2=0;
iter2+=scale2;
}
if (++ratioiter3>=ratio3){
ratioiter3=0;
iter3+=scale3;
}
++arg6;
if (++ratioiter7>=ratio7){
ratioiter7=0;
iter7+=scale7;
}
if ((mapbegin+i)%newline==0) {
iter0=getIndexOf(i+mapbegin,extents[0],dim, extents[6]);
iter1=getIndexOf(i+mapbegin,extents[1],dim, extents[6]);
iter2=getIndexOf(i+mapbegin,extents[2],dim, extents[6]);
iter3=getIndexOf(i+mapbegin,extents[3],dim, extents[6]);
iter7=getIndexOf(i+mapbegin,extents[7],dim, extents[6]);
}
}
}
void shader (::brook::stream iri,
::brook::stream irs,
::brook::stream ids,
::brook::stream ifs,
::brook::stream scene_triinfos,
::brook::stream scene_lights,
::brook::stream ors,
::brook::stream ofs) {
static const void *__shader_fp[] = {
"fp30", __shader_fp30,
"arb", __shader_arb,
"ps20", __shader_ps20,
"cpu", (void *) __shader_cpu,
"combine", 0,
NULL, NULL };
static __BRTKernel k(__shader_fp);
k->PushStream(iri);
k->PushStream(irs);
k->PushStream(ids);
k->PushStream(ifs);
k->PushGatherStream(scene_triinfos);
k->PushGatherStream(scene_lights);
k->PushOutput(ors);
k->PushOutput(ofs);
k->Map();
}
int oracle(int counter)
{
static int counter_inner = 0;
static int counter_dispatcher = NUMRAYPASSES;
static int last_state = STATE_INTERSECTING;
int new_state = last_state;
if (counter > NUMPASSES)
return STATE_DONE;
if (counter_dispatcher == 0)
{
switch (last_state)
{
case STATE_TRAVERSING:
case STATE_INTERSECTING:
new_state = STATE_SHADING;
break;
case STATE_SHADING:
new_state = STATE_DISPATCHING;
break;
case STATE_DISPATCHING:
counter_dispatcher = NUMRAYPASSES;
new_state = STATE_TRAVERSING;
break;
default:
assert(0);
}
last_state = new_state;
return new_state;
}
counter_dispatcher--;
if (counter_inner == 0)
{
switch (last_state)
{
case STATE_TRAVERSING:
counter_inner = 5;
new_state = STATE_INTERSECTING;
break;
case STATE_INTERSECTING:
counter_inner = 5;
new_state = STATE_TRAVERSING;
break;
}
}
counter_inner--;
last_state = new_state;
return new_state;
}
int raytracer(const char *filename)
{
char *state_table[] = { "DONE", "NONE", "TRAVERSING", "INTERSECTING", "SHADING", "DISPATCHING" };
int flip_dispatcherstate = 0;
int flip_traverserstate = 0;
int flip_intersectorstate = 0;
int flip_raystate = 0;
int flip_rayinfo = 0;
int flip_framebufferstate = 0;
int counter;
int old_state;
int new_state;
int total_tris = 0;
::brook::stream a_rayinfo(::brook::getStreamType(( t_rayinfo *)0), RAYSX , RAYSY,-1);
::brook::stream b_rayinfo(::brook::getStreamType(( t_rayinfo *)0), RAYSX , RAYSY,-1);
::brook::stream a_raystate(::brook::getStreamType(( t_raystate *)0), RAYSX , RAYSY,-1);
::brook::stream b_raystate(::brook::getStreamType(( t_raystate *)0), RAYSX , RAYSY,-1);
::brook::stream a_traverserstate(::brook::getStreamType(( t_traverserstate *)0), RAYSX , RAYSY,-1);
::brook::stream b_traverserstate(::brook::getStreamType(( t_traverserstate *)0), RAYSX , RAYSY,-1);
::brook::stream a_intersectorstate(::brook::getStreamType(( t_intersectorstate *)0), RAYSX , RAYSY,-1);
::brook::stream b_intersectorstate(::brook::getStreamType(( t_intersectorstate *)0), RAYSX , RAYSY,-1);
::brook::stream a_dispatcherstate(::brook::getStreamType(( t_dispatcherstate *)0), RAYSX , RAYSY,-1);
::brook::stream b_dispatcherstate(::brook::getStreamType(( t_dispatcherstate *)0), RAYSX , RAYSY,-1);
::brook::stream a_framebufferstate(::brook::getStreamType(( t_framebufferstate *)0), RAYSX , RAYSY,-1);
::brook::stream b_framebufferstate(::brook::getStreamType(( t_framebufferstate *)0), RAYSX , RAYSY,-1);
::brook::stream stream_scene_voxels(::brook::getStreamType(( t_voxel *)0), NUMVOXELS,-1);
::brook::stream stream_scene_trilist(::brook::getStreamType(( t_trilist *)0), NUMTRILIST,-1);
::brook::stream stream_scene_triinfos(::brook::getStreamType(( t_triinfo *)0), NUMTRIINFOS,-1);
::brook::stream stream_scene_lights(::brook::getStreamType(( t_light *)0), NUMLIGHTS_NOHACK,-1);
printf("loading & building scene '%s' ...\n",filename);
if (alloc_scene())
fail("unable to allocate scene");
if (load_scene(filename,&total_tris))
fail("unable to load scene");
if (build_scene(total_tris))
fail("unable to build scene");
printf("initializing engine ...\n");
if (init_engine())
fail("unable to setup engine");
printf("here we go !\n");
streamRead(stream_scene_voxels,scene_voxels);
streamRead(stream_scene_trilist,scene_trilist);
streamRead(stream_scene_triinfos,scene_triinfos);
streamRead(stream_scene_lights,scene_lights);
streamRead(DSTSTREAM(rayinfo),input_rayinfo);
FLIP(rayinfo);
streamRead(DSTSTREAM(raystate),input_raystate);
FLIP(raystate);
streamRead(DSTSTREAM(framebufferstate),input_framebufferstate);
FLIP(framebufferstate);
streamRead(DSTSTREAM(dispatcherstate),input_dispatcherstate);
FLIP(dispatcherstate);
counter = 0;
old_state = STATE_NONE;
while (true)
{
new_state = oracle(counter);
printf("engine step %03d [%15s, %15s]: ",counter,state_table[old_state],state_table[new_state]);
if (new_state == STATE_DONE)
{
printf("exiting the loop ...\n");
break;
}
switch (STATECODE(old_state,new_state))
{
case STATECODE(STATE_DISPATCHING,STATE_TRAVERSING):
case STATECODE(STATE_NONE,STATE_TRAVERSING):
{
printf("setup\n");
setup(SRCSTREAM(rayinfo),SRCSTREAM(raystate),stream_scene_voxels,DSTSTREAM(raystate),DSTSTREAM(traverserstate));
FLIP(raystate);
FLIP(traverserstate);
}
break;
case STATECODE(STATE_INTERSECTING,STATE_TRAVERSING):
case STATECODE(STATE_TRAVERSING,STATE_TRAVERSING):
{
printf("traverser\n");
traverser(SRCSTREAM(rayinfo),SRCSTREAM(raystate),SRCSTREAM(traverserstate),stream_scene_voxels,DSTSTREAM(raystate),DSTSTREAM(traverserstate));
FLIP(raystate);
FLIP(traverserstate);
}
break;
case STATECODE(STATE_TRAVERSING,STATE_INTERSECTING):
case STATECODE(STATE_INTERSECTING,STATE_INTERSECTING):
{
printf("intersector\n");
intersector(SRCSTREAM(rayinfo),SRCSTREAM(raystate),SRCSTREAM(intersectorstate),SRCSTREAM(traverserstate),stream_scene_trilist,stream_scene_triinfos,DSTSTREAM(raystate),DSTSTREAM(intersectorstate));
FLIP(raystate);
FLIP(intersectorstate);
}
break;
case STATECODE(STATE_TRAVERSING,STATE_SHADING):
case STATECODE(STATE_INTERSECTING,STATE_SHADING):
{
printf("shader\n");
shader(SRCSTREAM(rayinfo),SRCSTREAM(raystate),SRCSTREAM(dispatcherstate),SRCSTREAM(framebufferstate),stream_scene_triinfos,stream_scene_lights,DSTSTREAM(raystate),DSTSTREAM(framebufferstate));
FLIP(raystate);
FLIP(framebufferstate);
streamWrite(SRCSTREAM(framebufferstate),output_framebufferstate);
display_framebuffer();
}
break;
case STATECODE(STATE_SHADING,STATE_DISPATCHING):
{
printf("dispatcher\n");
dispatcher(SRCSTREAM(rayinfo),SRCSTREAM(raystate),SRCSTREAM(dispatcherstate),stream_scene_triinfos,stream_scene_lights,DSTSTREAM(rayinfo),DSTSTREAM(raystate),DSTSTREAM(dispatcherstate));
FLIP(rayinfo);
FLIP(raystate);
FLIP(dispatcherstate);
}
break;
default:
assert(0);
}
old_state = new_state;
counter++;
}
streamWrite(SRCSTREAM(framebufferstate),output_framebufferstate);
display_framebuffer();
printf("cleaning engine ...\n");
clean_engine();
printf("cleaning scene ...\n");
clean_scene();
return 0;
}
#endif // STRUCTURES_ONLY
| [
"[email protected]"
]
| [
[
[
1,
1797
]
]
]
|
d3a488e3213641bf90ff4d76f7dd74028522a86a | 80716d408715377e88de1fc736c9204b87a12376 | /TspLib3/Src/Lineconn.cpp | 51da77b608296f70ca7521a3c0fc914a35f1fc2d | []
| no_license | junction/jn-tapi | b5cf4b1bb010d696473cabcc3d5950b756ef37e9 | a2ef6c91c9ffa60739ecee75d6d58928f4a5ffd4 | refs/heads/master | 2021-03-12T23:38:01.037779 | 2011-03-10T01:08:40 | 2011-03-10T01:08:40 | 199,317 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 128,252 | cpp | /******************************************************************************/
//
// LINECONN.CPP - Source code for the CTSPILineConnection object
//
// Copyright (C) 1994-2004 JulMar Entertainment Technology, Inc.
// All rights reserved
//
// This file contains all the source to manage the line objects which are
// held by the CTSPIDevice.
//
// This source code is intended only as a supplement to the
// TSP++ Class Library product documentation. This source code cannot
// be used in part or whole in any form outside the TSP++ library.
//
/******************************************************************************/
/*---------------------------------------------------------------------------*/
// INCLUDE FILES
/*---------------------------------------------------------------------------*/
#include "stdafx.h"
#include <process.h>
#include <spbstrm.h>
/*----------------------------------------------------------------------------
Request map
-----------------------------------------------------------------------------*/
TRequestMap CTSPILineConnection::g_mapRequests;
///////////////////////////////////////////////////////////////////////////
// OfferCallThread
//
// Re-offers calls back to TAPI once the line is open. Workaround for
// lineOpen/SetDefaultMediaMode "issue" with TAPISRV in TAPI 2.1,
// this works for all known versions of TAPISRV.
//
unsigned __stdcall tsplib_OfferCallThread(void* pParam)
{
_TSP_DTRACEX(TRC_THREADS, _T("OfferCallThread(0x%lx) starting\n"), GetCurrentThreadId());
// Re-attempt up to 10 times to tell TAPI about our calls - we want the
// notification to happen ASAP so that calls using lineGetNewCalls see them
// there rather than appearing out of thin air.
for (int i = 0; i < 10; i++)
{
// If it is ok then exit.
if (reinterpret_cast<CTSPILineConnection*>(pParam)->OfferCallsToTAPISrv())
break;
// Otherwise wait and try again.
Sleep(250);
}
_TSP_DTRACEX(TRC_THREADS, _T("OfferCallThread(0x%lx) ending\n"), GetCurrentThreadId());
_endthreadex(0);
return 0;
}// OfferCallThread
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CTSPILineConnection
//
// Constructor for the line object
//
CTSPILineConnection::CTSPILineConnection() : CTSPIConnection(),
m_dwLineMediaModes(0), m_dwLineStates(0), m_lpfnEventProc(NULL),
m_htLine(0), m_dwConnectedCallCount(0), m_iLineType(Station),
m_guidMSP(IID_NULL)
{
ZeroMemory (&m_LineCaps, sizeof(LINEDEVCAPS));
ZeroMemory (&m_LineStatus, sizeof(LINEDEVSTATUS));
m_dwCallHubTracking = LINECALLHUBTRACKING_ALLCALLS;
}// CTSPILineConnection::CTSPILineConnection
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::~CTSPILineConnection
//
// Destructor for the line connection object. Remove all the address
// information structures allocated for this line.
//
CTSPILineConnection::~CTSPILineConnection()
{
// Remove the id from the map
if (m_dwDeviceID != 0xffffffff)
GetSP()->RemoveConnectionFromMap(m_dwDeviceID, this);
// Tell windows to close all UI dialogs.
for (TUIList::iterator i = m_lstUIDialogs.begin();
i != m_lstUIDialogs.end(); ++i)
SendDialogInstanceData((*i)->htDlgInstance);
}// CTSPILineConnection::~CTSPILineConnection
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::BaseInit
//
// Basic initialization required for both v2.x and v3.x line devices
//
void CTSPILineConnection::BaseInit(CTSPIDevice* /*pDevice*/, DWORD /*dwLineID*/)
{
#ifdef _UNICODE
m_LineCaps.dwStringFormat = STRINGFORMAT_UNICODE;
#else
m_LineCaps.dwStringFormat = STRINGFORMAT_ASCII;
#endif
m_LineCaps.dwAddressModes = LINEADDRESSMODE_ADDRESSID;
m_LineCaps.dwBearerModes = LINEBEARERMODE_VOICE;
m_LineCaps.dwLineStates =
(LINEDEVSTATE_OTHER |
LINEDEVSTATE_RINGING |
LINEDEVSTATE_CONNECTED |
LINEDEVSTATE_DISCONNECTED |
LINEDEVSTATE_MSGWAITON |
LINEDEVSTATE_MSGWAITOFF |
LINEDEVSTATE_INSERVICE |
LINEDEVSTATE_OUTOFSERVICE |
LINEDEVSTATE_MAINTENANCE |
LINEDEVSTATE_TERMINALS |
LINEDEVSTATE_NUMCALLS |
LINEDEVSTATE_NUMCOMPLETIONS |
LINEDEVSTATE_ROAMMODE |
LINEDEVSTATE_BATTERY |
LINEDEVSTATE_SIGNAL |
LINEDEVSTATE_LOCK |
LINEDEVSTATE_COMPLCANCEL |
LINEDEVSTATE_CAPSCHANGE |
LINEDEVSTATE_CONFIGCHANGE |
LINEDEVSTATE_TRANSLATECHANGE |
LINEDEVSTATE_REMOVED);
// This will be adjusted by each address added as the "SetAvailableMediaModes" API is called.
m_LineCaps.dwMediaModes = 0;
// This should be kept in synch with any PHONECAPS structures.
m_LineCaps.dwRingModes = 1;
// Always set the number of ACTIVE calls (i.e. connected) to one - derived
// classes may override this if they can support more than one active call
// at a time. Reset the value during the Initcall -AFTER- this function.
m_LineCaps.dwMaxNumActiveCalls = 1;
// Now fill in the line device status
m_LineStatus.dwNumActiveCalls = 0L; // This will be modified as callstates change
m_LineStatus.dwNumOnHoldCalls = 0L; // This will be modified as callstates change
m_LineStatus.dwNumOnHoldPendCalls = 0L; // This will be modified as callstates change
m_LineStatus.dwNumCallCompletions = 0L; // This is filled out by the call appearance
m_LineStatus.dwRingMode = 0;
m_LineStatus.dwBatteryLevel = 0xffff;
m_LineStatus.dwSignalLevel = 0xffff;
m_LineStatus.dwRoamMode = LINEROAMMODE_UNAVAIL;
m_LineStatus.dwDevStatusFlags = LINEDEVSTATUSFLAGS_CONNECTED | LINEDEVSTATUSFLAGS_INSERVICE;
// Set the device capability flags and v1.4 line features
if (GetSP()->CanHandleRequest(TSPI_LINEMAKECALL))
m_LineCaps.dwLineFeatures |= LINEFEATURE_MAKECALL;
if (GetSP()->CanHandleRequest(TSPI_LINESETMEDIACONTROL))
{
m_LineCaps.dwDevCapFlags |= LINEDEVCAPFLAGS_MEDIACONTROL;
m_LineCaps.dwLineFeatures |= LINEFEATURE_SETMEDIACONTROL;
m_LineStatus.dwLineFeatures |= LINEFEATURE_SETMEDIACONTROL;
}
if (GetSP()->CanHandleRequest(TSPI_LINEGATHERDIGITS))
{
m_LineCaps.dwGatherDigitsMinTimeout = LIBRARY_INTERVAL;
m_LineCaps.dwGatherDigitsMaxTimeout = 0xffffffff;
}
if (GetSP()->CanHandleRequest(TSPI_LINEDEVSPECIFIC))
{
m_LineCaps.dwLineFeatures |= LINEFEATURE_DEVSPECIFIC;
m_LineStatus.dwLineFeatures |= LINEFEATURE_DEVSPECIFIC;
}
if (GetSP()->CanHandleRequest(TSPI_LINEDEVSPECIFICFEATURE))
{
m_LineCaps.dwLineFeatures |= LINEFEATURE_DEVSPECIFICFEAT;
m_LineStatus.dwLineFeatures |= LINEFEATURE_DEVSPECIFICFEAT;
}
if (GetSP()->CanHandleRequest(TSPI_LINEFORWARD))
{
m_LineCaps.dwLineFeatures |= LINEFEATURE_FORWARD;
m_LineStatus.dwLineFeatures |= LINEFEATURE_FORWARD;
}
if (GetSP()->CanHandleRequest(TSPI_LINESETLINEDEVSTATUS))
{
m_LineCaps.dwLineFeatures |= LINEFEATURE_SETDEVSTATUS;
m_LineStatus.dwLineFeatures |= LINEFEATURE_SETDEVSTATUS;
}
// Add terminal support - the LINEDEVSTATUS field will be updated when
// the terminal is actually ADDED.
if (GetSP()->CanHandleRequest(TSPI_LINESETTERMINAL))
m_LineCaps.dwLineFeatures |= LINEFEATURE_SETTERMINAL;
// Address types will be adjusted as addresses are created.
m_LineCaps.dwAddressTypes = 0;
m_LineCaps.dwAvailableTracking = LINECALLHUBTRACKING_ALLCALLS;
m_LineCaps.ProtocolGuid = TAPIPROTOCOL_PSTN;
m_LineCaps.dwDevCapFlags |= LINEDEVCAPFLAGS_CALLHUB;
if (GetSP()->CanHandleRequest(TSPI_LINEGETCALLHUBTRACKING)) // We only check for get, not set.
m_LineCaps.dwDevCapFlags |= LINEDEVCAPFLAGS_CALLHUBTRACKING;
// Add in the "tapi/line" device class.
AddDeviceClass (_T("tapi/line"), GetDeviceID());
AddDeviceClass (_T("tapi/providerid"), GetDeviceInfo()->GetProviderID());
}// CTSPILineConnection::BaseInit
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::Init
//
// Initialize this line connection object
//
void CTSPILineConnection::Init(CTSPIDevice* pDevice, DWORD dwLineId, DWORD dwPos, DWORD_PTR /*dwItemData*/)
{
// Allow the base class to initialize
CTSPIConnection::Init(pDevice, dwLineId);
// Set our permanent line identifier which can be used to identify
// this object uniquely within the scope of this service provider.
SetPermanentLineID(MAKELONG((WORD)pDevice->GetProviderID(), dwPos+1));
// Fill in all the required structures
BaseInit(pDevice, dwLineId);
// Derived class should fill in the remainder of the line capabilities. We automatically
// will fill in: (through various Addxxx functions).
//
// dwNumTerminals, MinDialParams, MaxDialParams, dwMediaModes, dwBearerModes, dwNumAddresses
// dwLineNameSize, dwLineNameOffset, dwProviderInfoOffset, dwProviderInfoSize, dwSwitchInfoSize,
// dwSwitchInfoOffset, dwMaxRate.
//
// All the other values should be filled in or left zero if not supported. To fill them in
// simply use "GetLineDevCaps()" and fill it in or derive a object from this and override Init.
}// CTSPILineConnection::Init
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::InitWithStream
//
// Initialize the line connection with a stream
//
void CTSPILineConnection::InitWithStream(CTSPIDevice* pDevice, DWORD dwLineID, DWORD /*dwPos*/, TStream& istm)
{
TVersionInfo vi(istm);
// Allow the base class to initialize
CTSPIConnection::Init(pDevice, dwLineID);
// Initialize the basic line information
BaseInit(pDevice, dwLineID);
// Read the permanent line device id.
DWORD dwPermanentLineID;
istm >> dwPermanentLineID;
SetPermanentLineID(dwPermanentLineID);
// Read the type - we use this to call a specific INIT function
// which may be overriden by the derived provider.
istm >> m_iLineType;
// Read the associated phone id (if any)
DWORD dwPhoneID;
istm >> dwPhoneID;
if (dwPhoneID != 0xffffffff)
{
CTSPIPhoneConnection* pPhone = GetDeviceInfo()->FindPhoneConnectionByPermanentID(dwPhoneID);
if (pPhone != NULL)
{
AddDeviceClass(_T("tapi/phone"), pPhone->GetDeviceID());
pPhone->AddDeviceClass(_T("tapi/line"), GetDeviceID());
}
}
// Read the name of the line
istm >> m_strName;
// Read each of the addresses objects
unsigned int iAddressCount = 0;
istm >> iAddressCount;
for (unsigned int i = 0; i < iAddressCount; i++)
{
TVersionInfo viAddr(istm);
// Read all the information about this address and initialize it using the v2.x
// initialization process so we toggle all the appropriate line flags.
TString strName, strDN;
bool fAllowIncoming=false, fAllowOutgoing=false;
DWORD dwAvailMediaModes=0, dwBearerMode=0, dwMinRate=0, dwMaxRate=0;
DWORD dwMaxNumActiveCalls=0, dwMaxNumOnHoldCalls=0, dwMaxNumOnHoldPendCalls=0;
DWORD dwMaxNumConference=0, dwMaxNumTransConf=0;
LINEDIALPARAMS dp;
istm >> strName
>> strDN
>> fAllowIncoming
>> fAllowOutgoing
>> dwAvailMediaModes
>> dwBearerMode
>> dwMinRate
>> dwMaxRate
>> dwMaxNumActiveCalls
>> dwMaxNumOnHoldCalls
>> dwMaxNumOnHoldPendCalls
>> dwMaxNumConference
>> dwMaxNumTransConf
>> dp.dwDialPause
>> dp.dwDialSpeed
>> dp.dwDigitDuration
>> dp.dwWaitForDialtone;
DWORD dwAddressType = 0;
if (viAddr.GetVersion() >= 3) // TAPI 3.0 supported
istm >> dwAddressType;
// Create the address
CTSPIAddressInfo* pAddr = CreateAddress(strDN.c_str(), strName.c_str(),
fAllowIncoming, fAllowOutgoing, dwAvailMediaModes, dwBearerMode,
dwMinRate, dwMaxRate, &dp, dwMaxNumActiveCalls, dwMaxNumOnHoldCalls,
dwMaxNumOnHoldPendCalls, dwMaxNumConference, dwMaxNumTransConf, dwAddressType);
_TSP_ASSERTE(pAddr != NULL);
// Now allow the object to serialize for v3.x initialization.
pAddr->read(istm);
}
// Initialize the line based on the line type
if (GetLineType() == Queue)
{
// Adjust the ADDRESSCAPS for this queue.
for (int i = 0; i < GetAddressCount(); i++)
{
CTSPIAddressInfo* pAddr = GetAddress(i);
_TSP_ASSERTE (pAddr != NULL);
LPLINEADDRESSCAPS lpAddrCaps = pAddr->GetAddressCaps();
lpAddrCaps->dwAddrCapFlags = LINEADDRCAPFLAGS_QUEUE;
}
}
else if (GetLineType() == Trunk)
{
// Set the line features to drop only - most trunk devices on
// ACD/PBX systems rely on the queues/stations to work with the
// call. The trunk is simply siezed as a connection to the outside
// world. Many switch interfaces DO allow for the call to be dropped
// however. If your switch is different, change the features in the
// derived line initialization.
GetLineDevCaps()->dwAnswerMode = LINEANSWERMODE_NONE;
// Adjust the ADDRESSCAPS for this trunk.
for (int i = 0; i < GetAddressCount(); i++)
{
CTSPIAddressInfo* pAddr = GetAddress(i);
_TSP_ASSERTE (pAddr != NULL);
LPLINEADDRESSCAPS lpAddrCaps = pAddr->GetAddressCaps();
lpAddrCaps->dwAddrCapFlags = LINEADDRCAPFLAGS_NOINTERNALCALLS;
lpAddrCaps->dwAddressFeatures = 0;
lpAddrCaps->dwRemoveFromConfCaps =
lpAddrCaps->dwRemoveFromConfState =
lpAddrCaps->dwTransferModes = 0;
lpAddrCaps->dwCallFeatures &= (
LINECALLFEATURE_DROP | // We can drop calls
LINECALLFEATURE_SETCALLDATA); // We can set call data on calls
pAddr->SetAddressFeatures(0);
}
SetLineFeatures(0);
}
else if (GetLineType() == RoutePoint)
{
// Adjust the ADDRESSCAPS for this queue.
for (int i = 0; i < GetAddressCount(); i++)
{
CTSPIAddressInfo* pAddr = GetAddress(i);
_TSP_ASSERTE (pAddr != NULL);
LPLINEADDRESSCAPS lpAddrCaps = pAddr->GetAddressCaps();
lpAddrCaps->dwAddrCapFlags = LINEADDRCAPFLAGS_ROUTEPOINT;
}
}
else if (GetLineType() == PredictiveDialer)
{
// Adjust the ADDRESSCAPS for this dialer.
for (int i = 0; i < GetAddressCount(); i++)
{
CTSPIAddressInfo* pAddr = GetAddress(i);
_TSP_ASSERTE (pAddr != NULL);
LPLINEADDRESSCAPS lpAddrCaps = pAddr->GetAddressCaps();
lpAddrCaps->dwAddrCapFlags =
(LINEADDRCAPFLAGS_ORIGOFFHOOK |
LINEADDRCAPFLAGS_PREDICTIVEDIALER |
LINEADDRCAPFLAGS_DIALED);
lpAddrCaps->dwAddressFeatures = LINEADDRFEATURE_MAKECALL;
lpAddrCaps->dwPredictiveAutoTransferStates =
(LINECALLSTATE_ACCEPTED |
LINECALLSTATE_CONNECTED |
LINECALLSTATE_RINGBACK |
LINECALLSTATE_DISCONNECTED |
LINECALLSTATE_PROCEEDING |
LINECALLSTATE_BUSY);
lpAddrCaps->dwMaxNoAnswerTimeout = 0xffff;
}
}
// Read agent support
bool fSupportsAgents=0;
istm >> fSupportsAgents;
// If this is a version 3.x stream then load the TAPI 3.0 information
if (vi.GetVersion() >= 3)
{
GUID guid;
istm >> guid;
SetMSPGUID(guid);
// Load the CLSID for the device caps.
istm >> m_LineCaps.ProtocolGuid;
}
// Now allow the derived class to read the additional information
// stored in the stream
read(istm);
// If the agent flag was set then enable the agent proxy for this line.
// We do this after the read so that the agent features may be set correctly.
if (fSupportsAgents) EnableAgentProxy();
}// CTSPILineConnection::InitWithStream
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SaveToStream
//
// This function stores the line object off in the given stream.
//
void CTSPILineConnection::SaveToStream(TStream& ostm)
{
TVersionInfo vi(ostm, 3);
// Lookup the phone id.
DWORD dwPhoneID = 0xffffffff;
DEVICECLASSINFO* pDevClass = GetDeviceClass(_T("tapi/phone"));
if (pDevClass != NULL && pDevClass->dwStringFormat == STRINGFORMAT_BINARY &&
pDevClass->dwSize == sizeof(DWORD))
dwPhoneID = *(reinterpret_cast<LPDWORD>(pDevClass->lpvData.get()));
ostm << m_dwDeviceID << m_iLineType << dwPhoneID << m_strName;
// Write each of the addresses out
int nCount = GetAddressCount();
ostm << nCount;
for (int i = 0; i < nCount; i++)
GetAddress(i)->SaveToStream(ostm);
// Write our agent support
bool fSupportsAgents = (m_dwFlags & IsAgentEnabled) > 0;
ostm << fSupportsAgents;
// Save off the media information for TAPI 3.x
ostm << m_guidMSP;
ostm << m_LineCaps.ProtocolGuid;
// Now allow the object to serialize itself for v3.x initialization.
write(ostm);
}// CTSPILineConnection::SaveToStream
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::read
//
// Reads the object from a stream - should be overriden to provide
// initialization support in the v3.x INIT process.
//
TStream& CTSPILineConnection::read(TStream& istm)
{
return istm;
}// CTSPILineConnection::read
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::write
//
// Writes the object from a stream - should be overriden to provide
// extra data in the stream.
//
TStream& CTSPILineConnection::write(TStream& istm) const
{
return istm;
}// CTSPILineConnection::write
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindAddress
//
// Locate an address based on a dialable address.
//
CTSPIAddressInfo* CTSPILineConnection::FindAddress (LPCTSTR lpszAddress) const
{
// Note: we don't lock the object since we cannot DELETE address objects.
// Therefore once it is there, it is there to stay. If we ever have the ability
// to dynamically add/remove addresses under a line we will need to LOCK the
// line here.
for (TAddressArray::const_iterator it = m_arrAddresses.begin(); it != m_arrAddresses.end(); ++it)
{
if (!lstrcmpi((*it)->GetDialableAddress(), lpszAddress))
return (*it);
}
return NULL;
}// CTSPILineConnection::FindAddress
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetPermanentDeviceID
//
// Return a permanent device id for this line identifying the provider
// and line.
//
DWORD CTSPILineConnection::GetPermanentDeviceID() const
{
return m_LineCaps.dwPermanentLineID;
}// CTSPILineConnection::GetPermanentDeviceID
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnPreCallStateChange
//
// A call is about to change state on an address on this line.
//
void CTSPILineConnection::OnPreCallStateChange (CTSPIAddressInfo* /*pAddr*/, CTSPICallAppearance* /*pCall*/, DWORD dwNewState, DWORD dwOldState)
{
// If the state has not changed, ignore.
if (dwNewState == dwOldState)
return;
// Make sure only this thread is updating the status.
CEnterCode Key(this); // Synch access to object
// Determine if the number of active calls has changed.
bool fWasActive = CTSPICallAppearance::IsActiveCallState(dwOldState);
bool fIsActive = CTSPICallAppearance::IsActiveCallState(dwNewState);
if (fWasActive == false && fIsActive == true)
{
m_LineStatus.dwNumActiveCalls++;
m_dwFlags |= NotifyNumCalls;
}
else if (fWasActive == true && fIsActive == false)
{
if (--m_LineStatus.dwNumActiveCalls & 0x80000000)
m_LineStatus.dwNumActiveCalls = 0L;
m_dwFlags |= NotifyNumCalls;
}
// Determine if the HOLD status has changed.
if (dwNewState == LINECALLSTATE_ONHOLD)
{
m_LineStatus.dwNumOnHoldCalls++;
m_dwFlags |= NotifyNumCalls;
}
else if (dwNewState == LINECALLSTATE_ONHOLDPENDTRANSFER || dwNewState == LINECALLSTATE_ONHOLDPENDCONF)
{
m_LineStatus.dwNumOnHoldPendCalls++;
m_dwFlags |= NotifyNumCalls;
}
if (dwOldState == LINECALLSTATE_ONHOLD)
{
if (--m_LineStatus.dwNumOnHoldCalls & 0x80000000)
m_LineStatus.dwNumOnHoldCalls = 0L;
m_dwFlags |= NotifyNumCalls;
}
else if (dwOldState == LINECALLSTATE_ONHOLDPENDTRANSFER || dwOldState == LINECALLSTATE_ONHOLDPENDCONF)
{
if (--m_LineStatus.dwNumOnHoldPendCalls & 0x80000000)
m_LineStatus.dwNumOnHoldPendCalls = 0L;
m_dwFlags |= NotifyNumCalls;
}
Key.Unlock();
_TSP_DTRACE(_T("%s: Line 0x%lx Active=%ld, OnHold=%ld, OnHoldPend=%ld\n"), m_strName.c_str(), GetPermanentDeviceID(),
m_LineStatus.dwNumActiveCalls, m_LineStatus.dwNumOnHoldCalls, m_LineStatus.dwNumOnHoldPendCalls);
RecalcLineFeatures(true);
}// CTSPILineConnection::OnPreCallStateChange
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnCallStateChange
//
// A call has changed state on an address on this line. Update our
// status.
//
void CTSPILineConnection::OnCallStateChange (CTSPIAddressInfo* /*pAddr*/, CTSPICallAppearance* /*pCall*/,
DWORD /*dwNewState*/, DWORD /*dwOldState*/)
{
if (m_dwFlags & NotifyNumCalls)
{
OnLineStatusChange (LINEDEVSTATE_NUMCALLS);
m_dwFlags &= ~NotifyNumCalls;
}
// Recalc our line features based on the new call states.
RecalcLineFeatures(true);
}// CTSPILineConnection::OnCallStateChange
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnLineStatusChange
//
// This method is called when any of the values in our line device
// status record are changed. It is called internally by the library
// and should also be called by the derived class if the LINDEVSTATUS
// structure is modified directly.
//
void CTSPILineConnection::OnLineStatusChange (DWORD dwState, DWORD dwP2, DWORD dwP3)
{
if (GetLineHandle() && ((m_dwLineStates & dwState) || dwState == LINEDEVSTATE_REINIT))
Send_TAPI_Event (NULL, LINE_LINEDEVSTATE, dwState, dwP2, dwP3);
}// CTSPILineConnection::OnLineStatusChange
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetMSPGUID
//
// Assigns the MSP COM GUID for this line device.
//
void CTSPILineConnection::SetMSPGUID(GUID& guidMSP)
{
if (memcmp(&m_guidMSP, &guidMSP, sizeof(GUID)) != 0)
{
memcpy(&m_guidMSP, &guidMSP, sizeof(GUID));
if (guidMSP != IID_NULL)
m_LineCaps.dwDevCapFlags |= LINEDEVCAPFLAGS_MSP;
else
m_LineCaps.dwDevCapFlags &= ~LINEDEVCAPFLAGS_MSP;
OnLineCapabiltiesChanged();
}
}// CTSPILineConnection::SetMSPGUID
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::Open
//
// Open the line device
//
LONG CTSPILineConnection::Open (
HTAPILINE htLine, // TAPI opaque handle to use for line
LINEEVENT lpfnEventProc, // Event procedure address for notifications
DWORD dwTSPIVersion) // Version of TSPI to synchronize to
{
// If we are already open, return allocated.
if (GetLineHandle() != 0)
return LINEERR_ALLOCATED;
// Save off the event procedure for this line and the TAPI
// opaque line handle which represents this line to the application.
m_lpfnEventProc = lpfnEventProc;
m_htLine = htLine;
m_dwNegotiatedVersion = dwTSPIVersion;
// Tell our device to perform an open for this connection.
if (!OpenDevice())
{
m_lpfnEventProc = NULL;
m_htLine = 0;
m_dwNegotiatedVersion = 0;
return LINEERR_RESOURCEUNAVAIL;
}
// Force our line and addresses to calculate their feature set - this
// may the first time the address calculates it's feature set. (v3.0b)
RecalcLineFeatures(true);
return 0L;
}// CTSPILineConnection::Open
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::Close
//
// Close the line connection and destroy any call appearances that
// are active.
//
// The htLine handle is invalid after this completes.
//
LONG CTSPILineConnection::Close()
{
if (GetLineHandle() != 0)
{
// If the line capabilities specify that we DROP all existing calls
// on the line when it is closed, then spin through each of the
// calls active on this line and issue a drop request.
if ((GetLineDevCaps()->dwDevCapFlags & LINEDEVCAPFLAGS_CLOSEDROP) ==
LINEDEVCAPFLAGS_CLOSEDROP)
{
for (int iAddress = 0; iAddress < GetAddressCount(); iAddress++)
{
CTSPIAddressInfo* pAddress = GetAddress(iAddress);
for (int iCalls = 0; iCalls < pAddress->GetCallCount(); iCalls++)
{
CTSPICallAppearance* pCall = pAddress->GetCallInfo(iCalls);
if (pCall != NULL) pCall->DropOnClose();
}
}
}
// Make sure any pending call close operations complete.
WaitForAllRequests (NULL, REQUEST_DROPCALL);
// Remove any other pending requests for this connection.
RemovePendingRequests();
// Decrement our total line open count.
OnLineStatusChange (LINEDEVSTATE_CLOSE);
// Reset our event and line proc.
m_lpfnEventProc = NULL;
m_htLine = 0;
m_dwLineStates = 0L;
m_dwNegotiatedVersion = GetSP()->GetSupportedVersion();
// If the line has been removed, then mark it as DELETED now
// so we will refuse any further traffic on this line.
if (GetFlags() & _IsRemoved)
m_dwFlags |= _IsDeleted;
// If the TSP indicated that it wants to delete all the calls when the line
// is closed, then do so.
if (m_dwFlags & DelCallsOnClose)
{
for (int iAddress = 0; iAddress < GetAddressCount(); iAddress++)
{
// Loop through all calls on the address until we have none
// left to remove.
CTSPIAddressInfo* pAddress = GetAddress(iAddress);
while (pAddress->GetCallCount() > 0)
{
CTSPICallAppearance* pCall = pAddress->GetCallInfo(0);
if (pCall)
{
// Force the call to idle -- this will remove all calls
// from the address object.
if (pCall->GetCallState() != LINECALLSTATE_IDLE)
{
pCall->SetCallState(LINECALLSTATE_IDLE);
// Does a remove in OnCallStatusChange(..)
}
else // already idle -- remove it from the address.
{
pAddress->RemoveCallAppearance(pCall);
}
}
}
_TSP_ASSERTE(pAddress->GetCallCount() == 0);
}
}
// Now set our connected call count to zero. We do this after closing all
// calls so that we don't end up with a negative call count (since the IDLEing
// of the call will cause a function call to OnConnectedCallCountChange).
m_dwConnectedCallCount = 0;
// Tell our device to close.
CloseDevice();
// Finally, force a recalc of our features.
RecalcLineFeatures(true);
// Success
return 0L;
}
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::Close
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::Send_TAPI_Event
//
// Calls an event back into the TAPI DLL. It is assumed that the
// validity of the event has been verified before calling this
// function.
//
void CTSPILineConnection::Send_TAPI_Event(
CTSPICallAppearance* pCall, // Call appearance to send event for
DWORD dwMsg, // Message to send (LINExxx)
DWORD dwP1, // Parameter 1 (depends on above message)
DWORD dwP2, // Parameter 2 (depends on above message)
DWORD dwP3) // Parameter 3 (depends on above message)
{
HTAPILINE htLine = GetLineHandle();
if (dwMsg == LINE_CREATEDIALOGINSTANCE)
{
htLine = (HTAPILINE) GetDeviceInfo()->GetProviderHandle();
#ifdef _DEBUG
if (htLine == NULL)
{
// This happens because TSPI_providerEnumDevices
// is not exported. It must be exported in TAPI 2.x/3.0
_TSP_ASSERT (false);
_TSP_DTRACE(_T("ERROR: TSPI_providerEnumDevices needs to be exported!\n"));
return;
}
#endif
}
else if (dwMsg == LINE_SENDDIALOGINSTANCEDATA)
{
htLine = (HTAPILINE) dwP3;
dwP3 = 0L;
}
// If a call appearance was supplied, get the call handle from it.
HTAPICALL htCall = (HTAPICALL) 0;
if (pCall)
{
htCall = pCall->GetCallHandle();
// If the call handle is NULL then this call has been deallocated by TAPI
// and we don't need to inform about changes anymore.
if (htCall == NULL) return;
}
#ifdef _DEBUG
static LPCTSTR g_pszMsgs[] = {
{_T("Line_AddressState")}, // 0
{_T("Line_CallInfo")}, // 1
{_T("Line_CallState")}, // 2
{_T("Line_Close")}, // 3
{_T("Line_DevSpecific")}, // 4
{_T("Line_DevSpecificFeature")}, // 5
{_T("Line_GatherDigits")}, // 6
{_T("Line_Generate")}, // 7
{_T("Line_LineDevState")}, // 8
{_T("Line_MonitorDigits")}, // 9
{_T("Line_MonitorMedia")}, // 10
{_T("Line_MonitorTone")}, // 11
{_T("Line_Reply")}, // 12
{_T("Line_Request")}, // 13
{_T("Phone_Button")}, // 14
{_T("Phone_Close")}, // 15
{_T("Phone_DevSpecific")}, // 16
{_T("Phone_Reply")}, // 17
{_T("Phone_State")}, // 18
{_T("Line_Create")}, // 19
{_T("Phone_Create")}, // 20
{_T("Line_AgentSpecific")}, // 21
{_T("Line_AgentStatus")}, // 22
{_T("Line_AppNewCall")}, // 23
{_T("Line_ProxyRequest")}, // 24
{_T("Line_Remove")}, // 25
{_T("Phone_Remove")} // 26
};
static LPCTSTR g_pszTSPIMsgs[] = {
{_T("Line_NewCall")}, // 0
{_T("Line_CallDevSpecific")}, // 1
{_T("Line_CallDevSpecificFeature")}, // 2
{_T("Line_CreateDialogInstance")}, // 3
{_T("Line_SendDialogInstanceData")} // 4
};
LPCTSTR pszMsg = _T("???");
if (dwMsg <= 26)
pszMsg = g_pszMsgs[dwMsg];
else if (dwMsg >= TSPI_MESSAGE_BASE && dwMsg < TSPI_MESSAGE_BASE+5)
pszMsg = g_pszTSPIMsgs[dwMsg-TSPI_MESSAGE_BASE];
// Send the notification to TAPI.
_TSP_DTRACE(_T("%s: Send_TAPI_Event: <0x%lx> Line=0x%lx, Call=0x%lx, Msg=0x%lx (%s), P1=0x%lx, P2=0x%lx, P3=0x%lx\n"), m_strName.c_str(),
this, htLine, htCall, dwMsg, pszMsg, dwP1, dwP2, dwP3);
#endif
// If this is a PROXY request, send it up to the device.
if (dwMsg == LINE_AGENTSPECIFIC || dwMsg == LINE_AGENTSTATUS)
GetDeviceInfo()->ProxyNotify(this, dwMsg, dwP1, dwP2, dwP3);
else
{
if (m_lpfnEventProc != NULL)
(*m_lpfnEventProc)(htLine, htCall, dwMsg, dwP1, dwP2, dwP3);
}
}// CTSPILineConnection::Send_TAPI_Event
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CreateAddress
//
// Create a new address on this line.
//
CTSPIAddressInfo* CTSPILineConnection::CreateAddress (
LPCTSTR lpszDialableAddr, LPCTSTR lpszAddrName, bool fInput, bool fOutput,
DWORD dwAvailMediaModes, DWORD dwBearerMode, DWORD dwMinRate, DWORD dwMaxRate,
LPLINEDIALPARAMS lpDial, DWORD dwMaxNumActiveCalls, DWORD dwMaxNumOnHoldCalls,
DWORD dwMaxNumOnHoldPendCalls, DWORD dwMaxNumConference, DWORD dwMaxNumTransConf, DWORD dwAddressType)
{
CTSPIAddressInfo* pAddr = GetSP()->CreateAddressObject();
if (pAddr == NULL)
throw LINEERR_NOMEM;
// Add it to our array.
CEnterCode sLock(this); // Synch access to object
try
{
m_arrAddresses.push_back(pAddr);
}
catch(...)
{
delete pAddr;
throw;
}
int iPos = (m_arrAddresses.size()-1);
// Increment the number of addresses.
++m_LineCaps.dwNumAddresses;
// Update our line status features if they are now different.
if (fOutput && GetSP()->CanHandleRequest(TSPI_LINEMAKECALL))
m_LineStatus.dwLineFeatures |= LINEFEATURE_MAKECALL;
// Update our line device capabilities with mediamode, bearermode info.
m_LineCaps.dwBearerModes |= dwBearerMode;
m_LineCaps.dwMediaModes |= dwAvailMediaModes;
// Update the MAXRATE information. This field is used in two fashions:
// If the bearermode includes DATA, then this field indicates the top bit rate
// of the digital channel.
//
// Otherwise, if it doesn't include data, but has VOICE, and the mediamode includes
// DATAMODEM, then this should be set to the highest synchronous DCE bit rate
// supported (excluding compression).
if (dwMaxRate > m_LineCaps.dwMaxRate)
m_LineCaps.dwMaxRate = dwMaxRate;
// If we got a dial parameters list, modify our min/max dial parameters.
if (lpDial)
{
if (m_LineCaps.MinDialParams.dwDialPause > lpDial->dwDialPause)
m_LineCaps.MinDialParams.dwDialPause = lpDial->dwDialPause;
if (m_LineCaps.MinDialParams.dwDialSpeed > lpDial->dwDialSpeed)
m_LineCaps.MinDialParams.dwDialSpeed = lpDial->dwDialSpeed;
if (m_LineCaps.MinDialParams.dwDigitDuration > lpDial->dwDigitDuration)
m_LineCaps.MinDialParams.dwDigitDuration = lpDial->dwDigitDuration;
if (m_LineCaps.MinDialParams.dwWaitForDialtone > lpDial->dwWaitForDialtone)
m_LineCaps.MinDialParams.dwWaitForDialtone = lpDial->dwWaitForDialtone;
if (m_LineCaps.MaxDialParams.dwDialPause < lpDial->dwDialPause)
m_LineCaps.MaxDialParams.dwDialPause = lpDial->dwDialPause;
if (m_LineCaps.MaxDialParams.dwDialSpeed < lpDial->dwDialSpeed)
m_LineCaps.MaxDialParams.dwDialSpeed = lpDial->dwDialSpeed;
if (m_LineCaps.MaxDialParams.dwDigitDuration < lpDial->dwDigitDuration)
m_LineCaps.MaxDialParams.dwDigitDuration = lpDial->dwDigitDuration;
if (m_LineCaps.MaxDialParams.dwWaitForDialtone < lpDial->dwWaitForDialtone)
m_LineCaps.MaxDialParams.dwWaitForDialtone = lpDial->dwWaitForDialtone;
}
sLock.Unlock();
m_LineCaps.dwAddressTypes |= dwAddressType;
// Init the address
pAddr->Init (this, iPos, lpszDialableAddr, lpszAddrName, fInput, fOutput,
dwAvailMediaModes, dwBearerMode, dwMinRate, dwMaxRate,
dwMaxNumActiveCalls, dwMaxNumOnHoldCalls, dwMaxNumOnHoldPendCalls,
dwMaxNumConference, dwMaxNumTransConf, LINEADDRESSSHARING_PRIVATE, lpDial, dwAddressType);
// If the name of the address was NULL, then create a NEW name for the address.
if (lpszAddrName == NULL)
{
TCHAR szName[20];
wsprintf(szName, _T("Address%ld"), m_LineCaps.dwNumAddresses);
pAddr->SetName(szName);
}
return pAddr;
}// CTSPILineConnection::CreateAddress
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CreateMonitoredAddress
//
// This creates a monitored address (an address which has the sharing mode
// of LINEADDRESSSHARING_MONITORED.
//
CTSPIAddressInfo* CTSPILineConnection::CreateMonitoredAddress(LPCTSTR lpszDialableAddr,
LPCTSTR lpszAddrName, DWORD dwAvailMediaModes,
DWORD dwBearerMode, DWORD dwMinRate, DWORD dwMaxRate, DWORD dwMaxNumActiveCalls,
DWORD dwMaxNumOnHoldCalls, DWORD dwMaxNumOnHoldPendCalls, DWORD dwAddressType)
{
CTSPIAddressInfo* pAddr = GetSP()->CreateAddressObject();
if (pAddr == NULL)
throw LINEERR_NOMEM;
// Add it to our array.
CEnterCode sLock(this); // Synch access to object
try
{
m_arrAddresses.push_back(pAddr);
}
catch (...)
{
delete pAddr;
}
int iPos = (m_arrAddresses.size()-1);
// Increment the number of addresses.
++m_LineCaps.dwNumAddresses;
// Update our line device capabilities with mediamode, bearermode info.
m_LineCaps.dwBearerModes |= dwBearerMode;
m_LineCaps.dwMediaModes |= dwAvailMediaModes;
// Update the MAXRATE information. This field is used in two fashions:
// If the bearermode includes DATA, then this field indicates the top bit rate
// of the digital channel.
//
// Otherwise, if it doesn't include data, but has VOICE, and the mediamode includes
// DATAMODEM, then this should be set to the highest synchronous DCE bit rate
// supported (excluding compression).
if (dwMaxRate > m_LineCaps.dwMaxRate)
m_LineCaps.dwMaxRate = dwMaxRate;
sLock.Unlock();
m_LineCaps.dwAddressTypes |= dwAddressType;
// Init the address
pAddr->Init (this, iPos, lpszDialableAddr, lpszAddrName, false, false,
dwAvailMediaModes, dwBearerMode, dwMinRate, dwMaxRate,
dwMaxNumActiveCalls, dwMaxNumOnHoldCalls, dwMaxNumOnHoldPendCalls,
0,0, LINEADDRESSSHARING_MONITORED, NULL, dwAddressType);
// If the name of the address was NULL, then create a NEW name for the address.
if (lpszAddrName == NULL)
{
TCHAR szName[20];
wsprintf(szName, _T("Address%ld"), m_LineCaps.dwNumAddresses);
pAddr->SetName(szName);
}
return pAddr;
}// CTSPILineConnection::CreateMonitoredAddress
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GatherCapabilities
//
// Gather the line device capabilities for this list.
//
LONG CTSPILineConnection::GatherCapabilities (DWORD dwTSPIVersion, DWORD /*dwExtVer*/, LPLINEDEVCAPS lpLineCaps)
{
CEnterCode sLock(this); // Synch access to object
// Determine the full size required for our line capabilities
TString strLineName = GetName();
TString strProviderInfo = GetSP()->GetProviderInfo();
TString strSwitchInfo = GetDeviceInfo()->GetSwitchInfo();
// Get a list of the device classes to add
TString strDeviceNames;
for (TDeviceClassArray::iterator ii = m_arrDeviceClass.begin(); ii != m_arrDeviceClass.end(); ++ii)
{
DEVICECLASSINFO* pDevClass = (*ii).second;
strDeviceNames += pDevClass->strName + _T('~');
}
// Add a final NULL marker
if (!strDeviceNames.empty())
strDeviceNames += _T('~');
// Copy over the static structure of the specified size based on the TSPI version requested
// from TAPI. This is determined by the calling application's API level. This means that
// we can have older TAPI complient applications calling us which don't expect the extra
// information in our LINEDEVCAPS record.
DWORD dwReqSize = sizeof(LINEDEVCAPS);
if (dwTSPIVersion < TAPIVER_30)
dwReqSize -= (sizeof(GUID) + sizeof(DWORD)*2);
if (dwTSPIVersion < TAPIVER_22)
dwReqSize -= sizeof(GUID);
if (dwTSPIVersion < TAPIVER_20)
dwReqSize -= sizeof(DWORD) * 3;
if (dwTSPIVersion < TAPIVER_14)
dwReqSize -= sizeof(DWORD);
// Check the available size to make sure we have enough room.
m_LineCaps.dwTotalSize = lpLineCaps->dwTotalSize;
m_LineCaps.dwNeededSize = sizeof(LINEDEVCAPS);
m_LineCaps.dwUsedSize = dwReqSize;
// If we don't have enough space based on our negotiated version, return an error and tell
// TAPI how much we need for the full structure to come down.
_TSP_ASSERT(dwReqSize <= lpLineCaps->dwTotalSize);
if (dwReqSize > lpLineCaps->dwTotalSize)
{
lpLineCaps->dwNeededSize = m_LineCaps.dwNeededSize;
return LINEERR_STRUCTURETOOSMALL;
}
// Copy over only what is allowed for the negotiated version of TAPI.
MoveMemory(lpLineCaps, &m_LineCaps, dwReqSize);
// Remove the additional capabilities if we are not at the proper TSPI version.
if (dwTSPIVersion < TAPIVER_20)
{
lpLineCaps->dwBearerModes &= ~LINEBEARERMODE_RESTRICTEDDATA;
lpLineCaps->dwLineFeatures &= ~(LINEFEATURE_SETDEVSTATUS | LINEFEATURE_FORWARDFWD | LINEFEATURE_FORWARDDND);
}
if (dwTSPIVersion < TAPIVER_14)
{
lpLineCaps->dwBearerModes &= ~LINEBEARERMODE_PASSTHROUGH;
lpLineCaps->dwMediaModes &= ~LINEMEDIAMODE_VOICEVIEW;
lpLineCaps->dwLineStates &= ~(LINEDEVSTATE_CAPSCHANGE |
LINEDEVSTATE_CONFIGCHANGE |
LINEDEVSTATE_TRANSLATECHANGE |
LINEDEVSTATE_COMPLCANCEL |
LINEDEVSTATE_REMOVED);
}
// If we have enough room for the provider information, then add it to the end.
if (!strProviderInfo.empty())
AddDataBlock (lpLineCaps, lpLineCaps->dwProviderInfoOffset, lpLineCaps->dwProviderInfoSize,
strProviderInfo.c_str());
// If we have enough room for the line name, then add it.
if (!strLineName.empty())
AddDataBlock (lpLineCaps, lpLineCaps->dwLineNameOffset, lpLineCaps->dwLineNameSize,
strLineName.c_str());
// If we have enough room for the switch information, then add it.
if (!strSwitchInfo.empty())
AddDataBlock (lpLineCaps, lpLineCaps->dwSwitchInfoOffset, lpLineCaps->dwSwitchInfoSize,
strSwitchInfo.c_str());
// Handle the line terminal capabilities.
lpLineCaps->dwTerminalCapsSize = 0L;
TTerminalInfoArray::iterator it;
for (it = m_arrTerminalInfo.begin(); it != m_arrTerminalInfo.end(); ++it)
AddDataBlock (lpLineCaps, lpLineCaps->dwTerminalCapsOffset, lpLineCaps->dwTerminalCapsSize, &(*it)->Capabilities, sizeof(LINETERMCAPS));
// Add the terminal name information if we have the space.
unsigned int iTermNameLen = ((lpLineCaps->dwTerminalTextEntrySize-sizeof(wchar_t)) / sizeof(wchar_t));
lpLineCaps->dwTerminalTextSize = 0L;
for (it = m_arrTerminalInfo.begin(); it != m_arrTerminalInfo.end(); ++it)
{
TString strName = (*it)->strName;
strName.resize(iTermNameLen, _T(' '));
AddDataBlock (lpLineCaps, lpLineCaps->dwTerminalTextOffset, lpLineCaps->dwTerminalTextSize, strName.c_str());
}
// If we have some lineGetID supported device classes, return the list of supported device classes.
if (dwTSPIVersion >= TAPIVER_20)
{
if (AddDataBlock(lpLineCaps, lpLineCaps->dwDeviceClassesOffset, lpLineCaps->dwDeviceClassesSize, strDeviceNames.c_str()))
{
// Strip out the ~ and replace with nulls.
wchar_t* pbd = reinterpret_cast<wchar_t*>(reinterpret_cast<LPBYTE>(lpLineCaps)+lpLineCaps->dwDeviceClassesOffset);
std::transform(pbd, pbd+lpLineCaps->dwDeviceClassesSize,pbd, tsplib::substitue<wchar_t>(L'~',L'\0'));
}
}
return 0L;
}// CTSPILineConnection::GatherCapabilities
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GatherStatus
//
// Return the status of this line connection.
//
LONG CTSPILineConnection::GatherStatus (LPLINEDEVSTATUS lpLineDevStatus)
{
// Get the version the line opened negotiation to.
DWORD dwTSPIVersion = GetNegotiatedVersion();
if (dwTSPIVersion == 0)
dwTSPIVersion = GetSP()->GetSupportedVersion();
// Synch access to object
CEnterCode sLock(this);
// Run through the addresses and see what media modes are available on outgoing lines.
m_LineStatus.dwAvailableMediaModes = 0L;
for (int x = 0; x < GetAddressCount(); x++)
{
// If the call appearance can have another active call.. grab its available media modes
CTSPIAddressInfo* pAddr = GetAddress(x);
if (pAddr->CanMakeCalls() &&
pAddr->GetAddressStatus()->dwNumActiveCalls < pAddr->GetAddressCaps()->dwMaxNumActiveCalls)
{
m_LineStatus.dwAvailableMediaModes |= pAddr->GetAddressCaps()->dwAvailableMediaModes;
}
}
// Move over the pre-filled fields.
DWORD dwRequiredSize = sizeof(LINEDEVSTATUS);
m_LineStatus.dwTotalSize = lpLineDevStatus->dwTotalSize;
m_LineStatus.dwNeededSize = sizeof(LINEDEVSTATUS);
m_LineStatus.dwNumOpens = lpLineDevStatus->dwNumOpens;
m_LineStatus.dwOpenMediaModes = lpLineDevStatus->dwOpenMediaModes;
// Determine the required size of our TAPI structure based on the caller and the version
// the line originally negotiated at.
if (dwTSPIVersion < TAPIVER_20)
dwRequiredSize -= sizeof(DWORD)*3;
else
{
// Copy over the information which TAPI will supply.
m_LineStatus.dwAppInfoSize = lpLineDevStatus->dwAppInfoSize;
m_LineStatus.dwAppInfoOffset = lpLineDevStatus->dwAppInfoOffset;
}
#ifdef _DEBUG
// If we don't have enough space based on our negotiated version, return an error and tell
// TAPI how much we need for the full structure to come down. NOTE: This should never
// happen - TAPI.DLL is supposed to verify that there is enough space in the structure
// for the negotiated version and return an error. We only check this in DEBUG builds
// to insure that TAPI is doing its job.
if (lpLineDevStatus->dwTotalSize < dwRequiredSize)
{
_TSP_ASSERT (false);
lpLineDevStatus->dwNeededSize = m_LineStatus.dwNeededSize;
return LINEERR_STRUCTURETOOSMALL;
}
#endif
// Copy our structure onto the user structure
MoveMemory(lpLineDevStatus, &m_LineStatus, dwRequiredSize);
lpLineDevStatus->dwUsedSize = dwRequiredSize;
// Now fill in the additional fields.
lpLineDevStatus->dwNumCallCompletions = m_lstCompletions.size();
// Fill in the terminal information if we have space.
if (!m_arrTerminalInfo.empty())
{
for (unsigned int i = 0; i < m_arrTerminalInfo.size(); i++)
{
TERMINALINFO* lpTermInfo = m_arrTerminalInfo[i];
AddDataBlock(lpLineDevStatus, lpLineDevStatus->dwTerminalModesOffset,
lpLineDevStatus->dwTerminalModesSize, &lpTermInfo->dwMode, sizeof(DWORD));
}
}
return 0L;
}// CTSPILineConnection::GatherStatus
/////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindAvailableAddress
//
// Locate an address which is available for an outgoing call.
//
CTSPIAddressInfo* CTSPILineConnection::FindAvailableAddress (LPLINECALLPARAMS const lpCallParams,
DWORD dwFeature) const
{
// Walk through all our addresses and look to see if they can support
// the type of call desired.
for (int x = 0; x < GetAddressCount(); x++)
{
CTSPIAddressInfo* pAddr = GetAddress(x);
// If the call appearance can have another active call..
LINEADDRESSSTATUS* pAS = pAddr->GetAddressStatus();
LINEADDRESSCAPS* pAC = pAddr->GetAddressCaps();
// If no feature is specified, check the MAX number of
// calls available.
if (dwFeature == 0 &&
(pAS->dwNumActiveCalls >= pAC->dwMaxNumActiveCalls))
continue;
// If the feature(s) are available
if (dwFeature > 0 && (pAS->dwAddressFeatures & dwFeature) != dwFeature)
continue;
// And can support the type of call required..
if (lpCallParams && pAddr->CanSupportCall(lpCallParams) != 0)
continue;
// This address fits the bill.
return pAddr;
}
return NULL;
}// CTSPILineConnection::FindAvailableAddress
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CanSupportCall
//
// Return true/false whether this line can support the type of
// call specified.
//
LONG CTSPILineConnection::CanSupportCall (LPLINECALLPARAMS const lpCallParams) const
{
if ((lpCallParams->dwBearerMode & m_LineCaps.dwBearerModes) != lpCallParams->dwBearerMode)
return LINEERR_INVALBEARERMODE;
if (m_LineCaps.dwMaxRate > 0 && lpCallParams->dwMaxRate > m_LineCaps.dwMaxRate)
return LINEERR_INVALRATE;
if ((lpCallParams->dwMediaMode & m_LineCaps.dwMediaModes) != lpCallParams->dwMediaMode)
return LINEERR_INVALMEDIAMODE;
if (m_dwNegotiatedVersion >= TAPIVER_30 && (lpCallParams->dwAddressType > 0) &&
(lpCallParams->dwAddressType & m_LineCaps.dwAddressTypes) == 0)
return LINEERR_INVALADDRESSTYPE;
// If a specific address is identified, then run it through that address to
// insure that the other fields are ok, otherwise, check them all.
if (lpCallParams->dwAddressMode == LINEADDRESSMODE_ADDRESSID)
{
CTSPIAddressInfo* pAddr = GetAddress(lpCallParams->dwAddressID);
if (pAddr != NULL)
return pAddr->CanSupportCall (lpCallParams);
return LINEERR_INVALADDRESSID;
}
else
{
// Attempt to pass it to an address with the specified dialable address.
if (lpCallParams->dwAddressMode == LINEADDRESSMODE_DIALABLEADDR &&
lpCallParams->dwOrigAddressSize > 0)
{
LPTSTR lpBuff = reinterpret_cast<LPTSTR>(lpCallParams) + lpCallParams->dwOrigAddressOffset;
TString strAddress (lpBuff, lpCallParams->dwOrigAddressSize);
CTSPIAddressInfo* pAddr = FindAddress(strAddress.c_str());
if (pAddr != NULL)
return pAddr->CanSupportCall (lpCallParams);
}
// Search through ALL our addresses and see if any can support this call.
for (int x = 0; x < GetAddressCount(); x++)
{
CTSPIAddressInfo* pAddr = GetAddress(x);
if (pAddr && pAddr->CanSupportCall(lpCallParams) == false)
return false;
}
}
return LINEERR_INVALCALLPARAMS;
}// CTSPILineConnection::CanSupportCall
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::MakeCall
//
// Make a new call on our line connection. Allocate a call appearance
// from an available address on the line.
//
LONG CTSPILineConnection::MakeCall (
DRV_REQUESTID dwRequestID, // Asynchronous request ID
HTAPICALL htCall, // TAPI opaque call handle
LPHDRVCALL lphdCall, // return addr for TSPI call handle
LPCTSTR lpszDestAddr, // Address to call
DWORD dwCountryCode, // Country code (SP specific)
LPLINECALLPARAMS const lpCallParamsIn) // Optional call parameters
{
// Verify that the derived provider says MAKECALL is valid currently.
if ((m_LineStatus.dwLineFeatures & LINEFEATURE_MAKECALL) == 0)
return LINEERR_OPERATIONUNAVAIL;
CTSPIAddressInfo* pAddr = NULL;
LONG lResult = 0L;
// Validate the call parameters if they exist.
LPLINECALLPARAMS lpCallParams = NULL;
if (lpCallParamsIn)
{
// Validate the User to user information
if (lpCallParamsIn->dwUserUserInfoOffset > 0 &&
GetLineDevCaps()->dwUUIMakeCallSize > 0 &&
GetLineDevCaps()->dwUUIMakeCallSize < lpCallParamsIn->dwUserUserInfoSize)
return LINEERR_USERUSERINFOTOOBIG;
// Copy the call parameters into our own buffer so we keep a pointer
// to it during the asynchronous processing of this call.
lpCallParams = CopyCallParams(lpCallParamsIn);
if (lpCallParams == NULL)
return LINEERR_NOMEM;
// Validate them against our line configuration
lResult = GetSP()->ProcessCallParameters(this, lpCallParams);
if (lResult)
{
FreeMem(lpCallParams);
return lResult;
}
}
// Split the destination address out into multiple DIALINFO structures into a
// heap-based dial string array since the request will maintain it's own copy.
TDialStringArray arrDialInfo;
// Verify the destination address if it exists.
if (lpszDestAddr && *lpszDestAddr != _T('\0'))
{
lResult = GetSP()->CheckDialableNumber(this, NULL, lpszDestAddr, &arrDialInfo, dwCountryCode);
if (lResult)
{
// Changes by Ron Langham. No longer return error if number is not valid.
// This prevents from being able to dial SIP addresses.
// If invalid, just create DIALINFO passing the values exactly as passed
// Now store the information into a DIALINFO structure.
DIALINFO* pDialInfo = new DIALINFO ( false, lpszDestAddr, _T(""), _T("") );
arrDialInfo.push_back(pDialInfo);
// FreeMem(lpCallParams);
// return lResult;
}
}
// Lock the line connection until we add the request to the list.
// This is done specifically for the MAKECALL since it creates new call appearances
// and there is a window of opportunity if multiple threads are attempting to make
// calls simultaneously where both will be submitted as asychronous requests. To
// stop this, we lock the object for updates until it is submitted.
CEnterCode sLock (this, true);
// If we still have the bandwidth for one more call, but have a pending MAKECALL
// request in our queue..
if (m_LineCaps.dwMaxNumActiveCalls-1 == m_dwConnectedCallCount &&
FindRequest(NULL, REQUEST_MAKECALL) != NULL)
{
FreeMem(lpCallParams);
return LINEERR_RESOURCEUNAVAIL;
}
// Create a call appearance on a known address.
CTSPICallAppearance* pCall = NULL;
// If the user passes a specific call appearance in the
// call parameters, use it.
if (lpCallParams)
{
// If they specified a specific address ID, then find the address on this
// line and create the call appearance on the address.
if (lpCallParams->dwAddressMode == LINEADDRESSMODE_ADDRESSID)
{
pAddr = GetAddress(lpCallParams->dwAddressID);
if (pAddr == NULL)
{
_TSP_DTRACE(_T("%s: lineMakeCall: invalid address id <%ld>\n"), m_strName.c_str(), lpCallParams->dwAddressID);
FreeMem(lpCallParams);
return LINEERR_INVALADDRESSID;
}
// If the address currently doesn't support placing a
// call, then fail this attempt.
if ((pAddr->GetAddressStatus()->dwAddressFeatures & LINEADDRFEATURE_MAKECALL) == 0)
{
FreeMem(lpCallParams);
return LINEERR_CALLUNAVAIL;
}
// Create the call appearance on this address.
pCall = pAddr->CreateCallAppearance(htCall);
}
// Otherwise, if they specified a dialable address, then walk through all
// our addresses and find the matching address.
else if (lpCallParams->dwAddressMode == LINEADDRESSMODE_DIALABLEADDR)
{
if (lpCallParams->dwOrigAddressSize > 0 &&
lpCallParams->dwOrigAddressOffset > 0)
{
LPCTSTR lpszAddress = reinterpret_cast<LPCTSTR>(lpCallParams) + lpCallParams->dwOrigAddressSize;
for (int x = 0; x < GetAddressCount(); x++)
{
pAddr = GetAddress(x);
if (lstrcmp(pAddr->GetDialableAddress(), lpszAddress) == 0)
{
// If the address currently doesn't support placing a
// call, then fail this attempt.
if ((pAddr->GetAddressStatus()->dwAddressFeatures & LINEADDRFEATURE_MAKECALL) == 0)
{
FreeMem(lpCallParams);
return LINEERR_CALLUNAVAIL;
}
// Otherwise create the call on this address.
pCall = pAddr->CreateCallAppearance(htCall);
break;
}
}
if (pCall == NULL)
{
_TSP_DTRACE(_T("%s: lineMakeCall: address <%s> does not exist\n"), m_strName.c_str(), lpszAddress);
FreeMem(lpCallParams);
return LINEERR_INVALADDRESS;
}
}
}
}
// If they did not specify which call appearance to use by address, then locate one
// which matches the specifications they desire from our service provider.
if (pCall == NULL)
{
pAddr = FindAvailableAddress (lpCallParams, LINEADDRFEATURE_MAKECALL);
if (pAddr != NULL)
pCall = pAddr->CreateCallAppearance(htCall);
}
// If there are no more call appearances, exit.
if (pCall == NULL)
{
_TSP_DTRACE(_T("%s: lineMakeCall: no address available for outgoing call\n"), m_strName.c_str());
FreeMem(lpCallParams);
return LINEERR_CALLUNAVAIL;
}
// Return the call appearance handle.
*lphdCall = (HDRVCALL) pCall;
// Otherwise, tell the call appearance to make a call.
lResult = pCall->MakeCall (dwRequestID, &arrDialInfo, dwCountryCode, lpCallParams);
if (lResult != static_cast<LONG>(dwRequestID))
{
// Delete the call appearance.
pCall->GetAddressOwner()->RemoveCallAppearance(pCall);
*lphdCall = NULL;
FreeMem(lpCallParams);
}
return lResult;
}// CTSPILineConnection::MakeCall
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetAddressID
//
// This method returns the address ID associated with this line
// in the specified format.
//
LONG CTSPILineConnection::GetAddressID(
LPDWORD lpdwAddressId, // DWORD for return address ID
DWORD dwAddressMode, // Address mode in lpszAddress
LPCTSTR lpszAddress, // Address of the specified line
DWORD dwSize) // Size of the above string/buffer
{
// We don't support anything but the dialable address
if (dwAddressMode != LINEADDRESSMODE_DIALABLEADDR)
return LINEERR_INVALADDRESSMODE;
// Make sure the size field is filled out ok.
if (dwSize == 0)
dwSize = lstrlen(lpszAddress);
TString strAddress(lpszAddress, dwSize);
// Walk through all the addresses on this line and see if the
// address passed matches up.
CTSPIAddressInfo* pFinal = NULL;
for (int i = 0; i < GetAddressCount(); i++)
{
CTSPIAddressInfo* pAddr = GetAddress(i);
if (pAddr && !lstrcmp(strAddress.c_str(), pAddr->GetDialableAddress()))
{
pFinal = pAddr;
break;
}
}
// Never found it? return error.
if (pFinal == NULL)
return LINEERR_INVALADDRESS;
// Otherwise set the returned address id to the call appearance
// address id.
*lpdwAddressId = pFinal->GetAddressID();
return false;
}// CTSPILineConnection::GetAddressID
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetTerminalInformation
//
// Return the current terminal modes for the specified terminal
// identifier.
//
DWORD CTSPILineConnection::GetTerminalInformation (unsigned int iTerminalID) const
{
CEnterCode sLock(this); // Synch access to object
if (iTerminalID < m_arrTerminalInfo.size())
{
TERMINALINFO* lpTermInfo = m_arrTerminalInfo[iTerminalID];
if (lpTermInfo)
return lpTermInfo->dwMode;
}
return 0L;
}// CTSPILineConnection::GetTerminalInformation
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::AddTerminal
//
// Add a new terminal to the line connection.
//
int CTSPILineConnection::AddTerminal (LPCTSTR lpszName, LINETERMCAPS& Caps, DWORD dwModes)
{
TERMINALINFO* lpTermInfo = new TERMINALINFO;
lpTermInfo->strName = lpszName;
MoveMemory (&lpTermInfo->Capabilities, &Caps, sizeof(LINETERMCAPS));
lpTermInfo->dwMode = dwModes;
// Add it to our array.
CEnterCode sLock(this); // Synch access to object
try
{
m_arrTerminalInfo.push_back(lpTermInfo);
}
catch (...)
{
delete lpTermInfo;
throw;
}
int iPos = m_arrTerminalInfo.size()-1;
// Set the new terminal count
m_LineCaps.dwNumTerminals = m_arrTerminalInfo.size();
m_LineCaps.dwTerminalCapsSize = (m_LineCaps.dwNumTerminals * sizeof(LINETERMCAPS));
// Set our new text entry size for the terminal if it exceeds the total size of
// the biggest terminal name already in place.
DWORD dwTextLen = ((lpTermInfo->strName.length()+1) * sizeof(wchar_t));
if (m_LineCaps.dwTerminalTextEntrySize < dwTextLen)
m_LineCaps.dwTerminalTextEntrySize = dwTextLen;
m_LineCaps.dwTerminalTextSize = (m_LineCaps.dwTerminalTextEntrySize * m_LineCaps.dwNumTerminals);
sLock.Unlock();
// Tell all our address about the new terminal count
for (unsigned int i = 0; i < m_arrAddresses.size(); i++)
m_arrAddresses[i]->OnTerminalCountChanged(true, iPos, dwModes);
// Change the line features
SetLineFeatures(OnLineFeaturesChanged(m_LineStatus.dwLineFeatures | LINEFEATURE_SETTERMINAL));
// Tell TAPI our terminal information has changed.
OnLineStatusChange (LINEDEVSTATE_TERMINALS);
return iPos;
}// CTSPILineConnection::AddTerminal
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::RemoveTerminal
//
// Remove a terminal from our terminal list. This will cause our
// terminal numbers to be re-ordered!
//
void CTSPILineConnection::RemoveTerminal (unsigned int iTerminalId)
{
CEnterCode sLock(this); // Synch access to object
if (iTerminalId < m_arrTerminalInfo.size())
{
TERMINALINFO* lpInfo = m_arrTerminalInfo[iTerminalId];
_TSP_ASSERTE(lpInfo != NULL);
// Remove it and delete the object
m_arrTerminalInfo.erase(m_arrTerminalInfo.begin() + iTerminalId);
delete lpInfo;
// Set the new terminal count
m_LineCaps.dwNumTerminals = GetTerminalCount();
m_LineCaps.dwTerminalCapsSize = (m_LineCaps.dwNumTerminals * sizeof(LINETERMCAPS));
m_LineCaps.dwTerminalTextSize = m_LineCaps.dwTerminalTextEntrySize * m_LineCaps.dwNumTerminals;
sLock.Unlock();
// Tell all our address about the new terminal count
for (unsigned int i = 0; i < m_arrAddresses.size(); i++)
m_arrAddresses[i]->OnTerminalCountChanged(false, iTerminalId, 0L);
if (m_LineCaps.dwNumTerminals == 0)
SetLineFeatures(OnLineFeaturesChanged(m_LineStatus.dwLineFeatures & ~LINEFEATURE_SETTERMINAL));
// Tell TAPI our terminal information has changed.
OnLineStatusChange (LINEDEVSTATE_TERMINALS);
}
}// CTSPILineConnection::RemoveTerminal
///////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetTerminal
//
// This operation enables TAPI.DLL to specify to which terminal information
// related to a specified line, address, or call is to be routed. This
// can be used while calls are in progress on the line, to allow events
// to be routed to different devices as required.
//
LONG CTSPILineConnection::SetTerminal(DRV_REQUESTID dwRequestID,
CTSPIAddressInfo* pAddr, CTSPICallAppearance* pCall,
DWORD dwTerminalModes, DWORD dwTerminalID, bool bEnable)
{
// Make sure we handle this request tyupe
if ((GetLineDevStatus()->dwLineFeatures & LINEFEATURE_SETTERMINAL) == 0)
return LINEERR_OPERATIONUNAVAIL;
// Allocate a terminal request.
RTSetTerminal* pRequest = new RTSetTerminal(this, pAddr, pCall, dwRequestID,
dwTerminalModes, dwTerminalID, bEnable);
// Add it into the request list associated with the line.
if (AddAsynchRequest(pRequest))
return static_cast<LONG>(dwRequestID);
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::SetTerminal
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetTerminalModes
//
// This is the function which should be called when a lineSetTerminal is
// completed by the derived service provider class.
// This stores or removes the specified terminal from the terminal modes
// given, and then forces it to happen for any existing calls on the
// line.
//
void CTSPILineConnection::SetTerminalModes (unsigned int iTerminalID, DWORD dwTerminalModes, bool fRouteToTerminal)
{
CEnterCode sLock(this); // Synch access to object
if (iTerminalID < m_arrTerminalInfo.size())
{
TERMINALINFO* lpInfo = m_arrTerminalInfo[iTerminalID];
_TSP_ASSERTE(lpInfo != NULL);
// Either add the bits or mask them off based on what we are told
// by TAPI.
if (fRouteToTerminal)
lpInfo->dwMode |= dwTerminalModes;
else
lpInfo->dwMode &= ~dwTerminalModes;
// Notify TAPI about our device state changes
OnLineStatusChange (LINEDEVSTATE_TERMINALS);
// Force all the addresses to update the terminal list
for (unsigned int i = 0; i < m_arrAddresses.size(); i++)
m_arrAddresses[i]->SetTerminalModes (iTerminalID, dwTerminalModes, fRouteToTerminal);
}
}// CTSPILineConnection::SetTerminalModes
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetLineFeatures
//
// Used by the user to sets the current line features
//
void CTSPILineConnection::SetLineFeatures (DWORD dwFeatures)
{
// Make sure the capabilities structure reflects this ability.
if (dwFeatures && (m_LineCaps.dwLineFeatures & dwFeatures) == 0)
{
_TSP_DTRACE(_T("%s: LINEDEVCAPS.dwLineFeatures missing 0x%lx bit\n"), m_strName.c_str(), dwFeatures);
m_LineCaps.dwLineFeatures |= dwFeatures;
OnLineCapabiltiesChanged();
}
// Update it only if it has changed.
if (m_LineStatus.dwLineFeatures != dwFeatures)
{
m_LineStatus.dwLineFeatures = dwFeatures;
OnLineStatusChange (LINEDEVSTATE_OTHER);
}
_TSP_DTRACE(_T("%s: Adjusting line features with 0x%lx, New Caps=0x%lx, New Status=0x%lx\n"), m_strName.c_str(), dwFeatures, m_LineCaps.dwLineFeatures, m_LineStatus.dwLineFeatures);
}// CTSPILineConnection::SetLineFeatures
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnLineCapabilitiesChanged
//
// This function is called when the line capabilties change in the lifetime
// of the provider.
//
void CTSPILineConnection::OnLineCapabiltiesChanged()
{
// Verify that we haven't REMOVED capabilities from the line
// features. If so, remove them from the status as well.
m_LineStatus.dwLineFeatures &= m_LineCaps.dwLineFeatures;
OnLineStatusChange (LINEDEVSTATE_CAPSCHANGE);
}// CTSPILineConnection::OnLineCapabiltiesChanged
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnLineFeaturesChanged
//
// Hook to allow a derived line to adjust the line features.
//
DWORD CTSPILineConnection::OnLineFeaturesChanged(DWORD dwLineFeatures)
{
return dwLineFeatures;
}// CTSPILineConnection::OnLineFeaturesChanged
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetDeviceStatusFlags
//
// Sets the device status flags in the LINEDEVSTATUS structure
//
void CTSPILineConnection::SetDeviceStatusFlags (DWORD dwStatus)
{
DWORD dwOldStatus = m_LineStatus.dwDevStatusFlags;
DWORD dwNotify = 0;
m_LineStatus.dwDevStatusFlags = dwStatus;
// Send TAPI the appropriate notifications.
if ((dwOldStatus & LINEDEVSTATUSFLAGS_CONNECTED) &&
(dwStatus & LINEDEVSTATUSFLAGS_CONNECTED) == 0)
dwNotify |= LINEDEVSTATE_DISCONNECTED;
else if ((dwOldStatus & LINEDEVSTATUSFLAGS_CONNECTED) == 0 &&
(dwStatus & LINEDEVSTATUSFLAGS_CONNECTED))
dwNotify |= LINEDEVSTATE_CONNECTED;
if ((dwOldStatus & LINEDEVSTATUSFLAGS_MSGWAIT) &&
(dwStatus & LINEDEVSTATUSFLAGS_MSGWAIT) == 0)
dwNotify |= LINEDEVSTATE_MSGWAITOFF;
else if ((dwOldStatus & LINEDEVSTATUSFLAGS_MSGWAIT) == 0 &&
(dwStatus & LINEDEVSTATUSFLAGS_MSGWAIT))
dwNotify |= LINEDEVSTATE_MSGWAITON;
if ((dwOldStatus & LINEDEVSTATUSFLAGS_INSERVICE) &&
(dwStatus & LINEDEVSTATUSFLAGS_INSERVICE) == 0)
dwNotify |= LINEDEVSTATE_OUTOFSERVICE;
else if ((dwOldStatus & LINEDEVSTATUSFLAGS_INSERVICE) == 0 &&
(dwStatus & LINEDEVSTATUSFLAGS_INSERVICE))
dwNotify |= LINEDEVSTATE_INSERVICE;
if ((dwOldStatus & LINEDEVSTATUSFLAGS_LOCKED) &&
(dwStatus & LINEDEVSTATUSFLAGS_LOCKED) == 0)
dwNotify |= LINEDEVSTATE_LOCK;
else if ((dwOldStatus & LINEDEVSTATUSFLAGS_LOCKED) == 0 &&
(dwStatus & LINEDEVSTATUSFLAGS_LOCKED))
dwNotify |= LINEDEVSTATE_LOCK;
// Force the line to recalc its feature set.
RecalcLineFeatures(true);
// Inform TAPI about the changes in our device status.
OnLineStatusChange (dwNotify);
}// CTSPILineConnection::SetDeviceStatusFlags
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::Forward
//
// Forward a specific or all addresses on this line to a destination
// address.
//
LONG CTSPILineConnection::Forward(
DRV_REQUESTID dwRequestId, // Asynchronous request id
CTSPIAddressInfo* pAddr, // Address to forward to (NULL=all)
TForwardInfoArray* parrForwardInfo, // Array of TSPIFORWARDINFO elements
DWORD dwNumRingsNoAnswer, // Number of rings before "no answer"
HTAPICALL htConsultCall, // New TAPI call handle if necessary
LPHDRVCALL lphdConsultCall, // Our return call handle if needed
LPLINECALLPARAMS lpCallParams) // Used if creating a new call
{
// Pass it directly onto the address specified, or onto all our addresses.
if (pAddr != NULL)
return pAddr->Forward (dwRequestId, parrForwardInfo, dwNumRingsNoAnswer,
htConsultCall, lphdConsultCall, lpCallParams);
// Verify that a FORWARD is available on this line right now.
if ((m_LineStatus.dwLineFeatures &
(LINEFEATURE_FORWARD|LINEFEATURE_FORWARDFWD|LINEFEATURE_FORWARDDND)) == 0)
return LINEERR_OPERATIONUNAVAIL;
// Otherwise we are forwarding *all* addresses on this line.
// Synch access to object
CEnterCode sLock(this);
// Run through all the addresses and see if they can forward given the
// forwarding instructions. This function should NOT insert a request!
int iCount = m_arrAddresses.size();
for (int i = 0; i < iCount; i++)
{
LONG lResult = m_arrAddresses[i]->CanForward(parrForwardInfo, &dwNumRingsNoAnswer, iCount);
if (lResult != 0) return lResult;
}
// Unlock the object
sLock.Unlock();
// Create our request object to map this forwarding request.
RTForward* pRequest = new RTForward(this, NULL, dwRequestId, parrForwardInfo, dwNumRingsNoAnswer);
// Push the request onto the list.
if (AddAsynchRequest(pRequest))
return static_cast<LONG>(dwRequestId);
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::Forward
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetStatusMessages
//
// This operation enables the TAPI DLL to specify which notification
// messages the Service Provider should generate for events related to
// status changes for the specified line or any of its addresses.
//
LONG CTSPILineConnection::SetStatusMessages(DWORD dwLineStates, DWORD dwAddressStates)
{
// Set our new states based on what our LINEDEVCAPS says we can support.
m_dwLineStates = (dwLineStates & m_LineCaps.dwLineStates);
// Tell all the addresses which states to send.
for (unsigned int i = 0; i < m_arrAddresses.size(); i++)
m_arrAddresses[i]->SetStatusMessages (dwAddressStates);
return false;
}// CTSPILineConnection::SetStatusMessages
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::ConditionalMediaDetection
//
// This method is invoked by TAPI.DLL when the application requests a
// line open using the LINEMAPPER. This method will check the
// requested media modes and return an acknowledgement based on whether
// we can monitor all the requested modes.
//
LONG CTSPILineConnection::ConditionalMediaDetection(DWORD dwMediaModes, LPLINECALLPARAMS const lpCallParams)
{
// We MUST have call parameters (TAPI should always pass these).
if (lpCallParams == NULL)
return LINEERR_INVALCALLPARAMS;
// Copy the call params into our own private buffer so we may alter them.
LPLINECALLPARAMS lpMyCallParams = CopyCallParams(lpCallParams);
if (lpMyCallParams == NULL)
return LINEERR_NOMEM;
// Allow searching for ANY address.
if (lpMyCallParams->dwAddressMode == LINEADDRESSMODE_ADDRESSID)
lpMyCallParams->dwAddressMode = 0;
lpMyCallParams->dwMediaMode = dwMediaModes;
// Verify the call parameters for the line/address given.
LONG lResult = GetSP()->ProcessCallParameters(this, lpMyCallParams);
FreeMem(lpMyCallParams);
return lResult;
}// CTSPILineConnection::ConditionalMediaDetection
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::ValidateMediaControlList
//
// This method is called by the lineSetMediaControl to validate that
// the media control parameters are ok for this line device.
//
LONG CTSPILineConnection::ValidateMediaControlList(TSPIMEDIACONTROL* lpMediaControl) const
{
// If media control is not available, then exit.
if ((m_LineCaps.dwDevCapFlags & LINEDEVCAPFLAGS_MEDIACONTROL) == 0)
return LINEERR_OPERATIONUNAVAIL;
// Validate the media control elements.
if (lpMediaControl->arrDigits.size() > m_LineCaps.dwMedCtlDigitMaxListSize)
return LINEERR_INVALDIGITLIST;
unsigned int i;
for (i = 0; i< lpMediaControl->arrDigits.size(); i++)
{
LPLINEMEDIACONTROLDIGIT lpDigit = reinterpret_cast<LPLINEMEDIACONTROLDIGIT>(lpMediaControl->arrDigits[i]);
if ((lpDigit->dwDigitModes & m_LineCaps.dwMonitorDigitModes) != lpDigit->dwDigitModes)
return LINEERR_INVALDIGITLIST;
char cDigit = LOBYTE(LOWORD(lpDigit->dwDigit));
if (lpDigit->dwDigitModes & (LINEDIGITMODE_DTMF | LINEDIGITMODE_DTMFEND))
{
if (strchr ("0123456789ABCD*#", cDigit) == NULL)
return LINEERR_INVALDIGITLIST;
}
else if (lpDigit->dwDigitModes & LINEDIGITMODE_PULSE)
{
if (strchr ("0123456789", cDigit) == NULL)
return LINEERR_INVALDIGITLIST;
}
}
if (lpMediaControl->arrMedia.size() > m_LineCaps.dwMedCtlMediaMaxListSize)
return LINEERR_INVALMEDIALIST;
for (i = 0; i <lpMediaControl->arrMedia.size(); i++)
{
LPLINEMEDIACONTROLMEDIA lpMedia = reinterpret_cast<LPLINEMEDIACONTROLMEDIA>(lpMediaControl->arrMedia[i]);
if ((lpMedia->dwMediaModes & m_LineCaps.dwMediaModes) != lpMedia->dwMediaModes)
return LINEERR_INVALMEDIALIST;
}
if (lpMediaControl->arrTones.size() > m_LineCaps.dwMedCtlToneMaxListSize)
return LINEERR_INVALTONELIST;
for (i = 0; i < lpMediaControl->arrTones.size(); i++)
{
LPLINEMEDIACONTROLTONE lpTone = reinterpret_cast<LPLINEMEDIACONTROLTONE>(lpMediaControl->arrTones[i]);
unsigned int iFreqCount = 0;
if (lpTone->dwFrequency1 > 0)
++iFreqCount;
if (lpTone->dwFrequency2 > 0)
++iFreqCount;
if (lpTone->dwFrequency3 > 0)
++iFreqCount;
if (iFreqCount > m_LineCaps.dwMonitorToneMaxNumFreq)
return LINEERR_INVALTONELIST;
}
if (lpMediaControl->arrCallStates.size() > m_LineCaps.dwMedCtlCallStateMaxListSize)
return LINEERR_INVALCALLSTATELIST;
// Alls ok.
return false;
}// CTSPILineConnection::ValidateMediaControlList
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetMediaControl
//
// This function enables and disables control actions on the media stream
// associated with this line and all addresses/calls present here. Media control
// actions can be triggered by the detection of specified digits, media modes,
// custom tones, and call states. The new specified media controls replace
// all the ones that were in effect for this line, address, or call prior
// to this request.
//
void CTSPILineConnection::SetMediaControl (TSPIMEDIACONTROL* lpMediaControl)
{
// We don't need to store this at the LINE level -
// since addresses are static, we can simply pass it through them.
for (unsigned int i = 0; i < m_arrAddresses.size(); i++)
m_arrAddresses[i]->SetMediaControl(lpMediaControl);
}// CTSPILineConnection::SetMediaControl
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnRingDetected
//
// This method should be called by the service provider worker code
// when an incoming ring is detected on a line.
//
void CTSPILineConnection::OnRingDetected (DWORD dwRingMode, bool fFirstRing)
{
// If our ring count array is empty, then grab the total number of
// ring modes supported and add an entry for each.
if (m_arrRingCounts.size() < m_LineCaps.dwRingModes)
{
for (unsigned int i = 0; i < m_LineCaps.dwRingModes; i++)
m_arrRingCounts.push_back(0);
}
// Ring mode must be 1 to LineDevCaps.dwRingModes per TAPI spec. (3.043)
_TSP_ASSERTE(dwRingMode > 0 && dwRingMode <= m_arrRingCounts.size());
// Grab the current ring count.
UINT uiRingCount = (fFirstRing) ? 1 : m_arrRingCounts[dwRingMode-1]+1;
m_arrRingCounts[dwRingMode-1] = uiRingCount;
// Notify TAPI about the ring.
OnLineStatusChange (LINEDEVSTATE_RINGING, dwRingMode, static_cast<DWORD>(uiRingCount));
}// CTSPILineConnection::OnRingDetected
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnRequestComplete
//
// This virtual method is called when an outstanding request on this
// line device has completed. The return code indicates the success
// or failure of the request. Note that the request will filter to
// the address and caller where available.
//
void CTSPILineConnection::OnRequestComplete(CTSPIRequest* pReq, LONG lResult)
{
// If the request failed, ignore it.
if (lResult != 0)
return;
// Otherwise see if we need to process it.
switch (pReq->GetCommand())
{
// On a set terminal request, if it is successful, then go ahead and set the
// terminal identifiers up inside our class. This information can then be
// retrieved by TAPI through the GetAddressStatus/Caps methods.
case REQUEST_SETTERMINAL:
{
RTSetTerminal* pTermStruct = dynamic_cast<RTSetTerminal*>(pReq);
if (pTermStruct->GetLine() != NULL)
SetTerminalModes (pTermStruct->GetTerminalID(),
pTermStruct->GetTerminalModes(),
pTermStruct->Enable());
break;
}
// If this is a forwarding request, and there is no address information (ie: forward ALL
// addresses on the line), then route the request complete to each address so it will
// store the forwarding information.
case REQUEST_FORWARD:
{
if (pReq->GetAddressInfo() == NULL)
{
CEnterCode Key (this);
for (unsigned int i = 0; i < m_arrAddresses.size(); i++)
m_arrAddresses[i]->OnRequestComplete (pReq, lResult);
}
break;
}
// If this is a COMPLETION request then, if it was successful, mark the completion
// request and data filled in by the service provider.
case REQUEST_COMPLETECALL:
{
// Copy the request over to a new "storable" request.
RTCompleteCall* pRequest = dynamic_cast<RTCompleteCall*>(pReq);
RTCompleteCall* pWait = new RTCompleteCall(*pRequest);
// Add this new waiting request to our completion list.
CEnterCode Key (this);
try
{
m_lstCompletions.push_back(pWait);
}
catch(...)
{
delete pWait;
throw;
}
Key.Unlock();
// Note that the number of completions has changed.
OnLineStatusChange (LINEDEVSTATE_NUMCOMPLETIONS);
break;
}
// If this is a request to change the line device status bits and it completed
// successfully then manage it.
case REQUEST_SETDEVSTATUS:
{
RTSetLineDevStatus* pRequest = dynamic_cast<RTSetLineDevStatus*>(pReq);
DWORD dwFlags = GetLineDevStatus()->dwDevStatusFlags;
if (pRequest->TurnOnBits())
dwFlags |= pRequest->GetStatusBitsToChange();
else
dwFlags &= ~pRequest->GetStatusBitsToChange();
SetDeviceStatusFlags(dwFlags);
break;
}
// If this is an UNCOMPLETE call request which completed successfully, then
// remove the request from the list.
case REQUEST_UNCOMPLETECALL:
{
RTCompleteCall* pComplete = dynamic_cast<RTUncompleteCall*>(pReq)->GetRTCompleteCall();
RemoveCallCompletionRequest(pComplete->GetCompletionID(), false);
break;
}
// If this is a lineSetMediaControl event, then store the new MediaControl
// information in the line (and all of it's addresses).
case REQUEST_MEDIACONTROL:
{
RTSetMediaControl* pMC = dynamic_cast<RTSetMediaControl*>(pReq);
if (pMC->GetAddress() == NULL && pMC->GetCall() == NULL)
SetMediaControl(pMC->GetMediaControlInfo());
break;
}
// Default
default:
break;
}
}// CTSPILineConnection::OnRequestComplete
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindCallCompletionRequest
//
// Return the RTCompleteCall ptr associated with a completion ID.
//
RTCompleteCall* CTSPILineConnection::FindCallCompletionRequest (DWORD dwSwitchInfo, LPCTSTR pszSwitchInfo) const
{
CEnterCode sLock(this); // Synch access to object
for (TCompletionList::const_iterator pPos = m_lstCompletions.begin();
pPos != m_lstCompletions.end(); ++pPos)
{
RTCompleteCall* pRequest = (*pPos);
if (pRequest->GetNumericIdentifier() == dwSwitchInfo &&
(pszSwitchInfo == NULL ||
!lstrcmp(pRequest->GetStringIdentifier(), pszSwitchInfo)))
return pRequest;
}
return NULL;
}// CTSPILineConnection::FindCallCompletionRequest
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindCallCompletionRequest
//
// Locate a call completion request for a specific call appearance.
// Note that this will only locate call completions for CAMPed requests.
//
RTCompleteCall* CTSPILineConnection::FindCallCompletionRequest(CTSPICallAppearance* pCall) const
{
CEnterCode sLock(this); // Synch access to object
for (TCompletionList::const_iterator pPos = m_lstCompletions.begin();
pPos != m_lstCompletions.end(); ++pPos)
{
RTCompleteCall* pRequest = (*pPos);
if (pRequest->GetCompletionMode() == LINECALLCOMPLMODE_CAMPON &&
pRequest->GetCallInfo() == pCall)
return pRequest;
}
return NULL;
}// CTSPILineConnection::FindCallCompletionRequest
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindCallCompletionRequest
//
// Locate a call completion request based on a completion ID passed
// back to TAPI.
//
RTCompleteCall* CTSPILineConnection::FindCallCompletionRequest(DWORD dwCompletionID) const
{
CEnterCode sLock(this); // Synch access to object
for (TCompletionList::const_iterator pPos = m_lstCompletions.begin();
pPos != m_lstCompletions.end(); ++pPos)
{
RTCompleteCall* pRequest = (*pPos);
if (pRequest->GetCompletionID() == dwCompletionID)
return pRequest;
}
return NULL;
}// CTSPILineConnection::FindCallCompletionRequest
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::RemoveCallCompletionRequest
//
// Remove an existing call completion request from our array. This
// is called by the "OnRequestComplete"
//
void CTSPILineConnection::RemoveCallCompletionRequest(DWORD dwCompletionID, bool fNotifyTAPI)
{
CEnterCode sLock(this); // Synch access to object
// Locate the completion ID and delete it from our list.
TCompletionList::iterator pPos;
for (pPos = m_lstCompletions.begin();
pPos != m_lstCompletions.end(); ++pPos)
{
RTCompleteCall* pRequest = (*pPos);
if (pRequest->GetCompletionID() == dwCompletionID)
{
m_lstCompletions.remove((*pPos));
pRequest->DecRef();
break;
}
}
// If we didn't find any completion request, then ignore.
if (pPos == m_lstCompletions.end())
return;
// If we are to notify TAPI, then do so. This should only happen
// when the completion is canceled by the derived class (i.e. the hardware
// canceled the request.
if (fNotifyTAPI && GetNegotiatedVersion() >= TAPIVER_14)
OnLineStatusChange (LINEDEVSTATE_COMPLCANCEL, dwCompletionID);
OnLineStatusChange (LINEDEVSTATE_NUMCOMPLETIONS);
}// CTSPILineConnection::RemoveCallCompletionRequest
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::UncompleteCall
//
// Cancel a call completion request from TAPI.
//
LONG CTSPILineConnection::UncompleteCall (DRV_REQUESTID dwRequestID, DWORD dwCompletionID)
{
// Make sure the completion ID is valid.
RTCompleteCall* pCC = FindCallCompletionRequest(dwCompletionID);
if (pCC == NULL)
return LINEERR_INVALCOMPLETIONID;
// Build a new request from the original
RTUncompleteCall* pRequest = new RTUncompleteCall(this, dwRequestID, pCC);
// Submit the request to the worker code to uncode the actual line device.
if (AddAsynchRequest(pRequest))
return static_cast<LONG>(dwRequestID);
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::UncompleteCall
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnCallDeleted
//
// A call is being deleted from some address our line owns.
//
void CTSPILineConnection::OnCallDeleted(CTSPICallAppearance* /*pCall*/)
{
/* Do nothing */
}// CTSPILineConnection::OnCallDeleted
//////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetupConference
//
// Sets up a conference call for the addition of the third party.
//
LONG CTSPILineConnection::SetupConference(
DRV_REQUESTID dwRequestID, // Asynch. req. id
CTSPICallAppearance* pCall, // First party of the conference call
HTAPICALL htConfCall, // New conference call TAPI handle
LPHDRVCALL lphdConfCall, // Returning call handle
HTAPICALL htConsultCall, // Call to conference in
LPHDRVCALL lphdConsultCall, // Returning call handle
DWORD dwNumParties, // Number of parties expected.
LPLINECALLPARAMS const lpCallParamsIn) // Line parameters
{
// We need an address to create the conference call onto. If we got
// a valid call handle to start the call relationship with, then use
// it as the starting address.
CTSPIAddressInfo* pAddr = (pCall != NULL) ?
pCall->GetAddressOwner() : (lpCallParamsIn != NULL) ?
FindAvailableAddress(lpCallParamsIn) : GetAddress(0);
// If we were passed line parameters, verify them
LPLINECALLPARAMS lpCallParams = NULL;
if (lpCallParamsIn)
{
// Copy the call parameters into our own buffer so we keep a pointer
// to it during the asynchronous processing of this call.
lpCallParams = CopyCallParams(lpCallParamsIn);
if (lpCallParams == NULL)
return LINEERR_NOMEM;
// Process the call parameters
LONG lResult = GetSP()->ProcessCallParameters(this, lpCallParams);
if (lResult)
{
FreeMem(lpCallParams);
return lResult;
}
}
// Let the address do the work of setting up the conference.
LONG lResult = pAddr->SetupConference(dwRequestID, pCall, htConfCall, lphdConfCall,
htConsultCall, lphdConsultCall, dwNumParties, lpCallParams);
if (lResult != static_cast<LONG>(dwRequestID))
FreeMem(lpCallParams);
return lResult;
}// CTSPILineConnection::SetupConference
//////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetupTransfer
//
// This function sets up a call for transfer to a destination address.
// A new call handle is created which represents the destination
// address.
//
LONG CTSPILineConnection::SetupTransfer(
DRV_REQUESTID dwRequestID, // Asynch. request id
CTSPICallAppearance *pCall, // Call appearance to transfer
HTAPICALL htConsultCall, // Consultant call to create
LPHDRVCALL lphdConsultCall, // Return handle for call to create
LPLINECALLPARAMS const lpCallParamsIn) // Calling parameters
{
// If there are call parameters, then force the derived class to
// deal with them since there are device specific flags in the
// set.
LPLINECALLPARAMS lpCallParams = NULL;
if (lpCallParamsIn)
{
// Copy the call parameters into our own buffer so we keep a pointer
// to it during the asynchronous processing of this call.
lpCallParams = CopyCallParams(lpCallParamsIn);
if (lpCallParams == NULL)
return LINEERR_NOMEM;
// Process the call parameters
LONG lResult = GetSP()->ProcessCallParameters(pCall, lpCallParams);
if (lResult)
{
FreeMem(lpCallParams);
return lResult;
}
}
// Determine which address to use based on our CALLPARAMS. If they indicate
// a different address, then this is a cross-address transfer.
CTSPIAddressInfo* pAddr = pCall->GetAddressOwner();
if (lpCallParams)
{
if (lpCallParams->dwAddressMode == LINEADDRESSMODE_ADDRESSID)
{
pAddr = GetAddress(lpCallParams->dwAddressID);
if (pAddr == NULL)
{
FreeMem(lpCallParams);
return LINEERR_INVALCALLPARAMS;
}
}
}
// Now tell the address to setup the transfer.
LONG lResult = pAddr->SetupTransfer (dwRequestID, pCall, htConsultCall, lphdConsultCall, lpCallParams);
if (lResult != static_cast<LONG>(dwRequestID))
FreeMem(lpCallParams);
return lResult;
}// CTSPILineConnection::SetupTransfer
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::IsConferenceAvailable
//
// This determines whether there is a conference call active on the
// same line/address as the call passed.
//
bool CTSPILineConnection::IsConferenceAvailable(CTSPICallAppearance* pCall)
{
// Check on the same address.
CTSPIAddressInfo* pAddr = pCall->GetAddressOwner();
CEnterCode KeyAddr (pAddr); // Synch access to object
int iCall;
for (iCall = 0; iCall < pAddr->GetCallCount(); iCall++)
{
CTSPICallAppearance* pThisCall = pAddr->GetCallInfo(iCall);
if (pThisCall != NULL && pThisCall != pCall &&
pThisCall->GetCallType() == CTSPICallAppearance::Conference &&
(pThisCall->GetCallState() & (LINECALLSTATE_IDLE | LINECALLSTATE_DISCONNECTED)) == 0)
return true;
}
KeyAddr.Unlock();
// None found there, check on the same line if cross-address conferencing is
// available.
if (m_LineCaps.dwDevCapFlags & LINEDEVCAPFLAGS_CROSSADDRCONF)
{
CEnterCode sLock(this); // Synch access to object
for (int iAddr = 0; iAddr < GetAddressCount(); iAddr++)
{
CTSPIAddressInfo* pThisAddr = GetAddress(iAddr);
if (pThisAddr != pAddr)
{
CEnterCode KeyAddr (pThisAddr);
for (iCall = 0; iCall < pThisAddr->GetCallCount(); iCall++)
{
CTSPICallAppearance* pThisCall = pThisAddr->GetCallInfo(iCall);
if (pThisCall != NULL &&
pThisCall->GetCallType() == CTSPICallAppearance::Conference &&
(pThisCall->GetCallState() & (LINECALLSTATE_IDLE | LINECALLSTATE_DISCONNECTED)) == 0)
return true;
}
}
}
}
// No conference found.
return false;
}// CTSPILineConnection::IsConferenceAvailable
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::IsTransferConsultAvailable
//
// This determines whether there is a consultant call or some other
// call which we could transfer to right now.
//
bool CTSPILineConnection::IsTransferConsultAvailable(CTSPICallAppearance* pCall)
{
// See if we have an attached consultation call which can be used for
// transfer. This would have been created through the SetupTransfer API.
CTSPICallAppearance* pThisCall = pCall->GetAttachedCall();
if (pThisCall != NULL)
{
return ((pThisCall->GetCallState() & (LINECALLSTATE_CONNECTED |
LINECALLSTATE_RINGBACK |
LINECALLSTATE_BUSY |
LINECALLSTATE_PROCEEDING)) != 0);
}
// If the address supports creation of a new consultation call, then search
// our address for calls in the appropriate state. This may or may not have been
// created with the SetupTransfer API.
CTSPIAddressInfo* pAddr = pCall->GetAddressOwner();
if ((pAddr->GetAddressCaps()->dwAddrCapFlags & LINEADDRCAPFLAGS_TRANSFERMAKE) == 0)
return false;
// Walk through all the addresses checking for calls on addresses which
// support creation of TRANSFER consultation calls and are in the proper
// state.
for (int iAddr = 0; iAddr < GetAddressCount(); iAddr++)
{
CTSPIAddressInfo* pAddr = GetAddress(iAddr);
if ((pAddr->GetAddressCaps()->dwAddrCapFlags & LINEADDRCAPFLAGS_TRANSFERMAKE) != 0)
{
// Synch access to object - don't allow system lockup just for this.
CEnterCode KeyAddr(pAddr, FALSE);
if (KeyAddr.Lock(100))
{
for (int iCall = 0; iCall < pAddr->GetCallCount(); iCall++)
{
CTSPICallAppearance* pThisCall = pAddr->GetCallInfo(iCall);
if (pThisCall != pCall &&
((pThisCall->GetCallState() &
(LINECALLSTATE_CONNECTED |
LINECALLSTATE_RINGBACK |
LINECALLSTATE_BUSY |
LINECALLSTATE_PROCEEDING)) != 0))
return true;
}
KeyAddr.Unlock();
}
}
}
return false;
}// CTSPILineConnection::IsTransferConsultAvailable
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindCallByState
//
// Run through all our addresses and look for a call in the specified
// state.
//
CTSPICallAppearance* CTSPILineConnection::FindCallByState(DWORD dwState) const
{
for (int j = 0; j < GetAddressCount(); j++)
{
CTSPIAddressInfo* pAddr = GetAddress(j);
CEnterCode AddrLock(pAddr);
for (int i = 0; i < pAddr->GetCallCount(); i++)
{
CTSPICallAppearance* pThisCall = pAddr->GetCallInfo(i);
if (pThisCall != NULL &&
(dwState & pThisCall->GetCallState()))
return pThisCall;
}
}
return NULL;
}// CTSPILineConnection::FindCallByState
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindCallByType
//
// Run through all our addresses and look for the first call of the
// specified call type
//
CTSPICallAppearance* CTSPILineConnection::FindCallByType(int iType) const
{
for (int j = 0; j < GetAddressCount(); j++)
{
CTSPIAddressInfo* pAddr = GetAddress(j);
CEnterCode AddrLock(pAddr);
for (int i = 0; i < pAddr->GetCallCount(); i++)
{
CTSPICallAppearance* pCall = pAddr->GetCallInfo(i);
if (pCall != NULL && pCall->GetCallType() == iType &&
pCall->GetCallState() != LINECALLSTATE_IDLE)
return pCall;
}
AddrLock.Unlock();
}
return NULL;
}// CTSPILineConnection::FindCallByType
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FindCallByCallID
//
// Run through all our addresses and look for the first call with the
// specified call id.
//
CTSPICallAppearance* CTSPILineConnection::FindCallByCallID(DWORD dwCallID) const
{
for (int j = 0; j < GetAddressCount(); j++)
{
CTSPIAddressInfo* pAddr = GetAddress(j);
CEnterCode AddrLock(pAddr);
for (int i = 0; i < pAddr->GetCallCount(); i++)
{
CTSPICallAppearance* pCall = pAddr->GetCallInfo(i);
if (pCall != NULL && pCall->GetCallID() == dwCallID)
return pCall;
}
}
return NULL;
}// CTSPILineConnection::FindCallByCallID
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CreateUIDialog
//
// Create a new dialog on a user thread.
//
HTAPIDIALOGINSTANCE CTSPILineConnection::CreateUIDialog (
DRV_REQUESTID dwRequestID, // Request ID to work with
LPVOID lpItemData, // Item data passed back with Generic
LPVOID lpParams, // Parameter block
DWORD dwSize, // Size of param block
LPCTSTR lpszUIDLLName/*=NULL*/) // Different UI dll?
{
// If no UI dll was passed, use our own DLL as the UI dll.
TCHAR szPath[_MAX_PATH+1];
if (lpszUIDLLName == NULL || *lpszUIDLLName == _T('\0'))
{
GetSystemDirectory (szPath, _MAX_PATH);
if (szPath[lstrlen(szPath)-1] != _T('\\'))
lstrcat(szPath, _T("\\"));
lstrcat(szPath, GetSP()->GetUIManager());
lpszUIDLLName = szPath;
}
// Allocate a new UI structure
LINEUIDIALOG* pLineDlg = new LINEUIDIALOG;
// Ask TAPI for a UI dialog event.
USES_CONVERSION;
TUISPICREATEDIALOGINSTANCEPARAMS Params;
Params.dwRequestID = dwRequestID;
Params.hdDlgInst = (HDRVDIALOGINSTANCE) pLineDlg;
Params.htDlgInst = NULL;
Params.lpszUIDLLName = T2W(const_cast<LPTSTR>(lpszUIDLLName));
Params.lpParams = lpParams;
Params.dwSize = dwSize;
Send_TAPI_Event(NULL, LINE_CREATEDIALOGINSTANCE, reinterpret_cast<DWORD>(&Params), 0L, 0L);
if (Params.htDlgInst == NULL)
{
_TSP_DTRACE(_T("%s: Failed to create UI dialog for request ID 0x%lx\n"), m_strName.c_str(), dwRequestID);
delete pLineDlg;
}
else
{
_TSP_DTRACE(_T("%s: New UI dialog created TAPI=0x%lx, SP=0x%lx\n"), m_strName.c_str(), Params.htDlgInst, Params.hdDlgInst);
pLineDlg->pLineOwner = this;
pLineDlg->dwRequestID = dwRequestID;
pLineDlg->htDlgInstance = Params.htDlgInst;
pLineDlg->lpvItemData = lpItemData;
CEnterCode sLock(this); // Synch access to object
try
{
m_lstUIDialogs.push_back(pLineDlg);
}
catch(...)
{
delete pLineDlg;
throw;
}
}
return Params.htDlgInst;
}// CTSPILineConnection::CreateUIDialog
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetUIDialogItem
//
// Retrieve a UI dialog instance item data handle for a given TAPI
// dialog instance
//
LPVOID CTSPILineConnection::GetUIDialogItem(HTAPIDIALOGINSTANCE htDlgInst) const
{
CEnterCode sLock(this); // Synch access to object
for (TUIList::const_iterator iPos = m_lstUIDialogs.begin();
iPos != m_lstUIDialogs.end(); iPos++)
{
if ((*iPos)->htDlgInstance == htDlgInst)
return (*iPos)->lpvItemData;
}
return NULL;
}// CTSPILineConnection::GetUIDialog
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::FreeDialogInstance
//
// Destroy a user-interface dialog for this line connection. In general,
// don't call this function from user-level code.
//
LONG CTSPILineConnection::FreeDialogInstance(HTAPIDIALOGINSTANCE htDlgInst)
{
CEnterCode sLock(this); // Synch access to object
for (TUIList::iterator pos = m_lstUIDialogs.begin();
pos != m_lstUIDialogs.end(); ++pos)
{
if ((*pos)->htDlgInstance == htDlgInst)
{
// Remove it from our array.
LINEUIDIALOG* pLineDlg = (*pos);
m_lstUIDialogs.erase(pos);
// Given the line a chance to know that the thread on the client
// was destroyed.
OnUIDialogClosed(pLineDlg->htDlgInstance, pLineDlg->lpvItemData);
delete pLineDlg;
break;
}
}
return false;
}// CTSPILineConnection::FreeDialogInstance
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnUIDialogClosed
//
// Called when the UI dialog is being free'd by TAPI. Can be overridden
// to delete the item data, cancel a pending request, etc.
//
void CTSPILineConnection::OnUIDialogClosed(HTAPIDIALOGINSTANCE /*htDlgInst*/, LPVOID /*lpItemData*/)
{
}// CTSPILineConnection::OnUIDialogClosed
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetLineDevStatus
//
// Change the line device status according to what TAPI
// has requested. Derived provider should use the "SetDeviceStatusFlags"
// to actually set the flags.
//
LONG CTSPILineConnection::SetLineDevStatus (DRV_REQUESTID dwRequestID,
DWORD dwStatusToChange, bool fSet)
{
// Verify that we can execute this request right now.
if ((GetLineDevStatus()->dwLineFeatures & LINEFEATURE_SETDEVSTATUS) == 0)
return LINEERR_OPERATIONUNAVAIL;
// If this isn't one of the supported status bits, error out.
if ((dwStatusToChange & m_LineCaps.dwSettableDevStatus) == 0)
return LINEERR_INVALPARAM;
// Create the request object to mirror this event.
RTSetLineDevStatus* pRequest = new RTSetLineDevStatus(this, dwRequestID, dwStatusToChange, fSet);
// Submit the request and let the derived provider set the appropriate bits
// using the "SetDeviceStatusFlags" when it is finished.
if (AddAsynchRequest(pRequest))
return static_cast<LONG>(dwRequestID);
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::SetLineDevStatus
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetRingMode
//
// Set the ring mode for this line.
//
void CTSPILineConnection::SetRingMode (DWORD dwRingMode)
{
if (m_LineStatus.dwRingMode != dwRingMode)
{
m_LineStatus.dwRingMode = dwRingMode;
OnLineStatusChange (LINEDEVSTATE_OTHER);
}
}// CTSPILineConnection::SetRingMode
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetBatteryLevel
//
// Set the battery level for this line connection
//
void CTSPILineConnection::SetBatteryLevel (DWORD dwBattery)
{
if (dwBattery > 0xffff)
dwBattery = 0xffff;
if (m_LineStatus.dwBatteryLevel != dwBattery)
{
m_LineStatus.dwBatteryLevel = dwBattery;
OnLineStatusChange (LINEDEVSTATE_BATTERY);
}
}// CTSPILineConnection::SetBatteryLevel
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetSignalLevel
//
// Set the signal level for the line connection
//
void CTSPILineConnection::SetSignalLevel (DWORD dwSignal)
{
if (dwSignal > 0xffff)
dwSignal = 0xffff;
if (m_LineStatus.dwSignalLevel != dwSignal)
{
m_LineStatus.dwSignalLevel = dwSignal;
OnLineStatusChange (LINEDEVSTATE_SIGNAL);
}
}// CTSPILineConnection::SetSignalLevel
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetRoamMode
//
// Set the roaming mode for the line
//
void CTSPILineConnection::SetRoamMode (DWORD dwRoamMode)
{
if (m_LineStatus.dwRoamMode != dwRoamMode)
{
m_LineStatus.dwRoamMode = dwRoamMode;
OnLineStatusChange (LINEDEVSTATE_ROAMMODE);
}
}// CTSPILineConnection::SetRoamMode
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetDefaultMediaDetection
//
// This sets our current set of media mode detection being done
// on this line. The new modes should be tested for on any offering calls.
//
LONG CTSPILineConnection::SetDefaultMediaDetection(DWORD dwMediaModes)
{
// Validate the media modes
if ((dwMediaModes & m_LineCaps.dwMediaModes) != dwMediaModes)
return LINEERR_INVALMEDIAMODE;
// Set our new media mode into place.
m_dwLineMediaModes = dwMediaModes;
// If the media modes have changed, then start a thread which will
// wait a minute (for the line to be completely open) and then re-offer
// all the calls to TAPI which are still in our call list.
if (dwMediaModes > 0)
{
// Attempt to notify TAPI about all the calls now. If this fails, spawn
// a thread and retry until it is successful.
if (OfferCallsToTAPISrv() == false)
{
UINT uiThread;
_beginthreadex(NULL, 0, tsplib_OfferCallThread,
static_cast<void*>(this), 0, &uiThread);
}
}
return false;
}// CTSPILineConnection::SetDefaultMediaDetection
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OfferCallsToTAPISrv
//
// This offers existing call objects back to TAPI once the line has been
// opened by an owner.
//
// The optimal place for this would actually be in the SetDefaultMediaDetection
// code above. Unfortunately, TAPI 2.1 changed the way TAPISRV opens lines and
// now TAPISRV is not yet done opening the line (the line handle hasn't been
// moved into it's "open" structure), and so the LINE_NEWCALL fails because
// TAPI's htLine handle isn't recognized by TAPISRV - even though it sent it to us
// on a previous function call (TSPI_lineOpen). This was reported as a bug,
// but according to Microsoft this is the way it will be from now on so...
// we spawn a thread to get of TAPI's worker thread and wait for a minute.
//
bool CTSPILineConnection::OfferCallsToTAPISrv()
{
bool fAllOK = true;
// Now walk the call list and see if we have any calls on this
// line which are in the specified media mode BUT don't have TAPI
// call handles. This happens when TAPI closes the call but later
// gets a client which owns the line again.
for (int iAddress = 0; iAddress < GetAddressCount(); iAddress++)
{
CTSPIAddressInfo* pAddr = GetAddress(iAddress);
if (pAddr->GetAddressCaps()->dwAddressSharing == LINEADDRESSSHARING_MONITORED)
continue;
CEnterCode sAddrLock(pAddr);
for (int iCall = 0; iCall < pAddr->GetCallCount(); iCall++)
{
// Offer the call if we still have a valid object, we
// don't have a TAPI call handle for it, and the media mode
// of the call is something that TAPI cares about (otherwise it
// will turn around and drop it so don't bother to waste the CPU).
CTSPICallAppearance* pCall = pAddr->GetCallInfo(iCall);
if (pCall != NULL && pCall->GetCallHandle() == NULL &&
(pCall->GetCallInfo()->dwMediaMode & m_dwLineMediaModes))
{
if (!pCall->CreateCallHandle())
fAllOK = false;
}
}
}
return fAllOK;
}// CTSPILineConnection::OfferCallsToTAPISrv
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetDevConfig
//
// Return the device configuration for this line and device class.
//
LONG CTSPILineConnection::GetDevConfig(const TString& /*strDeviceClass*/, LPVARSTRING /*lpDeviceConfig*/)
{
// Derived class needs to supply the data structures for this based on what may be configured.
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetDevConfig
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetDevConfig
//
// Sets the device configuration for this line and device class.
//
LONG CTSPILineConnection::SetDevConfig(const TString& /*strDeviceClass*/,
LPVOID const /*lpDevConfig*/, DWORD /*dwSize*/)
{
// Derived class needs to supply the data structures for this based on
// what may be configured.
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::SetDevConfig
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::DevSpecific
//
// Invoke a device-specific feature on this line device.
//
LONG CTSPILineConnection::DevSpecific(CTSPIAddressInfo* /*pAddr*/,
CTSPICallAppearance* /*pCall*/, DRV_REQUESTID /*dwRequestID*/,
LPVOID /*lpParam*/, DWORD /*dwSize*/)
{
if ((m_LineStatus.dwLineFeatures & LINEFEATURE_DEVSPECIFIC) == 0)
return LINEERR_OPERATIONUNAVAIL;
// Derived class must manage device-specific features.
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::DevSpecific
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::DevSpecificFeature
//
// Invoke a device-specific feature on this line device.
//
LONG CTSPILineConnection::DevSpecificFeature(DWORD /*dwFeature*/, DRV_REQUESTID /*dwRequestId*/,
LPVOID /*lpParams*/, DWORD /*dwSize*/)
{
if ((m_LineStatus.dwLineFeatures & LINEFEATURE_DEVSPECIFICFEAT) == 0)
return LINEERR_OPERATIONUNAVAIL;
// Derived class must manage device-specific features.
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::DevSpecificFeature
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GenericDialogData
//
// This method is called when a dialog which sent in a LINE
// device ID called our UI callback.
//
LONG CTSPILineConnection::GenericDialogData(LPVOID /*lpvItemData*/, LPVOID /*lpParam*/, DWORD /*dwSize*/)
{
return FALSE;
}// CTSPILineConnection::GenericDialogData
//////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnCallFeaturesChanged
//
// This method gets called whenever a call changes its currently
// available features in the CALLINFO structure.
//
DWORD CTSPILineConnection::OnCallFeaturesChanged (CTSPICallAppearance* /*pCall*/, DWORD dwFeatures)
{
return dwFeatures;
}// CTSPILineConnection::OnCallFeaturesChanged
//////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnAddressFeaturesChanged
//
// This method gets called whenever an address changes its currently
// available features in the ADDRESSSTATUS structure.
//
DWORD CTSPILineConnection::OnAddressFeaturesChanged (CTSPIAddressInfo* /*pAddr*/, DWORD dwFeatures)
{
return dwFeatures;
}// CTSPILineConnection::OnAddressFeaturesChanged
//////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnConnectedCallCountChange
//
// This method gets called whenever any address on this line changes
// the total count of connected calls. This impacts the bandwidth of the
// service provider (i.e. whether MAKECALL and such may be called).
//
void CTSPILineConnection::OnConnectedCallCountChange(CTSPIAddressInfo* /*pInfo*/, int iDelta)
{
m_dwConnectedCallCount += iDelta;
_TSP_DTRACE(_T("%s: OnConnectedCallCountChange: Delta=%d, New Count=%ld\n"), m_strName.c_str(), iDelta, m_dwConnectedCallCount);
// Now adjust our LINE features based on the total counts.
RecalcLineFeatures();
}// CTSPILineConnection::OnConnectedCallCountChange
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnMediaConfigChanged
//
// This method may be used by the service provider to notify TAPI that
// the media configuration has changed.
//
void CTSPILineConnection::OnMediaConfigChanged()
{
// Tell TAPI the configuration has changed.
Send_TAPI_Event (NULL, LINE_LINEDEVSTATE, LINEDEVSTATE_CONFIGCHANGE);
}// CTSPILineConnection::OnMediaConfigChanged
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::OnMediaControl
//
// This method is called when a media control event was activated
// due to a media monitoring event being caught on this call.
//
void CTSPILineConnection::OnMediaControl (CTSPICallAppearance* /*pCall*/, DWORD /*dwMediaControl*/)
{
// User must override this or the CTSPICallAppearance::OnMediaControl
// and perform action on the media event.
_TSP_ASSERT (false);
}// CTSPILineConnection::OnMediaControl
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SupportsAgents
//
// true/false whether this line has an address which supports agent
// logon/logoff or some other feature.
//
bool CTSPILineConnection::SupportsAgents() const
{
int nAddrCount = GetAddressCount();
for (int iAddress = 0; iAddress < nAddrCount; iAddress++)
{
if (GetAddress(iAddress)->GetAgentCaps()->dwFeatures != 0)
return true;
}
return false;
}// CTSPILineConnection::SupportsAgents
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::RecalcLineFeatures
//
// This is called when the line device status changes to recalc our
// feature set based on the status and address/call information
//
void CTSPILineConnection::RecalcLineFeatures(bool fRecalcAllAddresses)
{
DWORD dwFeatures = m_LineStatus.dwLineFeatures;
DWORD dwStatus = m_LineStatus.dwDevStatusFlags;
bool isDisabled = ((dwStatus &
(LINEDEVSTATUSFLAGS_INSERVICE | LINEDEVSTATUSFLAGS_CONNECTED)) !=
(LINEDEVSTATUSFLAGS_INSERVICE | LINEDEVSTATUSFLAGS_CONNECTED));
// If we are NOT in-service now, we have NO line features.
if (isDisabled)
dwFeatures = 0;
else
{
dwFeatures = m_LineCaps.dwLineFeatures &
(LINEFEATURE_DEVSPECIFIC |
LINEFEATURE_DEVSPECIFICFEAT |
LINEFEATURE_FORWARD |
LINEFEATURE_MAKECALL |
LINEFEATURE_SETMEDIACONTROL |
LINEFEATURE_SETDEVSTATUS |
LINEFEATURE_FORWARDFWD |
LINEFEATURE_FORWARDDND);
// If we have the bandwidth for a call...
dwFeatures &= ~LINEFEATURE_MAKECALL;
if (m_dwConnectedCallCount < m_LineCaps.dwMaxNumActiveCalls)
{
int acount = GetAddressCount();
for (int i = 0; i < acount; i++)
{
if (GetAddress(i)->GetAddressStatus()->
dwAddressFeatures & LINEADDRFEATURE_MAKECALL)
{
dwFeatures |= LINEFEATURE_MAKECALL;
break;
}
}
}
// If we have terminals, allow SETTERMINAL.
if (GetTerminalCount() > 0)
dwFeatures |= (m_LineCaps.dwLineFeatures & LINEFEATURE_SETTERMINAL);
}
// Set the new features; this might not be accurate since we
// have not recalculated the address features which may remove
// the MAKECALL bit.
DWORD dwFeaturesNew = OnLineFeaturesChanged(dwFeatures & m_LineCaps.dwLineFeatures);
_TSP_DTRACE(_T("%s: Calculating new line features - 0x%lx, Final=0x%lx, ConnectedCalls=%d, Max=%d\n"), m_strName.c_str(), dwFeatures, dwFeaturesNew, m_dwConnectedCallCount, m_LineCaps.dwMaxNumActiveCalls);
SetLineFeatures(dwFeaturesNew);
// Recalculate address features if necessary
bool needRecalcLine = false;
if (fRecalcAllAddresses)
{
// Walk through each address and recalculate the available
// features for that address; also track whether the feature
// set actually changed, if so we will need to adjust our
// line features as appropriate.
int acount = GetAddressCount();
for (int i = 0; i < acount; i++)
{
CTSPIAddressInfo* pAddr = GetAddress(i);
DWORD dwCurrFeatures = pAddr->GetAddressStatus()->dwAddressFeatures;
pAddr->RecalcAddrFeatures();
if (dwCurrFeatures != pAddr->GetAddressStatus()->dwAddressFeatures)
needRecalcLine = true;
}
}
// If the address features changed, then we need to recalculate
// the new line features; however we do not want to go back
// through the address calculation a second time.
if (needRecalcLine && !isDisabled)
RecalcLineFeatures(false);
}// CTSPILineConnection::RecalcLineFeatures
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CreateTapiTerminalDeviceClassInfo
//
// This is called directly after the Init() function to create the
// "tapi/terminal" device class information - override this if the
// assumptions used for phone to terminal matchups are invalid for the
// device in question.
//
bool CTSPILineConnection::CreateTapiTerminalDeviceClassInfo()
{
// The default implementation requires that a phone was associated
// to this line during the initialization process.
CTSPIPhoneConnection* pPhone = GetAssociatedPhone();
if (pPhone == NULL)
return false;
// We assume that any terminal marked as "phone" on the line are associated
// with the given phone device.
TDWordArray arrTermInfo;
for (int iTerminalID = 0; iTerminalID < GetTerminalCount(); iTerminalID++)
{
TERMINALINFO* lpTermInfo = m_arrTerminalInfo[iTerminalID];
if (lpTermInfo->Capabilities.dwTermDev == LINETERMDEV_PHONE)
arrTermInfo.push_back(pPhone->GetDeviceID());
else
arrTermInfo.push_back(0xffffffff);
}
AddDeviceClass(_T("tapi/terminal"), STRINGFORMAT_BINARY, &arrTermInfo[0],
GetTerminalCount() * sizeof(DWORD));
return true;
}// CTSPILineConnection::CreateTapiTerminalDeviceClassInfo
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CreateAgent
//
// This creates a new agent for this line device.
//
LONG CTSPILineConnection::CreateAgent(DRV_REQUESTID dwRequestID, LPHAGENT lphAgent, LPCTSTR pszMachineName, LPCTSTR pszUserName, LPCTSTR pszAgentID, LPCTSTR pszAgentPIN)
{
UNREFERENCED_PARAMETER(dwRequestID);
UNREFERENCED_PARAMETER(lphAgent);
UNREFERENCED_PARAMETER(pszMachineName);
UNREFERENCED_PARAMETER(pszUserName);
UNREFERENCED_PARAMETER(pszAgentID);
UNREFERENCED_PARAMETER(pszAgentPIN);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::CreateAgent
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetAgentMeasurementPeriod
//
// This method changes the agent measurement period for collecting
// statistics for thie given agent.
//
LONG CTSPILineConnection::SetAgentMeasurementPeriod(DRV_REQUESTID dwRequestID, HAGENT hAgent, DWORD dwMeasurementPeriod)
{
UNREFERENCED_PARAMETER(dwRequestID);
UNREFERENCED_PARAMETER(hAgent);
UNREFERENCED_PARAMETER(dwMeasurementPeriod);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::SetAgentMeasurementPeriod
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetAgentInfo
//
// This function returns information about the given agent handle.
//
LONG CTSPILineConnection::GetAgentInfo(HAGENT hAgent, LPLINEAGENTINFO lpAgentInfo)
{
UNREFERENCED_PARAMETER(hAgent);
UNREFERENCED_PARAMETER(lpAgentInfo);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetAgentInfo
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::CreateAgentSession
//
// This function starts a new session for an agent. (agent login)
//
LONG CTSPILineConnection::CreateAgentSession(DRV_REQUESTID dwRequestID, LPHAGENTSESSION lphSession, HAGENT hAgent, LPCTSTR pszAgentPIN, const GUID& guid, DWORD dwWorkingAddressID)
{
UNREFERENCED_PARAMETER(dwRequestID);
UNREFERENCED_PARAMETER(lphSession);
UNREFERENCED_PARAMETER(hAgent);
UNREFERENCED_PARAMETER(pszAgentPIN);
UNREFERENCED_PARAMETER(guid);
UNREFERENCED_PARAMETER(dwWorkingAddressID);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::CreateAgentSession
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetAgentSessionList
//
// This returns a list of the sessions an agent is associated with.
//
LONG CTSPILineConnection::GetAgentSessionList(HAGENT hAgent, LPLINEAGENTSESSIONLIST lpSessionList)
{
UNREFERENCED_PARAMETER(hAgent);
UNREFERENCED_PARAMETER(lpSessionList);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetAgentSessionList
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetAgentSessionState
//
// This changes the agent session state.
//
LONG CTSPILineConnection::SetAgentSessionState(DRV_REQUESTID dwRequestID, HAGENTSESSION hSession, DWORD dwAgentSessionState, DWORD dwNextAgentSessionState)
{
UNREFERENCED_PARAMETER(dwRequestID);
UNREFERENCED_PARAMETER(hSession);
UNREFERENCED_PARAMETER(dwAgentSessionState);
UNREFERENCED_PARAMETER(dwNextAgentSessionState);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::SetAgentSessionState
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetAgentSessionInfo
//
// This returns information on a specific agent session
//
LONG CTSPILineConnection::GetAgentSessionInfo(HAGENTSESSION hSession, LPLINEAGENTSESSIONINFO lpSessionInfo)
{
UNREFERENCED_PARAMETER(hSession);
UNREFERENCED_PARAMETER(lpSessionInfo);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetAgentSessionInfo
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetQueueList
//
// This returns information about an agent queue
//
LONG CTSPILineConnection::GetQueueList(const GUID& GroupID, LPLINEQUEUELIST lpQueueList)
{
UNREFERENCED_PARAMETER(GroupID);
UNREFERENCED_PARAMETER(lpQueueList);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetQueueList
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetQueueMeasurementPeriod
//
// This changes the statistic gathering period for queues.
//
LONG CTSPILineConnection::SetQueueMeasurementPeriod(DRV_REQUESTID dwRequestID, DWORD dwQueueID, DWORD dwMeasurementPeriod)
{
UNREFERENCED_PARAMETER(dwRequestID);
UNREFERENCED_PARAMETER(dwQueueID);
UNREFERENCED_PARAMETER(dwMeasurementPeriod);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::SetQueueMeasurementPeriod
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetQueueInfo
//
// This retrieves information about the given queue.
//
LONG CTSPILineConnection::GetQueueInfo(DWORD dwQueueID, LPLINEQUEUEINFO lpQueueInfo)
{
UNREFERENCED_PARAMETER(dwQueueID);
UNREFERENCED_PARAMETER(lpQueueInfo);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetQueueInfo
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetGroupList
//
// This retrieves the list of agent groups.
//
LONG CTSPILineConnection::GetGroupList(LPLINEAGENTGROUPLIST lpGroupList)
{
UNREFERENCED_PARAMETER(lpGroupList);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::GetGroupList
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetAgentStateEx
//
// This changes the agent state
//
LONG CTSPILineConnection::SetAgentStateEx(DRV_REQUESTID dwRequestID, HAGENT hAgent, DWORD dwState, DWORD dwNextState)
{
UNREFERENCED_PARAMETER(dwRequestID);
UNREFERENCED_PARAMETER(hAgent);
UNREFERENCED_PARAMETER(dwState);
UNREFERENCED_PARAMETER(dwNextState);
return LINEERR_OPERATIONUNAVAIL;
}// CTSPILineConnection::SetAgentStateEx
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::MSPIdentify
//
// This function determines the associated MSP CLSID for each line
// device. This function requires TAPI 3.0 negotiation.
//
LONG CTSPILineConnection::MSPIdentify(GUID* pGUID)
{
memcpy(pGUID, &m_guidMSP, sizeof(GUID));
return (m_guidMSP == IID_NULL) ? LINEERR_OPERATIONUNAVAIL : 0;
}// CTSPILineConnection::MSPIdentify
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::ReceiveMSPData
//
// This function receives data sent by a media service provider (MSP).
// It requires TAPI 3.0 negotiation.
//
LONG CTSPILineConnection::ReceiveMSPData(CMSPDriver* /*pMSP*/, CTSPICallAppearance* /*pCall*/, LPVOID /*lpData*/, DWORD /*dwSize*/)
{
// Must be overridden by derived class
return LINEERR_OPERATIONFAILED;
}// CTSPILineConnection::ReceiveMSPData
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::GetCallHubTracking
//
// This function fills in the status of call hub tracking provided by the
// service proider. It requires TAPI 3.0 negotiation.
//
LONG CTSPILineConnection::GetCallHubTracking(LPLINECALLHUBTRACKINGINFO lpTrackingInfo)
{
// Mark that provider-level tracking is supported.
lpTrackingInfo->dwNeededSize = sizeof(LINECALLHUBTRACKINGINFO);
lpTrackingInfo->dwUsedSize = sizeof(LINECALLHUBTRACKINGINFO);
lpTrackingInfo->dwAvailableTracking = LINECALLHUBTRACKING_ALLCALLS;
lpTrackingInfo->dwCurrentTracking = m_dwCallHubTracking;
return 0;
}// CTSPILineConnection::GetCallHubTracking
////////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::SetCallHubTracking
//
// This function fills in the status of call hub tracking provided by the
// service proider. It requires TAPI 3.0 negotiation.
//
LONG CTSPILineConnection::SetCallHubTracking(LPLINECALLHUBTRACKINGINFO lpTrackingInfo)
{
// Set the new call hub tracking support; the TSP library actually ignores
// this at the moment as TAPISRV doesn't appear to expect anything different as
// of Win2K build 2195.
m_dwCallHubTracking = lpTrackingInfo->dwCurrentTracking;
return 0;
}// CTSPILineConnection::SetCallHubTracking
#ifdef _DEBUG
///////////////////////////////////////////////////////////////////////////
// CTSPILineConnection::Dump
//
// Debug "dump" of the object and it's contents.
//
TString CTSPILineConnection::Dump() const
{
TStringStream outstm;
outstm << _T("0x") << hex << (DWORD)this;
outstm << _T(",LineID=0x") << hex << m_LineCaps.dwPermanentLineID;
outstm << _T(",DeviceID=0x") << hex << m_dwDeviceID;
outstm << _T(",htLine=0x") << hex << m_htLine;
return(outstm.str());
}// CTSPILineConnection::Dump
#endif
| [
"Owner@.(none)"
]
| [
[
[
1,
3436
]
]
]
|
4aba22743dad8c3c9d72c8fded558839c16ec5b6 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /maxsdk2008/include/object.h | b10577fdde7bd27504c5443027a829b05ca229a6 | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 311,782 | h | /**********************************************************************
*<
FILE: object.h
DESCRIPTION: Defines Object Classes
CREATED BY: Dan Silva
HISTORY: created 9 September 1994
*> Copyright (c) 1994, All Rights Reserved.
**********************************************************************/
#ifndef _OBJECT_
#define _OBJECT_
#include "maxheap.h"
#include "inode.h"
#include "maxapi.h"
#include "plugapi.h"
#include "snap.h"
#include "genshape.h"
#include <hitdata.h>
#include "imtl.h"
#include "channels.h"
typedef short MtlIndex;
typedef short TextMapIndex;
CoreExport void setHitType(int t);
CoreExport int getHitType(void);
CoreExport BOOL doingXORDraw(void);
/*! \defgroup SceneAndNodeHitTestTypes Scene and Node Hit Test Types */
//@{
//! \brief Hit test by a single pick point.
#define HITTYPE_POINT 1
//! \brief Hit test by a rectangular area.
#define HITTYPE_BOX 2
//! \brief Hit test by circular selection area.
#define HITTYPE_CIRCLE 3
//! \brief Hit test a face as if it was solid, even in wireframe mode.
/*! Treating an item as solid means the face will be hit if the mouse is anywhere
inside the face region and not just over a visible edge. For example in 3ds Max when
an object is not selected and you put the mouse over it to select it, you need to
put it over the wireframe. When an object is selected however you can put the mouse
anywhere over the object and the system still considers this a valid area for hit
testing. This later case is treating the faces of the selected object as solids. */
#define HITTYPE_SOLID 4
//! \brief Hit testing by an arbitrary polygon fence.
#define HITTYPE_FENCE 5
//! \todo Need description for this define
#define HITTYPE_LASSO 6
//! \todo Need description for this define
#define HITTYPE_PAINT 7
//@}
// Flags for hit test.
/*! \defgroup SceneAndNodeHitTestFlags Scene and Node Hit Testing Flags
The following describes hit testing flags that can be sent to the node and
scene hit testing methods */
//@{
//! \brief Hit test selected items only.
#define HIT_SELONLY (1<<0)
//! \brief Hit test unselected items only.
#define HIT_UNSELONLY (1<<2)
//! \brief Abort the process of hit testing after finding any hit.
#define HIT_ABORTONHIT (1<<3)
//! \brief This treats selected items as solid and unselected items as not solid.
/*! Treating an item as solid means the face will be hit if the mouse is anywhere
inside the face region and not just over a visible edge. */
#define HIT_SELSOLID (1<<4)
//! \brief This treats any item as solid.
#define HIT_ANYSOLID (1<<5)
//! \brief This forces hit testing for the transform gizmos
#define HIT_TRANSFORMGIZMO (1<<6)
//! \brief This forces hit testing for the Switch axis when hit
/*! The selection processor that does the hit-testing will include this flag
when hit-testing on a MOUSE_POINT message, because when this flag is active
and the transform gizmo's hit-testing hits the manipulator, it should switch
the axis mode to the axis that is hit. Normally the transform gizmo hit-testing
will only highlight the axis if it hits it - but when this flag is active it
should also set the axis mode using PushAxisMode() or SetAxisMode() */
#define HIT_SWITCH_GIZMO (1<<7)
//! \brief This forces hit testing for sub-manipulators
#define HIT_MANIP_SUBHIT (1<<8)
//! \brief For hit testing everything which can be combined into the flags parameter.
#define HITFLTR_ALL (1<<10)
//! \brief For hit testing just objects which can be combined into the flags parameter.
#define HITFLTR_OBJECTS (1<<11)
//! \brief For hit testing just cameras which can be combined into the flags parameter.
#define HITFLTR_CAMERAS (1<<12)
//! \brief For hit testing just lights which can be combined into the flags parameter.
#define HITFLTR_LIGHTS (1<<13)
//! \brief For hit testing just helpers which can be combined into the flags parameter.
#define HITFLTR_HELPERS (1<<14)
//! \brief For hit testing just world space objects which can be combined into the flags parameter.
#define HITFLTR_WSMOBJECTS (1<<15)
//! \brief For hit testing just splines which can be combined into the flags parameter.
#define HITFLTR_SPLINES (1<<16)
//! \brief For hit testing just bones which can be combined into the flags parameter.
#define HITFLTR_BONES (1<<17)
//! \brief Lets you hitest scene xrefx; however, DO NOT make references to them
#define HIT_SCENEXREFS (1<<18)
//! \brief Starting at this bit through the 31st bit can be used by plug-ins for sub-object hit testing
#define HITFLAG_STARTUSERBIT 24
//@}
#define VALID(x) (x)
class Modifier;
class Object;
class NameTab;
class ExclList;
class Texmap;
class ISubObjType;
class MaxIcon;
typedef Object* ObjectHandle;
MakeTab(TextMapIndex)
typedef TextMapIndexTab TextTab;
#define BASEOBJAPPDATACID Class_ID(0x48a057d2, 0x44f70d8a)
#define BASEOBJAPPDATALASTSELCID Class_ID(0x1cef158c, 0x1da8486f)
#define BASEOBJAPPDATACURSELCID Class_ID(0x5b3b25fc, 0x35af6260)
#define BASEOBJAPPDATASCID USERDATATYPE_CLASS_ID
//---------------------------------------------------------------
/*! \sa Class Matrix3.\n\n
\par Description:
This class is another version of Matrix3 where the matrix is initialized to the
identity by the default constructor. */
class IdentityTM: public Matrix3 {
public:
/*! \remarks Constructor. The matrix is initialized to the identity
matrix.
\par Default Implementation:
<b>{ IdentityMatrix(); }</b>\n\n
There is also a global instance of this class available for use:\n\n
<b>extern IdentityTM idTM;</b> */
IdentityTM() { IdentityMatrix(); }
};
CoreExport extern IdentityTM idTM;
//-------------------------------------------------------------
// This is passed in to GetRenderMesh to allow objects to do
// view dependent rendering.
//
// flag defines for View::flags
#define RENDER_MESH_DISPLACEMENT_MAP 1 // enable displacement mapping
/*! \sa Class GeomObject, Class Interface, Class Control, Class Matrix3, Class Point3.\n\n
\par Description:
This class is passed in to <b>GeomObject::GetRenderMesh()</b> to allow objects
to do view dependent rendering. It is also passed to
<b>Control::EvalVisibility()</b>.\n\n
For example particle systems use this to have the particles exactly face the
camera (if this option is enabled). If <b>GetRenderMesh()</b> is called by the
renderer, the methods of this class are implemented by the system. If a plug-in
is calling this method, they must implement these methods. The sample code
below shown a null implementation that may be used if a viewport is not
involved:
\code
class NullView : public View
{
Point2 ViewToScreen(Point3 p)
{ return Point2(p.x,p.y); }
NullView() {
worldToView.IdentityMatrix();
screenW=640.0f; screenH = 480.0f;
}
};
\endcode
\par Data Members:
<b>float screenW, screenH;</b>\n\n
These hold the screen dimensions in pixels for width and height.\n\n
<b>Matrix3 worldToView;</b>\n\n
A transformation matrix from world into view space. This is into the camera's
space.\n\n
<b>int projType;</b>\n\n
The view projection type: <b>0</b> is perspective, <b>1</b> is parallel.\n\n
<b>float fov;</b>\n\n
The field of view in radians.\n\n
<b>float pixelSize;</b>\n\n
The pixel size setting.\n\n
<b>Matrix3 affineTM;</b>\n\n
This is the world to camera transformation matrix.\n\n
<b>DWORD flags;</b>\n\n
The following flag is defined.\n\n
<b>RENDER_MESH_DISPLACEMENT_MAP</b>\n\n
Indicates that Displacement Mapping is enabled. Note that this flag should be
tested, and not <b>Interface::GetRendDisplacement()</b>, because the values may
not be the same (for instance when rendering in the Materials Editor). */
class View : public InterfaceServer{
public:
float screenW, screenH; // screen dimensions
Matrix3 worldToView;
/*! \remarks This method is used to convert a point in view space to
screen space. This includes any perspective projection.
\param p The point in view space.
\return The point in screen space (in pixel coordinates). */
virtual Point2 ViewToScreen(Point3 p)=0;
// the following added for GAP
int projType;
float fov, pixelSize;
Matrix3 affineTM; // worldToCam
DWORD flags;
// Call during render to check if user has cancelled render.
// Returns TRUE iff user has cancelled.
/*! \remarks This method should be used by <b>GetRenderMesh()</b> implementations that
require a lot of processing time. This allows these processes to be
interupted by the user. An example of this in use is the extensive
computations done for displacement mapping. These may be interrupted by the
user during a render.\n\n
So, any implementation of <b>GetRenderMesh()</b> which takes a long time
should periodically call this method to see if the user has canceled the
render
\return Returns TRUE iff user has cancelled; otherwise FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL CheckForRenderAbort() { return FALSE; }
// Generic expansion function
virtual INT_PTR Execute(int cmd, ULONG_PTR arg1=0, ULONG_PTR arg2=0, ULONG_PTR arg3=0) { return 0; }
View() { projType = -1; flags = RENDER_MESH_DISPLACEMENT_MAP; } // projType not set, this is to deal with older renderers.
};
//-------------------------------------------------------------
// Class ID of general deformable object.
extern CoreExport Class_ID defObjectClassID;
//-------------------------------------------------------------
// Class ID of general texture-mappable object.
extern CoreExport Class_ID mapObjectClassID;
// an array of channel masks for all the channels *within*
// the Object.
CoreExport extern ChannelMask chMask[];
class Object;
//-- ObjectState ------------------------------------------------------------
// This is what is passed down the pipeline, and ultimately used by the Node
// to Display, Hittest, render:
// flags bits
/*! \sa Class Object, Class Matrix3.\n\n
\par Description:
The ObjectState is the structure that flows up the geometry pipeline. It
contains a matrix, a material index, some flags for channels, and a pointer to
the object in the pipeline.
\par Data Members:
<b>Object *obj;</b>\n\n
This is a pointer to the object in the pipeline. The validity interval of the
object can be retrieved using <b>obj-\>ObjectValidity()</b>. */
class ObjectState: public MaxHeapOperators {
ulong flags;
Matrix3 *tm;
Interval tmvi;
int mtl;
Interval mtlvi;
void AllocTM();
public:
Object *obj; // object: provides interval with obj->ObjectValidity()
/*! \remarks Constructor. The object pointer is initialized to NULL. */
CoreExport ObjectState();
/*! \remarks Constructor. The object pointer is set to the object passed.
The tm pointer is set to NULL and the tm and mtl validity intervals are set
to <b>FOREVER</b>.
\param ob The object to initialize the object pointer to. */
CoreExport ObjectState(Object *ob);
/*! \remarks Constructor. The object state is initialized to the object state passed.
\param os The object state to initialized to <b>os</b>. */
CoreExport ObjectState(const ObjectState& os);
/*! \remarks Destructor. If the <b>tm</b> exists, it is deleted. */
CoreExport ~ObjectState();
/*! \remarks Call this method to update the object state flags.
\param f The flags to set. The specified flags are ORed into the current state of the flags. */
void OSSetFlag(ulong f) { flags |= f; }
/*! \remarks Call this method to clear the specified object state flags.
\param f The flags to clear. */
void OSClearFlag(ulong f) { flags &= ~f; }
/*! \remarks Call this method to test the specified flags.
\param f The flags to test.
\return Nonzero if the specified flags are all set; otherwise 0. */
ulong OSTestFlag(ulong f) const { return flags&f; }
/*! \remarks Copies the specified flag settings from the specified object state to this object state.
\param f The flags to copy.
\param fromos The source object state. */
CoreExport void OSCopyFlag(ulong f, const ObjectState& fromos);
/*! \remarks Assignment operator. The object pointer, flags,
transformation matrix (and its validity interval), and material (and its
validity interval) are copied from the specified object state. */
CoreExport ObjectState& operator=(const ObjectState& os);
/*! \remarks Returns the validity interval of the object state's
transformation matrix. */
Interval tmValid() const { return tmvi; }
/*! \remarks Returns the validity interval of the object state's material. */
Interval mtlValid() const { return mtlvi; }
/*! \remarks Returns the validity interval of the object state. If the
object is not defined, this interval is NEVER. Otherwise it is the
intersection of the tm validity interval, the mtl validity interval and the
interval returned from obj-\>ObjectValidity(t).
\param t Specifies the time to retrieve the validity interval.
\return The validity interval of the object state. */
CoreExport Interval Validity(TimeValue t) const;
/*! \remarks Returns nonzero if the object state's transformation matrix
is the identity matrix; otherwise zero. */
CoreExport int TMIsIdentity() const;
/*! \remarks Sets the object state's transformation matrix to the
specified Matrix3 and its validity interval to the interval passed. If the
specified matrix is NULL, a new Matrix3 is allocated and is initialized to
the identity matrix.
\param mat Specifies the matrix to set.
\param iv Specifies the validity interval to set. */
CoreExport void SetTM(Matrix3* mat, Interval iv);
/*! \remarks Returns the object state's transformation matrix. */
CoreExport Matrix3* GetTM() const;
/*! \remarks Sets the object state tm to the identity transformation matrix. */
CoreExport void SetIdentityTM();
/*! \remarks Applies the specified matrix to the object state tm. The
object state tm is multiplied by the specified matrix. The specified
interval is intersected with the object state tm validity interval.
\param mat The matrix to apply.
\param iv The interval to intersect with the object state's tm validity interval. */
CoreExport void ApplyTM(Matrix3* mat, Interval iv);
/*! \remarks Copies the object state tm (and its validity interval) from
the specified object state's tm.
\param fromos The object state whose tm is to be copied. */
CoreExport void CopyTM(const ObjectState &fromos);
/*! \remarks Copies the object state material (and its validity interval)
from the specified object state's material.
\param fromos The object state whose material is to be copied. */
CoreExport void CopyMtl(const ObjectState &fromos);
/*! \remarks Invalidates the specified channels of the object state's
object.
\param channels The channels of the object to invalidate.
\param checkLock If <b>checkLock</b> is TRUE and <b>OBJ_CHANNELS</b> is one of the specified
channels, the object the object state points to is not deleted if it is
locked; otherwise it is deleted. */
CoreExport void Invalidate(ChannelMask channels, BOOL checkLock=FALSE);
/*! \remarks Deletes the object state's object.
\param checkLock If <b>checkLock</b> is TRUE, the object the object state points to is not
deleted if it is locked; otherwise it is always deleted.
\par Operators:
*/
CoreExport ChannelMask DeleteObj(BOOL checkLock=FALSE);
};
//! \brief Class representing a dynamic array of INodes.
class INodeTab : public Tab<INode*>
{
public:
//! \brief Deletes all temporary nodes, such as those of type INodeTransformed, from the array.
/*! \see INodeTransformed
*/
void DisposeTemporary() {
for (int i=0; i<Count(); i++) {
if ((*this)[i] != NULL) {
(*this)[i]->DisposeTemporary();
}
}
}
//! \brief Finds the specified node in the array and returns its index.
/*! \param node - The node to find
\return int - The index of the node in this array, or -1 if the node is not found
*/
int IndexOf(INode *node) {
for (int i=0; i<Count(); i++) {
if ((*this)[i] == node) {
return i;
}
}
return -1;
}
//! \brief Checks whether the specified node is in the array.
/*! \param node - The node to find
\return bool - true if the node is in the array, otherwise false
*/
bool Contains(INode *node) {
return (IndexOf(node) >= 0);
}
//! \brief Adds a node to the end of the array.
/*! \param node - The node to add to the array
\param allowDups - If true, the specified node is added to the array
without checking whether it's contained already in it. If false, the node
is added to the array only if it doesn't exist in it yet.
\param allocExtra - The number of extra items by which the array should
be enlarged if all its items have been filled with nodes.
\return - The number of nodes in the array prior to adding the specified node
*/
int AppendNode(INode* node, bool allowDups = false, int allocExtra = 0) {
if (!allowDups && Contains(node)) {
return Count();
}
return Append(1, &node, allocExtra);
}
//! \brief Inserts a node into the array at the specified position.
/*! \param node - The node to add to the array
\param at - Array index where to insert the specified node. If a negative
value is specified, the node will be appended to the array.
\param allowDups - If true, the specified node is added to the array
without checking whether it's contained already in it. If false, the node
is added to the array only if it doesn't exist in it yet.
\return - The array index at which the node was inserted, or -1 if the node
was not inserted into the array
*/
int InsertNode(INode* node, int at, bool allowDups = false) {
if (at < 0) {
AppendNode(node, allowDups);
return Count();
}
else if (allowDups || !Contains(node)) {
return Insert(at, 1, &node);
}
return -1;
}
};
//---------------------------------------------------------------
// A reference to a pointer to an instance of this class is passed in
// to ModifyObject(). The value of the pointer starts out as NULL, but
// the modifier can set it to point at an actual instance of a derived
// class. When the mod app is deleted, if the pointer is not NULL, the
// LocalModData will be deleted - the virtual destructor alows this to work.
/*! \sa Class ModContext.\n\n
\par Description:
This class allows a modifier to store application specific data. A reference to
a pointer to an instance of this class is passed in to <b>ModifyObject()</b> as
part of the <b>ModContext</b>. The value of the pointer starts out as NULL, but
the modifier can set it to point at an actual instance of a derived class. When
the mod app is deleted, if the pointer is not NULL, the <b>LocalModData</b>
will be deleted - the virtual destructor allows this to work. */
class LocalModData : public InterfaceServer {
public:
/*! \remarks A plug-in using local data should implement this method to free its local
data. */
virtual ~LocalModData() {}
/*! \remarks This method is called to allow a plug-in to copy its local data. It is
called when the system is copying a <b>ModContext</b>.
\return The plug-in should return a pointer to a new instance of its
LocalModData. */
virtual LocalModData *Clone()=0;
using InterfaceServer::GetInterface;
virtual void* GetInterface(ULONG id) { return NULL; } // to access sub-obj selection interfaces, JBW 2/5/99
};
/*! \sa Class LocalModData.\n\n
\par Description:
The ModContext stores information about the space the modifier was applied in,
and allows the modifier to store data is needs for its operation. All methods
are implemented by the system.
\par Data Members:
<b>Matrix3 *tm;</b>\n\n
This matrix represents the space the modifier was applied in. The modifier
plug-in uses this matrix when it deforms an object. The plug-in first
transforms the points with this matrix. Next it applies its own deformation.
Then it transforms the points back through the inverse of this transformation
matrix.\n\n
<b>Box3 *box;</b>\n\n
The Bounding Box of the Deformation. This represents the scale of the modifier.
For a single object it is the bounding box of the object. If the modifier is
being applied to a sub-object selection it represents the bounding box of the
sub-object selection. If the modifier is being applied to a selection set of
objects, then this is the bounding box of the entire selection set. For a
selection set of objects the bounding box is constant. In the case of a single
object, the bounding box is not constant.\n\n
<b>LocalModData *localData;</b>\n\n
A pointer to an instance of a class derived from the LocalModData class. This
is the part of the ModContext that the plug-in developer controls. It is the
place where a modifier may store application specific data. */
class ModContext : public BaseInterfaceServer {
public:
Matrix3 *tm;
Box3 *box;
LocalModData *localData;
/*! \remarks Destructor. The tm, bounding box and local data are freed. */
CoreExport ~ModContext();
/*! \remarks Constructor. The transformation matrix, bounding box, and
local data pointer are initialized to NULL. */
CoreExport ModContext();
/*! \remarks Constructor. The tm, bounding box and local data are
initialized to those of the specified ModContext.
\param mc The ModContext to copy. */
CoreExport ModContext(const ModContext& mc);
/*! \remarks Constructor. The tm, bounding box, and local data are
initialized to those specified.
\param tm The transform matrix to copy.
\param box The bounding box to copy.
\param localData The local data that will be cloned. */
CoreExport ModContext(Matrix3 *tm, Box3 *box, LocalModData *localData);
};
/*! \sa Template Class Tab, Class Interface (method <b>GetModContexts()</b>)\n\n
\par Description:
A modifier may be applied to several objects in the scene. The
<b>Interface::GetModContexts()</b> method retrieves a list of all the
ModContexts for the current place in the history. This class is used as a table
to hold the list of ModContexts. */
class ModContextList : public Tab<ModContext*> {};
class HitRecord;
// Values passed to NewSetByOperator()
#define NEWSET_MERGE 1
#define NEWSET_INTERSECTION 2
#define NEWSET_SUBTRACT 3
// Flags passed to Display()
#define USE_DAMAGE_RECT (1<<0)
#define DISP_SHOWSUBOBJECT (1<<1)
// The base class of Geometric objects, Lights, Cameras, Modifiers,
// Deformation objects--
// --anything with a 3D representation in the UI scene.
class IParamArray;
/*! \sa Class ReferenceTarget, Class INode, Class ViewExp, Class Box3, Class IPoint2, Class Matrix3, Structure SnapInfo, Class Point3, Class CreateMouseCallBack, Template Class Tab, Class Interface.\n\n
\par Description:
This is the base class for objects and modifiers. Anything with a
representation in the 3D viewports is derived from BaseObject (including
modifiers and controllers whose gizmos appear in the viewports). The methods
here are things such as displaying the object in the viewports, checking for
intersection of the object and points the user clicks with the mouse, snapping
to the object, and computing various bounding boxes for the object. Also there
are methods for returning the name of the object to appear in the modifier
stack, a method to deal with creating the object in the viewports (if
appropriate), and named selection set related methods. There are also methods
that allow other plug-ins to access the changeable parameters of the object.
Finally there are several method that deal with sub-object selection,
sub-object display, sub-object hit testing, and moving/rotating/scaling
sub-object components of the object.
\par Method Groups:
See <a href="class_base_object_groups.html">Method Groups for Class BaseObject</a>.
*/
class BaseObject : public ReferenceTarget {
friend class ModifyTaskImp;
int subObjLevel;
public:
CoreExport void* GetInterface(ULONG id);
virtual BaseInterface* GetInterface(Interface_ID id) { return ReferenceTarget::GetInterface(id); }
CoreExport BaseObject();
/*! \remarks This method is called to determine if the specified screen point intersects
the item. The method returns nonzero if the item was hit; otherwise 0.
\param t The time to perform the hit test.
\param inode A pointer to the node to test.
\param type The type of hit testing to perform. See \ref SceneAndNodeHitTestTypes for details.
\param crossing The state of the crossing setting. If TRUE crossing selection is on.
\param flags The hit test flags. See \ref SceneAndNodeHitTestFlags for details.
\param p The screen point to test.
\param vpt An interface pointer that may be used to call methods associated with the viewports.
\return Nonzero if the item was hit; otherwise 0.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt){return 0;};
/*! \remarks This method is used for storing mode-dependent display
attributes.\n\n
Before an object's Display() method is called, the appropriate bits of the
extended display flag variable are set and this method is called. After
that, the Display() method is called. If the object must display itself
differently based on the settings of the extended display bit fields, then
the object must save the flags passed into the this method. Otherwise,
there is no need for the object to store the flags.
\param flags The flags to store.
\par Default Implementation:
<b>{}</b> */
virtual void SetExtendedDisplay(int flags) {} // for setting mode-dependent display attributes
/*! \remarks This is called by the system to have the item display itself (perform a
quick render in viewport, using the current TM). Note: For this method to
be called the object's validity interval must be invalid at the specified
time <b>t</b>. If the interval is valid, the system may not call this
method since it thinks the display is already valid.
\param t The time to display the object.
\param inode The node to display.
\param vpt An interface pointer that may be used to call methods associated with the viewports.
\param flags See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_display_flags.html">List of Display Flags</a>.
\return The return value is not currently used.
\par Default Implementation:
<b>{ return 0; };</b> */
virtual int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags) { return 0; }; // quick render in viewport, using current TM.
/*! \remarks Checks the point passed for a snap and updates the <b>SnapInfo</b> structure.\n\n
\note Developers wanting to find snap points on an
Editable Mesh object should see the method <b>XmeshSnap::Snap()</b> in
<b>/MAXSDK/SAMPLES/SNAPS/XMESH/XMESH.CPP</b>.
\param t The time to check.
\param inode The node to check.
\param snap The snap info structure to update.
\param p The screen point to check.
\param vpt An interface pointer that may be used to call methods associated with the viewports. */
virtual void Snap(TimeValue t, INode* inode, SnapInfo *snap, IPoint2 *p, ViewExp *vpt) {} // Check for snap, updating SnapInfo
/*! \remarks This method returns the world space bounding box for Objects (see below for
the Sub-object gizmo or Modifiers gizmo version). The bounding box returned
by this method does not need to be precise. It should however be calculated
rapidly. The object can handle this by transforming the 8 points of its
local bounding box into world space and take the minimums and maximums of
the result. Although this isn't necessarily the tightest bounding box of
the objects points in world space, it is close enough.
\param t The time to compute the bounding box.
\param inode The node to calculate the bounding box for.
\param vp An interface pointer that can be used to call methods associated with the viewports.
\param box Contains the returned bounding box. */
virtual void GetWorldBoundBox(TimeValue t, INode * inode, ViewExp* vp, Box3& box ){}; // Box in world coords.
/*! \remarks This is the object space bounding box, the box in the object's local
coordinates. The system expects that requesting the object space bounding
box will be fast.
\param t The time to retrieve the bounding box.
\param inode The node to calculate the bounding box for.
\param vp An interface pointer that may be used to call methods associated with the viewports.
\param box Contains the returned bounding box. */
virtual void GetLocalBoundBox(TimeValue t, INode* inode, ViewExp* vp, Box3& box ){}; // box in objects local coords
/*! \remarks This method allows the system to retrieve a callback object used in
creating an object in the 3D viewports. This method returns a pointer to an
instance of a class derived from <b>CreateMouseCallBack</b>. This class has
a method <b>proc()</b> which is where the programmer defines the user/mouse
interaction during the object creation phase.
\return A pointer to an instance of a class derived from
<b>CreateMouseCallBack</b>. */
virtual CreateMouseCallBack* GetCreateMouseCallBack()=0;
// This is the name that will appear in the history browser.
/*! \remarks Returns the name that will appear in the history browser (modifier stack).
\par Default Implementation:
<b>{ return _T("Object"); }</b> */
virtual MCHAR *GetObjectName() { return _M("Object"); }
// Sends the \ref REFMSG_IS_OK_TO_CHANGE_TOPOLOGY off to see if any
// modifiers or objects down the pipeline depend on topology.
// modName will be set to the dependent modifier's name if there is one.
/*! \remarks Implemented by the System.\n\n
This method is called to see if any modifiers down in the pipeline depend
on topology. It sends the message \ref REFMSG_IS_OK_TO_CHANGE_TOPOLOGY to
see if any modifiers or objects down the pipeline depend on topology.
\param modName This parameter is set to the dependent modifier's name if there is an item
that depends on topology.
\return Returns TRUE if it is okay to change the topology; FALSE if it is
not okay to change the topology. */
CoreExport virtual BOOL OKToChangeTopology(MSTR &modName);
// Return true if this object(or modifier) is cabable of changing
//topology when it's parameters are being edited.
/*! \remarks This method asks the question of an object or modifier "Do you change
topology"? An object or modifier returns TRUE if it is capable of changing
topology when its parameters are being edited; otherwise FALSE.\n\n
When an item is selected for editing, and there is a modifier in the
pipeline that depends on topology, the system calls this method to see if
it may potentially change the topology. If this method returns TRUE the
system will put up a warning message indicating that a modifier exists in
the stack that depends on topology.
\par Default Implementation:
<b>{return TRUE;}</b> */
virtual BOOL ChangeTopology() {return TRUE;}
/*! \remarks This method is no longer used. */
virtual void ForceNotify(Interval& i)
{NotifyDependents(i, PART_ALL,REFMSG_CHANGE);}
// If an object or modifier wishes it can make its parameter block
// available for other plug-ins to access. The system itself doesn't
// actually call this method -- this method is optional.
/*! \remarks An object or modifier should implement this method if it wishes to make its
parameter block available for other plug-ins to access it. The system
itself doesn't actually call this method. This method is optional.
\return A pointer to the item's parameter block. See
Class IParamArray.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual IParamArray *GetParamBlock() {return NULL;}
// If a plug-in make its parameter block available then it will
// need to provide #defines for indices into the parameter block.
// These defines should probably not be directly used with the
// parameter block but instead converted by this function that the
// plug-in implements. This way if a parameter moves around in a
// future version of the plug-in the #define can be remapped.
// -1 indicates an invalid parameter id
/*! \remarks If a plug-in makes its parameter block available (using
<b>GetParamBlock()</b>) then it will need to provide #defines for indices
into the parameter block. These defines should not be directly used with
the parameter block but instead converted by this function that the plug-in
implements. This way if a parameter moves around in a future version of the
plug-in the #define can be remapped. A return value of -1 indicates an
invalid parameter id.
\param id The parameter block id. See: <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_pblock_ids.html">
List of Parameter Block IDs</a>.
\return The parameter block index or -1 if it is invalid.
\par Default Implementation:
<b>{return -1;}</b> */
virtual int GetParamBlockIndex(int id) {return -1;}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
//
// The following methods are for sub-object selection. If the
// derived class is NOT a modifier, the modContext pointer passed
// to some of the methods will be NULL.
//
// Affine transform methods
/*! \remarks When this method is called the plug-in should respond by moving its
selected sub-object components.
\param t The time of the transformation.
\param partm The 'parent' transformation matrix. This matrix represents a transformation
that would take points in the modifier's space and convert them into world
space points. This is constructed as the node's transformation matrix times
the inverse of the ModContext's transformation matrix. The node whose
transformation is used is the node the user clicked on in the scene -
modifiers can be instanced so there could be more than one node.
\param tmAxis The matrix that represents the axis system. This is the space in which the
transformation is taking place.
\param val This value is a vector with X, Y, and Z representing the movement along each axis.
\param localOrigin When TRUE the transformation is occurring about the sub-object's local origin. */
virtual void Move( TimeValue t, Matrix3& partm, Matrix3& tmAxis, Point3& val, BOOL localOrigin=FALSE ){}
/*! \remarks When this method is called the plug-in should respond by rotating its
selected sub-object components.
\param t The time of the transformation.
\param partm The 'parent' transformation matrix. This matrix represents a transformation
that would take points in the modifier's space and convert them into world
space points. This is constructed as the node's transformation matrix times
the inverse of the ModContext's transformation matrix. The node whose
transformation is used is the node the user clicked on in the scene -
modifiers can be instanced so there could be more than one node.
\param tmAxis The matrix that represents the axis system. This is the space in which the
transformation is taking place.
\param val The amount to rotate the selected components.
\param localOrigin When TRUE the transformation is occurring about the sub-object's local
origin. Note: This information may be passed onto a transform controller
(if there is one) so they may avoid generating 0 valued position keys for
rotation and scales. For example if the user is rotating an item about
anything other than its local origin then it will have to translate in
addition to rotating to achieve the result. If a user creates an object,
turns on the animate button, and rotates the object about the world origin,
and then plays back the animation, the object does not do what the was done
interactively. The object ends up in the same position, but it does so by
both moving and rotating. Therefore both a position and a rotation key are
created. If the user performs a rotation about the local origin however
there is no need to create a position key since the object didn't move (it
only rotated). So a transform controller can use this information to avoid
generating 0 valued position keys for rotation and scales. */
virtual void Rotate( TimeValue t, Matrix3& partm, Matrix3& tmAxis, Quat& val, BOOL localOrigin=FALSE ){}
/*! \remarks When this method is called the plug-in should respond by scaling its
selected sub-object components.
\param t The time of the transformation.
\param partm The 'parent' transformation matrix. This matrix represents a transformation
that would take points in the modifier's space and convert them into world
space points. This is constructed as the node's transformation matrix times
the inverse of the ModContext's transformation matrix. The node whose
transformation is used is the node the user clicked on in the scene -
modifiers can be instanced so there could be more than one node.
\param tmAxis The matrix that represents the axis system. This is the space in which the
transformation is taking place.
\param val This value is a vector with X, Y, and Z representing the scale along X, Y,
and Z respectively.
\param localOrigin When TRUE the transformation is occurring about the sub-object's local
origin. See the note above in the Rotate method.\n\n
The following methods may be used to receive notification about the
starting and ending phases of transforming the item when in sub-object
selection. */
virtual void Scale( TimeValue t, Matrix3& partm, Matrix3& tmAxis, Point3& val, BOOL localOrigin=FALSE ){}
// The following is called before the first Move(), Rotate() or Scale() call and
// before a hold is in effect
/*! \remarks This method is called before the first <b>Move()</b>, <b>Rotate()</b> or
<b>Scale()</b> call and before a hold is in effect.
\param t The current time when this method is called. */
virtual void TransformStart(TimeValue t) {}
// The following is called before the first Move(), Rotate() or Scale() call and
// after a hold is in effect
/*! \remarks This method is called before the first <b>Move()</b>, <b>Rotate()</b> or
<b>Scale()</b> call and after a hold is in effect.
\param t The current time when this method is called. */
virtual void TransformHoldingStart(TimeValue t) {}
// The following is called after the user has completed the Move, Rotate or Scale operation and
// before the undo object has been accepted.
/*! \remarks This method is called after the user has completed the <b>Move()</b>,
<b>Rotate()</b> or <b>Scale()</b> operation and before the undo object has
been accepted.
\param t The current time when this method is called. */
virtual void TransformHoldingFinish(TimeValue t) {}
// The following is called after the user has completed the Move, Rotate or Scale operation and
// after the undo object has been accepted.
/*! \remarks This method is called after the user has completed the <b>Move()</b>,
<b>Rotate()</b> or <b>Scale()</b> operation and the undo object has been
accepted.
\param t The current time when this method is called. */
virtual void TransformFinish(TimeValue t) {}
// The following is called when the transform operation is cancelled by a right-click and
// the undo has been cancelled.
/*! \remarks This method is called when the transform operation is
canceled by a right-click and the undo has been canceled.
\param t The current time when this method is called. */
virtual void TransformCancel(TimeValue t) {}
/*! \remarks This method is used in modifier gizmo hit testing. It is called to
determine if the specified screen point intersects the gizmo. The method
returns nonzero if the item was hit; otherwise 0.
\param t The time to perform the hit test.
\param inode A pointer to the node to test.
\param type The type of hit testing to perform. See \ref SceneAndNodeHitTestTypes for details.
\param crossing The state of the crossing setting. If TRUE crossing selection is on.
\param flags The hit test flags. See \ref SceneAndNodeHitTestFlags for details.
\param p The screen point to test.
\param vpt An interface pointer that may be used to call methods associated with the viewports.
\param mc A pointer to the modifiers ModContext.
\return Nonzero if the item was hit; otherwise 0.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int HitTest(TimeValue t, INode* inode, int type, int crossing, int flags, IPoint2 *p, ViewExp *vpt, ModContext* mc) { return 0; }
/*! \remarks When this method is called the plug-in should respond by performing a quick
render of the modifier gizmo in viewport using the current TM.\n\n
Note for Modifiers: For this method to be called properly, one must send
two reference messages using NotifyDependents.\n\n
In BeginEditParams send:\n\n
<b>NotifyDependents(Interval(t,t), PART_ALL, REFMSG_MOD_DISPLAY_ON);</b>\n\n
In EndEditParams send:\n\n
<b>NotifyDependents(Interval(t,t), PART_ALL, REFMSG_MOD_DISPLAY_OFF);</b>
\param t The time to display the item.
\param inode The node to render.
\param vpt An interface pointer that may be used to call methods associated with the viewports.
\param flags See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_display_flags.html">List of Display Flags</a>.
\param mc A pointer to the modifiers ModContext.
\return Nonzero if the item was displayed; otherwise 0.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int Display(TimeValue t, INode* inode, ViewExp *vpt, int flags, ModContext* mc) { return 0; }; // quick render in viewport, using current TM.
/*! \remarks This method computes the world space bounding box of the modifier gizmo (or
any object that when in sub-object mode has a gizmo).
\param t The time to compute the bounding box.
\param inode The node to calculate the bounding box for.
\param vpt An interface pointer that may be used to call methods associated with the viewports.
\param box The returned bounding box.
\param mc A pointer to the modifiers ModContext. */
virtual void GetWorldBoundBox(TimeValue t,INode* inode, ViewExp *vpt, Box3& box, ModContext *mc) {}
/*! \remarks This method is called to make a copy of the selected sub-object components
of the item. If this is called on an object, the selection level of the
object is used to determine which type of sub-objects are cloned. For
instance in a Mesh, the selection level determines if selected verticies,
edges or faces are cloned. If this is called on a Modifier then the
selection level of the modifier is used. Modifiers call
<b>Interface::GetModContexts()</b> to get a list of ModContexts, one for
each object the modifier is applied to. Then the selected sub-objects are
cloned for each object in the list.
\param t The time at which to clone the selected sub-object components. */
virtual void CloneSelSubComponents(TimeValue t) {}
/*! \remarks This method is called when the user mouses up after shift-cloning a
sub-object selection.
\param t The time at which the clone of the selected components is being done.
\par Default Implementation:
<b>{}</b> */
virtual void AcceptCloneSelSubComponents(TimeValue t) {}
// Changes the selection state of the component identified by the
// hit record.
/*! \remarks This method is called to change the selection state of the component
identified by <b>hitRec</b>.
\param hitRec Identifies the component whose selected state should be set. See Class HitRecord .
\param selected TRUE if the item should be selected; FALSE if the item should be de-selected.
\param all TRUE if all components in the HitRecord chain should be selected; FALSE if
only the top-level HitRecord should be selected. (A HitRecord contains a
Next() pointer; typically you want to do whatever you're doing to all the
Next()'s until Next() returns NULL).
\param invert This is set to TRUE when <b>all</b> is also set to TRUE and the user is
holding down the Shift key while region selecting in select mode. This
indicates the items hit in the region should have their selection state
inverted */
virtual void SelectSubComponent(
HitRecord *hitRec, BOOL selected, BOOL all, BOOL invert=FALSE) {}
// Clears the selection for the given sub-object type.
/*! \remarks This method is called to clear the selection for the given sub-object
level. All sub-object elements of this type should be deselected. This will
be called when the user chooses Select None from the 3ds Max Edit menu.
\param selLevel Specifies the selection level to clear.
\par Default Implementation:
<b>{}</b> */
virtual void ClearSelection(int selLevel) {}
/*! \remarks This method is called to select every element of the given sub-object
level. This will be called when the user chooses Select All from the 3ds
Max Edit menu.
\param selLevel Specifies the selection level to select.
\par Default Implementation:
<b>{}</b> */
virtual void SelectAll(int selLevel) {}
/*! \remarks This method is called to invert the specified sub-object
level. If the element is selected it should be deselected. If it's
deselected it should be selected. This will be called when the user chooses
Select Invert from the 3ds Max Edit menu.
\param selLevel Specifies the selection level to invert.
\par Default Implementation:
<b>{}</b> */
virtual void InvertSelection(int selLevel) {}
// Returns the index of the subobject entity identified by hitRec.
/*! \remarks Returns the index of the sub-object element identified by the HitRecord
hitRec. See Class HitRecord. The
sub-object index identifies a sub-object component. The relationship
between the index and the component is established by the modifier. For
example an edit modifier may allow the user to select a group of faces and
these groups of faces may be identified as group 0, group 1, group 2, etc.
Given a hit record that identifies a face, the edit modifier's
implementation of this method would return the group index that the face
belonged to.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int SubObjectIndex(HitRecord *hitRec) {return 0;}
// This notifies an object being edited that the current sub object
// selection level has changed. level==0 indicates object level selection.
// level==1 or greater refer to the types registered by the object in the
// order they appeared in the list when registered.
// If level >= 1, the object should specify sub-object xform modes in the
// modes structure (defined in cmdmode.h).
/*! \remarks When the user changes the selection of the sub-object drop down, this
method is called to notify the plug-in. This method should provide
instances of a class derived from
CommandMode to support move, rotate,
non-uniform scale, uniform scale, and squash modes. These modes replace
their object mode counterparts however the user still uses the
move/rotate/scale tool buttons in the toolbar to activate them. If a
certain level of sub-object selection does not support one or more of the
modes NULL may be passed. If NULL is specified the corresponding toolbar
button will be grayed out.
\param level The sub-object selection level the command modes should be set to support.
A <b>level</b> of 0 indicates object level selection. If <b>level</b> is
greater than or equal to 1 the index refers to the types registered by the
object in the order they appeared in the list when registered by
<b>Interface::RegisterSubObjectTypes()</b>. See Class Interface.
\param modes The command modes to support
\par Sample Code:
\code
void SimpleMod::ActivateSubobjSel(int level, XFormModes& modes)
{
switch ( level ) {
case 1: // Modifier box
modes = XFormModes(moveMode,rotMode,nuscaleMode,uscaleMode,squashMode,NULL);
break;
case 2: // Modifier Center
modes = XFormModes(moveMode,NULL,NULL,NULL,NULL,NULL);
break;
}
NotifyDependents(FOREVER,PART_DISPLAY,REFMSG_CHANGE);
}
\endcode
\sa Class XFormModes. */
virtual void ActivateSubobjSel(int level, XFormModes& modes ) {}
// An object that supports sub-object selection can choose to
// support named sub object selection sets. Methods in the the
// interface passed to objects allow them to add items to the
// sub-object selection set drop down.
// The following methods are called when the user picks items
// from the list.
/*! \remarks Returns TRUE if the plug-in supports named sub-object selection sets;
otherwise FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL SupportsNamedSubSels() {return FALSE;}
/*! \remarks When the user chooses a name from the drop down list this method is called.
The plug-in should respond by selecting the set identified by the name
passed.
\param setName The name of the set to select. */
virtual void ActivateSubSelSet(MSTR &setName) {}
/*! \remarks If the user types a new name into the named selection set drop down then
this method is called. The plug-in should respond by creating a new set and
give it the specified name.
\param setName The name for the selection set. */
virtual void NewSetFromCurSel(MSTR &setName) {}
/*! \remarks If the user selects a set from the drop down and then chooses Remove Named
Selections from the Edit menu this method is called. The plug-in should
respond by removing the specified selection set.
\param setName The selection set to remove. */
virtual void RemoveSubSelSet(MSTR &setName) {}
// New for version 2. To support the new edit named selections dialog,
// plug-ins must implemented the following methods:
/*! \remarks To support the new Edit Named Selections dialog, plug-ins must implement
this method.\n\n
This method is called to rebuild the named selelction set drop down list.
This is usually done by calling
<b>Interface::ClearSubObjectNamedSelSets()</b> followed by calls to
<b>Interface:: AppendSubObjectNamedSelSet()</b>.
\par Default Implementation:
<b>{}</b> */
virtual void SetupNamedSelDropDown() {}
/*! \remarks To support the new Edit Named Selections dialog, plug-ins must implement
this method.\n\n
Returns the number of named selection sets.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int NumNamedSelSets() {return 0;}
/*! \remarks To support the new Edit Named Selections dialog, plug-ins must implement
this method.\n\n
Returns the name of the 'i-th' named selection set.
\param i The index of the selection set whose name is returned.
\par Default Implementation:
<b>{return _T("");}</b> */
virtual MSTR GetNamedSelSetName(int i) {return _M("");}
/*! \remarks To support the new Edit Named Selections dialog, plug-ins must implement
this method.\n\n
This methods sets the name of the selection set whose index is passed to
the name passed.\n\n
Note: Developers need to implement Undo / Redo for modifications to their
named selection sets.
\param i The index of the selection set whose name is to be set.
\param newName The new name for the selection set the plug-in should store.
\par Default Implementation:
<b>{}</b> */
virtual void SetNamedSelSetName(int i,MSTR &newName) {}
/*! \remarks To support the new Edit Named Selections dialog, plug-ins must implement
this method.\n\n
The user may bring up the Edit Named Selections dialog via the Edit / Edit
Named Selection ... command. This dialog allows the user to create new
selection sets using 'boolean' operations to the sets including 'Combine',
'Subtract (A-B)', 'Subtract (B-A)' and 'Intersection'. This method is
called on the plug-in to generate a new selection set via one of these
operations.\n\n
This method assumes the developer will append a <b>new</b> seleciton set
with the name passed. This will result in two sets with identical names.
Then the system will call <b>RemoveSubSelSet()</b> afterwards, so that the
first one that is found (the old one, since the new one was appended) will
be deleted.\n\n
Note: Developers need to implement Undo / Redo for modifications to their
named selection sets. See <b>/MAXSDK/SAMPLES/MODIFIERS/MESHSEL.CPP</b> for
an example.
\param newName The new name for the selection set is passed here.
\param sets A table of the selection sets to operate on. There are <b>sets.Count()</b>
sets in the table.
\param op One of the following values:\n\n
<b>NEWSET_MERGE</b>\n\
The sets should be merged.\n\n
<b>NEWSET_INTERSECTION </b>\n
The sets should be intersected -- that is the items common to both sets
should appear in the new set.\n\n
<b>NEWSET_SUBTRACT</b>\n
The new set should be the result of subtracting the 1st thru nth set from
the 0th set.
\par Default Implementation:
<b>{}</b> */
virtual void NewSetByOperator(MSTR &newName,Tab<int> &sets,int op) {}
// New way of dealing with sub object coordinate systems.
// Plug-in enumerates its centers or TMs and calls the callback once for each.
// NOTE:cb->Center() should be called the same number of times and in the
// same order as cb->TM()
// NOTE: The SubObjAxisCallback class is defined in animatable and used in both the
// controller version and this version of GetSubObjectCenters() and GetSubObjectTMs()
/*! \remarks When the user is in a sub-object selection level, the system needs to get
the reference coordinate system definition from the current modifier being
edited so that it can display the axis. This method specifies the position
of the center. The plug-in enumerates its centers and calls the callback
<b>cb</b> once for each.
\param cb The callback object whose methods may be called. See Class SubObjAxisCallback.
\param t The time to enumerate the centers.
\param node A pointer to the node.
\param mc A pointer to the ModContext. */
virtual void GetSubObjectCenters(SubObjAxisCallback *cb,TimeValue t,INode *node,ModContext *mc) {}
/*! \remarks When the user is in a sub-object selection level, the system needs to get
the reference coordinate system definition from the current modifier being
edited so that it can display the axis. This method returns the axis system
of the reference coordinate system. The plug-in enumerates its TMs and
calls the callback <b>cb</b> once for each. See
<a href="ms-its:3dsmaxsdk.chm::/selns_sub_object_coordinate_systems.html">Sub-Object
Coordinate Systems</a>.
\param cb The callback object whose methods may be called.
\param t The time to enumerate the TMs.
\param node A pointer to the node.
\param mc A pointer to the ModContext. */
virtual void GetSubObjectTMs(SubObjAxisCallback *cb,TimeValue t,INode *node,ModContext *mc) {}
// Find out if the Object or Modifer is is generating UVW's
// on map channel 1.
/*! \remarks It is called to find out if the object is has UVW coordinates. This method
returns TRUE if the object has UVW coordinates; otherwise FALSE. In 3ds Max
2.0 and later there is code in the renderer that will automatically turn on
the UVW coordinates of the base object if UV's are missing (and needed).
The base object has to implement two simple methods to make this work:
<b>HasUVW()</b> and <b>SetGenUVW()</b>.\n\n
Developers are encouraged to put these methods in their objects: it makes
using the program easier for the user. If they are not implemented, it
doesn't cause any real harm: it will just operate as before and put up the
missing UVW's message.\n\n
Here is how the procedural sphere implements these methods:
\code
BOOL SphereObject::GetGenUVW()
{
BOOL genUVs;
Interval v;
pblock->GetValue(PB_GENUVS, 0, genUVs, v);
return genUVs;
}
void SphereObject::SetGenUVW(BOOL sw)
{
if (sw==GetGenUVW()) return;
pblock->SetValue(PB_GENUVS,0, sw);
}
\endcode
Important Note: The <b>pblock-\>SetValue()</b> will cause a call to
<b>NotifyDependents(FOREVER, PART_TEXMAP, REFMSG_CHANGE)</b>, which will
invalidate the UVW cache. It is essential that this call be made, so if the
'generate UVW' boolean is not handled by a parameter block, then
<b>NotifyDependents()</b> needs to be called explicitly.\n\n
Also Note: For "modifiable objects" that pass up the pipeline getting
modified, such as TriObject, EditTriObject, etc., which cannot generate
their own UVWs, but can carry them in their data structures, only this
<b>HasUVW()</b> method needs to be implemented. For example, here is the
implementation for TriObject:\n\n
<b>BOOL TriObject::HasUVW() { return mesh.tvFace?1:0; }</b>
\par Default Implementation:
<b>{ return 1; }</b> */
virtual BOOL HasUVW () { return 0; }
// or on any map channel:
/*! \remarks It is called to find out if the object is has UVW coordinates for the
specified mapping channel. This method returns TRUE if the object has UVW
coordinates; otherwise FALSE. See the method <b>HasUVW()</b> above for more
details.
\param mapChannel See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_mapping_channel_index_values.html">List of
Mapping Channels Values</a>.
\par Default Implementation:
<b>{ return (mapChannel==1) ? HasUVW() : FALSE; }</b>\n\n
*/
virtual BOOL HasUVW (int mapChannel) { return (mapChannel==1) ? HasUVW() : FALSE; }
// Change the state of the object's Generate UVW boolean.
// IFF the state changes, the object should send a REFMSG_CHANGED down the pipe.
/*! \remarks This method is called to change the state of its Generate UVW boolean. If
the state changes, the object must send a \ref REFMSG_CHANGE up the
pipeline by calling <b>NotifyDependents()</b>. This applies to map channel 1.
\param sw The new state for the generate UVW flag.
\par Default Implementation:
<b>{}</b> */
virtual void SetGenUVW(BOOL sw) { } // applies to mapChannel 1
/*! \remarks This method is called to change the state of its Generate UVW boolean for
the specified mapping channel. If the state changes, the object must send a
\ref REFMSG_CHANGE up the pipeline by calling <b>NotifyDependents()</b>.
\param mapChannel The mapping channel index. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_mapping_channel_index_values.html">List of Mapping
Channel Index Values</a>.
\param sw The new state for the generate UVW flag.
\par Default Implementation:
<b>{ if (mapChannel==1) SetGenUVW(sw); }</b> */
virtual void SetGenUVW (int mapChannel, BOOL sw) { if (mapChannel==1) SetGenUVW (sw); }
// Notify the BaseObject that the end result display has been switched.
// (Sometimes this is needed for display changes.)
/*! \remarks This method notifies the BaseObject that the end result display has been
switched (the "Show End Result" button has been toggled). Sometimes this is
needed for display changes.\n\n
This method is implemented in Edit Mesh, which uses it as shown below:\n\n
<b>void EditMeshMod::ShowEndResultChanged(BOOL showEndResult) {</b>\n\n
<b>NotifyDependents(FOREVER, PART_DISPLAY, REFMSG_CHANGE);</b>\n\n
<b>}</b>\n\n
This allows the Edit Mesh modifier to update itself in repsonse to a user
click of the "Show End Result" button in the modifier panel.
\param showEndResult TRUE if Show End Result is on; FALSE if off.
\par Default Implementation:
<b>{ }</b> */
virtual void ShowEndResultChanged (BOOL showEndResult) { }
//
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// This method is called before a modifier or object is collapsed. In case it
// is a modifier, the derObj contains the DerivedObject and the index the
// index of the modifier in the DerivedObject. In case it is a Object, derObj
// is NULL and index is 0.
/*! \remarks This method is called before a modifier or object is collapsed.
\sa Class NotifyCollapseEnumProc.
\param node Points to the node for the object being collapsed.
\param derObj If the object associated with <b>node</b> above is a Modifier this points
to the derived object.If it's an object then this is NULL.
\param index If the object associated with <b>node</b> above is a Modifier this is the
index of this modifier in the DerivedObject.. If it's an object then this is 0.
\par Default Implementation:
<b>{}</b> */
virtual void NotifyPreCollapse(INode *node, IDerivedObject *derObj, int index){};
// This method is called before a modifier or object is collapsed. In case it
// is a modifier, the derObj contains the DerivedObject and the index the
// index of the modifier in the DerivedObject. In case it is a Object, derObj
// is NULL and index is 0.
/*! \remarks This method is called after a modifier or object is collapsed.
\sa Class NotifyCollapseEnumProc.
\param node Points to the node for the object being collapsed.
\param obj
\param derObj If the object associated with <b>node</b> above is a Modifier this points
to the derived object. If it's an object then this is NULL.
\param index If the object associated with <b>node</b> above is a Modifier this is the
index of this modifier in the DerivedObject. If it's an object then this is 0.
\par Default Implementation:
<b>{}</b> */
virtual void NotifyPostCollapse(INode *node, Object *obj, IDerivedObject *derObj, int index){};
// New in R4. objects and modifiers, that support subobjects have to overwrite
// these 2 methods and return a class derived from ISubObjType in GetSubObjType().
// Developers can use the GenSubObjType for convenience.If the parameter passed
// into GetSubObjType is -1, the system requests a ISubObjType, for the current
// SubObjectLevel that flows up the modifier stack. If the subobject selection
// of the modifier or base object does not affect the subobj selection that
// flows up the stack, the method must return NULL. See meshsel.cpp for a
// sample implementation
/*! \remarks Returns the number of sub-object types supported by the object or modifier.
In R4 objects or modifier must override this method and GetSubObjType() below.
\par Default Implementation:
<b>{ return 0;}</b> */
virtual int NumSubObjTypes(){ return 0;}
/*! \remarks Returns a pointer to the sub-object type for the sub-object whose index is
passed.\n\n
If the parameter <b>i</b> passed is -1 the system requests an
<b>ISubObjType</b> for the current SubObjectLevel that flows up the
modifier stack. If the subobject selection of the modifier or base object
does not affect the sub-object selection that flows up the stack NULL must
be returned. See the sample code in <b>/MAXSDK/SAMPLES/MODIFIERS/MESHSEL.CPP</b>.
\param i The zero based index of the sub-object type to get. See the remarks above.
\return The sub-object type. See Class ISubObjType.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual ISubObjType *GetSubObjType(int i) { return NULL; }
// This method returns the subobject level, that the modifier or base
// object is in. The subObjLevel is set by the system. 0 is the object level
// and 1 - n are the subobject levels in the same order as they are
// returned by GetSubObjType(int i) (with an offset of 1 obviously).
/*! \remarks This method returns an integer which indicates the current sub-object level
of the modifier or base object.
\return A value of 0 indicates object level. A value of 1 through
<b>NumSubObjTypes()</b> are the sub-object levels in the same order as they
are returned by <b>GetSubObjType(int i)</b> (with an offset of 1 of
course). */
CoreExport virtual int GetSubObjectLevel();
// This method return true if GetWorldBoundBox returns different boxes
// for different viewports. It is used to inhibit a caching of the
// bounding box for all viewports. Default implementation returns false.
virtual BOOL HasViewDependentBoundingBox() { return false; }
// Prevent accident copying / assignment.
// It also prevents a compiler quirk/bug which will complain about
// Animatable not having a copy constructor, in some derived classes
// from this one.
private:
BaseObject(const BaseObject&);
BaseObject& operator=(const BaseObject&);
};
//-------------------------------------------------------------
// Callback object used by Modifiers to deform "Deformable" objects
/*! \sa Class Object, Class Point3.\n\n
\par Description:
This is the callback object used by modifiers to deform "Deformable" objects.
*/
class Deformer: public MaxHeapOperators {
public:
/*! \remarks This is the method that is called to deform or alter a single point. Note
that this method needs to be thread safe. A problem may occur when a
non-local variable is modified inside of Map(). Since two versions of Map()
could be executing at the same time, they could both end up modifying the
same variable simultaneously which usually causes problems. See the
Advanced Topics section
<a href="ms-its:3dsmaxsdk.chm::/render_thread_safe_plugins.html">Thread
Safe Plug-Ins</a> for more details.
\param i The index of the point to be altered. Note: An index of -1 may be passed.
This indicates that the deformer is not being applied to a regular object
but instead points that are generated on the fly for display purposes.
\param p The point to be altered.
\return The altered point. */
virtual Point3 Map(int i, Point3 p) = 0;
void ApplyToTM(Matrix3* tm);
};
// Mapping types passed to ApplyUVWMap()
#define MAP_PLANAR 0
#define MAP_CYLINDRICAL 1
#define MAP_SPHERICAL 2
#define MAP_BALL 3
#define MAP_BOX 4
#define MAP_FACE 5
#define MAP_ACAD_PLANAR 6
#define MAP_ACAD_BOX 7
#define MAP_ACAD_CYLINDRICAL 8
#define MAP_ACAD_SPHERICAL 9
/*-------------------------------------------------------------------
Object is the class of all objects that can be pointed to by a node:
It INcludes Lights,Cameras, Geometric objects, derived objects,
and deformation Objects (e.g. FFD lattices)
It EXcludes Modifiers
---------------------------------------------------------------------*/
enum { OBJECT_LOCKED = 0x08000000 };
class ShapeObject;
class XTCObject;
/*! \sa Class XTCObject\n\n
\par Description:
This class represents a container class for XTCObjects.
\par Data Members:
<b>XTCObject *obj;</b>\n\n
A pointer to the XTCObject.\n\n
<b>int prio;</b>\n\n
The priority.\n\n
<b>int branchID;</b>\n\n
The branch identifier. */
class XTCContainer: public MaxHeapOperators {
public:
XTCObject *obj;
int prio;
int branchID;
/*! \remarks Constructor.
\par Default Implementation:
<b>{obj = NULL; prio = 0; branchID = -1;}</b> */
XTCContainer(){obj = NULL; prio = 0; branchID = -1;}
};
#define IXTCACCESS_INTERFACE_ID Interface_ID(0x60b033d7, 0x3e1d4d0d)
/*! \sa Class Object, Class XTCObject\n\n
\par Description:
This class provides an interface to access Extension Channels. */
class IXTCAccess : public BaseInterface
{
public:
/*! \remarks This method returns the IXTCAccess interface ID.
\par Default Implementation:
<b>{ return IXTCACCESS_INTERFACE_ID; }</b> */
virtual Interface_ID GetID() { return IXTCACCESS_INTERFACE_ID; }
/*! \remarks This method allows enquiries into the actual lifetime policy
of a client and provide a server-controlled delete notify callback.
\return One of the following LifetimeTypes:\n\n
<b>noRelease</b>\n\n
Do not call release, use interface as long as you like.\n\n
<b>immediateRelease</b>\n\n
The interface is only good for one calls. The release is implied so a call
to release is not required.\n\n
<b>wantsRelease</b>\n\n
The clients are controlling the lifetime, so the interface needs a
Release() when the client has finished. This is the default.\n\n
<b>serverControlled</b>\n\n
The server controls the lifetime and will use the InterfaceNotifyCallback
to inform the code when it is gone.
\par Default Implementation:
<b>{ return noRelease; }</b> */
virtual LifetimeType LifetimeControl() { return noRelease; }
/*! \remarks This method adds an extension object into the pipeline.
\param pObj The extension object you wish to add.
\param priority The priority to set.
\param branchID The branch identifier to set. */
virtual void AddXTCObject(XTCObject *pObj, int priority = 0, int branchID = -1)=0;
/*! \remarks This method returns the number of extension objects. */
virtual int NumXTCObjects()=0;
/*! \remarks This method returns the I-th extension object.
\param index The index of the extension object to return. */
virtual XTCObject *GetXTCObject(int index)=0;
/*! \remarks This method allows you to remove the I-th extension object.
\param index The index of the extension object you wish to remove. */
virtual void RemoveXTCObject(int index)=0;
/*! \remarks This method allows you to set the priority for the I-th extension object.
\param index The index of the extension object for which to set the priority.
\param priority The priority to set. */
virtual void SetXTCObjectPriority(int index,int priority)=0;
/*! \remarks This method returns the priority for the I-th extension
object.
\param index The index of the extension object. */
virtual int GetXTCObjectPriority(int index)=0;
/*! \remarks This method allows you to set the branch identifier for the
I-th extension object.
\param index The index of the extension object.
\param branchID The branch identifier to set. */
virtual void SetXTCObjectBranchID(int index,int branchID)=0;
/*! \remarks This method returns the branch identifier for the I-th extension object.
\param index The index of the extension object. */
virtual int GetXTCObjectBranchID(int index)=0;
/*! \remarks This method has to be called whenever the CompoundObject
updates a branch (calling Eval on it). Object *from is the object returned
<b>from Eval (os.obj);</b> branchID is an int, that specifies that branch.
The extension channel will get a callback to
<b>RemoveXTCObjectOnMergeBranches()</b> and <b>MergeXTCObject()</b>. By
default it returns true to <b>RemoveXTCObjectOnMergeBranches()</b>, which
means, that the existing XTCObjects with that branchID will be deleted. The
method <b>MergeXTCObject()</b> simply copies the XTCObjects from the
incoming branch into the compound object.
\param from The object from which to merge additional channels
\param branchID The branch identifier. */
virtual void MergeAdditionalChannels(Object *from, int branchID)=0;
/*! \remarks This method has to be called on the CompoundObject, so it can
delete the XTCObjects for the specific branch. The XTCObject will have
again the final decision if the XTCObject gets really deleted or not in a
callback to <b>RemoveXTCObjectOnBranchDeleted()</b>, which will return
true, if the XTCObject should be removed.
\param branchID The branch identifier.
\param reorderChannels TRUE to reorder the channels, otherwise FALSE. */
virtual void BranchDeleted(int branchID, bool reorderChannels)=0;
/*! \remarks This method copies all extension objects from the "from"
objects into the current object. In case deleteOld is false, the objects
will be appended. In case it is true, the old XTCObjects will be deleted.
\param from The object to copy from.
\param deleteOld TRUE to delete the old channel, FALSE to append the channels.
\param bShallowCopy TRUE to create a shallow copy, FALSE to create a deep copy. */
virtual void CopyAdditionalChannels(Object *from, bool deleteOld = true, bool bShallowCopy = false)=0;
/*! \remarks This method allows you to delete all additional channels. */
virtual void DeleteAllAdditionalChannels()=0;
};
class XTCAccessImp;
/*! \sa Class BaseObject, Class Deformer, Class Interval, Class GraphicsWindow, Template Class Tab, <a href="ms-its:3dsmaxsdk.chm::/pipe_geometry_root.html">Geometry Pipeline System</a>.\n\n
\par Description:
The object class is the base class for all objects. An object is one of two
things: A procedural object or a derived object. Derived objects are part of
the system and may not be created by plug-ins. They are containers for
modifiers. Procedural objects can be many different things such as cameras,
lights, helper objects, geometric objects, etc. Methods of this class are
responsible for things such as allowing the object to be deformed (changing its
points), retrieving a deformed bounding box, converting the object between
different types (to a mesh or patch for example), texture mapping the object
(if appropriate) and interacting with the system regarding mapping. There are
other methods involved in validity intervals for the object and its channels,
and a method used to return the sub-object selection state of the object.
\par Method Groups:
See <a href="class_object_groups.html">Method Groups for Class Object</a>.
*/
class Object : public BaseObject {
ChannelMask locked; // lock flags for each channel + object locked flag
// WIN64 Cleanup: Shuler
Interval noEvalInterval; // used in ReducingCaches
Interval xtcValid;
Tab<XTCContainer *> xObjs;
XTCAccessImp *pXTCAccess;
public:
CoreExport Object();
CoreExport ~Object();
/*! \remarks Indicates whether the object may be rendered. Some objects such as
construction grids and helpers should not be rendered and can return zero.
\return Nonzero if the object may be rendered; otherwise 0. */
virtual int IsRenderable()=0; // is this a renderable object?
/*! \remarks This is the default name of the node when it is created.
\param s The default name of the node is stored here. */
virtual void InitNodeName(MSTR& s)=0;
/*! \remarks This method determines if the object color is used for display.
\return TRUE if the object color is used for display; otherwise FALSE.
\par Default Implementation:
<b>{ return TRUE; }</b> */
virtual int UsesWireColor() { return TRUE; } // TRUE if the object color is used for display
/*! \remarks If an object wants to draw itself in the 3D viewports in its selected state
in some custom manner this method should return nonzero. If this item
returns nonzero, the <b>BaseObject::Display()</b> method should respect the
selected state of the object when it draws itself. If this method returns
zero the system will use its standard method of showing the object as
selected.
\par Default Implementation:
<b>{ return 0; }</b>
\return Nonzero if the object will draw itself in the selected state;
otherwise 0. If nonzero, the plug-in developer is responsible for
displaying the object in the selected state as part of its <b>Display()</b>
method. */
virtual int DoOwnSelectHilite() { return 0; }
// This used to be in GeomObject but I realized that other types of objects may
// want this (mainly to participate in normal align) such as grid helper objects.
/*! \remarks This method is called to compute the intersection point and surface normal
at this intersection point of the ray passed and the object.
\param t The time to compute the intersection.
\param r Ray to intersect. See Class Ray.
\param at The point of intersection.
\param norm Surface normal at the point of intersection.
\par Default Implementation:
<b>{return FALSE;}</b>
\return Nonzero if a point of intersection was found; otherwise 0.\n\n
\sa The Mesh class implementation of this method. */
virtual int IntersectRay(TimeValue t, Ray& r, float& at, Point3& norm) {return FALSE;}
// Objects that don't support IntersectRay() (like helpers) can implement this
// method to provide a default vector for normal align.
/*! \remarks Objects that don't support the <b>IntersectRay()</b> method (such as helper
objects) can implement this method to provide a default vector for use with
the normal align command in 3ds Max.
\param t The time to compute the normal align vector.
\param pt The point of intersection.
\param norm The normal at the point of intersection.
\return TRUE if this method is implemented to return the normal align
vector; otherwise FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL NormalAlignVector(TimeValue t,Point3 &pt, Point3 &norm) {return FALSE;}
// locking of object as whole. defaults to NOT modifiable.
/*! \remarks Implemented by the System.\n\n
This method locks the object as a whole. The object defaults to not
modifiable. */
void LockObject() { locked |= OBJECT_LOCKED; }
/*! \remarks Implemented by the System.\n\n
This method unlocks the object as a whole. */
void UnlockObject() { locked &= ~OBJECT_LOCKED; }
/*! \remarks Implemented by the System.\n\n
Returns nonzero if the object is locked; otherwise 0. */
int IsObjectLocked() { return (locked&OBJECT_LOCKED ? 1 : 0); }
// WIN64 Cleanup: Shuler
// the validity intervals are now in the object.
/*! \remarks This method is called to evaluate the object and return the result as an
ObjectState. When the system has a pointer to an object it doesn't know if
it's a procedural object or a derived object. So it calls <b>Eval()</b> on
it and gets back an ObjectState. A derived object managed by the system may
have to call <b>Eval()</b> on its input for example. A plug-in (like a
procedural object) typically just returns itself.\n\n
A plug-in that does not just return itself is the Morph Object
(<b>/MAXSDK/SAMPLES/OBJECTS/MORPHOBJ.CPP</b>). This object uses a morph
controller to compute a new object and fill in an ObjectState which it returns.
\param t Specifies the time to evaluate the object.
\return The result of evaluating the object as an ObjectState.
\par Sample Code:
Typically this method is implemented as follows:\n\n
\code
{ return ObjectState(this); }
\endcode */
virtual ObjectState Eval(TimeValue t)=0;
// Access the lock flags for th specified channels
/*! \remarks Implemented by the System.\n\n
Locks the specified channels of the object.
\param channels The channels to lock. */
void LockChannels(ChannelMask channels) { locked |= channels; }
/*! \remarks Implemented by the System.\n\n
Unlocks the specified channel(s) of the object.
\param channels Specifies the channels to unlock. */
void UnlockChannels(ChannelMask channels) { locked &= ~channels; }
/*! \remarks Implemented by the System.\n\n
Returns the locked status of the channels.
\return The channels of the object that are locked. */
ChannelMask GetChannelLocks() { return locked; }
/*! \remarks Implemented by the System.\n\n
Sets the locked status of the object's channels.
\param channels The channel to set to locked. */
void SetChannelLocks(ChannelMask channels) { locked = channels; }
/*! \remarks Implemented by the System.\n\n
Returns the locked status of the channels.
\param m Not used.
\return The channels of the object that are locked. */
ChannelMask GetChannelLocks(ChannelMask m) { return locked; }
// Can this object have channels cached?
// Particle objects flow up the pipline without making shallow copies of themselves and therefore cannot be cached
/*! \remarks This method determines if this object can have channels cached. Particle
objects flow up the pipeline without making shallow copies of themselves
and therefore cannot be cached. Objects other than particle system can just
use the default implementation.
\return TRUE if the object can be cached; otherwise FALSE.
\par Default Implementation:
<b>{return TRUE;}</b> */
virtual BOOL CanCacheObject() {return TRUE;}
// This is called by a node when the node's world space state has
// become invalid. Normally an object does not (and should not) be
// concerned with this, but in certain cases (particle systems) an
// object is effectively a world space object an needs to be notified.
/*! \remarks This is called by a node when the node's world space state has become
invalid. Normally an object does not (and should not) be concerned with
this, but in certain cases like particle systems an object is effectively a
world space object an needs to be notified.
\par Default Implementation:
<b>{}</b> */
virtual void WSStateInvalidate() {}
// Identifies the object as a world space object. World space
// objects (particles for example) can not be instanced because
// they exist in world space not object space.
/*! \remarks Returns TRUE if the object as a world space object; otherwise FALSE. World
space objects (particles for example) can not be instanced because they
exist in world space not object space. Objects other than particle system
can just use the default implementation.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL IsWorldSpaceObject() {return FALSE;}
// This is only valid for world-space objects (they must return TRUE for
// the IsWorldSpaceObject method). It locates the node which contains the
// object. Non-world-space objects will return NULL for this!
CoreExport INode *GetWorldSpaceObjectNode();
// Is the derived class derived from ParticleObject?
virtual BOOL IsParticleSystem() {return FALSE;}
// copy specified flags from obj
/*! \remarks Implemented by the System.\n\n
Copies the specified channels from the object passed.
\param obj The source object.
\param needChannels Indicates the channels to copy. */
CoreExport void CopyChannelLocks(Object *obj, ChannelMask needChannels);
// topology has been changed by a modifier -- update mesh strip/edge lists
virtual void TopologyChanged() { }
//
// does this object implement the generic Deformable Object procs?
//
/*! \remarks Indicates whether this object is deformable. A deformable object is simply
an object with points that can be modified. Deformable objects must
implement the generic deformable object methods (<b>NumPoints(),
GetPoint(i), SetPoint(i), Deform()</b>).\n\n
A deformable object is simply an object with points that can be modified.
These points can be stored in any form the object wants. They are accessed
through a virtual array interface with methods to get and set the 'i-th'
point. If an object has tangents for instance, it would convert them to and
from points as necessary. For example, a simple Bezier spline object that
stored its control handles relative to the knot would convert them to be
absolute when <b>GetPoint()</b> was called with 'i' specifying one of the
control points. When the control point is later set, the object can convert
it back to be relative to its knot. At this point it could also apply any
constraints that it may have, such as maintaining a degree of continuity.
The idea is that the entity calling <b>GetPoint(i)</b> and
<b>SetPoint(i)</b> doesn't care what the point represents. It will simply
apply some function to the point.
\return Return nonzero if the object is deformable and implements the
generic deformable object methods; otherwise 0.
\par Default Implementation:
<b>{ return 0; }</b>\n\n
Deformable object methods. These only need to be implemented if the object
returns TRUE from the <b>IsDeformable()</b> method. */
virtual int IsDeformable() { return 0; }
// DeformableObject procs: only need be implemented
// IsDeformable() returns TRUE.
/*! \remarks The points of a deformable object are accessed through a virtual array
interface. This method specifies the number of points in the object. The
meaning of 'points' is defined by the object. A TriObject uses the vertices
as the points for example.
\par Default Implementation:
<b>{ return 0;}</b>
\return The number of points in the object. */
virtual int NumPoints(){ return 0;}
/*! \remarks The points of a deformable object are accessed through a virtual array
interface. This method returns the 'i-th' point of the object.
\note If your plug-in is a modifier and you want to operate on the selected
points of the object you are modifying, you can't tell which points are
selected unless you know the type of object. If it is a generic deformable
object there is no way of knowing since the way the object handles
selection is up to it. Therefore, if you want to operate on selected points
of a generic deformable object, use a Deformer.
\param i Specifies which point should be returned.
\par Default Implementation:
<b>{ return Point3(0,0,0); }</b>
\return The 'i-th' point of the object. */
virtual Point3 GetPoint(int i) { return Point3(0,0,0); }
/*! \remarks The points of a deformable object are accessed through a virtual array
interface. This method stores the 'i-th' point of the object.
\param i The index of the point to store.
\param p The point to store. */
virtual void SetPoint(int i, const Point3& p) {}
// Completes the deformable object access with two methods to
// query point selection.
// IsPointSelected returns a TRUE/FALSE value
// PointSelection returns the weighted point selection, if supported.
// Harry D, 11/98
/*! \remarks Returns TRUE if the 'i-th' point is selected; otherwise FALSE.
\param i The zero based index of the point to check.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL IsPointSelected (int i) { return FALSE; }
/*! \remarks Returns a floating point weighted point selection if the object supports
it. The default implementation just returns 1.0f if selected and 0.0f if
not.
\param i The zero based index of the point to check.
\par Default Implementation:
<b>{ return IsPointSelected(i) ? 1.0f : 0.0f; }</b> */
virtual float PointSelection (int i) {
return IsPointSelected(i) ? 1.0f : 0.0f;
}
// These allow the NURBS Relational weights to be modified
/*! \remarks Returns TRUE if the object has weights for its points that can be set;
otherwise FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL HasWeights() { return FALSE; }
/*! \remarks Returns the weight of the specified point of the object.
\param i The point to return the weight of.
\par Default Implementation:
<b>{ return 1.0; }</b> */
virtual double GetWeight(int i) { return 1.0; }
/*! \remarks Sets the weight of the specified point.
\param i The point whose weight to set.
\param w The value to set.
\par Default Implementation:
<b>{}</b> */
virtual void SetWeight(int i, const double w) {}
// Get the count of faces and vertices for the polyginal mesh
// of an object. If it return FALSE, then this function
// isn't supported. Plug-ins should use GetPolygonCount(Object*, int&, int&)
// to count the polys in an arbitrary object
/*! \remarks Retreives the number of faces and vertices of the polyginal mesh
representation of this object. If this method returns FALSE then this
functionality is not supported.\n\n
Note: Plug-In developers should use the global function
<b>GetPolygonCount(Object*, int\&, int\&)</b> to retrieve the number f
vertices and faces in an arbitrary object.
\param t The time at which to compute the number of faces and vertices.
\param numFaces The number of faces is returned here.
\param numVerts The number of vertices is returned here.
\return TRUE if the method is fully implemented; otherwise FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL PolygonCount(TimeValue t, int& numFaces, int& numVerts) { return FALSE; }
// informs the object that its points have been deformed,
// so it can invalidate its cache.
/*! \remarks Informs the object that its points have been deformed, so it can invalidate
its cache. A developer who uses the <b>GetPoint()</b> / <b>SetPoint()</b>
approach to modifying an object will call <b>PointsWereChanged()</b> to
invalidate the object's cache. For example, if a modifier calls
<b>SetPoint()</b>, when it is finished it should call this method so the
object can invalidate and/or update its bounding box and any other data it
might cache. */
virtual void PointsWereChanged(){}
// deform the object with a deformer.
/*! \remarks This is the method used to deform the object with a deformer. The developer
should loop through the object's points calling the <b>defProc</b> for each
point (or each selected point if <b>useSel</b> is nonzero).\n\n
The <b>Deform()</b> method is mostly a convenience. Modifiers can implement
a 'Deformer' callback object which is passed to the <b>Deform()</b> method.
The object then iterates through its points calling their deformer's
callback for each point. The only difference between using the
<b>Deform()</b> method as opposed to iterating through the points is that
the <b>Deform()</b> method should respect sub-object selection. For
example, the TriObject's implementation of <b>Deform()</b> iterates through
its vertices, if the TriObject's selection level is set to vertex then it
only calls the Deformer's callback for vertices that are selected. This way
modifiers can be written that can be applied only to selection sets without
any specific code to check selected points. The default implementation of
this method just iterates through all points using <b>GetPoint(i)</b> and
<b>SetPoint(i)</b>. If an object supports sub-object selection sets then it
should override this method.
\param defProc A pointer to an instance of the Deformer class. This is the callback object
that actually performs the deformation.
\param useSel A flag to indicate if the object should use the selected points only. If
nonzero the selected points are used; otherwise all the points of the object are used.
\par Default Implementation:
\code
void Object::Deform(Deformer *defProc,int useSel)
{
int nv = NumPoints();
for (int i=0; i<nv; i++)
SetPoint(i,defProc->Map(i,GetPoint(i)));
PointsWereChanged();
}
\endcode
\par Sample Code:
This code shows the <b><b>TriObject</b></b> implementation of this method.
Note how it looks at the <b><b>useSel</b></b> parameter to only call the
selected points if required.\n\n
\code
void TriObject::Deform(Deformer *defProc,int useSel)
{
int nv = NumPoints();
int i;
if ( useSel ) {
BitArray sel = mesh.VertexTempSel();
float *vssel = mesh.getVSelectionWeights ();
if (vssel) {
for (i=0; i<nv; i++) {
if(sel[i]) {
SetPoint(i,defProc->Map(i,GetPoint(i)));
continue;
}
if (vssel[i]==0) continue;
Point3 & A = GetPoint(i);
Point3 dir = defProc->Map(i,A) - A;
SetPoint(i,A+vssel[i]*dir);
}
}
else {
for (i=0; i<nv; i++) if (sel[i])
SetPoint(i,defProc->Map(i,GetPoint(i)));
}
}
else {
for (i=0; i<nv; i++)
SetPoint(i,defProc->Map(i,GetPoint(i)));
}
PointsWereChanged();
}
\endcode */
CoreExport virtual void Deform(Deformer *defProc, int useSel=0);
// box in objects local coords or optional space defined by tm
// If useSel is true, the bounding box of selected sub-elements will be taken.
/*! \remarks This method computes the bounding box in the objects local coordinates or
the optional space defined by <b>tm</b>.\n\n
Note: If you are looking for a precise bounding box, use this method and
pass in the node's object TM (<b>INode::GetObjectTM()</b>) as the matrix.
\param t The time to compute the box.
\param box A reference to a box the result is stored in.
\param tm This is an alternate coordinate system used to compute the box. If the
<b>tm</b> is not NULL this matrix should be used in the computation of the result.
\param useSel If TRUE, the bounding box of selected sub-elements should be computed;
otherwise the entire object should be used. */
CoreExport virtual void GetDeformBBox(TimeValue t, Box3& box, Matrix3 *tm=NULL, BOOL useSel=FALSE );
//
// does this object implement the generic Mappable Object procs?
//
/*! \remarks This method lets you know if the <b>ApplyUVWMap()</b> method
is available for this object. This is used by things like the UVW mapping
modifier, so that it can determine which objects can have their mapping
modified. Returns nonzero if the object is mappable; otherwise zero.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int IsMappable() { return 0; }
/*! \remarks Returns the maximum number of channels supported by this type of object.
TriObjects for instance return <b>MAX_MESHMAPS</b> which is currently set
to 100.
\par Default Implementation:
<b>{ return IsMappable(); }</b> */
virtual int NumMapChannels () { return IsMappable(); } // returns number possible.
/*! \remarks Returns the number of maps currently used by this object. This is at least
1+(highest channel in use). This is used so a plug-in that does something
to all map channels doesn't always have to do it to every channel up to
<b>MAX_MESHMAPS</b> but rather only to this value.
\par Default Implementation:
<b>{ return NumMapChannels(); }</b> */
virtual int NumMapsUsed () { return NumMapChannels(); } // at least 1+(highest channel in use).
// This does the texture map application -- Only need to implement if
// IsMappable returns TRUE
/*! \remarks This method may be called to map the object with UVW mapping
coordinates. If the object returns nonzero from <b>IsMappable()</b> then
this method should be implemented.
\param type The mapping type. One of the following values:\n\n
<b>MAP_PLANAR</b>\n
<b>MAP_CYLINDRICAL</b>\n
<b>MAP_SPHERICAL</b>\n
<b>MAP_BALL</b>\n
<b>MAP_BOX</b>\n
\param utile Number of tiles in the U direction.
\param vtile Number of tiles in the V direction.
\param wtile Number of tiles in the W direction.
\param uflip If nonzero the U values are mirrored.
\param vflip If nonzero the V values are mirrored.
\param wflip If nonzero the W values are mirrored.
\param cap This is used with <b>MAP_CYLINDRICAL</b>. If nonzero, then any face normal
that is pointing more vertically than horizontally will be mapped using planar coordinates.
\param tm This defines the mapping space. As each point is mapped, it is multiplied
by this matrix, and then it is mapped.
\param channel This indicates which channel the mapping is applied to. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_mapping_channel_index_values.html">List of Mapping
Channel Index Values</a>. */
virtual void ApplyUVWMap(int type,
float utile, float vtile, float wtile,
int uflip, int vflip, int wflip, int cap,
const Matrix3 &tm,int channel=1) {}
// Objects need to be able convert themselves
// to TriObjects. Most modifiers will ask for
// Deformable Objects, and triobjects will suffice.
/*! \remarks Indicates whether the object can be converted to the specified type. If the
object returns nonzero to indicate it can be converted to the specified
type, it must handle converting to and returning an object of that type
from <b>ConvertToType()</b>.
\sa Class ObjectConverter for additional details on converting objects between types.
\param obtype The Class_ID of the type of object to convert to. See
Class Class_ID, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_class_ids.html">List of Class_IDs</a>.
\return Nonzero if the object can be converted to the specified type;
otherwise 0.
\par Default Implementation:
<b>{ return 0; }</b> */
CoreExport virtual int CanConvertToType(Class_ID obtype);
// Developers have to make sure, that the channels, that the BaseObject implements
// (e.g. ExtensionChannels) are copied over to the new object as well. They can do this by simply
// calling CopyXTCObjects(this,false); The validity will be automatically copied with it..
/*! \remarks This method converts this object to the type specified and returns a
pointer it. Note that if ConvertToType() returns a new object it should be
a completely different object with no ties (pointers or references) to the
original.
\sa <a href="class_object_converter.html">Class ObjectConverter</a>
for additional details on converting objects between types.
\par The following is an issue that developers of world space modifiers need to
be aware of if the world space modifier specifies anything but generic
deformable objects as its input type. In other words, if a world space
modifier, in its implementation of <b>Modifier::InputType()</b>, doesn't
specifically return <b>defObjectClassID</b> then the following issue
regarding the 3ds Max pipeline needs to be considered. Developers of other
plug-ins that don't meet this condition don't need to be concerned with
this issue.
\par World space modifiers that work on anything other than generic deformable
objects are responsible for transforming the points of the object they
modify into world space using the ObjectState TM. To understand why this is
necessary, consider how 3ds Max applies the node transformation to the
object flowing down the pipeline.
\par In the geometry pipeline architecture, the node in the scene has its
transformation applied to the object in the pipeline at the transition
between the last object space modifier and the first world space modifier.
The node transformation is what places the object in the scene -- thus this
is what puts the object in world space. The system does this by
transforming the points of the object in the pipeline by the node
transformation. This is only possible however for deformable objects.
Deformable objects are those that support the
<b>Object::IsDeformable()</b>, <b>NumPoints()</b>, <b>GetPoint()</b> and
<b>SetPoint()</b> methods. These deformable objects can be deformed by the
system using these methods, and thus the system can modify the points to
put them in world space itself.
\par If a world space modifier does not specify that it works on deformable
objects, the system is unable to transform the points of the object into
world space. What it does instead is apply the transformation to the
ObjectState TM. In this case, a world space modifier is responsible for
transforming the points of the object into world space itself, and then
setting the ObjectState TM to the identity. There is an example of this in
the sample code for the Bomb space warp. The Bomb operates on
<b>TriObjects</b> and implements <b>InputType()</b> as <b>{ return
Class_ID(TRIOBJ_CLASS_ID,0); }</b>. Since it doesn't specifically return
<b>defObjectClassID</b>, it is thus responsible for transforming the points
of the object into world space itself. It does this in its implementation
of <b>ModifyObject()</b> as follows:\n\n
\code
if (os->GetTM())
{
Matrix3 tm = *(os->GetTM());
for (int i=0; i<triOb->mesh.getNumVerts(); i++) {
triOb->mesh.verts[i] = triOb->mesh.verts[i] *tm;
}
os->obj->UpdateValidity(GEOM_CHAN_NUM,os->tmValid());
os->SetTM(NULL,FOREVER);
}
\endcode
As the code above shows, the Bomb checks if the ObjectState TM is non-NULL.
If it is, the points of the object are still not in world space and thus
must be transformed. It does this by looping through the points of the
<b>TriObject</b> and multiplying each point by the ObjectState TM. When it
is done, it sets the ObjectState TM to NULL to indicate the points are now
in world space. This ensure that any later WSMs will not transform the
points with this matrix again.
\par For the Bomb world space modifier this is not a problem since it specifies
in its implementation of <b>ChannelsChanged()</b> that it will operate on
the geometry channel (<b>PART_GEOM</b>). Certain world space modifiers may
not normally specify <b>PART_GEOM</b> in their implementation of
<b>ChannelsChanged()</b>. Consider the camera mapping world space modifier.
Its function is to apply mapping coordinates to the object it is applied
to. Thus it would normally only specify <b>PART_TEXMAP</b> for
<b>ChannelsChanged()</b>. However, since it operates directly on
<b>TriObjects</b>, just like the Bomb, the system cannot transform the
points into world space, and therefore the camera mapping modifier must do
so in its implementation of <b>ModifyObject()</b>. But since it is actually
altering the points of the object by putting them into world space it
<b>is</b> altering the geometry channel. Therefore, it should really
specify <b>PART_GEOM | PART_TEXMAP</b> in its implementation of
<b>ChannelsChanged()</b>. If it didn't do this, but went ahead and modified
the points of the object anyway, it would be transforming not copies of the
points, but the original points stored back in an earlier cache or even the
base object.
\par This is the issue developers need to be aware of. To state this in simple
terms then: Any world space modifier that needs to put the points of the
object into world space (since it doesn't implement <b>InputType()</b> as
<b>defObjectClassID</b>) needs to specify <b>PART_GEOM</b> in its
implementation of <b>ChannelsChanged()</b>.
\param t The time at which to convert.
\param obtype The Class_ID of the type of object to convert to. See
Class Class_ID, <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_class_ids.html">List of Class_IDs</a>.
\return A pointer to an object of type <b>obtype</b>.
\par Default Implementation:
<b>{ return NULL; }</b>
\par Sample Code:
The following code shows how a <b>TriObject</b> can be retrieved from a
node. Note on the code that if you call <b>ConvertToType()</b> on an object
and it returns a pointer other than itself, you are responsible for
deleting that object.
\code
// Retrieve the TriObject from the node
int deleteIt;
TriObject *triObject = GetTriObjectFromNode(ip->GetSelNode(0),deleteIt);
// Use the TriObject if available
if (!triObject) return;
// ...
// Delete it when done...
if (deleteIt) triObject->DeleteMe();
// Return a pointer to a TriObject given an INode or return NULL
// if the node cannot be converted to a TriObject
TriObject *Utility::GetTriObjectFromNode(INode *node, int &deleteIt)
{
deleteIt = FALSE;
Object *obj = node->EvalWorldState(0).obj;
if (obj->CanConvertToType(Class_ID(TRIOBJ_CLASS_ID, 0))) {
TriObject *tri = (TriObject *) obj->ConvertToType(0,Class_ID(TRIOBJ_CLASS_ID, 0));
// Note that the TriObject should only be deleted
// if the pointer to it is not equal to the object
// pointer that called ConvertToType()
if (obj != tri)
deleteIt = TRUE;
return tri;
}
else {
return NULL;
}
}
\endcode */
CoreExport virtual Object* ConvertToType(TimeValue t, Class_ID obtype);
// Indicate the types this object can collapse to
/*! \remarks This method allows objects to specify the class that is the best class to
convert to when the user collapses the stack. The main base classes have
default implementations. For example, GeomObject specifies TriObjects as
its preferred collapse type and shapes specify splines as their preferred
collapse type
\par Default Implementation:
<b>{return Class_ID(0,0);}</b>
\return The Class_ID of the preferred object type. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_class_ids.html">List of Class_IDs</a>. */
virtual Class_ID PreferredCollapseType() {return Class_ID(0,0);}
/*! \remarks When the user clicks on the Edit Stack button in the modify branch a list of
'Convert To:' types is presented. The use may click on one of these choices to
collapse the object into one of these types (for instance, an Editable Mesh or
an Editable NURBS object). This method returns a list of Class_IDs and
descriptive strings that specify the allowable types of objects that this
object may be collapsed into.\n\n
Note: Most plug-ins call the base class method in <b>Object</b> in their
implementation of this method. The base class implementation provided by
<b>Object</b> checks if the object can convert to both an editable mesh and an
editable spline. If it can, these are added to the allowable types.
\param clist The table of allowable Class_IDs.
\param nlist The table of pointers to strings that correspond to the table of Class_IDs
above.
\par Sample Code:
\code
void SphereObject::GetCollapseTypes(Tab<Class_ID> &clist,Tab<TSTR*>&nlist)
{
Object::GetCollapseTypes(clist, nlist);
Class_ID id = EDITABLE_SURF_CLASS_ID;
MSTR *name = new MSTR(GetString(IDS_SM_NURBS_SURFACE));
clist.Append(1,&id);
nlist.Append(1,&name);
}
\endcode */
CoreExport virtual void GetCollapseTypes(Tab<Class_ID> &clist,Tab<MSTR*> &nlist);
/*! \remarks This method is called on the world space cache object when the stack gets
collapsed, that lets the pipeline object decide, if it wants to return a
different object than itself. The default implementation simply returns
this. A PolyObject e.g. can create and return an EditablePolyObject in this
method, so that the collapsed object has a UI. I only implemented this
method for PolyObject, but this can potentially implemented that way for
all pipeline objects, that currently pass up the editable version.\n\n
It is important, that all places, that collapse the stack are calling this
method after evaluating the stack.
\par It also is important, that the editable version implements this method to
simply return this, otherwise you'll get a non-editable object when you
collapse an editable polyobject.
\return A pointer to the resulting object.
\par Default Implementation:
<b>{ return this;}</b> */
virtual Object *CollapseObject() { return this;}
// return the current sub-selection state
/*! \remarks For objects that have sub selection levels, this method returns the current
selection level of the object. For example, a TriObject has the following
selection levels: object, vertex, face, edge. Other object types may have
different selection levels. The only standard is that a value of 0
indicates object level.
\par Default Implementation:
<b>{return 0;}</b>
\return The current selection level of the object. */
virtual DWORD GetSubselState() {return 0;}
virtual void SetSubSelState(DWORD s) {}
// If the requested channels are locked, replace their data
// with a copy/ and unlock them, otherwise leave them alone
/*! \remarks Implemented by the System.
\par If the requested channels are locked, this method will replace their data
with a copy and unlock them, otherwise it leaves them alone.
\param channels The channels to ready for modification. */
CoreExport void ReadyChannelsForMod(ChannelMask channels);
// Virtual methods to be implemented by plug-in object:-----
// NS: 12-14-99 Classes that derive from Object *have* to implement certain
// things to support the new Extension Channel (XTCObject)
// See examples in Triobj.cpp [START]
// access the current validity interval for the nth channel
// For this method, the derived class has to check if the channel is the
// Extension channel and return the base classes ChannelValidity :
// case EXTENSION_CHAN_NUM: return Object::ChannelValidity(t,nchan); break;
/*! \remarks Retrieve the current validity interval for the <b>nchan</b> channel of the
object.
\note Most procedural objects won't implement this method since they
don't have individual channels. Developers wanting to get the validity
interval for a procedural object should use <b>Object::ObjectValidity()</b>
instead.
\param t The time to retrieve the validity interval of the channel.
\param nchan Specifies the channel to return the validity interval of. See
<a href="#Object_Channel_Indices">Object Channel Indices</a>.
\return The validity interval of the specified channel.
\par Default Implementation:
<b>return FOREVER;</b> */
CoreExport virtual Interval ChannelValidity(TimeValue t, int nchan);
// The derived class has to simply call the implementation of the baseclass.
/*! \remarks Sets the validity interval of the specified channel.
\param nchan Specifies the channel. See <a href="#Object_Channel_Indices">Object Channel Indices</a>
\param v The validity interval for the channel. */
CoreExport virtual void SetChannelValidity(int nchan, Interval v);
// invalidate the specified channels
// The derived class has to simply call the implementation of the baseclass.
/*! \remarks This method invalidates the intervals for the given channel mask. This just
sets the validity intervals to empty (calling <b>SetEmpty()</b> on the interval).
\param channels Specifies the channels to invalidate. */
CoreExport virtual void InvalidateChannels(ChannelMask channels);
// validity interval of Object as a whole at current time
// The derived class has incorporate the BaseClasses validity into the returned validity
/*! \remarks This method returns the validity interval of the object as a whole at the
specified time.
\param t The time to compute the validity interval.
\par Default Implementation:
<b>{ return FOREVER; }</b>
\return The validity interval of the object. */
CoreExport virtual Interval ObjectValidity(TimeValue t);
// Makes a copy of its "shell" and shallow copies only the
// specified channels. Also copies the validity intervals of
// the copied channels, and sets Invalidates the other intervals.
// The derived class has to call ShallowCopy on the BaseClass, so it can copy all its channels
/*! \remarks This method must make a copy of its "shell" and then shallow copy (see
below) only the specified channels. It must also copy the validity
intervals of the copied channels, and invalidate the other intervals.
\param channels The channels to copy.
\return A pointer to the shallow copy of the object.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual Object *MakeShallowCopy(ChannelMask channels) { return NULL; }
// Shallow-copies the specified channels from the fromOb to this.
// Also copies the validity intervals.
// The derived class has to simply call the implementation of the baseclass.
/*! \remarks This method copies the specified channels from the <b>fromOb</b> to
<b>this</b> and copies the validity intervals.\n\n
A plug-in needs to copy the specified channels from the specified object
<b>fromOb</b> to itself by just copying pointers (not actually copying the
data). No new memory is typically allocated, this method is just copying
the pointers.
\param fromOb Object to copy the channels from.
\param channels Channels to copy. */
CoreExport virtual void ShallowCopy(Object* fromOb, ChannelMask channels);
// Free the specified channels
// The derived class has to simply call the implementation of the baseclass.
/*! \remarks This method deletes the memory associated with the specified channels and
set the intervals associated with the channels to invalid (empty).
\param channels Specifies the channels to free. */
CoreExport virtual void FreeChannels(ChannelMask channels);
// This replaces locked channels with newly allocated copies.
// It will only be called if the channel is locked.
// The derived class has to simply call the implementation of the baseclass.
/*! \remarks This method replaces the locked channels with newly allocated copies. It
will only be called if the channel is locked.
\param channels The channels to be allocate and copy. */
CoreExport virtual void NewAndCopyChannels(ChannelMask channels);
// Allow the object to enlarge its viewport rectangle, if it wants to.
// The derived class has to simply call the implementation of the baseclass.
/*! \remarks This method allows the object to enlarge its viewport rectangle, if it
wants to. The system will call this method for all objects when calculating
the viewport rectangle; the object can enlarge the rectangle if desired.
This is used by the Editable Spline code to allow extra room for vertex
serial numbers, which can extend outside the normal bounding rectangle.
\param gw Points to the GraphicsWindow associated with the viewport.
\param rect The enlarged rectangle is returned here.
\par Default Implementation:
<b>{}</b>
\par Sample Code:
\code
void SplineShape::MaybeEnlargeViewportRect(GraphicsWindow *gw, Rect &rect)
{
if(!showVertNumbers)
return;
TCHAR dummy[256];
SIZE size;
int maxverts = -1;
for(int i = 0; i < shape.splineCount; ++i) {
int verts = shape.splines[i]->KnotCount();
if(verts > maxverts)
maxverts = verts;
}
sprintf(dummy,"%d",maxverts);
gw->getTextExtents(dummy, &size);
rect.SetW(rect.w() + size.cx);
rect.SetY(rect.y() - size.cy);
rect.SetH(rect.h() + size.cy);
}
\endcode */
CoreExport virtual void MaybeEnlargeViewportRect(GraphicsWindow *gw, Rect &rect);
// quick render in viewport, using current TM.
//CoreExport virtual Display(TimeValue t, INode* inode, ViewExp *vpt, int flags) { return 0; };
// NS: 12-14-99 Classes that derive from Object *have* o call the following methods
// See examples in Triobj.cpp [END]
CoreExport bool IsBaseClassOwnedChannel(int nchan) { return (nchan == EXTENSION_CHAN_NUM) ? true : false;}
/*! \remarks When a modifier is applied to an object, it needs to include its own
validity interval in the interval of the object. To do this, a modifier
calls the <b>UpdateValidity()</b> method of an object. This method
intersects interval <b>v</b> to the <b>nchan</b> channel validity of the
object.
\param nchan The validity interval of the modifier is intersected with this channel of
the object. See <a href="#Object_Channel_Indices">Object Channel Indices</a>.
\param v The interval to intersect. */
CoreExport void UpdateValidity(int nchan, Interval v); // AND in interval v to channel validity
/*! \remarks This method is used internally. */
Interval GetNoEvalInterval() { return noEvalInterval; }
/*! \remarks This method is used internally. */
void SetNoEvalInterval(Interval iv) {noEvalInterval = iv; }
// Give the object chance to reduce its caches,
// depending on the noEvalInterval.
/*! \remarks This method give the object the chance to reduce its caches.
\param t The time to discard any caches the object has. */
CoreExport virtual void ReduceCaches(TimeValue t);
// Is this object a construction object:
/*! \remarks This is called to determine if this is a construction object or not.
\return Nonzero if the object is a construction object; otherwise 0.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int IsConstObject() { return 0; }
// Retreives sub-object branches from an object that supports branching.
// Certain objects combine a series of input objects (pipelines) into
// a single object. These objects act as a multiplexor allowing the
// user to decide which branch(s) they want to see the history for.
//
// It is up to the object how they want to let the user choose. The object
// may use sub object selection to allow the user to pick a set of
// objects for which the common history will be displayed.
//
// When the history changes for any reason, the object should send
// a notification (REFMSG_BRANCHED_HISTORY_CHANGED) via NotifyDependents.
// The selected parameter is new in Rel. 4 and must be supported by all
// compound objects.
// In case the selected parameter is true the obejct should only return
// the number of pipebranches, that are currently selected in the UI (this
// is the way it worked in R3 and before.
// In case this parameter is false, the object has to return the number of
// *all* branches, no matter if they are selected or not
/*! \remarks This method returns the number of pipeline branches combined by the object.
This is not the total number of branches, but rather the number that are
active. For example in the boolean object, if the user does not have any
operands selected, this methods would return zero. If they have one
selected it would return one.
\param selected This parameter must be supported by all compound objects. In case the
selected parameter is true the object should only return the number of
pipebranches, that are currently selected in the UI (this is the way it
worked in R3 and before. In case this parameter is false, the object has to
return the number of all branches, no matter if they are selected or not
\par Default Implementation:
<b>{return 0;}</b> */
virtual int NumPipeBranches(bool selected = true) {return 0;}
// The selected parameter is new in Rel. 4 and must be supported by all
// compound objects.
// In case the selected parameter is true the obejct should only consider
// the branches, that are currently selected in the UI (this
// is the way it worked in R3 and before.
// In case this parameter is false, the object has to consider
// *all* branches, no matter if they are selected or not
/*! \remarks Retrieves sub-object branches from an object that supports branching.
Certain objects combine a series of input objects (pipelines) into a single
object. These objects act as a multiplexer allowing the user to decide
which branch(s) they want to see the history for.\n\n
It is up to the object how they want to let the user choose. For example
the object may use sub-object selection to allow the user to pick a set of
objects for which the common history will be displayed.\n\n
When the history changes for any reason, the object should send a
notification (\ref REFMSG_BRANCHED_HISTORY_CHANGED) using \ref NotifyDependents().
\param i The branch index.
\param selected This parameter must be supported by all compound objects. In case the
selected parameter is true the object should only return the number of
pipebranches, that are currently selected in the UI (this is the way it
worked in R3 and before. In case this parameter is false, the object has to
return the number of all branches, no matter if they are selected or not
\return The 'i-th' sub-object branch.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual Object *GetPipeBranch(int i, bool selected = true) {return NULL;}
// When an object has sub-object branches, it is likely that the
// sub-objects are transformed relative to the object. This method
// gives the object a chance to modify the node's transformation so
// that operations (like edit modifiers) will work correctly when
// editing the history of the sub object branch.
// The selected parameter is new in Rel. 4 and must be supported by all
// compound objects.
// In case the selected parameter is true the obejct should only consider
// the branches, that are currently selected in the UI (this
// is the way it worked in R3 and before.
// In case this parameter is false, the object has to consider
// *all* branches, no matter if they are selected or not
/*! \remarks When an object has sub-object branches, it is likely that the sub-objects
are transformed relative to the object. This method gives the object a
chance to modify the node's transformation so that operations (like edit
modifiers) will work correctly when editing the history of the sub object
branch. An object can implement this method by returning a pointer to a new
<b>INodeTransformed</b> that is based on the node passed into this method.
See Class INodeTransformed.
\param t The time to get the INode.
\param node The original INode pointer.
\param i The branch index.
\param selected This parameter must be supported by all compound objects. In case the
selected parameter is true the object should only return the number of
pipebranches, that are currently selected in the UI (this is the way it
worked in R3 and before. In case this parameter is false, the object has to
return the number of all branches, no matter if they are selected or not
\return A pointer to an INode. This can be the original passed in (the
default implementation does this) or a new <b>INodeTransformed</b>.
\par Default Implementation:
<b>{return node;}</b> */
virtual INode *GetBranchINode(TimeValue t,INode *node,int i, bool selected = true) {return node;}
// Shape viewports can reference shapes contained within objects, so we
// need to be able to access shapes within an object. The following methods
// provide this access
/*! \remarks Returns the number of shapes contained inside this object. A shape
container may return zero if it doesn't currently have any shapes.
\return The number of shapes. A return value of -1 indicates this is not a
container.
\par Default Implementation:
<b>{ return -1; }</b> */
virtual int NumberOfContainedShapes() { return -1; } // NOT a container!
/*! \remarks This method returns the <b>ShapeObject</b> specified by the index passed at
the time specified. See Class ShapeObject.
\param t The time to return the shape.
\param index The index of the shape.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual ShapeObject *GetContainedShape(TimeValue t, int index) { return NULL; }
/*! \remarks Returns the matrix associated with the shape whose index is passed. This
matrix contains the offset within the object used to align the shape
viewport to the shape.
\param t The time to return the matrix.
\param index The index of the shape whose matrix to return.
\param mat The matrix is returned here.
\par Default Implementation:
<b>{}</b> */
virtual void GetContainedShapeMatrix(TimeValue t, int index, Matrix3 &mat) {}
/*! \remarks This is used by the lofter. The lofter can have several shapes selected,
and the bit array returned here will have a bit set for each selected
shape. See Class BitArray.
\return
\par Default Implementation:
<b>{ return BitArray(); }</b> */
virtual BitArray ContainedShapeSelectionArray() { return BitArray(); }
// Return TRUE for ShapeObject class or GeomObjects that are Shapes too
virtual BOOL IsShapeObject() { return FALSE; }
// For debugging only. TriObject inplements this method by making sure
// its face's vert indices are all valid.
/*! \remarks This method is used for debugging only. The TriObject implements this
method by making sure its face's vert indices are all valid.
\return TRUE if valid; otherwise FALSE.
\par Default Implementation:
<b>{return TRUE;}</b> */
virtual BOOL CheckObjectIntegrity() {return TRUE;}
// Find out if the Object is generating UVW's
virtual BOOL HasUVW() { return 0; }
// or on any map channel:
virtual BOOL HasUVW (int mapChannel) { return (mapChannel==1) ? HasUVW() : FALSE; }
// This is overridden by DerivedObjects to search up the pipe for the base object
/*! \remarks It is called to return a pointer to the base object (an object that is not
a derived object). This method is overridden by DerivedObjects to search
down the pipeline for the base object. The default implementation just
returns <b>this</b>. This function is still implemented by derived objects
and WSM's to search down the pipeline. This allows you to just call it on a
nodes ObjectRef without checking for type.
\par Default Implementation:
<b>{ return this; }</b> */
virtual Object *FindBaseObject() { return this; }
// Access a parametric position on the surface of the object
/*! \remarks There are several methods used to access a parametric position on the
surface of the object. If this method returns TRUE then
<b>Object::GetSurfacePoint()</b> will be called to return a point on the
surface that corresponds to the <b>u</b> and <b>v</b> parameters passed to
it. If this method returns FALSE then it is assumed the object does not
support returning a point on the surface based on parameteric values. For
sample code see <b>/MAXSDK/SAMPLES/OBJECTS/SPHERE.CPP</b>. If the object
has several parametric surfaces then a second version of
<b>GetSurfacePoint()</b> with an integer which specifies which surface will
be called.
\par Default Implementation:
\code
{ return FALSE; }
\endcode */
virtual BOOL IsParamSurface() {return FALSE;}
/*! \remarks Returns the number of parametric surfaces within the object.
\param t The time at which to check.
\par Default Implementation:
<b>{return 1;}</b> */
virtual int NumSurfaces(TimeValue t) {return 1;}
// Single-surface version (surface 0)
/*! \remarks This method needs to be implemented if <b>Object::IsParamSurface()</b>
returns TRUE. This method is used to retrieve a point on the surface of the
object based on two parameters of the surface, <b>u</b> and <b>v</b>.\n\n
Note: This method assumes there is a single parametric surface. If there is
more than 1 (<b>NumSurfaces()</b> returns \> 1, use the <b>GetSurface()</b>
method below which allows for multiple surfaces.
\param t The time to retrieve the point.
\param u The parameter along the horizontal axis of the surface.
\param v The parameter along the vertical axis of the surface.
\param iv This interval is updated based on the interval of the surface parameter.
\par Default Implementation:
<b>{return Point3(0,0,0);}</b> */
virtual Point3 GetSurfacePoint(TimeValue t, float u, float v,Interval &iv) {return Point3(0,0,0);}
// Multiple-surface version (Implement if you override NumSurfaces)
/*! \remarks This method is used to retrieve a point on the specified surface of the
object based on two parameters of the surface, <b>u</b> and <b>v</b>.
\param t The time to retrieve the point.
\param surface The zero based index of the surface. This number is <b>\>=0</b> and
<b>\<NumSurfaces()</b>.
\param u The parameter along the horizontal axis of the surface.
\param v The parameter along the vertical axis of the surface.
\param iv This interval is updated based on the interval of the surface parameter.
\par Default Implementation:
<b>{return Point3(0,0,0);}</b> */
virtual Point3 GetSurfacePoint(TimeValue t, int surface, float u, float v,Interval &iv) {return Point3(0,0,0);}
// Get information on whether a surface is closed (default is closed both ways)
/*! \remarks This method allows the object to return flags that indicate whether the
parametric surface is closed in the U and V dimensions. Set the appropriate
closure variables to TRUE if the surface is closed in that direction, FALSE
if it is not. A torus, for example, is closed in both directions.
\param t The time to check the surface.
\param surface The zero based index of the surface. This number is <b>\>=0</b> and
<b>\<NumSurfaces()</b>.
\param uClosed Set to TRUE if the surface is closed in U; otherwise to FALSE.
\param vClosed Set to TRUE if the surface is closed in V; otherwise to FALSE.
\par Default Implementation:
<b>{uClosed = vClosed = TRUE;}</b> */
virtual void SurfaceClosed(TimeValue t, int surface, BOOL &uClosed, BOOL &vClosed) {uClosed = vClosed = TRUE;}
// Allow an object to return extended Properties fields
// Return TRUE if you take advantage of these, and fill in all strings
/*! \remarks This method allows an object to return extended Properties fields. It is
called when the Object Properties dialog is being prepared. If you don't
want to display any extended properties, simply return FALSE.\n\n
To display extended property fields, place the field label in the
appropriate label string and the display value in a formatted string. Two
fields are supplied, each with a label and a data string; if only using
one, make the second label field and data field blank (""). Return TRUE to
indicate you have filled in the fields. The properties dialog will display
your returned values.
\param t The time at which the strings are requested.
\param prop1Label The string for the property 1 label.
\param prop1Data The formatted data string to appear as property 1.
\param prop2Label The string for the property 2 label.
\param prop2Data The formatted data string to appear as property 2.
\return TRUE if this method is implemented and the fields are filled in;
otherwise FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL GetExtendedProperties(TimeValue t, MSTR &prop1Label, MSTR &prop1Data, MSTR &prop2Label, MSTR &prop2Data) {return FALSE;}
// Animatable Overides...
CoreExport SvGraphNodeReference SvTraverseAnimGraph(IGraphObjectManager *gom, Animatable *owner, int id, DWORD flags);
CoreExport bool SvHandleDoubleClick(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport MSTR SvGetName(IGraphObjectManager *gom, IGraphNode *gNode, bool isBeingEdited);
CoreExport COLORREF SvHighlightColor(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvIsSelected(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport MultiSelectCallback* SvGetMultiSelectCallback(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvCanSelect(IGraphObjectManager *gom, IGraphNode *gNode);
//ExtensionChannel Access :
// Adds an extension object into the pipeline. The methods (Display,
// PreChanChangedNotify etc) of higher priority XTCObjects will becalled
// before those of lower priority XTCObjects
/*! \remarks This method adds an extension object into the pipeline.\n\n
Implemented by the System.
\param pObj Points to the extension object to add.
\param priority The priority of the object. The methods (XTCObject::Display(),
PreChanChangedNotify() etc) of higher priority XTCObjects will be called before
those of lower priority XTCObjects.
\param branchID The branch identifier of the object. */
CoreExport void AddXTCObject(XTCObject *pObj, int priority = 0, int branchID = -1);
/*! \remarks Returns the number of extension objects maintained by this Object.\n\n
Implemented by the System. */
CoreExport int NumXTCObjects();
/*! \remarks Returns a pointer to the specified extension object.\n\n
Implemented by the System.
\param index The zero based index of the extension object to return. */
CoreExport XTCObject *GetXTCObject(int index);
/*! \remarks Removes the extension object as indicated by the index.\n\n
Implemented by the System.
\param index The zero based index of the extension object to remove. */
CoreExport void RemoveXTCObject(int index);
/*! \remarks Sets the priority for the extension object whose index is passed.\n\n
Implemented by the System.
\param index The zero based index of the extension object to remove.
\param priority The new priority to assign. */
CoreExport void SetXTCObjectPriority(int index,int priority);
/*! \remarks Returns the integer priority number of the extension object whose index is
passed.\n\n
Implemented by the System.
\param index The zero based index of the extension object to check. */
CoreExport int GetXTCObjectPriority(int index);
/*! \remarks Sets the branch ID of the extension object whose index is passed.\n\n
Implemented by the System.
\param index The zero based index of the extension object whose branch ID is set.
\param branchID The branch identifier to set. */
CoreExport void SetXTCObjectBranchID(int index,int branchID);
/*! \remarks Returns the integer branch ID of the extension object whose index is
passed.\n\n
Implemented by the System.
\param index The zero based index of the extension object whose branch ID is to be returned. */
CoreExport int GetXTCObjectBranchID(int index);
// This method has to be called whenever the CompoundObject updates a branch
// (calling Eval on it). Object *from is the object returned from Eval
// (os.obj);branchID is an int, that specifies that branch. The extension
// channel will get a callback to RemoveXTCObjectOnMergeBranches and MergeXTCObject.
// By default it returns true to RemoveXTCObjectOnMergeBranches, which means,
// that the existing XTCObjects with that branchID will be deleted. The method
// MergeXTCObject simply copies the XTCObjects from the incoming branch into the
// compound object.
/*! \remarks This method has to be called whenever the CompoundObject updates a branch
(calling <b>Eval()</b> on it). Object <b>*from</b> is the object returned
from <b>Eval(os.obj)</b>. The branchID is an integer that specifies that
branch. The extension channel will get a callback to
<b>XTCObject::RemoveXTCObjectOnMergeBranches()</b> and
<b>XTCObject::MergeXTCObject()</b>. By default it returns true to
RemoveXTCObjectOnMergeBranches which means that the existing XTCObjects
with that branchID will be deleted. The method MergeXTCObject simply copies
the XTCObjects from the incoming branch into the compound object.\n\n
Implemented by the System.
\param from The object to merge additional channels from.
\param branchID The branch identifier to set. */
CoreExport void MergeAdditionalChannels(Object *from, int branchID);
// This method has to be called on the CompoundObject, so it can delete the
// XTCObjects for the specific branch. The XTCObject will have again the final
// decision if the XTCObject gets really deleted or not in a callback to
// RemoveXTCObjectOnBranchDeleted(), which will return true, if the XTCOject
// should be removed.
/*! \remarks This method has to be called on the CompoundObject so it can delete the
XTCObjects for the specified branch. The XTCObject will again have the
final decision if the XTCObject gets really deleted or not in a callback to
<b>XTCObject::RemoveXTCObjectOnBranchDeleted()</b> which will return true
if the XTCOject should be removed.\n\n
Implemented by the System.
\param branchID Specifies which brach of the compound object the extension objects are
deleted from.
\param reorderChannels TRUE to reorder the channels, otherwise FALSE. */
CoreExport void BranchDeleted(int branchID, bool reorderChannels);
// This method copies all extension objects from the "from" objects into the
// current object. In case deleteOld is false, the objects will be appended.
// In case it is true, the old XTCObjects will be deleted.
/*! \remarks This method copies all extension objects from the "from" object into the
current object. In case deleteOld is false the objects will be appended. If
it is true the old XTCObjects will be deleted.\n\n
Implemented by the System.
\param from The source object which contains extension objects.
\param deleteOld If true the original objects are deleted after the copy; if false they
remain after the copy.
\param bShallowCopy If true only a ShallowCopy() is performed; if false a complete copy of the
objects is done. */
CoreExport void CopyAdditionalChannels(Object *from, bool deleteOld = true, bool bShallowCopy = false);
/*! \remarks Implemented by the System.\n\n
This method will delete all additional channels. */
CoreExport void DeleteAllAdditionalChannels();
/*! \remarks This method allows an object to choose whether or not it will display selection
brackets in shaded viewports. The method will return FALSE if no selection
brackets are displayed or TRUE if it does display selection brackets.
\par Default Implementation:
<b>{ return TRUE; }</b> */
virtual BOOL UseSelectionBrackets() { return TRUE; }
// returns TRUE for manipulator objcts and FALSE for all others
virtual BOOL IsManipulator() { return FALSE; }
CoreExport void* GetInterface(ULONG id);
CoreExport BaseInterface* GetInterface(Interface_ID id);
//! \brief Should reduce any derived display data to save memory, since the node wont be drawn until the user undhides it
/*! This function should delete any derived data used to display the object such as gfx normals, direct mesh caches etc.
Tnis is called when the user hides the node or sets it as bounding box
*/
virtual void ReduceDisplayCaches() { }
};
// This function should be used to count polygons in an object.
// It uses Object::PolygonCount() if it is supported, and converts to
// a TriObject and counts faces and vertices otherwise.
/*! \remarks This global function (not part of class Object) may be used to count the number
of faces and vertices in an object. It uses <b>Object::PolygonCount()</b> if it
is supported, and converts to <b>TriObject</b> and counts faces and vertices
otherwise.
\param t time at which to compute the number of faces and vertices.
\param pObj to the object to check.
\param numFaces number of faces is returned here.
\param numVerts number of vertices is returned here. */
CoreExport void GetPolygonCount(TimeValue t, Object* pObj, int& numFaces, int& numVerts);
// This function to count trifaces of a mesh
// It works just like GetPolygonCount, where GetPolygonCount will count EditablePoly object's Polys as 1 Poly,
// instead of several trifaces. It also will not count splines unless their renderable property is true
CoreExport void GetTriMeshFaceCount(TimeValue t, Object* pObj, int& numFaces, int& numVerts);
// mjm - begin - 07.17.00
class CameraObject;
// -------------------------------
// multi-pass render camera effect
// -------------------------------
/*! \sa Class ReferenceTarget, Class CameraObject.\n\n
\par Description:
The multipass camera effect allows modification of viewpoints \& view
directions or time for each pass of a multipass rendering. Algorithms such as
Depth of Field, Scene motion blur can be implemented using multipass
techniques.\n\n
Basically, a multipass camera effect is a plug-in to camera objects. It allows
the renderer to query the camera for the view params for each pass of the
rendering, \& provides a dithered combining function to combine the bitmaps
produced by each pass into the final bitmap. It also allows time to be
manipulated for each rendering pass, providing effects such as motion blur.
*/
class IMultiPassCameraEffect : public ReferenceTarget
{
public:
// allows effect to declare it's compatibility with the current camera object
/*! \remarks Some cameras are not compatible with some render effects,
this method allows cameras to list compatible effects in the UI and as such
allows the effect to declare its compatibility with the current camera
object.
\param pCameraObject A pointer to a camera object.
\return TRUE if compatible, otherwise FALSE. */
virtual bool IsCompatible(CameraObject *pCameraObject) = 0;
// indicates that the renderer should display each pass as it is rendered (not used by viewport renderer)
/*! \remarks There is a UI option on multipass effects that indicates
whether the renderer should display each pass as it is rendered. Note this
is not used by viewport renderer, because of the hardware involvement. This
method returns whether to display individual passes as they are computed.
\param renderTime The rendertime at which to check the display passes.
\return TRUE if display is on, otherwise FALSE. */
virtual bool DisplayPasses(TimeValue renderTime) = 0;
// indicates the total number of passes to be rendered
/*! \remarks The multipass effect also has a variable number of passes.
This method tells the renderer how many passes to render per final output
frame and as such returns the total number of passes to be rendered
\param renderTime The rendertime at which to check the display passes. */
virtual int TotalPasses(TimeValue renderTime) = 0;
// called for each render pass. the effect can alter the camera node, camera object, or override the render time
/*! \remarks This method will modify the camera, camera node, or time
value to affect each pass.\n\n
This is the modify function called for each pass of the frame. The effect
can alter the camera node, camera object, or override the render time in
the course of this call. 3ds Max renderers take an optional parameter
viewParams* that when not NULL overrides the normal rendering camera. When
this is called the override render time will be set to the current frame
time. If the value is changed, this will be the time value used for the
pass. Note that at the time that apply is called, the renderer has not yet
been called, hence it is possible, with care, to alter the scene in a
general way, not just the camera \& time parameters. Apply should return
NULL if the normal unmodified camera is to be used.
\param pCameraNode A pointer to the node of the camera.
\param pCameraObject A pointer to the camera object.
\param passNum The number of the pass.
\param overrideRenderTime The time if you wish to override the render time.
\return The viewparams returned by apply which are supplied to the
renderer. */
virtual ViewParams *Apply(INode *pCameraNode, CameraObject *pCameraObject, int passNum, TimeValue &overrideRenderTime) = 0;
// allows the effect to blend its own passes (not used by the viewport renderer)
/*! \remarks This method will blend each pass (<b>src</b>) into the final
accumulator (<b>dest</b>).\n\n
After each pass is rendered, it needs to be combined into the final output
bitmap. The current multipass effects use a dithered combiner, so that hard
edges from the passes are more smoothly blended. There are many ways to do
this, with varying quality, so this method allows different future
implementations. Note that this is not used by the viewport renderer, as
there's no way to tell the hardware to do this. Hardware is for fast \&
edgy, software is for slow \& smooth.
\param pDest The destination bitmap.
\param pSrc The source bitmap.
\param passNum The number of the pass.
\param renderTime The render time. */
virtual void AccumulateBitmap(Bitmap *pDest, Bitmap *pSrc, int passNum, TimeValue renderTime) = 0;
// convenience function, called after all passes have been rendered. can be ignored.
/*! \remarks This method is called after all passes have been
rendered.\n\n
After all passes have been rendered \& accumulated, this method will be
called so that the effect can do any final cleanup. Currently unused, it
can be ignored by multipass effects if they wish. */
virtual void PostRenderFrame() = 0;
// from class ReferenceMaker
/*! \remarks This method is implemented to receive and respond to messages
broadcast by all the dependants in the entire system.
\param changeInt This is the interval of time over which the message is active.
\param hTarget This is the handle of the reference target the message was sent by. The
reference maker uses this handle to know specifically which reference
target sent the message.
\param partID This contains information specific to the message passed in. Some messages
don't use the partID at all. See \ref Reference_Messages
for more information about the meaning of the partID for some common messages.
\param message The msg parameters passed into this method is the specific message which
needs to be handled. See \ref Reference_Messages.
\return The return value from this method is of type RefResult. This is
usually <b>REF_SUCCEED</b> indicating the message was processed. Sometimes,
the return value may be <b>REF_STOP</b>. This return value is used to stop
the message from being propagated to the dependents of the item.
\par Default Implementation:
<b>{ return REF_SUCCEED; }</b> */
virtual RefResult NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message) { return REF_SUCCEED; }
// from class Animatable
/*! \remarks This method returns the super class ID of the creator of the
clip object.
\par Default Implementation:
<b>{ return MPASS_CAM_EFFECT_CLASS_ID; }</b> */
virtual SClass_ID SuperClassID() { return MPASS_CAM_EFFECT_CLASS_ID; }
virtual void BeginEditParams(IObjParam *ip, ULONG flags, Animatable *prev=NULL) {}
virtual void EndEditParams(IObjParam *ip, ULONG flags, Animatable *next=NULL) {}
};
// mjm - end
// ------------
// CameraObject
// ------------
#define CAM_HITHER_CLIP 1
#define CAM_YON_CLIP 2
#define ENV_NEAR_RANGE 0
#define ENV_FAR_RANGE 1
/*! \sa Class GenCamera.
\remarks Note: The camera looks down the negative Z axis, with X to the right and Y up.
*/
struct CameraState: public MaxHeapOperators {
inline CameraState() {cbStruct = sizeof(CameraState);}
DWORD cbStruct;
/*! \remarks Flag to indicate if the camera uses orthographic projection (TRUE) or perspective (FALSE). */
BOOL isOrtho; // true if cam is ortho, false for persp
/*! \remarks The camera field-of-view in radians. */
float fov; // field-of-view for persp cams, width for ortho cams
/*! \remarks Target distance for free cameras. */
float tdist; // target distance for free cameras
/*! \remarks Horizon line display state. */
BOOL horzLine; // horizon line display state
/*! \remarks Flag to indicate if camera has manual clipping enabled. */
int manualClip;
/*! \remarks Hither clipping plane distance. */
float hither;
/*! \remarks Yon clipping plane distance. */
float yon;
/*! \remarks Near camera range radius. */
float nearRange;
/*! \remarks Far camera range radius. */
float farRange;
};
/*! \sa Class Object.\n\n
\par Description:
This is a base class from which camera plug-ins may be derived. Methods of this
class are used to get and set properties of the camera. All methods of this
class are virtual. */
class CameraObject : public Object
{
public:
SClass_ID SuperClassID() { return CAMERA_CLASS_ID; }
int IsRenderable() { return(0);}
virtual void InitNodeName(MSTR& s) { s = _M("Camera"); }
virtual int UsesWireColor() { return FALSE; } // TRUE if the object color is used for display
// Methods specific to cameras:
//*************************************************************
// NOTE:
//
// To ensure that the camera has a valid targDist during
// network rendering, be sure to call:
//
// UpdateTargDistance( TimeValue t, INode* inode );
//
// This call should be made PRIOR to cameraObj->EvalWorldState(...)
//*************************************************************
/*! \remarks This method is called to update the CameraState and validity interval at
the specified time.
\param time Specifies the time to evaluate the camera.
\param valid The plug-in computes the validity interval of the camera at the specified
time and stores the result here.
\param cs The camera state to update. See Structure CameraState.
\note The view vector and 'up' vector for the camera are stored with the matrix
transform for the node. Cameras can be multiple-instanced so it must work
this way. To get at this matrix use the following method from
Class INode:
\code
virtual Matrix3 GetObjTMAfterWSM(TimeValue time, Interval* valid=NULL)=0;
\endcode
The scaling of this matrix may be removed by normalizing each of the rows.
\return <b>REF_SUCCEED</b> if the camera state was updated successfully;
otherwise <b>REF_FAIL</b>. */
virtual RefResult EvalCameraState(TimeValue time, Interval& valid, CameraState* cs)=0;
/*! \remarks Sets whether the camera is on ortho mode or not.
\param b Pass TRUE for ortho and FALSE for not ortho. */
virtual void SetOrtho(BOOL b)=0;
/*! \remarks Returns TRUE if the camera is in ortho mode and FALSE if it is not. */
virtual BOOL IsOrtho()=0;
/*! \remarks Sets the field-of-view of the camera at the specified time.
\param t The time at which to set the field-of-view.
\param f The value to set in radians. */
virtual void SetFOV(TimeValue t, float f)=0;
/*! \remarks Returns the field-of-view setting of the camera at the specified time and
adjusts the validity interval of the camera at this time to reflect the
field-of-view parameter.
\param t The time to retrieve the field-of-view setting.
\param valid The validity interval to set.
\return The field-of-view of the camera in radians. */
virtual float GetFOV(TimeValue t, Interval& valid = Interval(0,0))=0;
/*! \remarks Sets the target distance setting (for free cameras) at the specified time.
\param t The time at which to set the target distance.
\param f The value to set. */
virtual void SetTDist(TimeValue t, float f)=0;
/*! \remarks Returns the target distance setting of the camera at the specified time and
adjusts the validity interval of the camera to reflect the target distance
parameter.
\param t The time to retrieve the target distance setting.
\param valid This validity interval is intersected with the validity interval of the
target distance parameter.
\return The target distance of the camera. */
virtual float GetTDist(TimeValue t, Interval& valid = Interval(0,0))=0;
/*! \remarks Returns the manual clip flag. This indicates the camera will perform
clipping at its hither and yon distances.
\return Nonzero if manual clipping is enabled; otherwise 0. */
virtual int GetManualClip()=0;
/*! \remarks Sets the manual clip flag. This indicates the camera will perform clipping
at its hither and yon distances.
\param onOff The state of the manual clipping flag to set. Nonzero indicates clipping
will be performed. */
virtual void SetManualClip(int onOff)=0;
/*! \remarks Retrieves the clipping distance of the specified plane at the specified
time and modifies the validity interval to reflect the setting of the
clipping distance parameter.
\param t The time to retrieve the clipping distance.
\param which Indicates which distance to return. One of the following values:\n\n
<b>CAM_HITHER_CLIP</b> - The hither distance\n
<b>CAM_YON_CLIP</b> - The yon distance.\n
\param valid The validity interval that this method will update to reflect the clipping
distance interval.
\return The clipping distance. */
virtual float GetClipDist(TimeValue t, int which, Interval &valid=Interval(0,0))=0;
/*! \remarks Sets the clipping distance of the specified plane at the specified time.
\param t The time to set the clipping distance.
\param which Indicates which distance to set. One of the following values:\n\n
<b>CAM_HITHER_CLIP</b> - The hither distance\n
<b>CAM_YON_CLIP</b> - The yon distance.\n
\param val The distance to set. */
virtual void SetClipDist(TimeValue t, int which, float val)=0;
/*! \remarks Sets the environment range distance at the specified time.
\param time The time to set the environment range.
\param which Indicates which distance to set. One of the following values:\n\n
<b>ENV_NEAR_RANGE</b> - The near distance.\n
<b>ENV_FAR_RANGE</b> - The far distance.\n
\param f The distance to set. */
virtual void SetEnvRange(TimeValue time, int which, float f)=0;
/*! \remarks Retrieves the environment range distance at the specified time and
intersects the specified validity interval with the interval of the
environment range parameter.
\param t The time to retrieve the environment range.
\param which Indicate which distance to set. One of the following values:\n\n
<b>ENV_NEAR_RANGE</b> - The near distance.\n
<b>ENV_FAR_RANGE</b> - The far distance.\n
\param valid The validity interval that this method will update to reflect the
environment range setting.
\return The environment range distance at the specified time. */
virtual float GetEnvRange(TimeValue t, int which, Interval& valid = Interval(0,0))=0;
/*! \remarks Sets the environment range display flag. This indicates if the camera will
display its range settings.
\param b The flag state to set.
\param notify If notify is TRUE, dependents of this message are sent the \ref REFMSG_CHANGE message using
<b>NotifyDependents(FOREVER, PART_OBJ, REFMSG_CHANGE);</b>
Otherwise no notification is sent. */
virtual void SetEnvDisplay(BOOL b, int notify=TRUE)=0;
/*! \remarks Retrieves the environment range display setting.
\return TRUE if ranges are displayed; otherwise FALSE. */
virtual BOOL GetEnvDisplay(void)=0;
/*! \remarks This method is called on all cameras when the render aperture width has
changed.
\param t The time of the change. */
virtual void RenderApertureChanged(TimeValue t)=0;
/*! \remarks This method is called on all target cameras when the target distance has
changed. For instance, a distance shown in the user interface may be
updated in this method.
\param t The time of the change.
\param inode The camera node.
\par Default Implementation:
<b>{}</b> */
virtual void UpdateTargDistance(TimeValue t, INode* inode) { }
// mjm - begin - 07.17.00
/*! \remarks Enables or disables the multi-pass effect.
\param t The time at which to enable the effect.
\param enabled TRUE for enabled; FALSE for disabled.
\par Default Implementation:
<b>{ }</b> */
virtual void SetMultiPassEffectEnabled(TimeValue t, BOOL enabled) { }
/*! \remarks Returns the enabled or disabled state of the multi-pass effect setting for
the camera.
\param t The time at which to get the setting.
\param valid The validity interfal for the setting.
\return TRUE for enabled; FALSE for disabled.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL GetMultiPassEffectEnabled(TimeValue t, Interval& valid) { return FALSE; }
virtual void SetMPEffect_REffectPerPass(BOOL enabled) { }
virtual BOOL GetMPEffect_REffectPerPass() { return FALSE; }
/*! \remarks The <b>IMultiPassCameraEffect</b> should be checked to see if compatible
with the camera\n\n
before being assigned.
\param pIMultiPassCameraEffect The IMultiPassCameraEffect to assign.
\par Default Implementation:
<b>{ }</b> */
virtual void SetIMultiPassCameraEffect(IMultiPassCameraEffect *pIMultiPassCameraEffect) { }
/*! \remarks Returns a pointer to the current multi-pass camera effect. See
Class IMultiPassCameraEffect.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual IMultiPassCameraEffect *GetIMultiPassCameraEffect() { return NULL; }
// mjm - end
};
/*-------------------------------------------------------------------
LightObject:
---------------------------------------------------------------------*/
#define LIGHT_ATTEN_START 0
#define LIGHT_ATTEN_END 1
/*! \sa Class GenLight, Class LightObject, Class Color, Class Matrix3.
\remarks This structure describes the properties of a light.
*/
struct LightState: public MaxHeapOperators {
/*! One of the following values from enum LightType: \n
OMNI_LGT - Omnidirectional \n
SPOT_LGT - Spot (cone) \n
DIRECT_LGT - Directional (parallel) \n
AMBIENT_LGT - Global
*/
LightType type;
/*! The transformation matrix of the light. */
Matrix3 tm;
/*! The color of the light (its intensity). */
Color color;
/*! The multiplier applied to the color. */
float intens; // multiplier value
/*! The hotspot size in degrees. */
float hotsize;
/*! The hotspot falloff size in degrees. */
float fallsize;
/*! Nonzero if near attenuation is used; otherwise zero. */
int useNearAtten;
/*! The near attenuation start value. */
float nearAttenStart;
/*! The near attenuation end value. */
float nearAttenEnd;
/*! Nonzero if (far) attenuation is used; otherwise zero. */
int useAtten;
/*! The (far) start attenuation value. */
float attenStart;
/*! The (far) end attenuation value. */
float attenEnd;
/*! One of the following values: \n
RECT_LIGHT, CIRCLE_LIGHT */
int shape;
/*! The aspect ratio of the light. */
float aspect;
/*! TRUE if the light supports overshoot; otherwise FALSE. */
BOOL overshoot;
/*! TRUE if shadows are on; otherwise FALSE. */
BOOL shadow;
/*! TRUE if the light is on; otherwise FALSE. */
BOOL on; // light is on
/*! TRUE if affect diffuse is on; otherwise FALSE. */
BOOL affectDiffuse;
/*! TRUE if affect specular is on; otherwise FALSE. */
BOOL affectSpecular;
BOOL ambientOnly; // affect only ambient component
DWORD extra;
};
class LightDesc;
class RendContext;
// This is a callback class that can be given to a ObjLightDesc
// to have a ray traced through the light volume.
/*! \sa Class ObjLightDesc.\n\n
\par Description:
This is a callback class that can be given to a <b>ObjLightDesc</b> to have a
ray traced through the light volume. A plug-in derives a class from this one
and passes it as a callback in the <b>ObjLightDesc</b> method
<b>TraverseVolume()</b>. This allows a developer to integrate the illumination
of a segment due to a light. <b>t0</b> and <b>t1</b> define the segment in
terms of the given ray.\n\n
This is what the 3ds Max spotlights do: First they break the segment up into
three main pieces. The first piece is from the camera to where the ray
intersects the lights cone volume. The callback <b>Step()</b> is called once
over this segment (<b>t0</b> and <b>t1</b> will have this first piece). The
illumination is constant over this entire segment from <b>t0</b> to <b>t1</b>.
It is a constant black since the light is not illuminating it at all.\n\n
The next segment is inside the cone. This segment will be broken up into small
pieces. First as it's stepping along it will be between the falloff and the
hotspot. The illumination over this segment goes from black to brighter and
brighter as it moves towards to hotspot. Across the entire hotspot region the
illumination may be constant. Then as it steps from the hotspot to the falloff
the illumination will go back down to black.\n\n
Inside the hotspot region, if shadows are turned on, the light may be brighter
or darker depending on if it's inside a shadow or on the edge of a shadow. The
light handles all of this. It takes care of the shadows, attenuation, etc.\n\n
Now consider how the 3ds Max atmospheric effects such as the volume lights use
this information. For each light that they are bound to, they call the method
<b>TraverseVolume()</b> on the light. The volume light atmospheric effect
passes this callback to the <b>TraverseVolume()</b> method. The light then
calls this <b>Step()</b> method of the callback for each partial segment of the
ray. Given the illumination on the segment (<b>illum</b>) it computes the fog
density over that piece. The density may be constant if noise is not turned on,
or it may vary if noise is turned on. Using the fog density and the
illumination it computes the light reflected off the atmosphere for the
segment. */
class LightRayTraversal: public MaxHeapOperators {
public:
// This is called for every step (return FALSE to halt the integration).
// t0 and t1 define the segment in terms of the given ray.
// illum is the light intensity over the entire segment. It can be
// assumed that the light intensty is constant for the segment.
/*! \remarks This method is called for every step defined by <b>t0</b> and <b>t1</b>.
The illumination over this segment is passed in <b>illum</b>.
\param t0 The start of the segment. This is a distance along the ray. The ray is made
up of a point <b>p</b> and a unit length direction vector <b>dir</b>. The
point defined by <b>t0</b> is thus <b>ray.p+t0*ray.dir</b>.
\param t1 The end of the segment. This is a distance along the ray. The ray is made
up of a point <b>p</b> and a unit length direction vector <b>dir</b>. The
point defined by <b>t1</b> is thus <b>ray.p+t1*ray.dir</b>.
\param illum The light intensity over the entire segment. It can be assumed that the
light intensity is constant for the segment.
\param distAtten This parameter may be used so that volume effects can use the distance
attenuation value as an input variable to their effects. For instance, the
volume light uses this to change the fog color based on the distance from
the light.
\return TRUE to continue; FALSE to halt the integration (stop the
traversal). */
virtual BOOL Step(float t0, float t1, Color illum, float distAtten)=0;
};
// Flags passed to TraverseVolume
#define TRAVERSE_LOWFILTSHADOWS (1<<0)
#define TRAVERSE_HIFILTSHADOWS (1<<1)
#define TRAVERSE_USESAMPLESIZE (1<<2)
////////////////////////////////////////////////////////////////////////
// The following classes, IlluminateComponents & IlluminationComponents,
// have been added in 3ds max 4.2. If your plugin utilizes this new
// mechanism, be sure that your clients are aware that they
// must run your plugin with 3ds max version 4.2 or higher.
// Extension to provide the components of the Illuminate function to
// Shaders, materials & render elements
// This class holds the output components of illuminate
/*! \n\n
class IlluminateComponents : public BaseInterfaceServer\n\n
\par Description:
Provides the components of the Illuminate function to Shaders, Materials \&
Render\n\n
Elements. The interface to lights to return the illumination as a set of\n\n
components. This interface separates the illumination into various components
as well as the final result.\n\n
*/
class IlluminateComponents : public BaseInterfaceServer {
public:
/*! \remarks Light Vector*/
Point3 L; // light vector
/*! N dot L, N \& L are normalized*/
float NL; // N dot L
// these are the attenuations due to the light
/*! The contrast applied to N.L...this is equivalent to the diffCoef returned by
standard illuminate*/
float geometricAtten; // final constrast applied to N.L
/*! attenuation fraction due to cone(s) or rect falloff*/
float shapeAtten; // due to cone(s) falloff
/*! Attenuation due to distance falloff*/
float distanceAtten; // attenuation due to distance, falloff
// this is the composite attenuation due to all shadowing objects
// transparent bojects may supply some shadowAtten as well as filterAtten
/*! The composite attenuation due to all shadowing objects transparent objects may
supply some shadowAtten as well as filterAtten.\n\n
0 for all shadow, 1 for all light\n\n
light control over basic shading components*/
float shadowAtten; // 0 == all shadow, 1 == all light
// these allow smooth control over how the light
// affects these basic shading components
/*! light control over ambitient shading components\n\n
0 = no ambient, 1 = all ambient*/
float ambientAtten; // 0 == no ambient, 1 = all ambient
/*! light control over diffuse shading components\n\n
0 = no diffuse, 1 = all diffuse*/
float diffuseAtten; // 0 == no diffuse, 1 = all diffuse
/*! light control over specular shading components\n\n
0 = no specular, 1 = all specular*/
float specularAtten; // 0 == no specular, 1 = all specular
// The complete amount of light falling on the point sc.P() orientied
// in the direction sc.N() is the filteredColor. if( rawColor!=filteredColor)
// then it's filtered, else unfiltered
// light color modulated by map value,
// unattenuated, w/ raw light if no map
/*! Raw light color or mixed with light map value, unattenuated by shape, distance,
or shadow.*/
Color rawColor;
// light color modulated by map value,
// then filtered by a transparent object,
// raw color * filterAtten, otherwise unattenuated,
/*! Light color modulated by map value, then filtered by a transparent object, raw
color * filterAtten, otherwise unattenuated.*/
Color filteredColor;
// color due to user shadow color, modulated by a possible map,
// attenuated by 1-shadowAtten
/*! Shadow color, attenuated by shape, distance \& shadow fraction*/
Color shadowColor;
// these are the combined light colors modulated by the ambientAtten'uators
// they can be used by shaders to compute diffuse & specular shading
// complete component color is e.g. lightDiffuseColor+shadowColor
// NB: the geometric atten is to be applied by the shader, not the light
// e.g. lightAmbientColor =
// ambientAtten * (shapeAtten*distAtten*shadowAtten)
// * filteredColor;
/*! Ambient color due to light, attenuated, w/o shadow color*/
Color lightAmbientColor; // ambient color due to light, attenuated, w/o shadow color
/*! Diffuse color due to light, attenuated, w/o shadow color*/
Color lightDiffuseColor; // diffuse color due to light, attenuated, w/o shadow color
/*! Specular color due to light, attenuated, w/o shadow color */
Color lightSpecularColor; // specular color due to light, attenuated, w/o shadow color
// these are equivalent to 4.0 final illumination color, with & without shadows
// finalColor = shadowColor + (shapeAtten * distAtten * shadowAtten)
// * filteredColor;
/*! Equivalent to 4.0 final illumination color, with \& without shadows */
Color finalColor;
// Like final color but no shadow attenuation applied & no shadowColor
// finalColorNS = (shapeAtten * distAtten) * filteredColor;
/*! Equivalent to <b>finalColor</b>, but with no shadow attenuation applied \& no
shadow */
Color finalColorNS;
// user extensible component outputs, name matched
/*! The number of user illumination channels, returned by <b>nUserIllumChannels()</b>*/
int nUserIllumOut; // one set of names for all illum params instances
/*! Pointer to shared name array, never destroyed */
MCHAR** userIllumNames; // we just keep ptr to shared name array, never destroyed
/*! The user illumination color array, created and deleted with the class */
Color* userIllumOut; // the user illum color array, new'd & deleted w/ the class
IlluminateComponents(): nUserIllumOut(0),userIllumOut(NULL),userIllumNames(NULL) {}
CoreExport ~IlluminateComponents();
// returns number of user illum channels for this material
/*! \remarks return number of user illumination channels for
material\n\n
*/
int nUserIllumChannels(){ return nUserIllumOut; }
// returns null if no name array specified
/*! \remarks return the name of the index in channels name array
\param n The element in the <b>userIllumNames</b> array
\return The name of the user channel, NULL if no name specified\n\n
*/
MCHAR* GetUserIllumName( int n ) {
DbgAssert( n < nUserIllumOut );
if( userIllumNames )
return userIllumNames[n];
return NULL;
}
// render elements, mtls & shaders can use this to find the index associated with a name
// returns -1 if it can't find the name
/*! \remarks return the index associated with a name
\param name The channel name in the <b>userIllumNames</b> array
\return The index of the user channel, -1 if name no found\n\n
*/
CoreExport int FindUserIllumName( MCHAR* name );
// knowing the index, these set/get the user illum output color
/*! \remarks Set the output illumination color to indexed channel
\param n The channel index in the <b>userIllumOut</b> array
\param out The illumination color to set */
void SetUserIllumOutput( int n, Color& out ){
DbgAssert( n < nUserIllumOut );
userIllumOut[n] = out;
}
/*! \remarks Get the output illumination color of indexed channel
\param n The channel index in the <b>userIllumOut</b> array
\return The illumination color to get\n\n
*/
Color GetUserIllumOutput( int n ){
DbgAssert( n < nUserIllumOut );
return userIllumOut[n];
}
/*! \remarks It sets to black all the output colors */
void Reset(){
NL = geometricAtten = shapeAtten = distanceAtten = shadowAtten
= ambientAtten = diffuseAtten = specularAtten = 0.0f;
rawColor.Black();
filteredColor.Black();
lightAmbientColor.Black();
lightDiffuseColor.Black();
lightSpecularColor.Black();
shadowColor.Black();
finalColor.Black();
finalColorNS.Black();
L = Point3( 0,0,0 );
if(nUserIllumOut>0 && userIllumOut){
for(int i=0; i<nUserIllumOut; ++i )
userIllumOut[i].Black();
}
}
}; // end, IlluminateComponents
// must be greater than I_USERINTERFACE in maxsdk/include/animtbl.h
#define IID_IIlluminationComponents Interface_ID(0xdae00001, 0x0)
// this is the interface to use illumination by components
// this may be supported by a light object
// returned by lightObjDesc::GetInterface( IID_IIlluminationComponents );
class IIlluminationComponents : public BaseInterface {
public:
virtual BOOL Illuminate(ShadeContext& sc, Point3& normal, IlluminateComponents& illumComp )=0;
};
// End of IlluminateComponents & IlluminationComponent 3ds max 4.2 Extension
// A light must be able to create one of these to give to the renderer.
// The Illuminate() method (inherited from LightDesc) is called by the renderer
// to illuminate a surface point.
/*! \sa Class LightDesc, Class LightRayTraversal, Class INode, Class Point3, Class Matrix3, Class Ray, Class RendContext, Class ShadeContext, Class RenderInstance.\n\n
\par Description:
A light must be able to create one of these objects to give to the renderer. As
the renderer is getting ready to render, it will ask for one of these from each
of the lights. The <b>Illuminate()</b> method (inherited from <b>LightDesc</b>)
is called by the renderer to illuminate a surface point.\n\n
There is an <b>ObjLightDesc</b> for every instance of the light. The renderer
will ask each light object to produce one of these <b>ObjLightDescs</b>. It
will then set this data up in the node's render data (See
Class RenderData). For example in 3ds
Max's volume light implementation of <b>Atmospheric::Update()</b> it goes
through its node references to lights and calls <b>GetRenderData()</b>. It then
casts this as an <b>ObjLightDesc</b>. This is how a atmosphere effect can get
access to these descriptors at render time.
\par Data Members:
This data will be set up by the default implementation of <b>Update()</b>.\n\n
<b></b>\n\n
<b>LightState ls;</b>\n\n
The light state structure. See Structure LightState.\n\n
<b>INode *inode;</b>\n\n
This parameter is the <b>INode</b> pointer of the instance of the light that
created this <b>ObjLightDesc</b>.\n\n
<b>BOOL uniformScale;</b>\n\n
This indicates if the light's scale is uniform. TRUE if uniform; otherwise
FALSE. This saves some steps in the renderer if the scale is uniform.\n\n
<b>Point3 lightPos;</b>\n\n
The position of the light in camera space.\n\n
<b>Matrix3 lightToWorld;</b>\n\n
This is effectively the light node's object TM. This matrix will transform
points from light space to world space.\n\n
<b>Matrix3 worldToLight;</b>\n\n
This matrix will transform points from world space to light space. This is the
inverse of above.\n\n
<b>Matrix3 lightToCam;</b>\n\n
This matrix will transform points from light space to camera space. This is
updated in <b>UpdateViewDepParams()</b>.\n\n
<b>Matrix3 camToLight;</b>\n\n
This matrix will transform points from camera space to light space. This is
updated in <b>UpdateViewDepParams()</b>. For example, the renderer would have
points in camera space. To figure out if a point was in shadow it would
transform the point from camera space to light space using this matrix. It
could then look in the shadow buffer to see if the point was in shadow.\n\n
<b>int renderNumber;</b>\n\n
This is set by the renderer. It is used in
<b>RenderInstance::CastsShadowsFrom()</b>. This is a number used by the
renderer to identify the lights so it can quickly determine if a given light
casts shadows from a given object. It is for use by the renderer. */
class ObjLightDesc : public LightDesc {
public:
// This data will be set up by the default implementation of Update()
LightState ls;
INode *inode;
BOOL uniformScale; // for optimizing
Point3 lightPos;
Matrix3 lightToWorld;
Matrix3 worldToLight;
Matrix3 lightToCam; // updated in UpdateViewDepParams
Matrix3 camToLight; // updated in UpdateViewDepParams
int renderNumber; // set by the renderer. Used in RenderInstance::CastsShadowsFrom()
/*! \remarks Constructor. The <b>inode</b> data member is initialized to
<b>n</b>. */
CoreExport ObjLightDesc(INode *n);
/*! \remarks Destructor. */
CoreExport virtual ~ObjLightDesc();
/*! \remarks Retrieves the light's exclusion list.
\return See Class NameTab.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual ExclList* GetExclList() { return NULL; }
// update light state that depends on position of objects&lights in world.
/*! \remarks This method is called once per render to update the light state for things
that depend on the position of objects and lights in world space. A plug-in
light could update any data it would need to here. The default
implementation is shown below.
\param t The time of the render.
\param rc See Class RendContext.
\param rgc This pointer may be used to retireve information about the global rendering enviornment.
\param shadows TRUE if shadows are turned on (in the render parameters, not the light
parameters); otherwise FALSE.
\param shadowGeomChanged This tells the Update procedure that the geometry of the objects that are
shadowed by the light has changed (TRUE) or not (FALSE). If it is a shadow
buffer, <b>shadowGeomChanged == TRUE</b> means it has to re-render the
shadow buffer, <b>shadowGeomChanged == FALSE</b> means it can use the
shadow buffer from the previous frame.
\return The value return should normally be 1. A returned value of 0 means
an error has occured (such as out of memory) and the render will be halted.
\par Default Implementation:
\code
int ObjLightDesc::Update(TimeValue t, const RendContext& rc, RenderGlobalContext *rgc, BOOL shadows, BOOL shadowGeomChanged)
{
if (inode) {
Interval valid;
ObjectState os = inode->EvalWorldState(t);
assert(os.obj->SuperClassID()==LIGHT_CLASS_ID);
LightObject* lob = (LightObject *)os.obj;
lob->EvalLightState(t, valid, &ls);
lightToWorld = inode->GetObjTMAfterWSM(t);
worldToLight = Inverse(lightToWorld);
uniformScale = IsUniformScale(lightToWorld);
affectDiffuse = ls.affectDiffuse;
affectSpecular = ls.affectSpecular;
ambientOnly = ls.ambientOnly;
}
else {
uniformScale = TRUE;
lightToWorld.IdentityMatrix();
worldToLight.IdentityMatrix();
}
return 1;
}
\endcode */
CoreExport virtual int Update(TimeValue t, const RendContext &rc, RenderGlobalContext *rgc, BOOL shadows, BOOL shadowGeomChanged);
// update light state that depends on global light level.
/*! \remarks This method is called to update the light state that depends on the global light level.
\param globLightLevel The global light level.
\par Default Implementation:
<b>{}</b> */
CoreExport virtual void UpdateGlobalLightLevel(Color globLightLevel) {}
// update light state that depends on view matrix.
/*! \remarks This method is called to update the light state that depends on the view
matrix. This is used to cache certain computed quantities that are
dependent on where you are looking from. In a given scene at a given time,
the system may render from several viewpoints. This is because of things
like reflection maps and mirrors that need to get rendered. This method is
called for each of these different viewpoints.
\param worldToCam The world space to camera space transformation matrix. */
CoreExport virtual int UpdateViewDepParams(const Matrix3& worldToCam);
// default implementation
/*! \remarks This method is from <b>LightDesc</b>. Here it provides a
default implementation returning the <b>lightPos</b> data member.
\par Default Implementation:
<b>{ return lightPos; }</b> */
CoreExport virtual Point3 LightPosition() { return lightPos; }
// This function traverses a ray through the light volume.
// 'ray' defines the parameter line that will be traversed.
// 'minStep' is the smallest step size that caller requires, Note that
// the callback may be called in smaller steps if they light needs to
// take smaller steps to avoid under sampling the volume.
// 'tStop' is the point at which the traversal will stop (ray.p+tStop*ray.dir).
// Note that the traversal can terminate earlier if the callback returns FALSE.
// 'proc' is the callback object.
//
// attenStart/End specify a percent of the light attenuation distances
// that should be used for lighting durring the traversal.
//
// The shade context passed in should only be used for state (like are
// shadows globaly disabled). The position, normal, etc. serve no purpose.
/*! \remarks This function traverses a ray through the light volume. This method is
implemented by plug-in lights.
\par Consider how the 3ds Max atmospheric effects like the volume lights use
this information. For each light the atmospheric effect is bound to, it
calls the this method (<b>TraverseVolume()</b>) on the light. The volume
light atmospheric effect passes a callback to this method (<b>proc</b>).
The light then calls the <b>Step()</b> method of the callback for each
partial segment of the ray. Given the illumination on the segment it
computes the fog density over that segment. The density may be constant if
noise is not turned on, or it may change if noise is turned on. Using the
fog density and the illumination it computes the light reflected off the
atmosphere for the segment.
\param sc This is the <b>ShadeContext</b> passed into the <b>Shade()</b> method of
the Atmospheric effect. The shade context passed in should only be used for
state (like are shadows globally disabled). The position, normal, etc.
serve no purpose.
\param ray Defines the world space ray that will be traversed.
\param samples The number of samples to sample along the ray. A reasonable range is from
25-100. This is more or less the suggested number of times the
<b>proc-\>Step()</b> callback will be called. It is not precisely however
because the system may take greater or fewer steps than specified as it
needs to.
\param tStop This is the end of the <b>ray</b>. This is the point at which the traversal
will stop (<b>ray.p+tStop*ray.dir</b>). Note that the traversal can
terminate earlier if the callback returns FALSE.
\param attenStart Specifies a percent of the light attenuation distances that should be used
for lighting during the traversal. This is used so a light can have an
attenuation set to a certain percent, and then have the volume light be
attenuated at a different point.
\param attenEnd This specifies the ending percent of the light attenuation distances that
should be used for lighting during the traversal.
\param flags There are three ways the shadow maps can be sampled. If none of these flags
are set, the shadow map is sampled directly (this is the fastest). One of
the following values:\n\n
<b>TRAVERSE_LOWFILTSHADOWS</b>\n
This is a simple filtering where the system samples a point in the shadow
map and then some of the neighboring points. This corresponds to 'Medium'
in the Volume Light user interface (a value of 0 for flags is 'Low' -- just
sampling the shadow map with no filtering at all).\n\n
<b>TRAVERSE_HIFILTSHADOWS</b>\n
This is a higher resolution sampling. This corresponds to 'High' in the
Volume Light user interface.\n\n
<b>TRAVERSE_USESAMPLESIZE</b>\n
This produces the highest quality. This corresponds to 'Use Light Sample
Range' in the Volume Light user interface. This is like a box filter, but
also takes into consideration the position of the point within the pixel to
do additional weighting.\n
\param proc A developer derives a class from <b>LightRayTraversal</b> and implements
the <b>Step()</b> method. A pointer to it is passed here as the callback
object.
\par Default Implementation:
<b>{}</b> */
virtual void TraverseVolume(
ShadeContext& sc,
const Ray &ray, int samples, float tStop,
float attenStart, float attenEnd,
DWORD flags,
LightRayTraversal *proc) {}
};
// Values returned from GetShadowMethod()
#define LIGHTSHADOW_NONE 0
#define LIGHTSHADOW_MAPPED 1
#define LIGHTSHADOW_RAYTRACED 2
/*! \sa Class Object, Class ObjLightDesc, Class Interval, Class Texmap.\n\n
\par Description:
This is the base class from which plug-in lights may be derived. */
class LightObject : public Object {
public:
SClass_ID SuperClassID() { return LIGHT_CLASS_ID; }
int IsRenderable() { return(0);}
virtual void InitNodeName(MSTR& s) { s = _M("Light"); }
// Methods specific to Lights:
/*! \remarks This method is called to update the passed <b>LightState</b> and validity
interval of the light.
\param time The time to evaluate the light state.
\param valid The validity interval of the light about the specified time. This interval
should be updated to reflect the validity interval of the light.
\param ls A pointer to the <b>LightState</b> structure which describes the properties
of the light. This function updates the data in the structure to reflect
the properties of the light at the specified time. See
Structure LightState.
\return <b>REF_SUCCEED</b> if the <b>LightState</b> was updated; otherwise
<b>REF_FAIL</b>. */
virtual RefResult EvalLightState(TimeValue time, Interval& valid, LightState *ls)=0;
/*! \remarks When the renderer goes to render the scene it asks all of the lights to
create an <b>ObjectLighDesc</b> object. This is the method that is called
to return this object.
\param n The node pointer of the light.
\param forceShadowBuffer Forces the creation of a shadow buffer.
\return An instance of <b>ObjectLightDesc</b>. See
Class ObjectLightDesc.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual ObjLightDesc *CreateLightDesc(INode *n, BOOL forceShadowBuffer=FALSE) {return NULL;}
//JH 06/03/03 new api to pass globalRenderContext
virtual ObjLightDesc *CreateLightDesc(RenderGlobalContext *rgc, INode *inode, BOOL forceShadowBuf=FALSE ){return NULL;}
/*! \remarks Sets if the light is on or off.
\param onOff TRUE for on; FALSE for off. */
virtual void SetUseLight(int onOff)=0;
/*! \remarks Returns TRUE if the light is on; otherwise FALSE. */
virtual BOOL GetUseLight(void)=0;
/*! \remarks Sets the hotspot to the specified angle at the specified time.
\param time The time to set the hotspot angle.
\param f The angle to set in degrees. */
virtual void SetHotspot(TimeValue time, float f)=0;
/*! \remarks Retrieves the hotspot angle.
\param t The time to retrieve the angle.
\param valid The validity interval that this method will update to reflect the hotspot setting.
\return The hotspot angle (in degrees). */
virtual float GetHotspot(TimeValue t, Interval& valid = Interval(0,0))=0;
/*! \remarks Sets the falloff setting of the light.
\param time The time to set the falloff.
\param f The falloff angle in degrees. */
virtual void SetFallsize(TimeValue time, float f)=0;
/*! \remarks Returns the falloff angle of the light in radians.
\param t The time to retrieve the falloff angle.
\param valid The validity interval that this method will update to reflect the falloff
setting.
\return The falloff angle of the light in degrees. */
virtual float GetFallsize(TimeValue t, Interval& valid = Interval(0,0))=0;
/*! \remarks Sets the specified attenuation range distance at the time passed.
\param time The time to set the attenuation distance.
\param which Indicates which distance to set. One of the following values:\n\n
\ref LIGHT_ATTEN_START - The start range radius.\n
\ref LIGHT_ATTEN_END - The end range radius.\n
\param f The distance to set. */
virtual void SetAtten(TimeValue time, int which, float f)=0;
/*! \remarks Returns the specified attenuation range distance at the time passed.
\param t The time to retrieve the attenuation distance.
\param which Indicates which distance to retrieve. One of the following values:\n\n
\ref LIGHT_ATTEN_START - The start range radius.\n
\ref LIGHT_ATTEN_END - The end range radius.\n
\param valid The validity interval that this method will update to reflect the attenuation setting.
\return The specified attenuation range distance. */
virtual float GetAtten(TimeValue t, int which, Interval& valid = Interval(0,0))=0;
/*! \remarks Sets the light's target distance.
\param time The time to set the distance.
\param f The distance to set. */
virtual void SetTDist(TimeValue time, float f)=0;
/*! \remarks Retrieves the light's target distance.
\param t The time to retrieve the distance.
\param valid The validity interval that this method will update to reflect the target distance setting.
\return The light's target distance. */
virtual float GetTDist(TimeValue t, Interval& valid = Interval(0,0))=0;
/*! \remarks Sets the light's cone display flag. This controls if the cone is depicted
graphically in the viewports.
\param s Indicates if the cone display should be on or off. If nonzero, the cone
should be displayed; otherwise it should be turned off.
\param notify If notify is TRUE the plug-in should call <b>NotifyDependents()</b> to
notify its dependents. */
virtual void SetConeDisplay(int s, int notify=TRUE)=0;
/*! \remarks Retrieves the light's cone display setting. This indicates if the cone is
depicted graphically in the viewports.
\return TRUE to indicate the cone is displayed; FALSE to indicate it is
turned off. */
virtual BOOL GetConeDisplay(void)=0;
/*! \remarks Returns the type of shadows used by the light.
\return One of the following values:\n\n
\ref LIGHTSHADOW_NONE\n\n
\ref LIGHTSHADOW_MAPPED\n\n
\ref LIGHTSHADOW_RAYTRACED
\par Default Implementation:
<b>{return LIGHTSHADOW_NONE;}</b> */
virtual int GetShadowMethod() {return LIGHTSHADOW_NONE;}
/*! \remarks Sets the color of the light at the specified time.
\param t The time to set the color.
\param rgb The color to set. */
virtual void SetRGBColor(TimeValue t, Point3& rgb) {}
/*! \remarks Returns the color of the light at the specified time and updates the
validity interval to reflect this parameters validity interval.
\param t The time to retrieve the value.
\param valid The validity interval to intersect with this parameters interval.
\return The color of the light at the specified time.
\par Default Implementation:
<b>{return Point3(0,0,0);}</b> */
virtual Point3 GetRGBColor(TimeValue t, Interval &valid = Interval(0,0)) {return Point3(0,0,0);}
/*! \remarks Sets the intensity of the light to the value passed.
\param time The time to set the value.
\param f The value to set. */
virtual void SetIntensity(TimeValue time, float f) {}
/*! \remarks Retrieves the intensity of the light at the specified time and updates the
validity interval passed to reflect the validity interval of this
parameter.
\param t The time to retrieve the value.
\param valid The validity interval to intersect with this parameters interval.
\return The intensity of the light at the specified time
\par Default Implementation:
<b>{return 0.0f;}</b> */
virtual float GetIntensity(TimeValue t, Interval& valid = Interval(0,0)) {return 0.0f;}
/*! \remarks Sets the aspect ratio of the light at the specified time.
\param t The time to set the value.
\param f The value to set. */
virtual void SetAspect(TimeValue t, float f) {}
/*! \remarks Retrieves the aspect ratio of the light at the specified time and updates
the validity interval passed to reflect the validity interval of this
parameter.
\param t The time to retrieve the value.
\param valid The validity interval to intersect with this parameters interval.
\return The aspect ratio of the light at the specified time
\par Default Implementation:
<b>{return 0.0f;}</b> */
virtual float GetAspect(TimeValue t, Interval& valid = Interval(0,0)) {return 0.0f;}
/*! \remarks Sets the flag to indicate if the light is attenuated.
\param s Nonzero to indicate the light is attenuated; otherwise 0. */
virtual void SetUseAtten(int s) {}
/*! \remarks Returns TRUE to indicate the light is attenuated; otherwise FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL GetUseAtten(void) {return FALSE;}
/*! \remarks Sets the flag to indicate if the light attenuation ranges are displayed.
\param s Nonzero to indicate the light attenuation ranges are displayed; otherwise 0. */
virtual void SetAttenDisplay(int s) {}
/*! \remarks Returns TRUE if the light attenuation ranges are displayed; otherwise
FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL GetAttenDisplay(void) {return FALSE;}
/*! \remarks Sets the light to enabled or disables (on or off).
\param enab Nonzero to set the light to on; zero to turn the light off. */
virtual void Enable(int enab) {}
/*! \remarks Sets the map bias setting at the time passed.
\param t The time to set the value.
\param f The map bias value to set. The 3ds Max lights use a range of 0.0 to 100.0. */
virtual void SetMapBias(TimeValue t, float f) {}
/*! \remarks Returns the map bias setting at the time passed and updates the validity
interval to reflect the validity interval of this parameter.
\param t The time to retrieve the value.
\param valid The validity interval to update to reflect this parameters validity interval.
\return The map bias setting at the time passed.
\par Default Implementation:
<b>{return 0.0f;}</b> */
virtual float GetMapBias(TimeValue t, Interval& valid = Interval(0,0)) {return 0.0f;}
/*! \remarks Sets the map sample range setting to the value passed at the time passed.
\param t The time to set the value.\
\param f The value to set. The 3ds Max lights use a range of 0.0 to 20.0. */
virtual void SetMapRange(TimeValue t, float f) {}
/*! \remarks Retrieves the lights map sample range setting at the specified time and
updates the validity interval to reflect the validity interval of this
parameter.
\param t The time to retrieve the value.
\param valid The validity interval to update to reflect this parameters validity interval.
\return The lights map sample range setting.
\par Default Implementation:
<b>{return 0.0f;}</b> */
virtual float GetMapRange(TimeValue t, Interval& valid = Interval(0,0)) {return 0.0f;}
/*! \remarks Sets the lights map size parameter to the value passed at the time passed.
\param t The time to set the value.
\param f The value to set. */
virtual void SetMapSize(TimeValue t, int f) {}
/*! \remarks Returns the lights map size parameter at the specified time and updates the
validity interval passed to reflect the validity interval of this
parameter.
\param t The time to retrieve the value.
\param valid The validity interval to update to reflect this parameters validity interval.
\return The lights map size parameter.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetMapSize(TimeValue t, Interval& valid = Interval(0,0)) {return 0;}
/*! \remarks Sets the raytrace bias setting to the value passed at the specified time.
\param t The time to set the value.
\param f The value to set. */
virtual void SetRayBias(TimeValue t, float f) {}
/*! \remarks Returns the lights raytrace bias setting at the specified time and updates
the validity interval passed to reflect the validity interval of this
parameter.
\param t The time to retrieve the value.
\param valid The validity interval to update to reflect this parameters validity interval.
\return The lights raytrace bias setting at the specified time.
\par Default Implementation:
<b>{return 0.0f;}</b> */
virtual float GetRayBias(TimeValue t, Interval& valid = Interval(0,0)) {return 0.0f;}
/*! \remarks Returns the Use Global Settings flag setting.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetUseGlobal() {return 0;}
/*! \remarks Sets the lights Use Global Settings flag.
\param a Nonzero indicates the light uses the global settings; zero indicates the
light uses its own settings. */
virtual void SetUseGlobal(int a) {}
/*! \remarks Returns the lights Cast Shadows flag.
\return Nonzero indicates the light casts shadows; otherwise 0.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetShadow() {return 0;}
/*! \remarks Sets the lights Cast Shadows flag.
\param a Nonzero indicates the light casts shadows; zero indicates the light does
not cast shadows. */
virtual void SetShadow(int a) {}
/*! \remarks Retrieves the type of shadows used by the light - mapped or raytraced.
\return One of the following values:\n\n
<b>-1</b>: if the Shadow Generator is NULL. (R3 only).\n\n
<b>0</b>: if the light uses Shadow Maps.\n\n
<b>1</b>: if the light uses Raytraced Shadows.\n\n
<b>0xffff</b>: for any other Shadow Generators. (R3 only).
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetShadowType() {return 0;}
/*! \remarks Sets the type of shadows used by the light - mapped or raytraced.
\param a One of the following values:\n\n
<b>0</b>: This value plugs in a Shadow Map Generator\n
<b>1</b>: This value plugs in a Raytraced Shadow Generator.\n\n
Any other value is a NOOP. */
virtual void SetShadowType(int a) {}
/*! \remarks Returns the lights Absolute Map Bias setting.
\return Nonzero indicates Absolute Map Bias is on; zero indicates it is
off.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetAbsMapBias() {return 0;}
/*! \remarks Sets the lights Absolute Map Bias setting.
\param a Nonzero indicates Absolute Map Bias is on; zero indicates it is off. */
virtual void SetAbsMapBias(int a) {}
/*! \remarks Returns the lights Overshoot on / off setting. Nonzero indicates overshoot
is on; otherwise 0.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetOvershoot() {return 0;}
/*! \remarks Sets the lights Overshoot on / off setting.
\param a Nonzero indicates overshoot is on; otherwise 0. */
virtual void SetOvershoot(int a) {}
/*! \remarks Returns the lights Projector on / off setting. Nonzero indicates this light
projects an image; otherwise 0.
\par Default Implementation:
<b>{return 0;}</b> */
virtual int GetProjector() {return 0;}
/*! \remarks Sets the lights projector on / off setting.
\param a Nonzero indicates this light projects an image; otherwise 0. */
virtual void SetProjector(int a) {}
/*! \remarks Returns the list of names of items included or excluded by this light. See
Class NameTab.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual ExclList* GetExclList() {return NULL;}
/*! \remarks Returns TRUE if the light's name list is of items to be included by the
light. Returns FALSE if the list is of items to exclude from the light.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL Include() {return FALSE;}
/*! \remarks Returns the map used by a projector light.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual Texmap* GetProjMap() {return NULL;}
/*! \remarks Sets the image(s) used by the projector light.
\param pmap The map to use. */
virtual void SetProjMap(Texmap* pmap) {}
/*! \remarks Updates the display of the light's target distance in the light's rollup
page.
\param t The time to retrieve the distance.
\param inode The light node.
\par Default Implementation:
<b>{}</b> */
virtual void UpdateTargDistance(TimeValue t, INode* inode) {}
};
/*-------------------------------------------------------------------
HelperObject:
---------------------------------------------------------------------*/
/*! \sa Class Object, Class Animatable.\n\n
\par Description:
This is used as a base class to create helper object plug-ins. It simply
provides implementations for a few of the methods of Animatable and Object.
*/
class HelperObject : public Object {
public:
/*! \remarks Implemented by the System.\n\n
Returns the super class ID of this plug-in type: <b>HELPER_CLASS_ID</b> */
SClass_ID SuperClassID() { return HELPER_CLASS_ID; }
/*! \remarks Implemented by the System.\n\n
Returns 0 to indicate this object type may not be rendered. */
int IsRenderable() { return(0); }
/*! \remarks Implemented by the System.\n\n
Sets the default node name to <b>"Helper"</b>. */
virtual void InitNodeName(MSTR& s) { s = _M("Helper"); }
/*! \remarks Implemented by the System.\n\n
Returns TRUE to indicate the object color is used for display. */
virtual int UsesWireColor() { return FALSE; } // TRUE if the object color is used for display
virtual BOOL NormalAlignVector(TimeValue t,Point3 &pt, Point3 &norm) {pt=Point3(0,0,0);norm=Point3(0,0,-1);return TRUE;}
};
/*-------------------------------------------------------------------
ConstObject:
---------------------------------------------------------------------*/
#define GRID_PLANE_NONE -1
#define GRID_PLANE_TOP 0
#define GRID_PLANE_LEFT 1
#define GRID_PLANE_FRONT 2
#define GRID_PLANE_BOTTOM 3
#define GRID_PLANE_RIGHT 4
#define GRID_PLANE_BACK 5
/*! \sa Class HelperObject, Class INode, Class Object, Class ViewExp, Class Matrix3.\n\n
\par Description:
This is a base class used to create construction grid objects. It implements a
few of the methods of Animatable and Object and provides a few for working with
construction grids. */
class ConstObject : public HelperObject {
private:
bool m_transient;
bool m_temporary; // 030730 --prs.
public:
ConstObject() { m_transient = m_temporary = false; }
// Override this function in HelperObject!
/*! \remarks Implemented by the System.\n\n
Returns 1 to indicate this object is a construction grid object. */
int IsConstObject() { return 1; }
// Methods specific to construction grids:
/*! \remarks This method returns the construction grid transformation matrix. This is
the world space orientation and position of the construction plane.
\param t The time to retrieve the matrix.
\param inode The node in the scene corresponding to the construction grid object.
\param vpt The viewport the TM is being returned for. Certain construction grid
objects might have a different plane for different viewports.
\param tm The transform matrix for this view is returned here. */
virtual void GetConstructionTM( TimeValue t, INode* inode, ViewExp *vpt, Matrix3 &tm ) = 0; // Get the transform for this view
virtual void SetConstructionPlane(int which, int notify=TRUE) = 0;
virtual int GetConstructionPlane(void) = 0;
/*! \remarks This method is specific to construction grids. The system calls this method
to retrieve the snap dimension of the grid. In the 3ds Max user interface
for the construction grid helper object there is a spinner for 'Spacing'.
This is the spacing for the grid. When <b>GetSnaps()</b> is called the
Point3 returned will have this value in all three axes. This value is used,
for example, when you create a box or other primitive and are setting the
height dimension.
\param t The time to retrieve the snap values. */
virtual Point3 GetSnaps( TimeValue t ) = 0; // Get snap values
virtual void SetSnaps(TimeValue t, Point3 p) = 0;
virtual BOOL NormalAlignVector(TimeValue t,Point3 &pt, Point3 &norm) {pt=Point3(0,0,0);norm=Point3(0,0,-1);return TRUE;}
//JH 09/28/98 for design ver
bool IsTransient()const {return m_transient;}
void SetTransient(bool state = true) {m_transient = state;}
// grid bug fix, 030730 --prs.
bool IsTemporary() const { return m_temporary; }
void SetTemporary(bool state = true) { m_temporary = state; }
//JH 11/16/98
virtual void SetExtents(TimeValue t, Point3 halfbox)=0;
virtual Point3 GetExtents(TimeValue t)=0;
//JH 09/28/98 for design ver
// bool IsImplicit()const {return m_implicit;}
// void SetImplicit(bool state = true) {m_implicit = state;}
};
/*-------------------------------------------------------------------
GeomObject: these are the Renderable objects.
---------------------------------------------------------------------*/
/*! \sa Class Object, Class Mesh.\n\n
\par Description:
This is the base class for the creation of Geometric Object plug-ins. This
class represents an object that has geometry and is renderable. */
class GeomObject : public Object {
public:
virtual void InitNodeName(MSTR& s) { s = _M("Object"); }
SClass_ID SuperClassID() { return GEOMOBJECT_CLASS_ID; }
virtual int IsRenderable() { return(1); }
// If an object creates different meshes depending on the
// particular instance (view-dependent) it should return 1.
/*! \remarks If an object creates different meshes depending on the particular instance
(view-dependent) it should return nonzero; otherwise 0.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int IsInstanceDependent() { return 0; }
// GetRenderMesh should be implemented by all renderable GeomObjects.
// set needDelete to TRUE if the render should delete the mesh, FALSE otherwise
// Primitives that already have a mesh cached can just return a pointer
// to it (and set needDelete = FALSE).
/*! \remarks This method should be implemented by all renderable GeomObjects. It
provides a mesh representation of the object for use by the renderer.
Primitives that already have a mesh cached can just return a pointer to it
(and set <b>needDelete</b> to FALSE).\n\n
Implementations of this method which take a
long time should periodically call <b>View::CheckForRenderAbort()</b> to
see if the user has canceled the render. If canceled, the function can
either return NULL, or return a non null pointer with the appropriate value
for <b>needDelete</b>. (If <b>needDelete</b> is TRUE a non-null mesh will
be deleted.)
\param t The time to get the mesh.
\param inode The node in the scene.
\param view If the renderer calls this method it will pass the view information here.
See Class View.
\param needDelete Set to TRUE if the renderer should delete the mesh, FALSE otherwise.
\return A pointer to the mesh object. */
CoreExport virtual Mesh* GetRenderMesh(TimeValue t, INode *inode, View& view, BOOL& needDelete);
// Objects may now supply multiple render meshes ( e.g. particle systems). If this function
// returns a positive number, then GetMultipleRenderMesh and GetMultipleRenderMeshTM will be
// called for each mesh, instead of calling GetRenderMesh // DS 5/10/00
/*! \remarks Objects may supply multiple render meshes ( e.g. particle systems). If this
method returns a positive number, then <b>GetMultipleRenderMesh</b> and
<b>GetMultipleRenderMeshTM</b> will be called for each mesh, instead of
calling <b>GetRenderMesh</b>.
\return The number of render meshes, or 0 to indicate that multiple meshes
aren't supported.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int NumberOfRenderMeshes() { return 0; } // 0 indicates multiple meshes not supported.
// For multiple render meshes, this method must be implemented.
// set needDelete to TRUE if the render should delete the mesh, FALSE otherwise
// meshNumber specifies which of the multiplie meshes is being asked for.// DS 5/10/00
/*! \remarks For multiple render meshes, this method must be implemented. set
<b>needDelete</b> to TRUE if the render should delete the mesh, FALSE
otherwise.
\param t The time at which to obtain the mesh.
\param inode The pointer to the node.
\param view A reference to the view.
\param needDelete TRUE if the mesh needs to be deleted, otherwise FALSE.
\param meshNumber Specifies which of the multiplie meshes is being asked for.
\par Default Implementation:
<b>{ return NULL; }</b> */
virtual Mesh* GetMultipleRenderMesh(TimeValue t, INode *inode, View& view, BOOL& needDelete, int meshNumber) { return NULL; }
// For multiple render meshes, this method must be implemented.
// meshTM should be returned with the transform defining the offset of the particular mesh in object space.
// meshTMValid should contain the validity interval of meshTM // DS 5/10/00
/*! \remarks For multiple render meshes, this method must be implemented.
\param t The time at which to obtain the mesh.
\param inode The pointer to the node.
\param view A reference to the view.
\param meshNumber Specifies which of the multiplie meshes is being asked for.
\param meshTM Should be returned with the transform defining the offset of the particular
mesh in object space.
\param meshTMValid Should contain the validity interval of <b>meshTM</b>.
\par Default Implementation:
<b>{ return; }</b> */
virtual void GetMultipleRenderMeshTM(TimeValue t, INode *inode, View& view, int meshNumber,
Matrix3& meshTM, Interval& meshTMValid) { return; }
// If this returns NULL, then GetRenderMesh will be called
/*! \remarks This method provides a patch mesh representation of the object for use by the
renderer. If this method returns NULL, then <b>GetRenderMesh()</b> will be
called.
\param t The time to get the patch mesh.
\param inode The node in the scene.
\param view If the renderer calls this method it will pass the view information here. See Class View.
\param needDelete Set to TRUE if the renderer should delete the patch mesh, FALSE otherwise.
\return A pointer to the patch mesh. See Class PatchMesh. */
CoreExport virtual PatchMesh* GetRenderPatchMesh(TimeValue t, INode *inode, View& view, BOOL& needDelete);
CoreExport Class_ID PreferredCollapseType();
/*! \remarks Returns TRUE if this object can do displacement mapping; otherwise FALSE.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual BOOL CanDoDisplacementMapping() { return 0; }
private:
};
//-- Particle Systems ---------------------------------------------------
// A force field can be applied to a particle system by a SpaceWarp.
// The force field provides a function of position in space, velocity
// and time that gives a force.
// The force is then used to compute an acceleration on a particle
// which modifies its velocity. Typically, particles are assumed to
// to have a normalized uniform mass==1 so the acceleration is F/M = F.
/*! \sa Class Point3, Class WSMObject.\n\n
\par Description:
A Space Warp modifier usually uses an instance of this class and implements the
<b>Force()</b> method. The force field is then applied to the particle system
when the particle system is bound to the Space Warp. This class is similar in
some respects to the Deformer class as used by a modifier. The difference is
that a deformer modifies the points of the object. A force field is really an
acceleration - it modifies velocity rather than position.\n\n
The force field provides a function of position in space, velocity and time
that gives a force. The force is then used to compute an acceleration on a
particle which modifies its velocity. Typically, particles are assumed to have
a normalized uniform mass equal to 1 so the acceleration is F/M = F. */
class ForceField : public InterfaceServer {
public:
/*! \remarks This method is called to compute a force on the particle based on its
position, velocity and the current time.
\param t The time to compute the force.
\param pos The current position of the particle.
\param vel The current velocity of the particle.
\param index The index of the particle being forced.
\return The force vector as a Point3. This vector is added to the
velocity. */
virtual Point3 Force(TimeValue t,const Point3 &pos, const Point3 &vel, int index)=0;
virtual void SetRandSeed(int seed) {}
/*! \remarks This method is callled to delete this instance of the ForceField. This
should be called, for example, by developers who use the
<b>WSMObject::GetForceField()</b> method.
\par Default Implementation:
<b>{}</b> */
virtual void DeleteThis() {}
};
// A collision object can be applied to a particle system by a SpaceWarp.
// The collision object checks a particle's position and velocity and
// determines if the particle will colide with it in the next dt amount of
// time. If so, it modifies the position and velocity.
/*! \sa Class Point3.\n\n
\par Description:
A collision object can be applied to a particle system by a Space Warp. The
collision object checks a particle's position and velocity and determines if
the particle will collide with it in the next <b>dt</b> amount of time. If so,
it modifies the position and velocity. */
class CollisionObject : public InterfaceServer {
public:
// Check for collision. Return TRUE if there was a collision and the position and velocity have been modified.
/*! \remarks This method checks a particles position and velocity to determine if there
was be a collision between the particle and this collision object. If there
was a collision, the particles position and velocity should be
modified.\n\n
The plug-in may compute a line segment between where the particle is now,
and where it will be in <b>dt</b> amount of time. The plug-in then checks
if the line segment intersects the collision object. If so, it would
compute the resulting position, and modify the velocity vector <b>vel</b>
to point in the new direction (presumably reflected across the surface
normal).\n\n
3ds Max 3.0 introduced interparticle collision (where particles may collide
with other particles). In order to implement interparticle collision (IPC)
in the presence of collision objects, it became necessary to generalize the
operation of the deflectors so that they didn't always work in discrete
time intervals.\n\n
That is, in the general case of an unidentified number of particles
interacting in an unspecified way, it was necessary to allow everything
involved in that system to update to specified times without moving
<b>past</b> that time.\n\n
In the absence of IPC enabled, the particle system calls the bound
collision objects with the parameter <b>UpdatePastCollide == TRUE</b>, and
the deflector checks all collisions, updates particles based on their
collisions with deflectors and the ensuing, remaining time intervals in
<b>dt</b> subsequent to the collisions.\n\n
In the presence of IPC that won't work. When IPC is active, all particles
need to be updated to the time of the first collision in the system in
<b>dt</b>, whether that collision be between particles or between particles
and deflectors. Thus, in the presence of IPC, all particle updates to bound
deflectors are called with <b>UpdatePastCollide == FALSE</b>. In that case,
the collision objects return both the position and velocity of the updated
particles <b>and</b> the time at which the collision occurred.\n\n
All such times are compared, along with all possible internally calculated
IPC event times. If there are any nonnegative times returned greater than
or equal to zero, all particle states are reverted to their states at the
beginning of the interval and then updated to the precise minimum time
returned as the earliest collision. <b>And then</b> everything starts up
again trying to update itself to the next integral time, when control can
pass back to whatever is asking the particles to update themselves. If
there are other collisions in that time, it happens again.\n\n
This whole set of operations happens after any true returns from the
trilinear sort/sweep correlator that looks for the <b>possibility</b> of
collisions. If there are no possible collisions, everything proceeds
through a complete interval normally.
\param t The time to check for collision.
\param pos The position of the particle to check and potentially modify.
\param vel The velocity vector of the particle to check and potentially modify.
\param dt This is an increment of time - the step size. The method checks if the
particle will collide in this amount of time.
\param index The index of the particle being collided.
\param ct An array of floating point times at which the collisions occurred.
\param UpdatePastCollide This is a flag to tell the collision object to update the particle past the
collision to the remainder of input <b>dt</b> or to output the state of the
particle at the collision. In the presence of interparticle collision
enable, we have to update to the times of collisions and then retest from
there. See the Remarks.
\return TRUE if there was a collision and the position and velocity have
been modified; otherwise FALSE. */
virtual BOOL CheckCollision(TimeValue t,Point3 &pos, Point3 &vel, float dt,int index, float *ct=NULL, BOOL UpdatePastCollide=TRUE)=0;
/*! \remarks This method provides a way of identifying the 'parent' Deflector for a
CollisionObject available to a particle system. This must be implemented by
all Deflectors. It returns the object pointer to the Deflector from which
the Collision object is derived. */
virtual Object *GetSWObject()=0;
virtual void SetRandSeed(int seed) {}
virtual void DeleteThis() {}
};
// Values returned from ParticleCenter()
#define PARTCENTER_HEAD 1 // Particle geometry lies behind the particle position
#define PARTCENTER_CENTER 2 // Particle geometry is centered around particle position
#define PARTCENTER_TAIL 3 // Particle geometry lies in front of the particle position
// The particle system class derived from GeomObject and still has
// GEOMOBJECT_CLASS_ID as its super class.
//
// Given an object, to determine if it is a ParticleObject, call
// GetInterface() with the ID I_PARTICLEOBJ or use the macro
// GetParticleInterface(anim) which returns a ParticleObject* or NULL.
/*! \sa Class GeomObject, Class ForceField, Class CollisionObject, Class ShadeContext.\n\n
\par Description:
This is the base class for creating particle system plug-ins.\n\n
Many particle systems may be derived from class <b>SimpleParticle</b> instead
of this class. See Class SimpleParticle for more details.\n\n
Note: This class is derived from GeomObject and still has
<b>GEOMOBJECT_CLASS_ID</b> as its super class. To determine if an object is a
ParticleObject, call:\n\n
<b>Animatable::GetInterface()</b> with the ID <b>I_PARTICLEOBJ</b> or use the
macro:\n\n
<b>GetParticleInterface(anim)</b> where <b>anim</b> is the object in question.
This will return a <b>ParticleObject*</b> or <b>NULL</b>. See
Class Animatable .\n\n
Note: See the method <b>Animatable::GetProperty()</b> for details on choosing
the method used to evaluate the particle system during motion blur rendering.
See Class Animatable. */
class ParticleObject : public GeomObject {
public:
BOOL IsParticleSystem() {return TRUE;}
/*! \remarks This method is called to add the force field object passed to the list of
force field objects operating on this particle system.
\param ff Points to an instance of a ForceField object.
\par Sample Code:
\code
void SimpleParticle::ApplyForceField(ForceField *ff)
{
fields.Append(1,&ff);
}
\endcode */
virtual void ApplyForceField(ForceField *ff)=0;
/*! \remarks This method is called to add the collision object passed to the list of
collision objects operating on this particle system.
\param co Points to an instance of a collision object.
\return If a particle does not support this method it should return FALSE;
otherwise return TRUE.
\par Sample Code:
\code
BOOL SimpleParticle::ApplyCollisionObject(CollisionObject *co)
{
cobjs.Append(1,&co);
return TRUE;
}
\endcode */
virtual BOOL ApplyCollisionObject(CollisionObject *co)=0; // a particle can choose no to support this and return FALSE
// A particle object IS deformable, but does not let itself be
// deformed using the usual GetPoint/SetPoint methods. Instead
// a space warp must apply a force field to deform the particle system.
/*! \remarks Implemented by the System.\n\n
This method returns TRUE to indicate it is deformable. A particle object is
deformable, but does not let itself be deformed using the usual
<b>GetPoint()</b> / <b>SetPoint()</b> methods. Instead a space warp must
apply a force field to deform the particle system. */
int IsDeformable() {return TRUE;}
// Particle objects don't actually do a shallow copy and therefore
// cannot be cached.
/*! \remarks Implemented by the System.\n\n
This method returns FALSE to indicate the object cannot be cached. Particle
objects don't perform a shallow copy and therefore cannot be cached. */
BOOL CanCacheObject() {return FALSE;}
/*! \remarks Implemented by the System.\n\n
This method is inherited from Class Object.
This is a default implementation provided for particle systems.
\param t The time to compute the normal align vector.
\param pt The point of intersection.
\param norm The normal at the point of intersection.
\return TRUE if this method is implemented to return the normal align
vector; otherwise FALSE.
\par Default Implementation:
<b>{pt=Point3(0,0,0);norm=Point3(0,0,-1);return TRUE;}</b> */
virtual BOOL NormalAlignVector(TimeValue t,Point3 &pt, Point3 &norm) {pt=Point3(0,0,0);norm=Point3(0,0,-1);return TRUE;}
// These methods provide information about individual particles
/*! \remarks Returns the position of the specified particle in world space at the time
passed.\n\n
The Particle Age texture map and the Particle Motion Blur texture map use
this method.
\param t The time to return the particle position.
\param i The index of the particle.
\note When a texture map calls these methods, the particle index <b>i</b>
is passed to the texmap in the data member <b>ShadeContext::mtlNum</b>. The
particle systems encode the index of the particle associated with the face
of the particle mesh being shaded into the <b>mtlNum</b>. For instance,
once the particle system generates a mesh to be rendered, every face of the
mesh corresponds to a particle. This isn't a one-to-one correspondance
because there are more faces than particles (if the particles are
represented as tetrahedrons there are four faces per particle). When a
texture map or material that is shading a mesh generated by a particle
system wants to know which particle the face is associated with it gets
this info out of the <b>ShadeContext::mtlNum</b>.\n\n
For example, here is a fragment of the code from the Particle Age texture
map where it evaluates the color of the point being shaded:
\code
AColor PartAgeTex::EvalColor(ShadeContext& sc)
{
...
// Evaluate...
Object *ob = sc.GetEvalObject();
if (ob && ob->IsParticleSystem()) {
ParticleObject *obj = (ParticleObject*)ob;
TimeValue t = sc.CurTime();
TimeValue age = obj->ParticleAge(t,sc.mtlNum);
TimeValue life = obj->ParticleLife(t,sc.mtlNum);
...etc.
}
}
\endcode
\par Default Implementation:
<b>{return Point3(0,0,0);}</b> */
virtual Point3 ParticlePosition(TimeValue t,int i) {return Point3(0,0,0);}
/*! \remarks Returns the velocity of the specified particle at the time passed (in 3ds
Max units per tick). This is specified as a vector. The Particle Age
texture map and the Particle Motion Blur texture map use this method.
\param t The time to return the particle velocity.
\param i The index of the particle.
\par Default Implementation:
<b>{return Point3(0,0,0);};</b> */
virtual Point3 ParticleVelocity(TimeValue t,int i) {return Point3(0,0,0);}
/*! \remarks Returns the world space size of the specified particle in at the time
passed.\n\n
The Particle Age texture map and the Particle Motion Blur texture map use
this method.
\param t The time to return the particle size.
\param i The index of the particle.
\par Default Implementation:
<b>{return 0.0f;};</b> */
virtual float ParticleSize(TimeValue t,int i) {return 0.0f;}
/*! \remarks Returns a value indicating where the particle geometry (mesh) lies in
relation to the particle position.\n\n
This is used by Particle Motion Blur for example. It gets the point in
world space of the point it is shading, the size of the particle from
<b>ParticleSize()</b>, and the position of the mesh from
<b>ParticleCenter()</b>. Given this information, it can know where the
point is, and it makes the head and the tail more transparent.
\param t The time to return the particle center.
\param i The index of the particle.
\return One of the following:\n\n
\ref PARTCENTER_HEAD\n\n
The particle geometry lies behind the particle position.\n\n
\ref PARTCENTER_CENTER\n\n
The particle geometry is centered around particle position.\n\n
\ref PARTCENTER_TAIL\n\n
The particle geometry lies in front of the particle position.
\par Default Implementation:
<b>{return PARTCENTER_CENTER;}</b> */
virtual int ParticleCenter(TimeValue t,int i) {return PARTCENTER_CENTER;}
/*! \remarks Returns the age of the specified particle -- the length of time it has been
'alive'.\n\n
The Particle Age texture map and the Particle Motion Blur texture map use
this method.
\param t Specifies the time to compute the particle age.
\param i The index of the particle.
\par Default Implementation:
<b>{return -1;}</b> */
virtual TimeValue ParticleAge(TimeValue t, int i) {return -1;}
/*! \remarks Returns the life of the particle -- the length of time the particle will be
'alive'.\n\n
The Particle Age texture map and the Particle Motion Blur texture map use
this method.
\param t Specifies the time to compute the particle life span.
\param i The index of the particle.
\par Default Implementation:
<b>{return -1;}</b> */
virtual TimeValue ParticleLife(TimeValue t, int i) {return -1;}
// This tells the renderer if the ParticleObject's topology doesn't change over time
// so it can do better motion blur. This means the correspondence of vertex id to
// geometrical vertex must be invariant.
/*! \remarks If a particle system has a fixed number of particles of fixed topology,
then it can return TRUE for this method, and the renderer will then compute
the image motion blur velocities based on the vertex motions, giving motion
blur for rotating particles etc. If the particle system is topology-varying
it should return FALSE.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual BOOL HasConstantTopology() { return FALSE; }
};
//----------------------------------------------------------------------
/*-------------------------------------------------------------------
ShapeObject: these are the open or closed hierarchical shape objects.
---------------------------------------------------------------------*/
class PolyShape;
class BezierShape;
class MeshCapInfo;
class PatchCapInfo;
class ShapeHierarchy;
// This class may be requested in the pipeline via the GENERIC_SHAPE_CLASS_ID,
// also set up in the Class_ID object genericShapeClassID
// Options for steps in MakePolyShape (>=0: Use fixed steps)
#define PSHAPE_BUILTIN_STEPS -2 // Use the shape's built-in steps/adaptive settings (default)
#define PSHAPE_ADAPTIVE_STEPS -1 // Force adaptive steps
// Parameter types for shape interpolation (Must match types in spline3d.h & polyshp.h)
#define PARAM_SIMPLE 0 // Parameter space based on segments
#define PARAM_NORMALIZED 1 // Parameter space normalized to curve length
// GenerateMesh Options
#define GENMESH_DEFAULT -1 // Use whatever is stored in the ShapeObject's UseViewport flag
#define GENMESH_VIEWPORT 0
#define GENMESH_RENDER 1
// Defines for number of ShapeObject references/subanims
#define SHAPE_OBJ_NUM_REFS 1
#define SHAPE_OBJ_NUM_SUBS 1
class IParamBlock;
class IParamMap;
#define SHAPE_RECT_RENDERPARAMS_PROPID PROPID_USER+10
//! Rectangular Shape Render Parameters API
//! This interface gives access to the new Renderable SPline parameters for Rectangular Shapes
//! The IShapeRectRenderParams interface can be retrieved like this:
//! IShapeRectRenderParams* rparams = (IShapeRectRenderParams*)obj->GetProperty(SHAPE_RECT_RENDERPARAMS_PROPID);
//! Note that this interface contains VPT and non VPT parameters. The non VPT parameters are used for the renderer
//! and the viewport in case GetViewportOrRenderer() returns true, or if GetViewportOrRenderer() returns false and GetUseViewPort() returns false.
//! Otherwise the non vpt settings only control the mesh for the renderer, not the viewport.
class IShapeRectRenderParams : public AnimProperty
{
protected :
ShapeObject *mShape;
public:
//! Constructor
//! \param so - ShapeObject that publishes this interface
IShapeRectRenderParams(ShapeObject *so) : mShape(so)
{
}
//! Gets the Rectangular setting of the shape
//! \param t - Time to get the value for
//! \return Rectangular setting of the shape
CoreExport BOOL GetRectangular(TimeValue t) const;
//! Sets the Rectangular setting of the shape
//! \param t - Time to set the value for
//! \param rectangular - if true, shape is rectangular, if false radial
CoreExport void SetRectangular(TimeValue t, BOOL rectangular);
//! Gets the Width of the rectangular section of the shape
//! \param t - Time to get the value for
//! \return Width of the rectangular section of the shape
CoreExport float GetWidth(TimeValue t) const;
//! Sets the Width of the rectangular section of the shape
//! \param t - Time to set the value for
//! \param width - Width Value (must be positive)
CoreExport void SetWidth(TimeValue t, float width);
//! Gets the Length of the rectangular section of the shape
//! \param t - Time to get the value for
//! \return Length of the rectangular section of the shape
CoreExport float GetLength(TimeValue t) const;
//! Sets the Length of the rectangular section of the shape
//! \param t - Time to set the value for
//! \param length - Length Value (must be positive)
CoreExport void SetLength(TimeValue t, float length);
//! Gets the Angle of the rectangular section of the shape
//! \param t - Time to get the value for
//! \return Angle of the rectangular section of the shape
CoreExport float GetAngle2(TimeValue t) const;
//! Sets the Angle of the rectangular section of the shape
//! \param t - Time to set the value for
//! \param angle - Angle Value for rectangular shape
CoreExport void SetAngle2(TimeValue t, float angle);
//! Gets the AspectLock parameter of the rectangular section of the shape
//! \param t - Time to get the value for
//! \return AspectLock parameter of the rectangular section of the shape
CoreExport BOOL GetAspectLock(TimeValue t) const;
//! Sets the AspectLock parameter of the rectangular section of the shape
//! \param t - Time to set the value for
//! \param aspectLock - TRUE if aspect is locked, FALSE otherwise
CoreExport void SetAspectLock(TimeValue t, BOOL aspectLock);
//! Gets the Rectangular setting of the shape for the viewport
//! \param t - Time to get the value for
//! \return Rectangular setting of the shape for the viewport
CoreExport BOOL GetVPTRectangular(TimeValue t) const;
//! Sets the Rectangular parameter of the rectangular section of the shape for the viewport
//! \param t - Time to set the value for
//! \param rectangular - if true, shape is rectangular, if false radial
CoreExport void SetVPTRectangular(TimeValue t, BOOL rectangular);
//! Gets the Width of the rectangular section of the shape for the viewport
//! \param t - Time to get the value for
//! \return Width of the rectangular section of the shape for the viewport
CoreExport float GetVPTWidth(TimeValue t) const;
//! Sets the Width of the rectangular section of the shape for the viewport
//! \param t - Time to set the value for
//! \param width - Width Value (must be positive)
CoreExport void SetVPTWidth(TimeValue t, float width);
//! Gets the Length of the rectangular section of the shape for the viewport
//! \param t - Time to get the value for
//! \return Length of the rectangular section of the shape for the viewport
CoreExport float GetVPTLength(TimeValue t) const;
//! Sets the Length of the rectangular section of the shape for the viewport
//! \param t - Time to set the value for
//! \param length - Length Value (must be positive)
CoreExport void SetVPTLength(TimeValue t, float length);
//! Gets the Angle of the rectangular section of the shape for the viewport
//! \param t - Time to get the value for
//! \return Angle of the rectangular section of the shape for the viewport
CoreExport float GetVPTAngle2(TimeValue t) const;
//! Sets the Angle of the rectangular section of the shape for the viewport
//! \param t - Time to set the value for
//! \param angle - Angle Value for rectangular shape
CoreExport void SetVPTAngle2(TimeValue t, float angle);
//! Gets the AspectLock parameter of the rectangular section of the shape for the viewport
//! \param t - Time to get the value for
//! \return AspectLock parameter of the rectangular section of the shape for the viewport
CoreExport BOOL GetVPTAspectLock(TimeValue t) const;
//! Sets the AspectLock parameter of the rectangular section of the shape for the viewport
//! \param t - Time to set the value for
//! \param aspectLock - TRUE if aspect is locked, FALSE otherwise
CoreExport void SetVPTAspectLock(TimeValue t, BOOL aspectLock);
//! Gets the AutoSmooth parameter of the shape
//! \param t - Time to get the value for
//! \return AutoSmooth parameter of the shape
CoreExport BOOL GetAutosmooth(TimeValue t) const;
//! Sets the AutoSmooth parameter of the shape for the viewport
//! \param t - Time to set the value for
//! \param autosmooth - TRUE if resulting mesh should be autosmoothed, FALSE otherwise
CoreExport void SetAutosmooth(TimeValue t, BOOL autosmooth);
//! Gets the AutoSmooth Threshold of the shape
//! \param t - Time to get the value for
//! \return AutoSmooth Threshold of the shape
CoreExport float GetAutosmoothThreshold(TimeValue t) const;
//! Sets the AutoSmooth Threshold of the shape
//! \param t - Time to set the value for
//! \param threshold - threashold angle in radians
CoreExport void SetAutosmoothThreshold(TimeValue t, float threshold);
//! ID of this AnimProperty
//! \return ID of this AnimProperty
DWORD ID() { return SHAPE_RECT_RENDERPARAMS_PROPID;}
};
/*! \sa Class GeomObject, Class PolyShape.\n\n
\par Description:
ShapeObjects are open or closed hierarchical shapes made up of one or more
pieces. This base class defines a set of methods that plug-in shapes must
implement.\n\n
Note: Many plug-in shapes may be derived from
Class SimpleSpline rather than this
class and have fewer methods to implement. See that class for more details.\n\n
Any classes subclassing
off of ShapeObject should be sure to call the ShapeObject constructor in their
constructor, in order to properly initialize the fields contained in the
ShapeObject. This is the thickness field, which specifies the
thickness of the mesh generated from the shape at rendering time. For
example:
\code
LinearShape::LinearShape() : ShapeObject()
{
...
}
\endcode
Also, the ShapeObject contains Load and Save methods, which handle the
storage of the data contained within the ShapeObject. In order to properly
store this information, classes which subclass off of ShapeObject need to call
the ShapeObject Load and Save methods before storing their information. For
example:\n\n
\code
IOResult LinearShape::Save(ISave *isave)
{
IOResult res = ShapeObject::Save(isave);
if(res != IO_OK)
return res;
...
}
IOResult LinearShape::Load(ILoad *iload)
{
IOResult res = ShapeObject::Load(iload);
if(res != IO_OK)
return res;
...
}
\endcode
The number of ShapeObject references/subanims are defined as
<b>SHAPE_OBJ_NUM_REFS</b> and <b>SHAPE_OBJ_NUM_SUBS</b> in /include/object.h
and are set to the number of references and subanims in the ShapeObject class,
you can use them to make your code more bullet-proof should the number of
references change in the future. See maxsdk/include/splshape.h for an example
of how they can be used. */
class ShapeObject : public GeomObject {
friend class SObjRenderingDlgProc;
friend class ShapePostLoadCallback;
friend class IShapeRectRenderParams;
IObjParam *ip;
IParamBlock *sopblock; // New for r4, renderable version parameter block
static IParamMap *pmap;
int loadVersion;
// Display mesh cache stuff
Mesh meshCache;
Interval cacheValid;
int cacheType;
public:
CoreExport ShapeObject();
CoreExport ~ShapeObject(); // Must call this on destruction
virtual BOOL IsShapeObject() { return TRUE; }
/*! \remarks Computes the intersection point of the ray passed and the shape.\n\n
\note This method has a default implementation and
it is not necessary to define this method in classes derived from
<b>ShapeObject</b>.
\param t The time to compute the intersection.
\param ray Ray to intersect.
\param at The point of intersection.
\param norm The surface normal at the point of intersection.
\return Nonzero if a point of intersection was found; otherwise 0.
\par Default Implementation:
<b>{return FALSE;}</b> */
virtual int IntersectRay(TimeValue t, Ray& ray, float& at, Point3& norm) {return FALSE;}
virtual void InitNodeName(MSTR& s) { s = _M("Shape"); }
SClass_ID SuperClassID() { return SHAPE_CLASS_ID; }
CoreExport virtual int IsRenderable();
/*! \remarks In order to simplify things for subclasses of ShapeObject, this method is
now available. It should be called whenever the ShapeObject-based object is
copied. It takes care of copying all the data to the ShapeObject from
another ShapeObject-based object\n\n
Implemented by the System.
\param from The ShapeObject to copy from. */
CoreExport virtual void CopyBaseData(ShapeObject &from);
// Access methods
/*! \remarks Implemented by the System.\n\n
Returns the shape's thickness setting.
\param t The time to obtain the thickness.
\param ivalid The validity interval. */
CoreExport float GetThickness(TimeValue t, Interval &ivalid);
/*! \remarks This method returns the number of sides for the cross-section of the
rendering mesh version of the shape for the specified time.
\param t The time to obtain the thickness.
\param ivalid The validity interval. */
CoreExport int GetSides(TimeValue t, Interval &ivalid);
/*! \remarks This method returns the angle that the cross-section of the rendering mesh
will be rotated to, for the specified time.
\param t The time to obtain the thickness.
\param ivalid The validity interval. */
CoreExport float GetAngle(TimeValue t, Interval &ivalid);
/*! \remarks This method returns the thickness of the viewport version of the rendering
mesh. This is not an animated parameter. */
CoreExport float GetViewportThickness();
/*! \remarks This method returns the number of sides for the cross-section for the
viewport version of the rendering mesh. This is not an animated parameter.
*/
CoreExport int GetViewportSides();
/*! \remarks This method returns the angle that the cross-section of the viewport
version of the rendering mesh will be rotated to. This is not an animated
parameter. */
CoreExport float GetViewportAngle();
/*! \remarks Implemented by the System.\n\n
The ShapeObject class now has a "renderable" flag contained within it.
Access to this is via this method and SetRenderable(). If this is set to
TRUE and the node is set to renderable, the spline will be rendered. This
defaults to FALSE. */
CoreExport BOOL GetRenderable();
/*! \remarks Implemented by the System.\n\n
Returns TRUE if the generate UVs switch is on; FALSE if off. */
CoreExport BOOL GetGenUVs();
/*! \remarks This method returns TRUE if the "Display Render Mesh" switch is on. FALSE
when the switch is off. */
CoreExport BOOL GetDispRenderMesh();
/*! \remarks This method returns TRUE if the "Use Viewport Settings" switch is on. FALSE
when the switch is off. */
CoreExport BOOL GetUseViewport();
/*! \remarks This method returns the value of the Viewport/Render switch and either
returns <b>GENMESH_VIEWPORT</b> or <b>GENMESH_RENDER</b>. */
CoreExport BOOL GetViewportOrRenderer();
/*! \remarks Implemented by the System.\n\n
Sets the thickness setting of the shape to the specified value.
\param t The time at which to set the thickness.
\param thick The new thickness setting for the shape. */
CoreExport void SetThickness(TimeValue t, float thick);
/*! \remarks This method allows you to set the number of sides for the rendering mesh
version of the shape for the specified time. The allowable ranges for this
parameter are 3-100.
\param t The time at which to set the number of sides.
\param s The number of sides you wish to set. */
CoreExport void SetSides(TimeValue t, int s);
/*! \remarks This method allows you to set the cross-section rotation angle for the
rendering mesh version of the shape, in degrees, for the specified time.
\param t The time at which to set the angle.
\param a The angle you wish to set, in degrees. */
CoreExport void SetAngle(TimeValue t, float a);
CoreExport void SetViewportThickness(float thick);
/*! \remarks This method allows you to set the number of sides for the viewport version
of the rendering mesh. This is not an animated parameter.
\param s The number of viewport sides you wish to set. */
CoreExport void SetViewportSides(int s);
/*! \remarks This method allows you to set the angle that the cross-section of the
viewport version of the rendering mesh will be rotated to, in degrees. This
is not an animated parameter.
\param a The viewport angle you wish to set, in degrees. */
CoreExport void SetViewportAngle(float a);
/*! \remarks Implemented by the System.\n\n
Sets the rendering flag to the specified value.
\param sw TRUE for on; FALSE for off. */
CoreExport void SetRenderable(BOOL sw);
/*! \remarks Implemented by the System.\n\n
Pass TRUE to set the generate UVs switch to on; FALSE to set it off.
\param sw TRUE for on; FALSE for off. */
CoreExport void SetGenUVs(BOOL sw);
/*! \remarks This method allows you to turn the "Display Render Mesh" switch on or off.
\param sw TRUE or FALSE to set or unset the "Display Render Mesh" switch. */
CoreExport void SetDispRenderMesh(BOOL sw);
/*! \remarks This method allows you to turn the "Use Viewport Settings" switch on or
off.
\param sw TRUE or FALSE to set or unset the "Use Viewport Settings" switch. */
CoreExport void SetUseViewport(BOOL sw);
/*! \remarks This method allows you to set the value of the Viewport/Render switch.
\param sw Set this parameter to <b>GENMESH_VIEWPORT</b> or <b>GENMESH_RENDER</b>. */
CoreExport void SetViewportOrRenderer(BOOL sw);
CoreExport virtual Mesh* GetRenderMesh(TimeValue t, INode *inode, View& view, BOOL& needDelete);
/*! \remarks Returns information on the rendering mesh.\n\n
Implemented by the System.
\param t The time to get the information.
\param inode The node associated with the mesh.
\param view Describes properties of the view associated with the render. See Class View.
\param nverts The number of vertices in the render mesh.
\param nfaces The number of faces in the render mesh. */
CoreExport virtual void GetRenderMeshInfo(TimeValue t, INode *inode, View& view, int &nverts, int &nfaces); // Get info on the rendering mesh
/*! \remarks This method will generate a mesh based on either the viewport or rendering
parameters for the specified time.
\param t The time at which to generate the mesh.
\param option The option can be either GENMESH_VIEWPORT, GENMESH_RENDER, or
GENMESH_DEFAULT. When using the default definition the mesh generator will
use whatever is in the Viewport/Render switch in the parameter block.
\param mesh A pointer to a Mesh object. If this is set to NULL, the mesh will be
generated and cached, but not returned. */
CoreExport virtual void GenerateMesh(TimeValue t, int option, Mesh *mesh);
/*! \remarks This method is used by the Summary Info and Object Properties dialogs to inform
the user how many vertices or CVs are in the object. The method is passed a
TimeValue and a curve index; if the curve index is \<0, the function should
return the number of vertices/CVs in the entire shape. Otherwise, it should
return the number of vertices/CVs in the specified curve.
\param t The time at which the number of vertices is to be computed.
\param curve The curve index. See note above.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int NumberOfVertices(TimeValue t, int curve = -1) { return 0; } // Informational only, curve = -1: total in all curves
/*! \remarks Returns the number of polygons in the shape. */
virtual int NumberOfCurves()=0; // Number of curve polygons in the shape
/*! \remarks This method is called to determine if the specified curve of the shape is
closed at the time passed.
\param t The time to check.
\param curve The index of the curve to check.
\return TRUE if the curve is closed; otherwise FALSE. */
virtual BOOL CurveClosed(TimeValue t, int curve)=0; // Returns TRUE if the curve is closed
/*! \remarks This method returns a point interpolated on the entire curve. This method
returns the point but you don't know which segment the point falls on. See
method <b>InterpPiece3D()</b>.
\param t The time to evaluate.
\param curve The index of the curve to evaluate.
\param param The 'distance' along the curve where 0 is the start and 1 is the end.
\param ptype The parameter type for spline interpolation. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_ptypes_for_shape.html">List of Parameter Types for
Shape Interpolation</a>.
\return The interpolated point on the curve. */
virtual Point3 InterpCurve3D(TimeValue t, int curve, float param, int ptype=PARAM_SIMPLE)=0; // Interpolate from 0-1 on a curve
/*! \remarks This method returns a tangent vector interpolated on the entire curve. Also
see method <b>TangentPiece3D()</b>.
\param t The time at which to evaluate the curve.
\param curve The index of the curve to evaluate.
\param param The 'distance' along the curve where 0.0 is the start and 1.0 is the end.\n\n
<b>int ptype=PARAM_SIMPLE</b>\n\n
The parameter type for spline interpolation. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_ptypes_for_shape.html">List of Parameter Types for
Shape Interpolation</a>.
\return The tangent vector */
virtual Point3 TangentCurve3D(TimeValue t, int curve, float param, int ptype=PARAM_SIMPLE)=0; // Get tangent at point on a curve
/*! \remarks Returns the length of the specified curve.\n\n
Note: This method makes no allowance for non-uniform scaling in the object
transform. To do that, see the following code fragment (<b>os</b> is the
<b>ObjectState</b> with the shape object and <b>xfm</b> is the NodeTM of
the shape object node).
\code
if (os.obj->SuperClassID() == SHAPE_CLASS_ID)
{
ShapeObject *sobj;
sobj = (ShapeObject *) os.obj;
int cct = sobj->NumberOfCurves();
PolyShape workShape;
sobj->MakePolyShape(ip->GetTime(), workShape);
workShape.Transform(xfm);
float len = 0.0f;
for (int i=0; i<cct; i++)
len += workShape.lines[i].CurveLength();
}
\endcode
\param t The time at which to compute the length.
\param curve The index of the curve. */
virtual float LengthOfCurve(TimeValue t, int curve)=0; // Get the length of a curve
/*! \remarks Returns the number of sub-curves in a curve.
\param t The time at which to check.
\param curve The index of the curve. */
virtual int NumberOfPieces(TimeValue t, int curve)=0; // Number of sub-curves in a curve
/*! \remarks This method returns the interpolated point along the specified sub-curve
(segment). For example consider a shape that is a single circle with four
knots. If you called this method with curve=0 and piece=0 and param=0.0
you'd get back the point at knot 0. If you passed the same parameters
except param=1.0 you'd get back the point at knot 1.
\param t The time to evaluate the sub-curve.
\param curve The curve to evaluate.
\param piece The segment to evaluate.
\param param The position along the curve to return where 0.0 is the start and 1.0 is the end.
\param ptype The parameter type for spline interpolation. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_ptypes_for_shape.html">List of Parameter Types for
Shape Interpolation</a>.
\return The point in world space. */
virtual Point3 InterpPiece3D(TimeValue t, int curve, int piece, float param, int ptype=PARAM_SIMPLE)=0; // Interpolate from 0-1 on a sub-curve
/*! \remarks Returns the tangent vector on a sub-curve at the specified 'distance' along
the curve.
\param t The time to evaluate the sub-curve.
\param curve The curve to evaluate.
\param piece The sub-curve (segment) to evaluate.
\param param The position along the curve to return where 0 is the start and 1 is the end.
\param ptype The parameter type for spline interpolation. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_ptypes_for_shape.html">List of Parameter Types for
Shape Interpolation</a>.
\return The tangent vector. */
virtual Point3 TangentPiece3D(TimeValue t, int curve, int piece, float param, int ptype=PARAM_SIMPLE)=0; // Get tangent on a sub-curve
/*! \remarks This method provides access to the material IDs of the shape. It returns
the material ID of the specified segment of the specified curve of this
shape at the time passed. There is a default implementation so there is no
need to implement this method if the shape does not support material
IDs.\n\n
Note: <b>typedef unsigned short MtlID;</b>
\param t The time to evaluate the sub-curve.
\param curve The zero based index of the curve to evaluate.
\param piece The sub-curve (segment) to evaluate.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual MtlID GetMatID(TimeValue t, int curve, int piece) { return 0; }
/*! \remarks This method is called to determine if the shape can be converted to a
bezier representation.
\return TRUE if the shape can turn into a bezier representation; otherwise
FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL CanMakeBezier() { return FALSE; } // Return TRUE if can turn into a bezier representation
/*! \remarks Creates the bezier representation of the shape.
\param t The time to convert.
\param shape The bezier representation is stored here.
\par Default Implementation:
<b>{}</b> */
virtual void MakeBezier(TimeValue t, BezierShape &shape) {} // Create the bezier representation
/*! \remarks This method is called to prepare the shape for lofting, extrusion, etc.
This methods looks at the shape organization, and puts together a shape
hierarchy. This provides information on how the shapes are nested.
\param t The time to organize the curves.
\param hier This class provides information about the hierarchy. See Class ShapeHierarchy. */
virtual ShapeHierarchy &OrganizeCurves(TimeValue t, ShapeHierarchy *hier=NULL)=0; // Ready for lofting, extrusion, etc.
/*! \remarks Create a PolyShape representation with optional fixed steps.
\param t The time to make the <b>PolyShape</b>.
\param shape The <b>PolyShape</b> representation is stored here.
\param steps The number of steps between knots. Values \>=0 indicates the use of fixed steps:\n\n
<b>PSHAPE_BUILTIN_STEPS</b>\n
Use the shape's built-in steps/adaptive settings (default).\n\n
<b>PSHAPE_ADAPTIVE_STEPS</b>\n
Force adaptive steps.\n
\param optimize If TRUE intermediate steps are removed from linear segments. */
virtual void MakePolyShape(TimeValue t, PolyShape &shape, int steps = PSHAPE_BUILTIN_STEPS, BOOL optimize = FALSE)=0; // Create a PolyShape representation with optional fixed steps & optimization
/*! \remarks This method generates a mesh capping info for the shape.
\param t The time to create the cap info.
\param capInfo The cap info to update.
\param capType See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_shape_capping_types.html">List of Cap Types</a>.
\return Nonzero if the cap info was generated; otherwise zero. */
virtual int MakeCap(TimeValue t, MeshCapInfo &capInfo, int capType)=0; // Generate mesh capping info for the shape
/*! \remarks This method creates a patch cap info out of the shape. Only implement this
method if <b>CanMakeBezier()</b> returns TRUE.
\param t The time to create the cap info.
\param capInfo The cap info to update.
\return Nonzero if the cap info was generated; otherwise zero.
\par Default Implementation:
<b>{ return 0; }</b> */
virtual int MakeCap(TimeValue t, PatchCapInfo &capInfo) { return 0; } // Only implement if CanMakeBezier=TRUE -- Gen patch cap info
/*! \remarks This method is called to attach the shape of <b>attachNode</b> to
<b>thisNode</b> at the specified time. If any endpoints of the curves in
the shape being attached are within the threshold distance to endpoints of
an existing curve, and the weld flag is TRUE, they should be welded.
\param t The time to attach.
\param thisNode This is the node associated with this shape object.
\param attachNode The node of the shape to attach.
\param weldEnds If TRUE the endpoints of the shape should be welded together (based on the
threshold below). If FALSE no welding is necessary.
\param weldThreshold If any endpoints of the curves in the shape being attached are within this
threshold distance to endpoints of an existing curve, and the weld flag is
TRUE, they should be welded
\return Return TRUE if attached; otherwise FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL AttachShape(TimeValue t, INode *thisNode, INode *attachNode, BOOL weldEnds=FALSE, float weldThreshold=0.0f) { return FALSE; } // Return TRUE if attached
// UVW Mapping switch access
virtual BOOL HasUVW() { return GetGenUVs(); }
virtual BOOL HasUVW (int mapChannel) { return (mapChannel==1) ? HasUVW() : FALSE; }
virtual void SetGenUVW(BOOL sw) { SetGenUVs(sw); }
virtual void SetGenUVW (int mapChannel, BOOL sw) { if (mapChannel==1) SetGenUVW (sw); }
// These handle loading and saving the data in this class. Should be called
// by derived class BEFORE it loads or saves any chunks
/*! \remarks Implemented by the System.\n\n
This method handles the storage of the data contained within the
ShapeObject. In order to properly store this information, classes which
subclass off of ShapeObject need to call this methods before storing their
information.
\param isave An interface for saving data. See Class ISave. */
CoreExport virtual IOResult Save(ISave *isave);
/*! \remarks Implemented by the System.\n\n
This method handles the loading of the data contained within the
ShapeObject. In order to properly load this information, classes which
subclass off of ShapeObject need to call this methods before loading their
information.
\param iload An interface for loading data. See Class ILoad. */
CoreExport virtual IOResult Load(ILoad *iload);
/*! \remarks Implemented by the System.\n\n
This is an implementation of the <b>Object</b> method. It simply returns
<b>splineShapeClassID</b>. */
CoreExport virtual Class_ID PreferredCollapseType();
/*! \remarks Implemented by the System.\n\n
This is an implementation of the <b>Object</b> method. It fills in the
property fields with the number of vertices and curves in the shape. */
CoreExport virtual BOOL GetExtendedProperties(TimeValue t, MSTR &prop1Label, MSTR &prop1Data, MSTR &prop2Label, MSTR &prop2Data);
/*! \remarks Implemented by the System.\n\n
Objects derived from this class which have RescaleWorldUnits methods
implemented need to call this method. The following example is the
SplineShape implementation of this method from core.
\code
void SplineShape::RescaleWorldUnits(float f)
{
if (TestAFlag(A_WORK1))
return;
// Call the base class's rescale (this sets the A_WORK1 flag)
ShapeObject::RescaleWorldUnits(f);
// Now rescale stuff inside our data structures
Matrix3 stm = ScaleMatrix(Point3(f, f, f));
shape.Transform(stm);
}
\endcode
Note that the A_WORK1 flags is tested first to be sure it isn't processing
the rescale twice. The code then calls ShapeObject::RescaleWorldUnits,
which sets the A_WORK1 flag and performs the necessary rescale methods for
all references for the object, and scales the renderable thickness value.
\param f The parameter to scale. */
CoreExport virtual void RescaleWorldUnits(float f);
// New reference support for r4
/*! \remarks This method will notify the Shape Object of changes in values in its parameter
block. The ShapeObject's parameter block is reference number zero. If
subclasses implement this method, they should pass any messages referring to
the ShapeObject's parameter block to it. For example:\n\n
<b>// If this isn't one of our references, pass it on to the
ShapeObject...</b>\n\n
<b>if(hTarget == GetReference(0))</b>\n\n
<b>return ShapeObject::NotifyRefChanged(</b>\n\n
<b>changeInt, hTarget, partID, message);</b>\n\n
This is a vital part of the mechanism; When a parameter in the parameter block
changes, the ShapeObject must be able to flush its cached mesh which will no
longer be valid.
\param changeInt This is the interval of time over which the message is active.
\param hTarget This is the handle of the reference target the message was sent by. The
reference maker uses this handle to know specifically which reference target
sent the message.
\param partID This contains information specific to the message passed in. Some messages
don't use the partID at all. See the section \ref Reference_Messages
for more information about the meaning of the partID for some common messages.
\param message The msg parameter passed into this method is the specific message which needs
to be handled. See \ref Reference_Messages.
\return The return value from this method is of type <b>RefResult</b>. This is
usually <b>REF_SUCCEED</b> indicating the message was processed. Sometimes, the
return value may be <b>REF_STOP</b>. This return value is used to stop the
message from being propagated to the dependents of the item. */
CoreExport virtual RefResult ShapeObject::NotifyRefChanged(Interval changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message );
/*! \remarks This method allows the ShapeObject to return a pointer to its parameter
block. Any subclasses implementing this method must pass on the call if it
indicates the ShapeObject's reference. For example:
\code
>RefTargetHandle SomeShape::GetReference(int i) {
If(i == 0) return ShapeObject::GetReference(i);
}
\endcode
\param i The reference handle to retrieve.
\return The handle to the Reference Target. */
CoreExport virtual RefTargetHandle GetReference(int i);
/*! \remarks This method sets the ShapeObject's parameter block pointer. Any subclasses
implementing this method must pass on the call to the ShapeObject if it
refers to index 0. For example:\n\n
<b>void SomeShape::SetReference(int i, RefTargetHandle rtarg) {</b>\n\n
<b>if(i == 0) ShapeObject::SetReference(i, rtarg);</b>\n\n
<b>}</b>
\param i The virtual array index of the reference to store.
\param rtarg The reference handle to store. */
CoreExport virtual void SetReference(int i, RefTargetHandle rtarg);
/*! \remarks This method returns the ShapeObject's animatable pointer. Derived classes
implementing this method must pass on references to index 0 to the
ShapeObject. For example::\n\n
<b>Animatable* SomeShape::SubAnim(int i) {</b>\n\n
<b>if(i == 0) return ShapeObject::SubAnim(i);</b>\n\n
<b>}</b>
\param i This is the index of the sub-anim to return. */
CoreExport virtual Animatable* SubAnim(int i);
/*! \remarks This method returns the name of the animatable's name. Derived classes
implementing this method must pass on references to index 0 to the
ShapeObject. For example:\n\n
<b>MSTR SomeShape::SubAnimName(int i) {</b>\n\n
<b>if(i == 0) return ShapeObject::SubAnimName(i);</b>\n\n
<b>}</b>
\param i This is the index of the sub-anim's name to return. */
CoreExport virtual MSTR SubAnimName(int i);
/*! \remarks This method returns the parameter dimension of the parameter whose index is
passed.
\param pbIndex The index of the parameter to return the dimension of.
\return Pointer to a ParamDimension. */
CoreExport ParamDimension *GetParameterDim(int pbIndex);
/*! \remarks This method returns the name of the parameter whose index is passed.
\param pbIndex The index of the parameter to return the dimension of. */
CoreExport MSTR GetParameterName(int pbIndex);
/*! \remarks This method remaps references at load time so that files saved from
previous versions of 3ds Max get their references adjusted properly to
allow for the new ShapeObject reference. If derived classes implement this
method, they must properly pass on the call to the ShapeObject's code. An
example from the SplineShape code:\n\n
<b>int SplineShape::RemapRefOnLoad(int iref) {</b>\n\n
<b>// Have the ShapeObject do its thing first...</b>\n\n
<b>iref = ShapeObject::RemapRefOnLoad(iref); </b>\n\n
<b> if(loadRefVersion == ES_REF_VER_0)</b>\n\n
<b>return iref+1;</b>\n\n
<b> return iref;</b>\n\n
<b>}</b>\n\n
Note that the SplineShape first calls ShapeObject's remapper, then applies
its remapping operation to the index returned by the ShapeObject code.
IMPORTANT NOTE: For this remapping to operate properly, the derived class
MUST call ShapeObject::Save as the first thing in its ::Save method, and
must call ShapeObject::Load as the first thing in its ::Load method. This
allows the ShapeObject to determine file versions and the need for
remapping references.
\param iref The input index of the reference.
\return The output index of the reference. */
CoreExport virtual int RemapRefOnLoad(int iref);
/*! \remarks The ShapeObject makes 1 reference; this is where it tells the system. Any
derived classes implementing this method must take this into account when
returning the number of references they make. A good idea is to implement
NumRefs in derived classes as:\n\n
<b>Int SomeShape::NumRefs() {</b>\n\n
<b>return myNumRefs + ShapeObject::NumRefs();</b>\n\n
<b>}</b>
\par Default Implementation:
<b>{return 1;}</b> */
virtual int NumRefs() {return 1;}
virtual int NumSubs() {return 1;}
/*! \remarks This method allows the ShapeObject to create its new "Rendering" rollup. To
use it, the derived class simply calls it first thing in its own
BeginEditParams method. An example from the SplineShape code:\n\n
<b>void SplineShape::BeginEditParams(IObjParam *ip, ULONG flags,Animatable
*prev )</b>\n\n
<b>{</b>\n\n
<b>ShapeObject::BeginEditParams(ip, flags, prev);</b>\n\n
<b> // ...</b>\n\n
<b>}</b>
\param ip The interface pointer passed to the plug-in.
\param flags The flags passed along to the plug-in in
<b>Animatable::BeginEditParams()</b>.
\param prev The pointer passed to the plug-in in <b>Animatable::BeginEditParams()</b>. */
CoreExport void BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev);
/*! \remarks Similarly to BeginEditParams, this method allows the ShapeObject to remove
its "Rendering" rollup. A derived class simply calls this first thing in
its own EndEditParams. An example from the SplineShape code:\n\n
<b>void SplineShape::EndEditParams( IObjParam *ip, ULONG flags,Animatable
*next )</b>\n\n
<b>{</b>\n\n
<b>ShapeObject::EndEditParams(ip, flags, next);</b>\n\n
<b>// ...</b>\n\n
<b>}</b>
\param ip The interface pointer passed to the plug-in.
\param flags The flags passed along to the plug-in in
<b>Animatable::BeginEditParams()</b>.
\param prev The pointer passed to the plug-in in <b>Animatable::BeginEditParams()</b>.
*/
CoreExport void EndEditParams( IObjParam *ip, ULONG flags,Animatable *next);
// Get the validity of the ShapeObject parts
/*! \remarks This method gets the validity interval for the ShapeObject's internal
parameters only. It DOES NOT include those of the derived classes. So, if
you called this method on a ShapeObject that was a circle with an animated
radius, you wouldn't see the effect of the animated radius on the interval
- All you'd see would be the interval of the ShapeObject's rendering
parameters. To get the entire ShapeObject's interval, you would call
<b>ShapeObject::ObjectShapeObjValidity(t)</b>.
\param t The time about which the interval is computed. */
CoreExport Interval GetShapeObjValidity(TimeValue t);
// The following displays the shape's generated mesh if necessary
/*! \remarks This method displays the shape's generated mesh if necessary. Objects
derived from ShapeObject will want to have the ShapeObject code display the
rendering mesh in the viewport; this method will do that for them. Simply
set the viewport transform and call this method. An example from the
SplineShape code:\n\n
<b>int SplineShape::Display(TimeValue t, INode *inode, ViewExp* vpt, int
flags)</b>\n\n
<b>{</b>\n\n
<b>Eval(t);</b>\n\n
<b>GraphicsWindow *gw = vpt-\>getGW();</b>\n\n
<b>gw-\>setTransform(inode-\>GetObjectTM(t));</b>\n\n
<b>ShapeObject::Display(t, inode, vpt, flags);</b>\n\n
<b>// ...</b>\n\n
<b>}</b>\n\n
If the ShapeObject's "Display Render Mesh" switch is off, it will do
nothing. Otherwise, it will display the proper mesh as specified by its
parameter block.
\param t The time to display the object.
\param inode The node to display.
\param vpt An interface pointer that may be used to call methods associated with the viewports.
\param flags See <a href="ms-its:listsandfunctions.chm::/idx_R_list_of_display_flags.html">List of Display Flags</a>.
\return The return value is not currently used. */
CoreExport int Display(TimeValue t, INode *inode, ViewExp* vpt, int flags);
// Get the bounding box for the shape, if it's active. Leaves bbox unchanged if not.
/*! \remarks This method returns a bounding box for the shape, if it's active, if the
"Display Render Mesh" switch is on. It is necessary to include this box
when computing the bounding box for a shape, otherwise the viewport display
will not work properly.
\param t The time to get the bounding box.
\param tm</b>\n\n
The points of ShapeObject are transformed by this matrix prior to the
bounding box computations. */
CoreExport virtual Box3 GetBoundingBox(TimeValue t, Matrix3 *tm=NULL);
/*! \remarks This method is very important - It causes the ShapeObject to flush its
cached rendering mesh. Most objects have their own "InvalidateGeomCache"
methods; simply call this when a shape derived from ShapeObject changes and
it will ensure that the rendering mesh is regenerated the next time it is
evaluated. Failure to call this method will result in improper rendering
mesh updates. */
CoreExport virtual void InvalidateGeomCache();
//! \brief Associates data passed in to given id
/*! Retains and associates passed in AnimProperty data to the id passed in by client.
\param id An id used to identify the property.
\param data A pointer (needs to be castable to AnimProperty *) that contains the
data to be kept.
\return returns 1
*/
int SetProperty(ULONG id, void *data)
{
AnimProperty *prop = (AnimProperty *)GetProperty(id);
if (prop) prop = (AnimProperty*)data;
else
{
prop = (AnimProperty *)data;
aprops.Append(1, &prop);
}
return 1;
}
//! \brief Retrieves data associated with id.
/*! Retrieves the AnimProperty data associated with the passed in id.
\param id Id that is associated with desired data.
\return The associated data (castable to AnimProperty *), or NULL if no
data is associated with this id. */
void *GetProperty(ULONG id)
{
for(int i = 0;i<aprops.Count();i++)
if (aprops[i] && aprops[i]->ID() == id )
return aprops[i];
return NULL;
}
// Get/Set the UsePhyicalScaleUVs flag. When true, the UV's
// assigned to renderable spline are scaled to the size
// of the object.
/*! \remarks Queries whether if real world texture size is used or not. */
CoreExport BOOL GetUsePhysicalScaleUVs();
/*! \remarks Sets whether real world texture size is used or not. */
CoreExport void SetUsePhysicalScaleUVs(BOOL flag);
private:
/*! Adjusts spinner to correctly reflect current aspect ratio of viewport or renderer.
\param hWnd Handle to spinner whose aspect has changed.
*/
void SetAspect(HWND hWnd);
/*!Calculates aspect ratio of viewport or renderer settings.
\param t time value which calculation is made at
\param viewport control parameter to indicate whether viewport or renderer is desired
\return length/width calculated aspect ratio
*/
float GetAspect(TimeValue t, BOOL viewport);
void CheckAspectLock(HWND hWnd);
/*!An internal callback method for when the aspect ratio of the viewport or renderer changes.
\param hWnd Handle to spinner whose aspect has changed.
*/
void OnAspectChange(HWND hWnd);
void OnLengthWidthChange(HWND hWnd, BOOL lengthChange);
/*! Internal method for determining whether viewport or render params should be used.
\return TRUE if viewport params should be used, FALSE otherwise
*/
BOOL UseViewOrRenderParams();
BOOL CanLockAspect(BOOL vpt);
};
// Set ShapeObject's global Constant Cross-Section angle threshold (angle in radians) --
// Used for renderable shapes.
CoreExport void SetShapeObjectCCSThreshold(float angle);
/*-------------------------------------------------------------------
WSMObject : This is the helper object for the WSM modifier
---------------------------------------------------------------------*/
/*! \sa Class Object, Class SimpleWSMObject, Class ForceField, Class CollisionObject.\n\n
\par Description:
This class is a base class used to derived the helper object for a space warp
modifier (WSM Modifier).\n\n
World Space Object plug-ins use a Super Class ID of <b>WSM_OBJECT_CLASS_ID</b>.
*/
class WSMObject : public Object {
public:
/*! \remarks Implemented by the System.\n\n
Returns the super class ID of this plug-in type:
<b>WSM_OBJECT_CLASS_ID</b>. */
SClass_ID SuperClassID() { return WSM_OBJECT_CLASS_ID; }
/*! \remarks When the user binds a node to a space warp, a new modifier must be created
and added to the node's WSM derived object. This method creates the new
modifier.
\param node The node of the WSMObject.
\return A pointer to the new modifier. */
virtual Modifier *CreateWSMMod(INode *node)=0;
/*! \remarks This is a method of <b>Object</b>. Below is shown the default
implementation provided by this class.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual int UsesWireColor() { return FALSE; } // TRUE if the object color is used for display
/*! \remarks This is a method of <b>Object</b>. Below is shown the default
implementation provided by this class.
\par Default Implementation:
<b>{pt=Point3(0,0,0);norm=Point3(0,0,-1);return TRUE;}</b> */
virtual BOOL NormalAlignVector(TimeValue t,Point3 &pt, Point3 &norm) {pt=Point3(0,0,0);norm=Point3(0,0,-1);return TRUE;}
/*! \remarks Returns TRUE if spacewarp or collision object supports Dynamics; otherwise
FALSE.
\par Default Implementation:
<b>{ return FALSE; }</b> */
virtual BOOL SupportsDynamics() { return FALSE; } // TRUE if spacewarp or collision object supports Dynamics
/*! \remarks Returns a pointer to a <b>ForceField</b>. This pointer can be used during
dynamics calculations, but should not be hung on to after that. For
example, you shouldn't have the pointer long enough for it to be possible
for the user to delete the space warp object. When you're done using the
<b>ForceField</b> call its <b>DeleteThis()</b> method. This method may be
called several times on the same space warp object with different
<b>INode</b>* if it is instanced.
\param node This is the space warp object's node.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual ForceField *GetForceField(INode *node) {return NULL;}
/*! \remarks This method returns the collision object for the WSM. This works just like
<b>GetForceField()</b> documented above.
\param node This is the space warp object's node.
\par Default Implementation:
<b>{return NULL;}</b> */
virtual CollisionObject *GetCollisionObject(INode *node) {return NULL;}
CoreExport void* GetInterface(ULONG id);
};
//---------------------------------------------------------------------------------
class ControlMatrix3;
// Used with EnumModContexts()
/*! \sa Class ModContext.\n\n
\par Description:
Callback object used with <b>Modifier::EnumModContexts()</b>. The <b>proc()</b>
method is called by the system. */
class ModContextEnumProc: public MaxHeapOperators {
public:
/*! \remarks This is called by <b>Modifier::EnumModContexts().</b>
\param mc The ModContext.
\return Return FALSE to stop, TRUE to continue.\n\n
\sa <b>Modifier::EnumModContexts(),</b>
Modifier. */
virtual BOOL proc(ModContext *mc)=0; // Return FALSE to stop, TRUE to continue.
};
/*-------------------------------------------------------------------
Modifier: these are the ObjectSpace and World Space modifiers: They are
subclassed off of BaseObject so that they can put up a graphical
representation in the viewport.
---------------------------------------------------------------------*/
/*! \sa Class BaseObject, Class ObjectState, Class ModContext, Class ModContextEnumProc, Class Interval, Class ISave, Class ILoad, Class Class_ID.\n\n
\par Description:
This is the class from which you may derive Object Space and Space Warp (World
Space) Modifier plug-ins. This class is subclassed off of <b>BaseObject</b> so
the modifier can put up a graphical representation in the viewport to use as a
gizmo.
\par Method Groups:
See <a href="class_modifier_groups.html">Method Groups for Class Modifier</a>. */
class Modifier : public BaseObject {
friend class ModNameRestore;
MSTR modName;
public:
/*! \remarks Implemented by the System.\n\n
Returns the name of the modifier. */
CoreExport virtual MSTR GetName();
/*! \remarks Implemented by the System.\n\n
Sets the name of the modifier to the name passed.
\param n Specifies the name to set. */
CoreExport virtual void SetName(MSTR n);
SClass_ID SuperClassID() { return OSM_CLASS_ID; }
// Disables all mod apps that reference this modifier _and_ have a select
// anim flag turned on.
/*! \remarks This method is used internally. */
void DisableModApps() { NotifyDependents(FOREVER,PART_OBJ,REFMSG_DISABLE); }
/*! \remarks This method is used internally. */
void EnableModApps() { NotifyDependents(FOREVER,PART_OBJ,REFMSG_ENABLE); }
// This disables or enables the mod. All mod apps referencing will be affected.
/*! \remarks Implemented by the System.\n\n
This disables the modifier in the history browser (modifier stack). */
void DisableMod() {
SetAFlag(A_MOD_DISABLED);
NotifyDependents(FOREVER,PART_ALL|PART_OBJECT_TYPE,REFMSG_CHANGE);
}
/*! \remarks Implemented by the System.\n\n
This enables the modifier in the history browser (modifier stack). */
void EnableMod() {
ClearAFlag(A_MOD_DISABLED);
NotifyDependents(FOREVER,PART_ALL|PART_OBJECT_TYPE,REFMSG_CHANGE);
}
/*! \remarks Implemented by the System.\n\n
This returns the status (enabled or disabled) of the modifier in the
history browser.
\return Nonzero if enabled; otherwise 0.\n\n
*/
int IsEnabled() { return !TestAFlag(A_MOD_DISABLED); }
// Same as above but for viewports only
/*! \remarks Implemented by the System.\n\n
Disables the modifier in the viewports (it remains active in the renderer
unless <b>DisableMod()</b> above is used). */
void DisableModInViews() {
SetAFlag(A_MOD_DISABLED_INVIEWS);
NotifyDependents(FOREVER,PART_ALL|PART_OBJECT_TYPE,REFMSG_CHANGE);
}
/*! \remarks Implemented by the System.\n\n
Enables the modifier in the viewports. */
void EnableModInViews() {
ClearAFlag(A_MOD_DISABLED_INVIEWS);
NotifyDependents(FOREVER,PART_ALL|PART_OBJECT_TYPE,REFMSG_CHANGE);
}
/*! \remarks Implemented by the System.\n\n
Returns nonzero if the modifier is enabled in the viewports; otherwise
zero. */
int IsEnabledInViews() { return !TestAFlag(A_MOD_DISABLED_INVIEWS); }
// Same as above but for renderer only
/*! \remarks Implemented by the System.\n\n
This turns off the modifier in the renderer\n\n
*/
void DisableModInRender() {
SetAFlag(A_MOD_DISABLED_INRENDER);
NotifyDependents(FOREVER,PART_ALL|PART_OBJECT_TYPE,REFMSG_CHANGE);
}
/*! \remarks Implemented by the System.\n\n
This turns on the modifier in the renderer\n\n
*/
void EnableModInRender() {
ClearAFlag(A_MOD_DISABLED_INRENDER);
NotifyDependents(FOREVER,PART_ALL|PART_OBJECT_TYPE,REFMSG_CHANGE);
}
/*! \remarks Implemented by the System.\n\n
This returns the status (enabled or disabled) of the modifier in the
renderer.
\return Nonzero if enabled; otherwise 0.\n\n
*/
int IsEnabledInRender() { return !TestAFlag(A_MOD_DISABLED_INRENDER); }
/*! \remarks This method returns the validity interval of a modifier. It is simply the
combination of the validity of all the modifier's parameters. It's used to
determine when to cache in the pipeline, but is not directly responsible
for determining when <b>ModifyObject()</b> is called. <b>ModifyObject()</b>
is called when the pipeline needs to be evaluated either because someone
sent a \ref REFMSG_CHANGE message or the validity of the object does not
include the current time.
\par If a modifier is not animated it's OK to simply return <b>FOREVER</b> from
this method. In the case where the modifier changes because a user changes
a non-animated control in the user interface (for instance a check box),
you can cause reevaluation by notifying your dependents of the change, i.e.:
\code
<b>NotifyDependents(FOREVER, PART_ALL, REFMSG_CHANGE);</b>
\endcode
\param t The time to calculate the Interval.
\sa Advanced Topics on
<a href="ms-its:3dsmaxsdk.chm::/start_conceptual_overview.html#heading_08">Intervals</a>.
*/
CoreExport virtual Interval LocalValidity(TimeValue t);
/*! \remarks These are channels that the modifier needs in order to perform its
modification. This should at least include the channels specified in
<b>ChannelsChanged()</b> but may include more.\n\n
Note that <b>ChannelsUsed()</b> is called many times but the channels
returned should not change on the fly.
\return The channels required. See \ref ObjectChannelBitFlags.
\par Sample Code:
\code
{ return GEOM_CHANNEL|TOPO_CHANNEL; }
\endcode */
virtual ChannelMask ChannelsUsed()=0;
/*! \remarks These are the channels that the modifier actually modifies. Note that
<b>ChannelsChanged()</b> is called many times but the channels returned
should not change on the fly.
\return The channels that are changed. See \ref ObjectChannelBitFlags */
virtual ChannelMask ChannelsChanged()=0;
// this is used to invalidate cache's in Edit Modifiers:
/*! \remarks This method is called when an item in the modifier stack before this
modifier sends a \ref REFMSG_CHANGE message via
<b>NotifyDependents()</b>.\n\n
Consider the following example: Assume the modifier stack contains a Sphere
Object, then a Bend, then a Edit Mesh. The Edit Mesh modifier does not have
a reference to the Bend or the Sphere because it does not officially depend
on these items. However it does depend on them in a certain sense, because
it modifies the data that these items produce. So, if they change it may
affect the modifier. A modifier may build a cache based on its input
object. The modifier needs a way to know when to discard this cache because
the input object has changed. Whenever one of the items before this
modifier in the stack sends out a \ref REFMSG_CHANGE message via
<b>NotifyDependents()</b> to indicate it has changed this method is called.
The modifier may respond in a way appropriate to it, for example by
discarding its cache of the input object.\n\n
It is not legal, to issue a <b>NotifyDependent()'s</b> in the
<b>NotifyInputChanged()</b> method of a modifier, without checking for
reentrancy. Imagine, you have an instanced modifier applied to the same
object in the stack. Sending a refmsg from the <b>NotifyInputChanged</b>
method will casue an endles loop. Simply putting a guard in, that checks
for reentrancy should get rid of the problem.
\param changeInt This is the interval from the message. It is reserved for future use - now
it will always be FOREVER.
\param partID This is the partID from the message.
\param message This is the message sent.
\param mc The ModContext for the pipeline that changed. If a modifier is applied to
multiple objects, then there are ModApps in each pipeline that it is
applied to. These ModApps are pointing to the same modifier. Consider the
following example: Say you apply a Bend modifier to a Sphere, a Cylinder
and a Box object. There are three ModApps but only one Bend modifier. Then
you go to the Sphere and adjust its Radius. This will cause
<b>NotifyInputChanged()</b> to be called on the Bend because the Bend's
input changed. However only one of its inputs changed - only the Sphere
changed and not the Cylinder or the Box. Therefore
<b>NotifyInputChanged()</b> will be called once, and the ModContext passed
in will be for the Sphere's changed pipeline. It is possible that all three
objects could change at the same time. If an instanced float controller was
assigned to the radius, width, and height - one parameter for each object -
then the controller was adjusted in the function curve editor, all three
items would change. In this case <b>NotifyInputChanged()</b> would be
called three times on the Bend. Once for each pipeline, once with each
ModContext. */
virtual void NotifyInputChanged(Interval changeInt, PartID partID, RefMessage message, ModContext *mc) {}
// This method indicates if the modifier changes the selection type channel or not.
// If a modifier wants to change dynamically if it changes the subobj sel type
// or not, it can overwrite this method.
// ChannelsChanged() however can not be dynamically implemented.
/*! \remarks If a modifier want to make it possible to sitch dynamically between
changing the selection type that flows up the stack, or leaving it like it
is, it can overwrite this. The default implementation indicates that it
changes the selection type, if the <b>SUBSEL_TYPE_CHANNEL</b> is part of
<b>ChannelsChanged()</b>. Note that <b>ChannelsChanged()</b> can not
dynamically changed for various reasons.
\par Default Implementation:
<b>{ return ChannelsChanged()\&SUBSEL_TYPE_CHANNEL ? true : false; }</b> */
virtual bool ChangesSelType(){ return ChannelsChanged()&SUBSEL_TYPE_CHANNEL ? true : false;}
// These call ChannelsUsed/Changed() but also OR in GFX_DATA_CHANNEL as appropriate.
/*! \remarks Returns the same value as <b>ChannelsUsed()</b> above except
<b>GFX_DATA_CHANNEL</b> will be ORed in if the <b>TOPO_CHANNEL</b> or the
<b>TEXMAP_CHANNEL</b> are being used. */
CoreExport ChannelMask TotalChannelsUsed();
/*! \remarks Returns the same value as <b>ChannelsChanged()</b> above
except <b>GFX_DATA_CHANNEL</b> will be ORed in if the <b>TOPO_CHANNEL</b>,
the <b>TEXMAP_CHANNEL</b> , or the <b>VERTCOLOR_CHANNEL</b> are being
changed. */
CoreExport ChannelMask TotalChannelsChanged();
// This is the method that is called when the modifier is needed to
// apply its effect to the object. Note that the INode* is always NULL
// for object space modifiers.
/*! \remarks This is the method that actually modifies the input object. This method is
responsible for altering the object and then updating the validity interval
of the object to reflect the validity of the modifier.
\param t The time at which the modification is being done.
\param mc A reference to the ModContext.
\param os The object state flowing through the pipeline. This contains a pointer to
the object to modify.
\param node The node the modifier is applied to. This parameter is always NULL for
Object Space Modifiers and non-NULL for World Space Modifiers (Space
Warps). This is because a given WSM is only applied to a single node at a
time whereas an OSM may be applied to several nodes. This may be used for
example by particle system space warps to get the transformation matrix of
the node at various times.
\sa The topic on <a href="ms-its:3dsmaxsdk.chm::/mods_modifiers.html">Modifiers</a> in the
Programmers Guide. */
virtual void ModifyObject(TimeValue t, ModContext &mc, ObjectState* os, INode *node)=0;
// this should return FALSE for things like edit modifiers
/*! \remarks This method is no longer used. */
virtual int NeedUseSubselButton() { return 1; }
// Modifiers that place a dependency on topology should return TRUE
// for this method. An example would be a modifier that stores a selection
// set base on vertex indices.
/*! \remarks Modifiers that place a dependency on topology should return TRUE for this
method. An example would be a modifier that stores a selection set base on
vertex indices. This modifier depends on the indices being intact for it to
operate correctly.
\param mc Reference to the ModContext.
\par Default Implementation:
<b>{ returns FALSE; }</b>
\return TRUE if the modifier depends on topology; otherwise FALSE. */
virtual BOOL DependOnTopology(ModContext &mc) {return FALSE;}
// this can return:
// DEFORM_OBJ_CLASS_ID -- not really a class, but so what
// MAPPABLE_OBJ_CLASS_ID -- ditto
// TRIOBJ_CLASS_ID
// BEZIER_PATCH_OBJ_CLASS_ID
/*! \remarks This is the type of object that the modifier knows how to modify. Simple
modifiers that just modify points of an object can operate on generic
'Deformable' objects. Deformable objects are any type of object that has
points. A modifier could also work on a particular type of object such as a
TriObject or PatchObject.
\return The Class_ID of the item. You can request any Class_ID for your
input type. For example, <b>Class_ID(OMNI_LIGHT_CLASS_ID, 0)</b>. See
<a href="ms-its:listsandfunctions.chm::/idx_R_list_of_class_ids.html">List of Class_IDs</a>. */
virtual Class_ID InputType()=0;
virtual void ForceNotify(Interval& i)
{NotifyDependents(i,ChannelsChanged(),REFMSG_CHANGE );}
/*! \remarks When a 3ds Max file is being saved, this method is called so that the
modifier can save the localData structure that is hung off each ModContext.
If the modifier doesn't store any data in the ModContext it can ignore this
method.
\param isave You may use this pointer to call methods of ISave to write data.
\param ld Pointer to the LocalModData for the modifier.
\return One of the following values: <b>IO_OK, IO_ERROR</b>. */
virtual IOResult SaveLocalData(ISave *isave, LocalModData *ld) { return IO_OK; }
/*! \remarks When a 3ds Max file is being loaded, this method is called so that the
modifier can load the LocalModData structure that is hung off each
ModContext. If the modifier doesn't store any data in the ModContext it can
ignore this method.
\param iload You may use this pointer to call methods of ILoad to read data.
\param pld A pointer to a pointer in the ModContext. The modifier must set this
pointer to point at a new LocalModData derived class.
\return One of the following values: <b>IO_OK, IO_ERROR</b>. */
virtual IOResult LoadLocalData(ILoad *iload, LocalModData **pld) { return IO_OK; }
// These handle loading and saving the modifier name. Should be called
// by derived class BEFORE it loads or saves any chunks
/*! \remarks Implemented by the System.\n\n
This method handles saving the modifier name. This method should be called
by the derived class BEFORE it saves any chunks. See the sample code below.
\param isave You may use this pointer to call methods of ISave to write data.
\return One of the following values: <b>IO_OK, IO_ERROR</b>.
\par Sample Code:
\code
IOResult DispMod::Save(ISave *isave)
{
// First save the modifier name by calling the base class version.
Modifier::Save(isave);
// Then save this modifiers data.
isave->BeginChunk(BMIO_CHUNK);
bi.Save(isave);
isave->EndChunk();
return IO_OK;
}
\endcode */
CoreExport IOResult Save(ISave *isave);
/*! \remarks Implemented by the System.
\param iload You may use this pointer to call methods of ILoad to read data.
\return One of the following values: <b>IO_OK, IO_ERROR</b>. */
CoreExport IOResult Load(ILoad *iload);
// This will call proc->proc once for each application of the modifier.
/*! \remarks Implemented by the System.\n\n
This method will call the callback object proc method once for each
application of the modifier.
\param proc The callback object whose proc method is called.
\sa Class ModContextEnumProc. */
CoreExport void EnumModContexts(ModContextEnumProc *proc);
// This method will return the IDerivedObject and index of this modifier
// for a given modifier context.
/*! \remarks This method will retrieve the IDerivedObject and index of this modifier for
a given modifier context.
\param mc Points to the ModContext for the modifier.
\param derObj A pointer to the IDerivedObject is returned here.
\param modIndex The zero based index of the modifier in the derived object is returned here. */
CoreExport void GetIDerivedObject(ModContext *mc, IDerivedObject *&derObj, int &modIndex);
// In case the modifier changes the object type (basically the os->obj pointer in ModifyObject)
// *and* changes the ExtensionChannel, it has to overwrite this method and copy only the channels
// that it doesn't modify/added already to the new object.
/*! \remarks In case the modifier changes the object type (basically the os-\>obj
pointer in ModifyObject) *and* changes the ExtensionChannel, it has to
overwrite this method and copy only the channels that it doesn't
modify/added already to the new object.
\param fromObj
\param toObj
\par Default Implementation:
<b>{ toObj-\>CopyAdditionalChannels(fromObj);}</b> */
CoreExport virtual void CopyAdditionalChannels(Object *fromObj, Object *toObj) { toObj->CopyAdditionalChannels(fromObj);}
// Animatable Overides...
CoreExport SvGraphNodeReference SvTraverseAnimGraph(IGraphObjectManager *gom, Animatable *owner, int id, DWORD flags);
CoreExport MSTR SvGetName(IGraphObjectManager *gom, IGraphNode *gNode, bool isBeingEdited);
CoreExport bool SvCanSetName(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvSetName(IGraphObjectManager *gom, IGraphNode *gNode, MSTR &name);
CoreExport bool SvHandleDoubleClick(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport COLORREF SvHighlightColor(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvIsSelected(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport MultiSelectCallback* SvGetMultiSelectCallback(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvCanSelect(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvCanInitiateLink(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvCanConcludeLink(IGraphObjectManager *gom, IGraphNode *gNode, IGraphNode *gNodeChild);
CoreExport bool SvLinkChild(IGraphObjectManager *gom, IGraphNode *gNodeThis, IGraphNode *gNodeChild);
CoreExport bool SvCanRemoveThis(IGraphObjectManager *gom, IGraphNode *gNode);
CoreExport bool SvRemoveThis(IGraphObjectManager *gom, IGraphNode *gNode);
private:
};
/*! \sa Class Modifier, Class SimpleMod.\n\n
\par Description:
This is a base class developers creating object space modifiers may derives
their plug-ins from. It simply provides a default implementation of
<b>SuperClassID()</b>. */
class OSModifier : public Modifier {
public:
/*! \remarks Implemented by the System.\n\n
Returns the Super Class ID of this plug-in type: <b>OSM_CLASS_ID</b>. */
SClass_ID SuperClassID() { return OSM_CLASS_ID; }
};
/*! \sa Class Modifier, SimpleWSMMod.\n\n
\par Description:
This is a base class for creating world space modifiers. It simply provides a
default implementation of <b>SuperClassID()</b>.\n\n
World Space Modifier plug-ins use a Super Class ID of <b>WSM_CLASS_ID</b>. <br>
*/
class WSModifier : public Modifier {
public:
/*! \remarks Implemented by the System.\n\n
Returns the Super Class ID of this plug-in type: <b>WSM_CLASS_ID</b>. */
SClass_ID SuperClassID() { return WSM_CLASS_ID; }
};
CoreExport void MakeHitRegion(HitRegion& hr, int type, int crossing, int epsi, IPoint2 *p);
/*! \sa Class DrawLineProc, Class BoxLineProc, Class GraphicsWindow.\n\n
\par Description:
This is a callback used to draw a series of lines. A developer would implement
a class derived from this one that has a <b>GraphicsWindow</b> pointer within
it. This is the base class used by <b>DrawLineProc</b> and <b>BoxLineProc</b>.
Below is the code from DrawLineProc showing how this is used:\n\n
<b>class DrawLineProc:public PolyLineProc {</b>\n\n
<b>GraphicsWindow *gw;</b>\n\n
<b></b>\n\n
<b>DrawLineProc() { gw = NULL; }</b>\n\n
<b>DrawLineProc(GraphicsWindow *g) { gw = g; }</b>\n\n
<b>int proc(Point3 *p, int n)</b>\n\n
<b>{ gw-\>polyline(n, p, NULL, NULL, 0, NULL); return 0; }</b>\n\n
<b>void SetLineColor(float r, float g, float b)</b>\n\n
<b>{gw-\>setColor(LINE_COLOR,r,g,b);}</b>\n\n
<b>};</b>\n\n
Typically a developer would not have to use this class, but would rather use
Class DrawLineProc, and
Class BoxLineProc. */
class PolyLineProc: public MaxHeapOperators {
public:
/*! \remarks Draws a polyline between the specified points.
\param p Array of vertices of the polyline.
\param n Number of vertices in the polyline. */
virtual int proc(Point3 *p, int n)=0;
/*! \remarks Sets the color used to draw the polyline.
\param r Red component in the range 0.0 to 1.0
\param g Green component in the range 0.0 to 1.0
\param b Blue component in the range 0.0 to 1.0 */
virtual void SetLineColor(float r, float g, float b) {}
virtual void SetLineColor(Point3 c) {}
virtual void Marker(Point3 *p,MarkerType type) {}
};
/*! \sa Class PolyLineProc, Class GraphicsWindow\n\n
\par Description:
This class provides a simplified way to draw a connected series of lines to the
GraphicsWindow passed to the class constructor. */
class DrawLineProc : public PolyLineProc {
GraphicsWindow *gw;
public:
/*! \remarks Constructor. The graphics window pointer is set to NULL. */
DrawLineProc() { gw = NULL; }
/*! \remarks Constructor. The graphics window pointer is set to <b>g</b>.
*/
DrawLineProc(GraphicsWindow *g) { gw = g; }
/*! \remarks Implemented by the System.\n\n
Draws a connected series of lines between the points to the GraphicsWindow
passed to the class constructor.
\param p Array of vertices of the polyline.
\param n Number of vertices in the polyline. */
int proc(Point3 *p, int n) { gw->polyline(n, p, NULL, NULL, 0, NULL); return 0; }
/*! \remarks Implemented by the System.\n\n
Sets the color used to draw the lines.
\param r Red component in the range 0.0 to 1.0
\param g Green component in the range 0.0 to 1.0
\param b Blue component in the range 0.0 to 1.0 */
void SetLineColor(float r, float g, float b) {gw->setColor(LINE_COLOR,r,g,b);}
void SetLineColor(Point3 c) {gw->setColor(LINE_COLOR,c);}
void Marker(Point3 *p,MarkerType type) {gw->marker(p,type);}
};
/*! \sa Class PolyLineProc.\n\n
\par Description:
This class provides a bounding box and a matrix. It will compute a bounding box
based on a set of points passed to it after these points have been transformed
by the matrix. All methods of this class are implemented by the system. */
class BoxLineProc : public PolyLineProc {
Box3 box;
Matrix3 *tm;
public:
/*! \remarks Constructor. The bounding box is set to empty. */
BoxLineProc() { box.Init();}
/*! \remarks Constructor. The bounding box is set to empty and the matrix
is initialized to the matrix passed. */
BoxLineProc(Matrix3* m) { tm = m; box.Init(); }
/*! \remarks Returns the computed box. */
Box3& Box() { return box; }
/*! \remarks Implemented by the System.\n\n
This takes the points passed and expands the bounding box to include the
points after they have been transformed by the matrix.
\param p The points to include
\param n Number of points.
\return Always returns zero. */
CoreExport int proc(Point3 *p, int n);
CoreExport void Marker(Point3 *p,MarkerType type);
};
// Apply the PolyLineProc to each edge (represented by an array of Point3's) of the box
// after passing it through the Deformer def.
CoreExport void DoModifiedBox(Box3& box, Deformer &def, PolyLineProc& lp);
CoreExport void DoModifiedLimit(Box3& box, float z, int axis, Deformer &def, PolyLineProc& lp);
CoreExport void DrawCenterMark(PolyLineProc& lp, Box3& box );
// Some functions to draw mapping icons
CoreExport void DoSphericalMapIcon(BOOL sel,float radius, PolyLineProc& lp);
CoreExport void DoCylindricalMapIcon(BOOL sel,float radius, float height, PolyLineProc& lp);
CoreExport void DoPlanarMapIcon(BOOL sel,float width, float length, PolyLineProc& lp);
//---------------------------------------------------------------------
// Data structures for keeping log of hits during sub-object hit-testing.
//---------------------------------------------------------------------
class HitLog;
/*! \sa Class HitLog, Class HitData\n\n
\par Description:
This class provides a data structure used during sub-object hit-testing.
\par Data Members:
<b>INode *nodeRef;</b>\n\n
Points the node that was hit.\n\n
<b>ModContext *modContext;</b>\n\n
Points to the ModContext of the modifier.\n\n
<b>DWORD distance;</b>\n\n
The 'distance' of the hit. To classify as a hit, the sub-object component must
be within some threshold distance of the mouse. This distance is recorded in
the hit record so that the closest of all the hits can be identified. What the
distance actually represents depends on the rendering level of the viewport.
For wireframe modes, it refers to the distance in the screen XY plane from the
mouse to the sub-object component. In a shaded mode, it refers to the Z depth
of the sub-object component. In both cases, smaller values indicate that the
sub-object component is 'closer' to the mouse cursor.\n\n
<b>ulong hitInfo;</b>\n\n
A general unsigned long value. Most modifiers will just need this to identity
the sub-object element. The edit mesh modifier uses the value to store the
index of the vertex or face that was hit for example.\n\n
<b>HitData *hitData;</b>\n\n
In case 4 bytes is not enough space to identity the sub-object element, this
pointer is available. To use this, a developer would define a class derived
from HitData that would contain the necessary data. The HitData class has one
member function, a virtual destructor, so the derived class can be properly
deleted when the HitRecord instance is deleted. */
class HitRecord: public MaxHeapOperators {
friend class HitLog;
HitRecord *next;
public:
INode *nodeRef;
ModContext *modContext;
DWORD distance;
ulong hitInfo;
HitData *hitData;
/*! \remarks Constructor. The following initialization is performed:
<b>next = NULL; modContext = NULL; distance = 0; hitInfo = 0; hitData =
NULL;</b> */
HitRecord() { next = NULL; modContext = NULL; distance = 0; hitInfo = 0; hitData = NULL;}
/*! \remarks Constructor. The data members are initialized to the data passed.
*/
HitRecord(INode *nr, ModContext *mc, DWORD d, ulong inf, HitData *hitdat) {
next = NULL;
nodeRef = nr; modContext = mc; distance = d; hitInfo = inf; hitData = hitdat;
}
/*! \remarks Constructor. The data members are initialized to the data passed.
*/
HitRecord(HitRecord *n,INode *nr, ModContext *mc, DWORD d, ulong inf, HitData *hitdat) {
next = n;
nodeRef = nr; modContext = mc; distance = d; hitInfo = inf; hitData = hitdat;
}
/*! \remarks Implemented by the System.\n\n
Each <b>HitRecord</b> maintains a pointer to another <b>HitRecord</b>. This
method returns the next hit record. */
HitRecord * Next() { return next; }
/*! \remarks Implemented by the System.\n\n
Destructor. If <b>HitData</b> has been allocated, it is deleted as well. */
CoreExport ~HitRecord();
};
/*! \sa Class HitRecord, Class HitData\n\n
\par Description:
This class provides a data structure for keeping a log of hits during
sub-object hit-testing. It provides a list of <b>HitRecords</b> that may be
added to and cleared. A developer may also request the 'closest' hit record in
the list. */
class HitLog: public MaxHeapOperators {
HitRecord *first;
int hitIndex;
bool hitIndexReady; // CAL-07/10/03: hitIndex is ready to be increased.
public:
/*! \remarks Constructor. The list of HitRecords is set to NULL. */
HitLog() { first = NULL; hitIndex = 0; hitIndexReady = false; }
/*! \remarks Destructor. Clears the hit log. */
~HitLog() { Clear(); }
/*! \remarks Clears the log of hits by deleting the list of HitRecords. */
CoreExport void Clear();
CoreExport void ClearHitIndex(bool ready = false) { hitIndex = 0; hitIndexReady = ready; }
CoreExport void IncrHitIndex() { if (hitIndexReady) hitIndex++; else hitIndexReady = true; }
/*! \remarks Implemented by the System.\n\n
Returns the first <b>HitRecord</b>. */
HitRecord* First() { return first; }
/*! \remarks Implemented by the System.\n\n
Returns the <b>HitRecord</b> that was 'closest' to the mouse position when
hit testing was performed. This is the <b>HitRecord</b> with the minimum
<b>distance</b>. */
CoreExport HitRecord* ClosestHit();
/*! \remarks Implemented by the System.\n\n
This method is called to log a hit. It creates a new <b>HitRecord</b>
object using the data passed and adds it to the hit log.
\param nr The node that was hit.
\param mc The ModContext of the modifier.
\param dist The 'distance' of the hit. What the distance actually represents depends on
the rendering level of the viewport. For wireframe modes, it refers to the
distance in the screen XY plane from the mouse to the sub-object component.
In a shaded mode, it refers to the Z depth of the sub-object component. In
both cases, smaller values indicate that the sub-object component is
'closer' to the mouse cursor.
\param info Identifies the sub-object component that was hit.
\param hitdat If the info field is insufficient to indicate the sub-object component that
was hit, pass an instance of the <b>HitData</b> class that contains the
needed information. */
CoreExport void LogHit(INode *nr, ModContext *mc, DWORD dist, ulong info, HitData *hitdat = NULL);
};
// Creates a new empty derived object, sets it to point at the given
// object and returns a pointer to the derived object.
/*! \remarks Creates a new empty derived object, sets it to point at the given
object and returns a pointer to the derived object.
\param obj object reference of the derived object will point at this object.
\return A pointer to the derived object. */
CoreExport Object *MakeObjectDerivedObject(Object *obj);
// Category strings for space warp objects:
#define SPACEWARP_CAT_GEOMDEF 1
#define SPACEWARP_CAT_MODBASED 2
#define SPACEWARP_CAT_PARTICLE 3
CoreExport MCHAR *GetSpaceWarpCatString(int id);
// ObjectConverter - allows users to register methods to (for example)
// allow Max to convert TriObjects directly into their plug-in object type.
/*! \sa Class InterfaceServer, Class Class_ID, Class Object, Class TriObject, Class PatchObject.\n\n
\par Description:
This virtual class is implemented by applications that want to supply a
conversion method from one object type to another. A typical use would be to
support conversion of a native 3ds Max type (such as TriObject) to a plug-in's
object type. There are a set of global functions that can be used with this
class. These are documented at the bottom of the topic. One of these is called
to register the ObjectConverter with the system.\n\n
Note that the registered object converters are called from the methods:\n\n
<b>Object::CanConvertToType</b> and <b>Object::ConvertToType</b>.\n\n
So for individual objects to support these, they'll need to add the line\n\n
<b>if (Object::CanConvertToType(obtype)) return 1;</b>\n\n
to the end of their CanConvertToType methods and\n\n
<b>if (Object::CanConvertToType(obtype))</b>\n\n
<b>return Object::ConvertToType(t, obtype);</b>\n\n
to the end of their ConvertToType methods. */
class ObjectConverter : public InterfaceServer {
public:
/*! \remarks This method returns the Class ID of the object this converter
converts from. */
virtual Class_ID ConvertsFrom ()=0;
/*! \remarks This method returns the Class ID of the object this converter
converts to. */
virtual Class_ID ConvertsTo ()=0;
// NOTE: There's a serious problem in that this method does not accept a TimeValue.
// See below for details.
/*! \remarks This method actually performs the conversion, creating and
returning a new object with the class ID specified in <b>ConvertsTo()</b>.
\param from Points to the object to convert. */
virtual Object *Convert (Object *from)=0;
/*! \remarks This should delete the ObjectConverter if necessary.
\par Default Implementation:
<b>{}</b>\n\n
*/
virtual void DeleteThis () { }
};
// There was a problem in the above ObjectConverter class in that its Convert
// method doesn't accept a time parameter. It's too late to change that, so we've
// implemented the following interface to supply the correct method. Users'
// ObjectConverters should subclass off of both ObjectConverter and
// ITimeBasedConverter. They should implement the GetInterface method as
// follows:
//BaseInterface *MyConverter::GetInterface (Interface_ID id) {
//if (id == INTERFACE_TIME_BASED_CONVERTER) return (ITimeBasedConverter *)this;
//return ObjectConverter::GetInterface (id);
//}
// They should then implement ConvertWithTime properly, and use Convert only
// to call ConvertWithTime with a time of GetCOREInterface()->GetTime().
// Convert should not be called (and won't be called by the system if this
// interface is properly set up).
#define INTERFACE_TIME_BASED_CONVERTER Interface_ID(0x1e064bad,0x716643db)
class ITimeBasedConverter : public BaseInterface {
public:
Interface_ID GetID () { return INTERFACE_TIME_BASED_CONVERTER; }
// This is the method that should be used to do the right conversion:
virtual Object *ConvertWithTime (TimeValue t, Object *from)=0;
};
/*! \remarks Registers an object converter with the system.
\param conv to the ObjectConverter instance to register.
\return Returns true if the converter could be added; false if not. */
CoreExport bool RegisterObjectConverter (ObjectConverter *conv);
/*! \remarks Indicates if a TriObject can convert to the specified class ID.\n\n
Note: this actually checks if an Editable Mesh object can convert to the
specified type, since an Editable Mesh is what you get when you call
<b>CreateNewTriObject ()</b>.\n\n
This method may be used in an object's <b>CanConvertToType()</b> and
<b>ConvertToType()</b> methods. If your object supports conversion to a
TriObject, but doesn't support conversion to the given class ID, you can use
this method to find out if TriObjects can be used as an "intermediary". If so,
you can construct a temporary TriObject, convert it to the given class ID, and
call the temporary TriObject's <b>DeleteThis()</b> method.
\param to Class ID to convert to.
\return Nonzero if the TriObject can be converted to the specified objec type;
otherwise zero. */
CoreExport int CanConvertTriObject (Class_ID to);
/*! \remarks Indicates if a PatchObject can convert to the specified class ID.
\param to Class ID to convert to.
\return Nonzero if the PatchObject can be converted to the specified objec
type; otherwise zero. */
CoreExport int CanConvertPatchObject (Class_ID to);
/*! \remarks Indicates if a SplineObject can convert to the specified class ID.
\param to Class ID to convert to.
\return Nonzero if the SplineObject can be converted to the specified objec
type; otherwise zero. */
CoreExport int CanConvertSplineShape (Class_ID to);
/*! \remarks This method will register the object passed as the editable tri object.
\param triob object to register as the editable tri object. */
CoreExport void RegisterStaticEditTri (Object *triob);
/*! \remarks Registers a class ID of an object that the user can collapse other objects to.
The type will only appear if the current object returns nonzero from
<b>CanConvertTo(cid)</b>.
\param cid class ID the object will collapse to.
\param name name of the collapse-to object type (such as "Editable Poly").
\param canSelfConvert whether an object should be allowed to collapse to itself. (false is
generally preferred, so that the collapse-to menu only has relevant entries.)
*/
CoreExport void RegisterCollapseType (Class_ID cid, MSTR name, bool canSelfConvert=false);
// Developers have to return a class derived from this class with implementations for
// all memberfunctions when implementing subobjects for obejcts and modifiers (see GetSubObjType())
/*! \sa Class InterfaceServer, Class BaseObject, Class MaxIcon, Class GenSubObjType.\n\n
\par Description:
Developers have to return a class derived from this class with implementations
for all the methods when implementing sub-objects for obejcts and modifiers
(see <b>BaseObject::GetSubObjType()</b>). */
class ISubObjType : public InterfaceServer
{
public:
/*! \remarks Returns a pointer to the icon for this sub-object type. This
icon appears in the stack view beside the name. */
virtual MaxIcon *GetIcon()=0;
/*! \remarks Returns the name of this sub-object type that appears in the
stack view. */
virtual MCHAR *GetName()=0;
};
// Generic implementation for subobject types. This SubObjectType will either use the
// SubObjectIcons_16i.bmp and SubObjectIcons_16a.bmp bitmaps in the UI directory
// (for the GenSubObjType(int idx) constructor), or any other bmp file that is specified
// in the GenSubObjType(MCHAR *nm, MCHAR* pFilePrefix, int idx) constructor. The
// bitmap files have to reside in the UI directory.
/*! \sa Class ISubObjType, Class BaseObject, Class MaxIcon.\n\n
\par Description:
This class provides a generic implementation for sub-object types. Instead of
having to create a sub-class of <b>ISubObjType</b> the constructors of this
class may be used to initialize private data members of the class. Then
implementations of the <b>GetName()</b> and <b>GetIcon()</b> methods of
<b>ISubObjType</b> are provided which simply return the data members.\n\n
This SubObjectType will either use the <b>subObjectIcons_16i.bmp</b> and
<b>SubObjectIcons_16a.bmp</b> bitmaps in the <b>UI/icons</b> directory (for the
<b>GenSubObjType(int idx)</b> constructor), or any other bmp file that is
specified in the <b>GenSubObjType(TCHAR *nm, TCHAR* pFilePrefix, int idx)</b>
constructor. The bitmap files have to reside in the <b>UI/icons</b>
directory.\n\n
All methods of this class are implemented by the System. */
class GenSubObjType : public ISubObjType {
MSTR name;
MaxIcon *mIcon;
int mIdx;
MSTR mFilePrefix;
public:
/*! \remarks Constructor. The private data members are inialized to the values
passed and the corresponding Get methods of this class will return these data
members.
\param nm The name for this sub-object type.
\param pFilePrefix The BMP imagelist file name prefix for this sub-object type. This is the file
name, without the extension, and with the assumption that the file is in the
<b>ui/icons</b> directory. For example specifying _T("SubObjectIcons") for this
parameter indicates the file <b>UI/icons/SubObjectIcons_16i.bmp</b> if the
small icons are in use and <b>SubObjectIcons_24i.bmp</b> if the large icons are
in use.
\param idx This is the one based index into the image list of the icon to use. */
GenSubObjType(MCHAR *nm, MCHAR* pFilePrefix, int idx) : name(nm), mIcon(NULL), mIdx(idx), mFilePrefix(pFilePrefix) {}
/*! \remarks This constructor assumes that the icons are in either
<b>UI/icons/SubObjectIcons_16i.bmp</b> or <b>SubObjectIcons_24i.bmp</b>
depending on which size icons are in use by the system. In this case only the
index into the image list is required.
\param idx This is the one based index into the image list of the icon to use. */
GenSubObjType(int idx) : mIcon(NULL), mIdx(idx), mFilePrefix(_M("SubObjectIcons")) {}
/*! \remarks Destructor. */
CoreExport ~GenSubObjType();
/*! \remarks Sets the name for this sub-object type.
\param nm The name to set. */
void SetName(MCHAR *nm){name = nm;}
/*! \remarks Returns the name for this sub-object type. This is the
implementation of the ISubObjType method. */
MCHAR *GetName() { return name;}
/*! \remarks Returns the icon for this sub-object type. This is the
implementation of the ISubObjType method. */
CoreExport MaxIcon *GetIcon();
};
#endif //_OBJECT_
| [
"[email protected]"
]
| [
[
[
1,
6061
]
]
]
|
6b8c527418a6593142f186b9507b191bf079c49b | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /MPChatScreen.cpp | 6f53481d85e2de36daffd3c4b045494120c9444c | []
| no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,490 | cpp | #ifdef PRECOMPILEDHEADERS
#include "JA2 All.h"
#else
#include "sgp.h"
#include "screenids.h"
#include "Timer Control.h"
#include "sys globals.h"
#include "fade screen.h"
#include "sysutil.h"
#include "vobject_blitters.h"
#include "MercTextBox.h"
#include "wcheck.h"
#include "cursors.h"
#include "font control.h"
#include "Game Clock.h"
#include "Map Screen Interface.h"
#include "renderworld.h"
#include "gameloop.h"
#include "english.h"
#include "GameSettings.h"
#include "Interface Control.h"
#include "cursor control.h"
#include "laptop.h"
#include "text.h"
#include "Text Input.h"
#include "overhead map.h"
#include "MPChatScreen.h"
#include "WordWrap.h"
#include "Render Dirty.h"
#include "message.h"
#include "utilities.h"
#include "connect.h"
#endif
#define CHATBOX_WIDTH 310 // 350 is the max size, the PrepareMercPopupBox will add the X_MARGIN to both sides
#define CHATBOX_Y_MARGIN_NOLOG 25
#define CHATBOX_Y_MARGIN_LOG 80
#define CHATBOX_Y_MARGIN_BOTTOM 80
#define CHATBOX_X_MARGIN 30 // pad box width 20 either side of text pixel length, but i use half of this value for control margins
#define CHATBOX_LOG_WIDTH 300
#define CHATBOX_LOG_HEIGHT 80
#define CHATBOX_LOG_TXTBORDER 4 // offset till text renderable area on all sides
#define CHATBOX_SCROLL_WIDTH 17
#define CHATBOX_SCROLL_HEIGHT 80
#define CHATBOX_SCROLL_GAPX 5
#define CHATBOX_BUTTON_WIDTH 61
#define CHATBOX_BUTTON_HEIGHT 20
#define CHATBOX_BUTTON_X_SEP 15
#define CHATBOX_SMALL_BUTTON_WIDTH 31
#define CHATBOX_SMALL_BUTTON_X_SEP 8
#define CHATBOX_TOGGLE_WIDTH 120
#define CHATBOX_TOGGLE_HEIGHT 12
#define CHATBOX_Y_GAP 10
#define CHATBOX_SLIDER_GAP 5
#define CHATBOX_INPUT_HEIGHT 20
#define CHATBOX_FONT_COLOR 73
#define CHATBOX_FONT_TITLE FONT14ARIAL
#define CHATBOX_FONT_TOGGLE FONT10ARIAL
// old mouse x and y positions
extern SGPPoint pOldMousePosition;
SGPRect ChatBoxRestrictedCursorRegion;
// if the cursor was locked to a region
extern BOOLEAN fCursorLockedToArea;
BOOLEAN gfInChatBox = FALSE;
//extern BOOLEAN fMapExitDueToMessageBox;
extern BOOLEAN fInMapMode;
extern BOOLEAN gfOverheadMapDirty;
//OJW - 20090208
CHAR16 gszChatBoxInputString[255];
BOOLEAN gbChatSendToAll = true;
void OKChatBoxCallback(GUI_BUTTON *btn, INT32 reason );
void CancelChatBoxCallback(GUI_BUTTON *btn, INT32 reason );
void ChatBoxClickCallback( MOUSE_REGION * pRegion, INT32 iReason );
UINT32 ExitChatBox( INT8 ubExitCode );
UINT16 GetChatBoxButtonWidth( INT32 iButtonImage );
extern SGPRect gOldCursorLimitRectangle;
MESSAGE_BOX_STRUCT gChatBox;
BOOLEAN gfNewChatBox = FALSE;
extern BOOLEAN gfStartedFromGameScreen;
extern BOOLEAN gfStartedFromMapScreen;
BOOLEAN fRestoreBackgroundForChatBox = FALSE;
extern BOOLEAN gfDontOverRideSaveBuffer; //this variable can be unset if ur in a non gamescreen and DONT want the msg box to use the save buffer
extern void HandleTacticalUILoseCursorFromOtherScreen( );
extern STR16 pUpdatePanelButtons[];
#define NUM_CHAT_TOGGLES 2
INT32 guiChatToggles[ NUM_CHAT_TOGGLES ];
void BtnChatTogglesCallback(GUI_BUTTON *btn,INT32 reason);
void RestoreChatToggleBackGrounds();
bool gIncludeChatLog = false;
SGPRect gChatTextBoxRegion;
// OPTIONAL CHAT MESSAGE LOG SETUP
SGPRect gChatMessageLogRegion;
UINT32 guiCHATLOGIMG; // Images for chat message log
// button enums
enum{
CHAT_SCROLL_MESSAGE_UP =0,
CHAT_SCROLL_MESSAGE_DOWN,
};
UINT32 guiChatSliderBar;
UINT16 CHATLOG_SCROLL_AREA_START_Y; //(SCREEN_HEIGHT - 90) //390
UINT16 CHATLOG_SCROLL_AREA_END_Y; //(SCREEN_HEIGHT - 32) //448
UINT16 CHATLOG_SCROLL_AREA_HEIGHT; //( CHATLOG_SCROLL_AREA_END_Y - CHATLOG_SCROLL_AREA_START_Y + 1 )
// CHRISL: Use these if we want scroll bar based on left edge of screen
UINT16 CHATLOG_SCROLL_AREA_START_X; //330
UINT16 CHATLOG_SCROLL_AREA_END_X; //344
UINT16 CHATLOG_SCROLL_AREA_WIDTH; //( CHATLOG_SCROLL_AREA_END_X - CHATLOG_SCROLL_AREA_START_X + 1 )
#define CHATLOG_BTN_SCROLL_TIME 100
#define CHAT_SLIDER_HEIGHT 11
#define CHAT_SLIDER_WIDTH 11
#define MAX_CHATLOG_MESSAGES 8
UINT16 CHAT_SLIDER_BAR_RANGE;
// buttons
UINT32 guiChatLogScrollButtons[ 2 ];
// buttons images
UINT32 guiChatLogScrollButtonsImage[ 2 ];
// mouse regions
MOUSE_REGION gChatLogScrollBarRegion;
void LoadChatLogSliderBar( void );
void DeleteChatLogSliderBar( void );
void DisplayChatLogScrollBarSlider( );
void CreateChatLogMessageScrollBarRegion( void );
void DeleteChatLogMessageScrollRegion( void );
void ChatScreenMsgScrollDown( UINT8 ubLinesDown );
void ChatScreenMsgScrollUp( UINT8 ubLinesUp );
void ChangeCurrentChatScreenMessageIndex( UINT8 ubNewMessageIndex );
void MoveToEndOfChatScreenMessageList( void );
void BtnMessageDownChatLogCallback( GUI_BUTTON *btn,INT32 reason );
void BtnMessageUpChatLogCallback( GUI_BUTTON *btn,INT32 reason );
void ChatScreenMessageScrollBarCallBack(MOUSE_REGION * pRegion, INT32 iReason );
void EnableDisableChatLogScrollButtonsAndRegions( void );
// the local logical message index
UINT8 gubFirstChatLogMessageIndex = 0;
// Chat Log Messages List
UINT8 gubStartOfChatLogMessageList = 0; // Front of the Message Queue
UINT8 gubEndOfChatLogMessageList = 0; // End of the Message Queue
UINT8 gubCurrentChatLogMessageString = 0; // // index of the current string we are looking at
static ScrollStringStPtr gChatLogMessageList[ 256 ]; // The message Queue
void InitChatMessageList( void );
void FreeChatMessageList( void );
void DisplayStringsInChatLogMessageList( void );
void AddStringToChatLogMessageList( STR16 pString, UINT16 usColor, UINT32 uiFont, BOOLEAN fStartOfNewString, UINT8 ubPriority );
UINT8 GetRangeOfChatLogMessages( void );
void ClearWrappedStringsCHAT( WRAPPED_STRING *pStringWrapperHead );
#define CHAT_LINE_WIDTH 292
#define CHAT_MESSAGE_FONT TINYFONT1
INT32 DoChatBox( bool bIncludeChatLog, const STR16 zString, UINT32 uiExitScreen, MSGBOX_CALLBACK ReturnCallback, SGPRect *pCenteringRect )
{
VSURFACE_DESC vs_desc;
UINT16 usTextBoxWidth;
UINT16 usTextBoxHeight;
UINT16 usYMargin;
SGPRect aRect;
UINT32 uiDestPitchBYTES, uiSrcPitchBYTES;
UINT8 *pDestBuf, *pSrcBuf;
INT16 sButtonX, sButtonY;
UINT8 ubMercBoxBackground = BASIC_MERC_POPUP_BACKGROUND, ubMercBoxBorder = BASIC_MERC_POPUP_BORDER;
UINT8 ubFontColor, ubFontShadowColor;
UINT16 usCursor;
INT32 iId = -1;
// clear the ouput string
memset(gszChatBoxInputString,0,sizeof(CHAR16)*255);
gIncludeChatLog = bIncludeChatLog;
GetMousePos( &pOldMousePosition );
if (bIncludeChatLog)
usYMargin = CHATBOX_Y_MARGIN_LOG;
else
usYMargin = CHATBOX_Y_MARGIN_NOLOG;
//this variable can be unset if ur in a non gamescreen and DONT want the msg box to use the save buffer
gfDontOverRideSaveBuffer = TRUE;
SetCurrentCursorFromDatabase( CURSOR_NORMAL );
if( gChatBox.BackRegion.uiFlags & MSYS_REGION_EXISTS )
{
return( 0 );
}
// set style
ubMercBoxBackground = DIALOG_MERC_POPUP_BACKGROUND;
ubMercBoxBorder = DIALOG_MERC_POPUP_BORDER;
// Add button images
gChatBox.iButtonImages = LoadButtonImage( "INTERFACE\\popupbuttons.sti", -1,0,-1,1,-1 );
ubFontColor = CHATBOX_FONT_COLOR;
ubFontShadowColor = DEFAULT_SHADOW;
usCursor = CURSOR_NORMAL;
// Use default!
aRect.iTop = 0;
aRect.iLeft = 0;
aRect.iBottom = SCREEN_HEIGHT;
aRect.iRight = SCREEN_WIDTH;
// Set some values!
//gChatBox.usFlags = usFlags;
gChatBox.uiExitScreen = uiExitScreen;
gChatBox.ExitCallback = ReturnCallback;
gChatBox.fRenderBox = TRUE;
gChatBox.bHandled = 0;
// Init message box
if (bIncludeChatLog)
// we need a string just long enough to give 1 line, but max length of the box, we render the chatlog over this string so well never see it. DONT DELETE ANY SPACES
gChatBox.iBoxId = PrepareMercPopupBox( iId, ubMercBoxBackground, ubMercBoxBorder, L"A string that will be hidden, ", CHATBOX_WIDTH, CHATBOX_X_MARGIN, usYMargin, CHATBOX_Y_MARGIN_BOTTOM, &usTextBoxWidth, &usTextBoxHeight );
else
gChatBox.iBoxId = PrepareMercPopupBox( iId, ubMercBoxBackground, ubMercBoxBorder, zString, CHATBOX_WIDTH, CHATBOX_X_MARGIN, usYMargin, CHATBOX_Y_MARGIN_BOTTOM, &usTextBoxWidth, &usTextBoxHeight );
if( gChatBox.iBoxId == -1 )
{
#ifdef JA2BETAVERSION
AssertMsg( 0, "Failed in DoMessageBox(). Probable reason is because the string was too large to fit in max message box size." );
#endif
return 0;
}
// Save height,width
gChatBox.usWidth = usTextBoxWidth;
gChatBox.usHeight = usTextBoxHeight;
// Determine position ( centered in rect )
gChatBox.sX = (INT16)( ( ( ( aRect.iRight - aRect.iLeft ) - usTextBoxWidth ) / 2 ) + aRect.iLeft );
gChatBox.sY = (INT16)( ( ( ( aRect.iBottom - aRect.iTop ) - usTextBoxHeight ) / 2 ) + aRect.iTop );
if ( guiCurrentScreen == GAME_SCREEN )
{
gfStartedFromGameScreen = TRUE;
}
if ( (fInMapMode == TRUE ) )
{
// fMapExitDueToMessageBox = TRUE;
gfStartedFromMapScreen = TRUE;
fMapPanelDirty = TRUE;
}
// Set pending screen
SetPendingNewScreen( MP_CHAT_SCREEN);
// Init save buffer
vs_desc.fCreateFlags = VSURFACE_CREATE_DEFAULT | VSURFACE_SYSTEM_MEM_USAGE;
vs_desc.usWidth = usTextBoxWidth;
vs_desc.usHeight = usTextBoxHeight;
vs_desc.ubBitDepth = 16;
if( AddVideoSurface( &vs_desc, &gChatBox.uiSaveBuffer) == FALSE )
{
return( - 1 );
}
//Save what we have under here...
pDestBuf = LockVideoSurface( gChatBox.uiSaveBuffer, &uiDestPitchBYTES);
pSrcBuf = LockVideoSurface( FRAME_BUFFER, &uiSrcPitchBYTES);
Blt16BPPTo16BPP((UINT16 *)pDestBuf, uiDestPitchBYTES,
(UINT16 *)pSrcBuf, uiSrcPitchBYTES,
0 , 0,
gChatBox.sX , gChatBox.sY,
usTextBoxWidth, usTextBoxHeight );
UnLockVideoSurface( gChatBox.uiSaveBuffer );
UnLockVideoSurface( FRAME_BUFFER );
// Create top-level mouse region
MSYS_DefineRegion( &(gChatBox.BackRegion), 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, MSYS_PRIORITY_HIGHEST,
usCursor, MSYS_NO_CALLBACK, ChatBoxClickCallback );
// Add region
MSYS_AddRegion(&(gChatBox.BackRegion) );
// findout if cursor locked, if so, store old params and store, restore when done
if( IsCursorRestricted() )
{
fCursorLockedToArea = TRUE;
GetRestrictedClipCursor( &ChatBoxRestrictedCursorRegion );
FreeMouseCursor( );
}
// vars for positioning controls on the chatbox
int usPosX = 0;
int usPosY = gChatBox.sY + GetFontHeight(CHATBOX_FONT_TITLE) + CHATBOX_Y_GAP + 5;
if (bIncludeChatLog)
{
// CREATE BUTTONS AND IMAGES FOR CHATLOG
VOBJECT_DESC VObjectDesc;
// will create buttons for interface bottom
VObjectDesc.fCreateFlags=VOBJECT_CREATE_FROMFILE;
FilenameForBPP( "INTERFACE\\mpchatbox.sti", VObjectDesc.ImageFile );
if( !AddVideoObject( &VObjectDesc, &guiCHATLOGIMG ) )
Assert( false );
gChatMessageLogRegion.iTop = usPosY;
gChatMessageLogRegion.iLeft = gChatBox.sX + (CHATBOX_X_MARGIN / 2);
gChatMessageLogRegion.iBottom = usPosY + CHATBOX_LOG_HEIGHT;
gChatMessageLogRegion.iRight = gChatMessageLogRegion.iLeft + CHATBOX_LOG_WIDTH;
// SETUP SCROLLING AREA BOUNDS
CHATLOG_SCROLL_AREA_START_Y = gChatMessageLogRegion.iTop+20;
CHATLOG_SCROLL_AREA_END_Y = gChatMessageLogRegion.iBottom-20;
CHATLOG_SCROLL_AREA_HEIGHT = ( CHATLOG_SCROLL_AREA_END_Y - CHATLOG_SCROLL_AREA_START_Y + 1 );
CHATLOG_SCROLL_AREA_START_X = gChatMessageLogRegion.iRight + CHATBOX_SLIDER_GAP + 1;
CHATLOG_SCROLL_AREA_END_X = gChatMessageLogRegion.iRight + CHATBOX_SLIDER_GAP + 1 + CHAT_SLIDER_WIDTH;
CHATLOG_SCROLL_AREA_WIDTH = ( CHATLOG_SCROLL_AREA_END_X - CHATLOG_SCROLL_AREA_START_X + 1 );
CHAT_SLIDER_BAR_RANGE = ( CHATLOG_SCROLL_AREA_HEIGHT - CHAT_SLIDER_HEIGHT );
LoadChatLogSliderBar();
// Load Scroll button images
guiChatLogScrollButtonsImage[ CHAT_SCROLL_MESSAGE_UP ]= LoadButtonImage( "INTERFACE\\map_screen_bottom_arrows.sti" ,11,4,-1,6,-1 );
guiChatLogScrollButtonsImage[ CHAT_SCROLL_MESSAGE_DOWN ]= LoadButtonImage( "INTERFACE\\map_screen_bottom_arrows.sti" ,12,5,-1,7,-1 );
// Create buttons
guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_UP ] = QuickCreateButton( guiChatLogScrollButtonsImage[ CHAT_SCROLL_MESSAGE_UP ], gChatMessageLogRegion.iRight + CHATBOX_SLIDER_GAP + 2 , gChatMessageLogRegion.iTop + 1 ,
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST,
(GUI_CALLBACK)BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnMessageUpChatLogCallback);
guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_DOWN ] = QuickCreateButton( guiChatLogScrollButtonsImage[ CHAT_SCROLL_MESSAGE_DOWN ], gChatMessageLogRegion.iRight + CHATBOX_SLIDER_GAP + 2, gChatMessageLogRegion.iBottom - 16,
BUTTON_TOGGLE, MSYS_PRIORITY_HIGHEST,
(GUI_CALLBACK)BtnGenericMouseMoveButtonCallback, (GUI_CALLBACK)BtnMessageDownChatLogCallback);
usPosY = gChatBox.sY + CHATBOX_Y_MARGIN_LOG + (CHATBOX_Y_GAP * 2) + GetFontHeight(FONT12ARIAL) + 5;
// END CREATE CHATLOG
}
else
usPosY = gChatBox.sY + CHATBOX_Y_MARGIN_NOLOG + (CHATBOX_Y_GAP * 2) + GetFontHeight(FONT12ARIAL);
// get the middle of the box
UINT16 middleBox = ( usTextBoxWidth / 2 );
// CREATE SEND TO ALLIES / ALL TOGGLES
// send to all
int toggleWidth = 32 + StringPixLength( gzMPChatToggleText[ 0 ], CHATBOX_FONT_TOGGLE );
usPosX = gChatBox.sX + ((middleBox - toggleWidth)/2);
guiChatToggles[ 0 ] = CreateCheckBoxButton( usPosX, usPosY,
"INTERFACE\\OptionsCheckBoxes_12x12.sti", MSYS_PRIORITY_HIGHEST,
BtnChatTogglesCallback );
MSYS_SetBtnUserData( guiChatToggles[ 0 ], 0, 0 );
// send to allies
toggleWidth = 32 + StringPixLength( gzMPChatToggleText[ 1 ], CHATBOX_FONT_TOGGLE );
usPosX = gChatBox.sX + middleBox + ((middleBox - toggleWidth)/2);
guiChatToggles[ 1 ] = CreateCheckBoxButton( usPosX, usPosY,
"INTERFACE\\OptionsCheckBoxes_12x12.sti", MSYS_PRIORITY_HIGHEST,
BtnChatTogglesCallback );
MSYS_SetBtnUserData( guiChatToggles[ 1 ], 0, 1 );
usPosY += CHATBOX_TOGGLE_HEIGHT + CHATBOX_Y_GAP;
// SET DEFAULT FLAGGED
if (gbChatSendToAll)
ButtonList[ guiChatToggles[ 0 ] ]->uiFlags |= BUTTON_CLICKED_ON;
else
ButtonList[ guiChatToggles[ 1 ] ]->uiFlags |= BUTTON_CLICKED_ON;
// END CREATE TOGGLES
// CREATE TEXT INPUT BOX
InitTextInputMode(); // API call to initialise text input mode for this screen
// does not mean we are inputting text right away
// Player Name field
SetTextInputCursor( CUROSR_IBEAM_WHITE );
SetTextInputFont( (UINT16) FONT12ARIALFIXEDWIDTH ); //FONT12ARIAL //FONT12ARIALFIXEDWIDTH
Set16BPPTextFieldColor( Get16BPPColor(FROMRGB( 0, 0, 0) ) );
SetBevelColors( Get16BPPColor(FROMRGB(136, 138, 135)), Get16BPPColor(FROMRGB(24, 61, 81)) );
SetTextInputRegularColors( FONT_WHITE, 2 );
SetTextInputHilitedColors( 2, FONT_WHITE, FONT_WHITE );
SetCursorColor( Get16BPPColor(FROMRGB(255, 255, 255) ) );
usPosX = gChatBox.sX + (CHATBOX_X_MARGIN / 2);
//Add Player Name textbox
AddTextInputField( usPosX ,
usPosY ,
usTextBoxWidth - CHATBOX_X_MARGIN,
20,
MSYS_PRIORITY_HIGH+2,
gszChatBoxInputString,
255,
INPUTTYPE_ASCII );//23
gChatTextBoxRegion.iTop = usPosY;
gChatTextBoxRegion.iLeft = usPosX;
gChatTextBoxRegion.iBottom = usPosY+20;
gChatTextBoxRegion.iRight = usPosX+usTextBoxWidth - CHATBOX_X_MARGIN;
// exit text input mode in this screen and clean up text boxes
SetActiveField( 0 );
usPosY += CHATBOX_INPUT_HEIGHT + CHATBOX_Y_GAP;
// END CREATE TEXT INPUT BOX
// CREATE OK AND CANCEL BUTTONS
// get the button width
UINT16 btnWidth = GetChatBoxButtonWidth( gChatBox.iButtonImages );
// Create OK Button
sButtonX = middleBox + ((middleBox - btnWidth)/2);
sButtonY = usTextBoxHeight - CHATBOX_BUTTON_HEIGHT - 10;
gChatBox.uiOKButton = CreateIconAndTextButton( gChatBox.iButtonImages, pMessageStrings[ MSG_OK ], FONT12ARIAL,
CHATBOX_FONT_COLOR, ubFontShadowColor,
CHATBOX_FONT_COLOR, ubFontShadowColor,
TEXT_CJUSTIFIED,
(INT16)(gChatBox.sX + sButtonX ), (INT16)(gChatBox.sY + sButtonY ), BUTTON_TOGGLE ,MSYS_PRIORITY_HIGHEST,
DEFAULT_MOVE_CALLBACK, (GUI_CALLBACK)OKChatBoxCallback );
SetButtonCursor(gChatBox.uiOKButton, usCursor);
ForceButtonUnDirty( gChatBox.uiOKButton );
// move the mouse over the ok button
if( gGameSettings.fOptions[ TOPTION_DONT_MOVE_MOUSE ] == FALSE )
{
SimulateMouseMovement( ( gChatBox.sX + sButtonX + 27 ), ( gChatBox.sY + sButtonY + 10) );
}
// Create Cancel Button
sButtonX = ((middleBox - btnWidth)/2);
sButtonY = usTextBoxHeight - CHATBOX_BUTTON_HEIGHT - 10;
gChatBox.uiNOButton = CreateIconAndTextButton( gChatBox.iButtonImages, pMessageStrings[ MSG_CANCEL ], FONT10ARIAL,
CHATBOX_FONT_COLOR, ubFontShadowColor,
CHATBOX_FONT_COLOR, ubFontShadowColor,
TEXT_CJUSTIFIED,
(INT16)(gChatBox.sX + sButtonX ), (INT16)(gChatBox.sY + sButtonY ), BUTTON_TOGGLE ,MSYS_PRIORITY_HIGHEST,
DEFAULT_MOVE_CALLBACK, (GUI_CALLBACK)CancelChatBoxCallback );
SetButtonCursor(gChatBox.uiNOButton, usCursor);
ForceButtonUnDirty( gChatBox.uiNOButton );
// END CREATE BUTTONS
#if 0
gChatBox.fWasPaused = GamePaused();
if (!gChatBox.fWasPaused)
{
InterruptTime();
PauseGame();
LockPauseState( 1 );
// Pause timers as well....
PauseTime( TRUE );
}
#endif
// Save mouse restriction region...
GetRestrictedClipCursor( &gOldCursorLimitRectangle );
FreeMouseCursor( );
gfNewChatBox = TRUE;
gfInChatBox = TRUE;
return( iId );
}
UINT32 ExitChatBox( INT8 ubExitCode )
{
UINT32 uiDestPitchBYTES, uiSrcPitchBYTES;
UINT8 *pDestBuf, *pSrcBuf;
SGPPoint pPosition;
// Delete popup!
RemoveMercPopupBoxFromIndex( gChatBox.iBoxId );
gChatBox.iBoxId = -1;
// OJW - 20090208 - Add text input box type
// exit text input mode in this screen and clean up text boxes
KillAllTextInputModes();
RemoveButton( gChatBox.uiOKButton );
RemoveButton( gChatBox.uiNOButton );
// Delete button images
UnloadButtonImage( gChatBox.iButtonImages );
//Remove the toggle buttons
for(int cnt=0; cnt<NUM_CHAT_TOGGLES; cnt++)
{
RemoveButton( guiChatToggles[ cnt ] );
}
// delete graphics and scrolling buttons / slider
if (gIncludeChatLog)
{
RemoveButton( guiChatLogScrollButtons[ 0 ] );
RemoveButton( guiChatLogScrollButtons[ 1 ] );
UnloadButtonImage( guiChatLogScrollButtonsImage[ 0 ] );
UnloadButtonImage( guiChatLogScrollButtonsImage[ 1 ] );
DeleteVideoObjectFromIndex( guiCHATLOGIMG );
DeleteChatLogSliderBar();
}
#if 0
if (!gChatBox.fWasPaused)
{
// Unpause game....
UnLockPauseState();
UnPauseGame();
// UnPause timers as well....
PauseTime( FALSE );
}
#endif
// Restore mouse restriction region...
RestrictMouseCursor( &gOldCursorLimitRectangle );
gfInChatBox = FALSE;
// Call done callback!
if ( gChatBox.ExitCallback != NULL )
{
(*(gChatBox.ExitCallback))( ubExitCode );
}
//if ur in a non gamescreen and DONT want the msg box to use the save buffer, unset gfDontOverRideSaveBuffer in ur callback
if( ( ( gChatBox.uiExitScreen != GAME_SCREEN ) || ( fRestoreBackgroundForMessageBox == TRUE ) ) && gfDontOverRideSaveBuffer )
{
// restore what we have under here...
pSrcBuf = LockVideoSurface( gChatBox.uiSaveBuffer, &uiSrcPitchBYTES);
pDestBuf = LockVideoSurface( FRAME_BUFFER, &uiDestPitchBYTES);
Blt16BPPTo16BPP((UINT16 *)pDestBuf, uiDestPitchBYTES,
(UINT16 *)pSrcBuf, uiSrcPitchBYTES,
gChatBox.sX , gChatBox.sY,
0, 0,
gChatBox.usWidth, gChatBox.usHeight );
UnLockVideoSurface( gChatBox.uiSaveBuffer );
UnLockVideoSurface( FRAME_BUFFER );
InvalidateRegion( gChatBox.sX, gChatBox.sY, (INT16)( gChatBox.sX + gChatBox.usWidth ), (INT16)( gChatBox.sY + gChatBox.usHeight ) );
}
fRestoreBackgroundForMessageBox = FALSE;
gfDontOverRideSaveBuffer = TRUE;
if( fCursorLockedToArea == TRUE )
{
GetMousePos( &pPosition );
if( ( pPosition.iX > ChatBoxRestrictedCursorRegion.iRight ) || ( pPosition.iX > ChatBoxRestrictedCursorRegion.iLeft ) && ( pPosition.iY < ChatBoxRestrictedCursorRegion.iTop ) && ( pPosition.iY > ChatBoxRestrictedCursorRegion.iBottom ) )
{
SimulateMouseMovement( pOldMousePosition.iX , pOldMousePosition.iY );
}
fCursorLockedToArea = FALSE;
RestrictMouseCursor( &ChatBoxRestrictedCursorRegion );
}
// Remove region
MSYS_RemoveRegion(&(gChatBox.BackRegion) );
// Remove save buffer!
DeleteVideoSurfaceFromIndex( gChatBox.uiSaveBuffer );
switch( gChatBox.uiExitScreen )
{
case GAME_SCREEN:
if ( InOverheadMap( ) )
{
gfOverheadMapDirty = TRUE;
}
else
{
SetRenderFlags( RENDER_FLAG_FULL );
}
break;
case MAP_SCREEN:
fMapPanelDirty = TRUE;
break;
}
if ( gfFadeInitialized )
{
SetPendingNewScreen(FADE_SCREEN);
return( FADE_SCREEN );
}
return( gChatBox.uiExitScreen );
}
UINT32 MPChatScreenInit( )
{
InitChatMessageList();
return( TRUE );
}
UINT32 MPChatScreenHandle( )
{
InputAtom InputEvent;
if ( gfNewChatBox )
{
// If in game screen....
if ( ( gfStartedFromGameScreen )||( gfStartedFromMapScreen ) )
{
//UINT32 uiDestPitchBYTES, uiSrcPitchBYTES;
//UINT8 *pDestBuf, *pSrcBuf;
if( gfStartedFromGameScreen )
{
HandleTacticalUILoseCursorFromOtherScreen( );
}
else
{
HandleMAPUILoseCursorFromOtherScreen( );
}
gfStartedFromGameScreen = FALSE;
gfStartedFromMapScreen = FALSE;
}
gfNewChatBox = FALSE;
return( MP_CHAT_SCREEN );
}
UnmarkButtonsDirty( );
// Render the box!
if ( gChatBox.fRenderBox )
{
// Render the Background ( this includes the text string)
RenderMercPopUpBoxFromIndex( gChatBox.iBoxId, gChatBox.sX, gChatBox.sY, FRAME_BUFFER );
UINT16 usWidth = StringPixLength( gzMPChatboxText[0], CHATBOX_FONT_TITLE );
int usPosY = 0;
int usPosX = 0;
usPosY = gChatBox.sY + 10;
usPosX = gChatBox.sX + ((gChatBox.usWidth - usWidth) / 2);
DrawTextToScreen( gzMPChatboxText[0], usPosX, usPosY, usWidth, CHATBOX_FONT_TITLE, CHATBOX_FONT_COLOR, DEFAULT_SHADOW, FALSE, CENTER_JUSTIFIED | TEXT_SHADOWED );
// Render the toggle button strings
for(UINT8 cnt=0; cnt<NUM_CHAT_TOGGLES; cnt++)
{
GUI_BUTTON* btn = ButtonList[ guiChatToggles[ cnt ] ];
usPosX = btn->XLoc + 12 + 10;
usPosY = btn->YLoc;
usWidth = StringPixLength( gzMPChatToggleText[ cnt ], CHATBOX_FONT_TOGGLE );
DrawTextToScreen( gzMPChatToggleText[ cnt ], usPosX, usPosY, usWidth, CHATBOX_FONT_TOGGLE, CHATBOX_FONT_COLOR, FONT_MCOLOR_BLACK, FALSE, LEFT_JUSTIFIED );
}
if (gIncludeChatLog)
{
// draw chatbox
HVOBJECT hHandle;
// get and blt panel
GetVideoObject(&hHandle, guiCHATLOGIMG );
BltVideoObject( FRAME_BUFFER , hHandle, 0, gChatMessageLogRegion.iLeft, gChatMessageLogRegion.iTop, VO_BLT_SRCTRANSPARENCY,NULL );
BltVideoObject( FRAME_BUFFER , hHandle, 1, gChatMessageLogRegion.iRight+CHATBOX_SLIDER_GAP, gChatMessageLogRegion.iTop, VO_BLT_SRCTRANSPARENCY,NULL );
// draw slider
DisplayChatLogScrollBarSlider( );
// draw chat log text
DisplayStringsInChatLogMessageList();
}
}
MarkButtonsDirty();
EnableDisableChatLogScrollButtonsAndRegions();
// Render buttons
RenderButtons( );
// render text boxes
//SaveFontSettings();
SetFontDestBuffer( FRAME_BUFFER, gChatTextBoxRegion.iLeft , gChatTextBoxRegion.iTop , gChatTextBoxRegion.iRight , gChatTextBoxRegion.iBottom, FALSE );
RenderAllTextFields(); // textbox system call
SetFontDestBuffer( FRAME_BUFFER, 0 , 0 , SCREEN_WIDTH , SCREEN_HEIGHT , FALSE );
//RestoreFontSettings();
EndFrameBufferRender( );
// carter, need key shortcuts for clearing up message boxes
// Check for esc
bool bHandled;
while (DequeueEvent(&InputEvent) == TRUE)
{
bHandled = false;
if(InputEvent.usEvent == KEY_DOWN )
{
if( ( InputEvent.usParam == ESC ) )
{
// Exit messagebox
gChatBox.bHandled = MSG_BOX_RETURN_NO;
memset(gszChatBoxInputString,0,sizeof(CHAR16)*255);
bHandled = true;
}
if( InputEvent.usParam == ENTER )
{
// retrieve the string from the text box
Get16BitStringFromField( 0, gszChatBoxInputString, 255 ); // these indexes are based on the order created
// Exit messagebox
gChatBox.bHandled = MSG_BOX_RETURN_OK;
bHandled = true;
}
// OJW - 20090403 - add better key control
UINT8 ubDesiredMessageIndex;
UINT8 ubNumMessages;
ubNumMessages = GetRangeOfChatLogMessages();
if ( ubNumMessages > MAX_CHATLOG_MESSAGES )
{
if (InputEvent.usParam == PGUP)
{
//move up a page
ChatScreenMsgScrollUp( MAX_CHATLOG_MESSAGES );
bHandled = true;
}
if (InputEvent.usParam == PGDN)
{
// move down a page
ChatScreenMsgScrollDown( MAX_CHATLOG_MESSAGES );
bHandled = true;
}
if (InputEvent.usParam == HOME)
{
// move to the beginning
ChangeCurrentChatScreenMessageIndex( 0 );
bHandled = true;
}
if (InputEvent.usParam == END)
{
// move to end
ubDesiredMessageIndex = ubNumMessages - MAX_CHATLOG_MESSAGES;
ChangeCurrentChatScreenMessageIndex( ubDesiredMessageIndex );
bHandled = true;
}
}
}
// send to text box
if (!bHandled)
HandleTextInput( &InputEvent );
}
if ( gChatBox.bHandled )
{
SetRenderFlags( RENDER_FLAG_FULL );
return( ExitChatBox( gChatBox.bHandled ) );
}
return( MP_CHAT_SCREEN );
}
UINT32 MPChatScreenShutdown( )
{
FreeChatMessageList();
return( FALSE );
}
UINT16 GetChatBoxButtonWidth( INT32 iButtonImage )
{
return( GetWidthOfButtonPic( (UINT16)iButtonImage, ButtonPictures[iButtonImage].OnNormal ) );
}
void CancelChatBoxCallback(GUI_BUTTON *btn, INT32 reason )
{
static BOOLEAN fLButtonDown = FALSE;
if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags |= BUTTON_CLICKED_ON;
fLButtonDown = TRUE;
}
else if( ( reason & MSYS_CALLBACK_REASON_LBUTTON_UP ) && fLButtonDown )
{
btn->uiFlags &= (~BUTTON_CLICKED_ON );
// OK, exit
gChatBox.bHandled = MSG_BOX_RETURN_NO;
// clear the ouput string
memset(gszChatBoxInputString,0,sizeof(CHAR16)*255);
}
else if ( reason & MSYS_CALLBACK_REASON_LOST_MOUSE )
{
fLButtonDown = FALSE;
}
}
void OKChatBoxCallback(GUI_BUTTON *btn, INT32 reason )
{
static BOOLEAN fLButtonDown = FALSE;
if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags |= BUTTON_CLICKED_ON;
fLButtonDown = TRUE;
}
else if( ( reason & MSYS_CALLBACK_REASON_LBUTTON_UP ) && fLButtonDown )
{
btn->uiFlags &= (~BUTTON_CLICKED_ON );
// OK, exit
gChatBox.bHandled = MSG_BOX_RETURN_OK;
// retrieve the string from the text box
Get16BitStringFromField( 0, gszChatBoxInputString, 255 ); // these indexes are based on the order created
}
else if ( reason & MSYS_CALLBACK_REASON_LOST_MOUSE )
{
fLButtonDown = FALSE;
}
}
void BtnChatTogglesCallback( GUI_BUTTON *btn, INT32 reason )
{
UINT8 ubButton = (UINT8)MSYS_GetBtnUserData( btn, 0 );
if (ubButton == 1 && cGameType != MP_TYPE_TEAMDEATMATCH)
return;
if( reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if( btn->uiFlags & BUTTON_CLICKED_ON )
{
// disable all buttons in grp
UINT8 cnt;
for( cnt=0; cnt<NUM_CHAT_TOGGLES; cnt++)
{
ButtonList[ guiChatToggles[ cnt ] ]->uiFlags &= ~BUTTON_CLICKED_ON;
}
// reselect the current button
btn->uiFlags |= BUTTON_CLICKED_ON;
gbChatSendToAll = ubButton == 0; // 0 is send to all
}
else
{
// check if any other buttons are checked
UINT8 cnt;
BOOLEAN fAnyChecked=FALSE;
for( cnt=0; cnt<NUM_CHAT_TOGGLES; cnt++)
{
if( ButtonList[ guiChatToggles[ cnt ] ]->uiFlags & BUTTON_CLICKED_ON )
{
fAnyChecked = TRUE;
}
}
//if none are checked, re check this one
if( !fAnyChecked )
btn->uiFlags |= BUTTON_CLICKED_ON;
}
}
}
void RestoreChatToggleBackGrounds()
{
UINT8 cnt;
//Redraw toggle buttons
for( cnt=0; cnt<NUM_CHAT_TOGGLES; cnt++)
{
GUI_BUTTON* btn = ButtonList[ guiChatToggles[ cnt ] ];
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
}
void ChatBoxClickCallback( MOUSE_REGION * pRegion, INT32 iReason )
{
}
// SCROLLING FOR CHAT LOG
void BtnMessageDownChatLogCallback( GUI_BUTTON *btn,INT32 reason )
{
static INT32 iLastRepeatScrollTime = 0;
if( reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
btn->uiFlags|=(BUTTON_CLICKED_ON);
iLastRepeatScrollTime = 0;
}
else if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
// down a line
ChatScreenMsgScrollDown( 1 );
}
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT )
{
if( GetJA2Clock() - iLastRepeatScrollTime >= CHATLOG_BTN_SCROLL_TIME )
{
// down a line
ChatScreenMsgScrollDown( 1 );
iLastRepeatScrollTime = GetJA2Clock( );
}
}
else if( reason & MSYS_CALLBACK_REASON_RBUTTON_DWN )
{
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
btn->uiFlags|=(BUTTON_CLICKED_ON);
iLastRepeatScrollTime = 0;
}
else if(reason & MSYS_CALLBACK_REASON_RBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
// down a page
ChatScreenMsgScrollDown( MAX_CHATLOG_MESSAGES );
}
}
else if( reason & MSYS_CALLBACK_REASON_RBUTTON_REPEAT )
{
if( GetJA2Clock() - iLastRepeatScrollTime >= CHATLOG_BTN_SCROLL_TIME )
{
// down a page
ChatScreenMsgScrollDown( MAX_CHATLOG_MESSAGES );
iLastRepeatScrollTime = GetJA2Clock( );
}
}
}
void BtnMessageUpChatLogCallback( GUI_BUTTON *btn,INT32 reason )
{
static INT32 iLastRepeatScrollTime = 0;
if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags|=(BUTTON_CLICKED_ON);
// redraw region
if( btn->Area.uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
iLastRepeatScrollTime = 0;
}
else if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
// up a line
ChatScreenMsgScrollUp( 1 );
}
}
else if( reason & MSYS_CALLBACK_REASON_LBUTTON_REPEAT )
{
if( GetJA2Clock() - iLastRepeatScrollTime >= CHATLOG_BTN_SCROLL_TIME )
{
// up a line
ChatScreenMsgScrollUp( 1 );
iLastRepeatScrollTime = GetJA2Clock( );
}
}
else if( reason & MSYS_CALLBACK_REASON_RBUTTON_DWN )
{
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
btn->uiFlags|=(BUTTON_CLICKED_ON);
iLastRepeatScrollTime = 0;
}
else if(reason & MSYS_CALLBACK_REASON_RBUTTON_UP )
{
if (btn->uiFlags & BUTTON_CLICKED_ON)
{
btn->uiFlags&=~(BUTTON_CLICKED_ON);
// redraw region
if( btn->uiFlags & MSYS_HAS_BACKRECT )
{
gChatBox.fRenderBox = TRUE;
}
// up a page
ChatScreenMsgScrollUp( MAX_CHATLOG_MESSAGES );
}
}
else if( reason & MSYS_CALLBACK_REASON_RBUTTON_REPEAT )
{
if( GetJA2Clock() - iLastRepeatScrollTime >= CHATLOG_BTN_SCROLL_TIME )
{
// up a page
ChatScreenMsgScrollUp( MAX_CHATLOG_MESSAGES );
iLastRepeatScrollTime = GetJA2Clock( );
}
}
}
void EnableDisableChatLogScrollButtonsAndRegions( void )
{
UINT8 ubNumMessages;
ubNumMessages = GetRangeOfChatLogMessages();
// if no scrolling required, or already showing the topmost message
if( ( ubNumMessages <= MAX_CHATLOG_MESSAGES ) || ( gubFirstChatLogMessageIndex == 0 ) )
{
DisableButton( guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_UP ] );
ButtonList[ guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_UP ] ]->uiFlags &= ~( BUTTON_CLICKED_ON );
}
else
{
EnableButton( guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_UP ] );
}
// if no scrolling required, or already showing the last message
if( ( ubNumMessages <= MAX_CHATLOG_MESSAGES ) ||
( ( gubFirstChatLogMessageIndex + MAX_CHATLOG_MESSAGES ) >= ubNumMessages ) )
{
DisableButton( guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_DOWN ] );
ButtonList[ guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_DOWN ] ]->uiFlags &= ~( BUTTON_CLICKED_ON );
}
else
{
EnableButton( guiChatLogScrollButtons[ CHAT_SCROLL_MESSAGE_DOWN ] );
}
if( ubNumMessages <= MAX_CHATLOG_MESSAGES )
{
MSYS_DisableRegion( &gChatLogScrollBarRegion );
}
else
{
MSYS_EnableRegion( &gChatLogScrollBarRegion );
}
if (cGameType==MP_TYPE_TEAMDEATMATCH)
{
// Only enable Allies toggle for team deathmatch
EnableButton( guiChatToggles[1] );
}
else
{
gbChatSendToAll = true;
DisableButton( guiChatToggles[1] );
}
}
void ChatScreenMsgScrollDown( UINT8 ubLinesDown )
{
UINT8 ubNumMessages;
ubNumMessages = GetRangeOfChatLogMessages();
// check if we can go that far, only go as far as we can
if ( ( gubFirstChatLogMessageIndex + MAX_CHATLOG_MESSAGES + ubLinesDown ) > ubNumMessages )
{
ubLinesDown = ubNumMessages - gubFirstChatLogMessageIndex - min( ubNumMessages, MAX_CHATLOG_MESSAGES );
}
if ( ubLinesDown > 0 )
{
ChangeCurrentChatScreenMessageIndex( ( UINT8 ) ( gubFirstChatLogMessageIndex + ubLinesDown ) );
}
}
void ChatScreenMsgScrollUp( UINT8 ubLinesUp )
{
UINT8 ubNumMessages;
ubNumMessages = GetRangeOfChatLogMessages();
// check if we can go that far, only go as far as we can
if ( gubFirstChatLogMessageIndex < ubLinesUp )
{
ubLinesUp = gubFirstChatLogMessageIndex;
}
if ( ubLinesUp > 0 )
{
ChangeCurrentChatScreenMessageIndex( ( UINT8 ) ( gubFirstChatLogMessageIndex - ubLinesUp ) );
}
}
void MoveToEndOfChatScreenMessageList( void )
{
UINT8 ubDesiredMessageIndex;
UINT8 ubNumMessages;
ubNumMessages = GetRangeOfChatLogMessages();
ubDesiredMessageIndex = ubNumMessages - min( ubNumMessages, MAX_CHATLOG_MESSAGES );
ChangeCurrentChatScreenMessageIndex( ubDesiredMessageIndex );
}
void ChangeCurrentChatScreenMessageIndex( UINT8 ubNewMessageIndex )
{
Assert( ubNewMessageIndex + MAX_CHATLOG_MESSAGES <= max( MAX_CHATLOG_MESSAGES, GetRangeOfChatLogMessages() ) );
gubFirstChatLogMessageIndex = ubNewMessageIndex;
gubCurrentChatLogMessageString = ( gubStartOfChatLogMessageList + gubFirstChatLogMessageIndex ) % 256;
// set fact we just went to a new message
// gfNewScrollMessage = TRUE;
// refresh screen
gChatBox.fRenderBox = TRUE;
}
void LoadChatLogSliderBar( void )
{
// this function will load the message slider bar
VOBJECT_DESC VObjectDesc;
VObjectDesc.fCreateFlags=VOBJECT_CREATE_FROMFILE;
FilenameForBPP( "INTERFACE\\map_screen_bottom_arrows.sti", VObjectDesc.ImageFile );
if( !AddVideoObject( &VObjectDesc, &guiChatSliderBar ) )
Assert(false);
CreateChatLogMessageScrollBarRegion();
}
void DeleteChatLogSliderBar( void )
{
// this function will delete message slider bar
DeleteVideoObjectFromIndex( guiChatSliderBar );
DeleteChatLogMessageScrollRegion();
}
void CreateChatLogMessageScrollBarRegion( void )
{
MSYS_DefineRegion( &gChatLogScrollBarRegion, CHATLOG_SCROLL_AREA_START_X, CHATLOG_SCROLL_AREA_START_Y,
CHATLOG_SCROLL_AREA_END_X, CHATLOG_SCROLL_AREA_END_Y,
MSYS_PRIORITY_HIGHEST, MSYS_NO_CURSOR, MSYS_NO_CALLBACK, ChatScreenMessageScrollBarCallBack );
}
void DeleteChatLogMessageScrollRegion( void )
{
MSYS_RemoveRegion( &gChatLogScrollBarRegion );
}
void ChatScreenMessageScrollBarCallBack( MOUSE_REGION *pRegion, INT32 iReason )
{
POINT MousePos;
UINT8 ubMouseYOffset;
UINT8 ubDesiredSliderOffset;
UINT8 ubDesiredMessageIndex;
UINT8 ubNumMessages;
if (iReason & MSYS_CALLBACK_REASON_INIT)
{
return;
}
if ( iReason & ( MSYS_CALLBACK_REASON_LBUTTON_DWN | MSYS_CALLBACK_REASON_LBUTTON_REPEAT ) )
{
// how many messages are there?
ubNumMessages = GetRangeOfChatLogMessages();
// region is supposed to be disabled if there aren't enough messages to scroll. Formulas assume this
if ( ubNumMessages > MAX_CHATLOG_MESSAGES )
{
// where is the mouse?
GetCursorPos( &MousePos );
ScreenToClient(ghWindow, &MousePos); // In window coords!
ubMouseYOffset = (UINT8) MousePos.y - CHATLOG_SCROLL_AREA_START_Y;
// if clicking in the top 5 pixels of the slider bar
if ( ubMouseYOffset < ( CHAT_SLIDER_HEIGHT / 2 ) )
{
// scroll all the way to the top
ubDesiredMessageIndex = 0;
}
// if clicking in the bottom 6 pixels of the slider bar
else if ( ubMouseYOffset >= ( CHATLOG_SCROLL_AREA_HEIGHT - ( CHAT_SLIDER_HEIGHT / 2 ) ) )
{
// scroll all the way to the bottom
ubDesiredMessageIndex = ubNumMessages - MAX_CHATLOG_MESSAGES;
}
else
{
// somewhere in between
ubDesiredSliderOffset = ubMouseYOffset - ( CHAT_SLIDER_HEIGHT / 2 );
Assert( ubDesiredSliderOffset <= CHAT_SLIDER_BAR_RANGE );
// calculate what the index should be to place the slider at this offset (round fractions of .5+ up)
ubDesiredMessageIndex = ( ( ubDesiredSliderOffset * ( ubNumMessages - MAX_CHATLOG_MESSAGES ) ) + ( CHAT_SLIDER_BAR_RANGE / 2 ) ) / CHAT_SLIDER_BAR_RANGE;
}
// if it's a change
if ( ubDesiredMessageIndex != gubFirstChatLogMessageIndex )
{
ChangeCurrentChatScreenMessageIndex( ubDesiredMessageIndex );
}
}
}
}
void DisplayChatLogScrollBarSlider( )
{
// will display the scroll bar icon
UINT8 ubNumMessages;
UINT8 ubSliderOffset;
HVOBJECT hHandle;
ubNumMessages = GetRangeOfChatLogMessages();
// only show the slider if there are more messages than will fit on screen
if ( ubNumMessages > MAX_CHATLOG_MESSAGES )
{
// calculate where slider should be positioned
ubSliderOffset = ( CHAT_SLIDER_BAR_RANGE * gubFirstChatLogMessageIndex ) / ( ubNumMessages - MAX_CHATLOG_MESSAGES );
GetVideoObject( &hHandle, guiChatSliderBar );
BltVideoObject( FRAME_BUFFER, hHandle, 8, CHATLOG_SCROLL_AREA_START_X + 2, CHATLOG_SCROLL_AREA_START_Y + ubSliderOffset, VO_BLT_SRCTRANSPARENCY, NULL );
}
}
// END MESSAGE SCROLLING
// CHAT MESSAGE ADDING AND PRINTING FUNCTIONS
void ChatLogMessage( UINT16 usColor, UINT8 ubPriority, STR16 pStringA, ... )
{
// this function sets up the string into several single line structures
//ScrollStringStPtr pStringSt;
UINT32 uiFont = CHAT_MESSAGE_FONT;
//STR16pString;
va_list argptr;
CHAR16 DestString[512];
WRAPPED_STRING *pStringWrapper=NULL;
WRAPPED_STRING *pStringWrapperHead=NULL;
BOOLEAN fNewString = FALSE;
UINT16 usLineWidthIfWordIsWiderThenWidth;
/*pStringSt=pStringS;
while(GetNextString(pStringSt))
pStringSt=GetNextString(pStringSt);*/
va_start(argptr, pStringA); // Set up variable argument pointer
vswprintf(DestString, pStringA, argptr); // process gprintf string (get output str)
va_end(argptr);
// send message to tactical screen and map screen
ScreenMsg( usColor, ubPriority, DestString );
pStringWrapperHead=LineWrap(uiFont, CHAT_LINE_WIDTH, &usLineWidthIfWordIsWiderThenWidth, DestString);
pStringWrapper=pStringWrapperHead;
if(!pStringWrapper)
return;
fNewString = TRUE;
while(pStringWrapper->pNextWrappedString!=NULL)
{
AddStringToChatLogMessageList(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority );
fNewString = FALSE;
pStringWrapper=pStringWrapper->pNextWrappedString;
}
AddStringToChatLogMessageList(pStringWrapper->sString, usColor, uiFont, fNewString, ubPriority );
// clear up list of wrapped strings
ClearWrappedStringsCHAT( pStringWrapperHead );
// play new message beep
//PlayNewMessageSound( );
MoveToEndOfChatScreenMessageList( );
//LeaveMutex(SCROLL_MESSAGE_MUTEX, __LINE__, __FILE__);
}
// add string to the chat log message list
void AddStringToChatLogMessageList( STR16 pString, UINT16 usColor, UINT32 uiFont, BOOLEAN fStartOfNewString, UINT8 ubPriority )
{
ScrollStringStPtr pStringSt = NULL;
pStringSt = (ScrollStringStPtr) MemAlloc(sizeof(ScrollStringSt));
SetString(pStringSt, pString);
SetStringColor(pStringSt, usColor);
pStringSt->uiFont = uiFont;
pStringSt->fBeginningOfNewString = fStartOfNewString;
pStringSt->uiFlags = ubPriority;
pStringSt->iVideoOverlay = -1;
// next/previous are not used, it's strictly a wraparound queue
SetStringNext(pStringSt, NULL);
SetStringPrev(pStringSt, NULL);
// Figure out which queue slot index we're going to use to store this
// If queue isn't full, this is easy, if is is full, we'll re-use the oldest slot
// Must always keep the wraparound in mind, although this is easy enough with a static, fixed-size queue.
// always store the new message at the END index
// check if slot is being used, if so, clear it up
if( gChatLogMessageList[ gubEndOfChatLogMessageList ] != NULL )
{
MemFree( gChatLogMessageList[ gubEndOfChatLogMessageList ]->pString16 );
MemFree( gChatLogMessageList[ gubEndOfChatLogMessageList ] );
}
// store the new message there
gChatLogMessageList[ gubEndOfChatLogMessageList ] = pStringSt;
// increment the end
gubEndOfChatLogMessageList = ( gubEndOfChatLogMessageList + 1 ) % 256;
// if queue is full, end will now match the start
if ( gubEndOfChatLogMessageList == gubStartOfChatLogMessageList )
{
// if that's so, increment the start
gubStartOfChatLogMessageList = ( gubStartOfChatLogMessageList + 1 ) % 256;
}
}
void DisplayStringsInChatLogMessageList( void )
{
UINT8 ubCurrentStringIndex;
UINT8 ubLinesPrinted;
INT16 sX, sY;
UINT16 usSpacing;
// Limit drawing to chat log region only, dont want any overdraw
sX = gChatMessageLogRegion.iLeft + 4;
SetFontDestBuffer( FRAME_BUFFER, sX , gChatMessageLogRegion.iTop + 4, gChatMessageLogRegion.iRight - 4, gChatMessageLogRegion.iBottom - 4, FALSE );
SetFont( CHAT_MESSAGE_FONT ); // no longer supports variable fonts
SetFontBackground( FONT_BLACK );
SetFontShadow( DEFAULT_SHADOW );
ubCurrentStringIndex = gubCurrentChatLogMessageString;
sY = gChatMessageLogRegion.iTop + 4;
usSpacing = GetFontHeight( CHAT_MESSAGE_FONT );
for ( ubLinesPrinted = 0; ubLinesPrinted < MAX_CHATLOG_MESSAGES; ubLinesPrinted++ )
{
// reached the end of the list?
if ( ubCurrentStringIndex == gubEndOfChatLogMessageList )
{
break;
}
// nothing stored there?
if ( gChatLogMessageList[ ubCurrentStringIndex ] == NULL )
{
break;
}
// set font color
SetFontForeground( ( UINT8 )( gChatLogMessageList[ ubCurrentStringIndex ]->usColor ) );
// print this line
mprintf_coded( sX, sY, gChatLogMessageList[ ubCurrentStringIndex ]->pString16 );
sY = sY + usSpacing;
// next message index to print (may wrap around)
ubCurrentStringIndex = ( ubCurrentStringIndex + 1 ) % 256;
}
// reset region to whole screen
SetFontDestBuffer( FRAME_BUFFER, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, FALSE );
}
void InitChatMessageList( void )
{
INT32 iCounter = 0;
for( iCounter = 0; iCounter < 256; iCounter++ )
{
gChatLogMessageList[ iCounter ] = NULL;
}
gubEndOfChatLogMessageList = 0;
gubStartOfChatLogMessageList = 0;
gubCurrentChatLogMessageString = 0;
return;
}
void FreeChatMessageList( void )
{
INT32 iCounter = 0;
for( iCounter = 0; iCounter < 256; iCounter++ )
{
// check if next unit is empty, if not...clear it up
if( gChatLogMessageList[ iCounter ] != NULL )
{
MemFree( gChatLogMessageList[ iCounter ]->pString16 );
MemFree( gChatLogMessageList[ iCounter ] );
}
}
InitChatMessageList( );
return;
}
UINT8 GetRangeOfChatLogMessages( void )
{
UINT8 ubRange = 0;
// NOTE: End is non-inclusive, so start/end 0/0 means no messages, 0/1 means 1 message, etc.
if( gubStartOfChatLogMessageList <= gubEndOfChatLogMessageList )
{
ubRange = gubEndOfChatLogMessageList - gubStartOfChatLogMessageList;
}
else
{
// this should always be 255 now, since this only happens when queue fills up, and we never remove any messages
ubRange = ( gubEndOfChatLogMessageList + 256 ) - gubStartOfChatLogMessageList;
}
return ( ubRange );
}
// helper function to clear a list of wrapped strings
// This same function exists in message.cpp
// copied here because i didnt want to include wordwrap.h in message.h
void ClearWrappedStringsCHAT( WRAPPED_STRING *pStringWrapperHead )
{
WRAPPED_STRING *pNode = pStringWrapperHead;
WRAPPED_STRING *pDeleteNode = NULL;
// clear out a link list of wrapped string structures
// error check, is there a node to delete?
if( pNode == NULL )
{
// leave,
return;
}
do
{
// set delete node as current node
pDeleteNode = pNode;
// set current node as next node
pNode = pNode->pNextWrappedString;
//delete the string
MemFree( pDeleteNode->sString );
pDeleteNode->sString = NULL;
// clear out delete node
MemFree( pDeleteNode );
pDeleteNode = NULL;
} while( pNode );
// MemFree( pNode );
pStringWrapperHead = NULL;
} | [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
1613
]
]
]
|
4463685146dd76c6f1712f232984f84091755df1 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/nluaserver/src/lua/lmathlib.cc | 164107d9538a5203de51317c081dc2120d5c651f | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,778 | cc | /*
** $Id: lmathlib.cc,v 1.2 2004/03/26 00:39:30 enlight Exp $
** Standard mathematical library
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
#include <math.h>
#define lmathlib_c
#include "lua/lua.h"
#include "lua/lauxlib.h"
#include "lua/lualib.h"
#undef PI
#define PI (3.14159265358979323846)
#define RADIANS_PER_DEGREE (PI/180.0)
/*
** If you want Lua to operate in degrees (instead of radians),
** define USE_DEGREES
*/
#ifdef USE_DEGREES
#define FROMRAD(a) ((a)/RADIANS_PER_DEGREE)
#define TORAD(a) ((a)*RADIANS_PER_DEGREE)
#else
#define FROMRAD(a) (a)
#define TORAD(a) (a)
#endif
static int math_abs (lua_State *L) {
lua_pushnumber(L, fabs(luaL_checknumber(L, 1)));
return 1;
}
static int math_sin (lua_State *L) {
lua_pushnumber(L, sin(TORAD(luaL_checknumber(L, 1))));
return 1;
}
static int math_cos (lua_State *L) {
lua_pushnumber(L, cos(TORAD(luaL_checknumber(L, 1))));
return 1;
}
static int math_tan (lua_State *L) {
lua_pushnumber(L, tan(TORAD(luaL_checknumber(L, 1))));
return 1;
}
static int math_asin (lua_State *L) {
lua_pushnumber(L, FROMRAD(asin(luaL_checknumber(L, 1))));
return 1;
}
static int math_acos (lua_State *L) {
lua_pushnumber(L, FROMRAD(acos(luaL_checknumber(L, 1))));
return 1;
}
static int math_atan (lua_State *L) {
lua_pushnumber(L, FROMRAD(atan(luaL_checknumber(L, 1))));
return 1;
}
static int math_atan2 (lua_State *L) {
lua_pushnumber(L, FROMRAD(atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2))));
return 1;
}
static int math_ceil (lua_State *L) {
lua_pushnumber(L, ceil(luaL_checknumber(L, 1)));
return 1;
}
static int math_floor (lua_State *L) {
lua_pushnumber(L, floor(luaL_checknumber(L, 1)));
return 1;
}
static int math_mod (lua_State *L) {
lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
return 1;
}
static int math_sqrt (lua_State *L) {
lua_pushnumber(L, sqrt(luaL_checknumber(L, 1)));
return 1;
}
static int math_pow (lua_State *L) {
lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
return 1;
}
static int math_log (lua_State *L) {
lua_pushnumber(L, log(luaL_checknumber(L, 1)));
return 1;
}
static int math_log10 (lua_State *L) {
lua_pushnumber(L, log10(luaL_checknumber(L, 1)));
return 1;
}
static int math_exp (lua_State *L) {
lua_pushnumber(L, exp(luaL_checknumber(L, 1)));
return 1;
}
static int math_deg (lua_State *L) {
lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE);
return 1;
}
static int math_rad (lua_State *L) {
lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE);
return 1;
}
static int math_frexp (lua_State *L) {
int e;
lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e));
lua_pushnumber(L, e);
return 2;
}
static int math_ldexp (lua_State *L) {
lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2)));
return 1;
}
static int math_min (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
lua_Number dmin = luaL_checknumber(L, 1);
int i;
for (i=2; i<=n; i++) {
lua_Number d = luaL_checknumber(L, i);
if (d < dmin)
dmin = d;
}
lua_pushnumber(L, dmin);
return 1;
}
static int math_max (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
lua_Number dmax = luaL_checknumber(L, 1);
int i;
for (i=2; i<=n; i++) {
lua_Number d = luaL_checknumber(L, i);
if (d > dmax)
dmax = d;
}
lua_pushnumber(L, dmax);
return 1;
}
static int math_random (lua_State *L) {
/* the `%' avoids the (rare) case of r==1, and is needed also because on
some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
switch (lua_gettop(L)) { /* check number of arguments */
case 0: { /* no arguments */
lua_pushnumber(L, r); /* Number between 0 and 1 */
break;
}
case 1: { /* only upper limit */
int u = luaL_checkint(L, 1);
luaL_argcheck(L, 1<=u, 1, "interval is empty");
lua_pushnumber(L, (int)floor(r*u)+1); /* int between 1 and `u' */
break;
}
case 2: { /* lower and upper limits */
int l = luaL_checkint(L, 1);
int u = luaL_checkint(L, 2);
luaL_argcheck(L, l<=u, 2, "interval is empty");
lua_pushnumber(L, (int)floor(r*(u-l+1))+l); /* int between `l' and `u' */
break;
}
default: return luaL_error(L, "wrong number of arguments");
}
return 1;
}
static int math_randomseed (lua_State *L) {
srand(luaL_checkint(L, 1));
return 0;
}
static const luaL_reg mathlib[] = {
{"abs", math_abs},
{"sin", math_sin},
{"cos", math_cos},
{"tan", math_tan},
{"asin", math_asin},
{"acos", math_acos},
{"atan", math_atan},
{"atan2", math_atan2},
{"ceil", math_ceil},
{"floor", math_floor},
{"mod", math_mod},
{"frexp", math_frexp},
{"ldexp", math_ldexp},
{"sqrt", math_sqrt},
{"min", math_min},
{"max", math_max},
{"log", math_log},
{"log10", math_log10},
{"exp", math_exp},
{"deg", math_deg},
{"pow", math_pow},
{"rad", math_rad},
{"random", math_random},
{"randomseed", math_randomseed},
{NULL, NULL}
};
/*
** Open math library
*/
LUALIB_API int luaopen_math (lua_State *L) {
luaL_openlib(L, LUA_MATHLIBNAME, mathlib, 0);
lua_pushliteral(L, "pi");
lua_pushnumber(L, PI);
lua_settable(L, -3);
lua_pushliteral(L, "__pow");
lua_pushcfunction(L, math_pow);
lua_settable(L, LUA_GLOBALSINDEX);
return 1;
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
246
]
]
]
|
59dafcc6c56c8160a66b1542fb011b697c73186f | b7d5640a8078e579f61d54f81858cc1dff3fa7ae | /GameClient/include/engine/engine.h | f160a32b100bbd13f918169d36869cf5e59f8858 | []
| no_license | gemini14/Typhon | 7497d225aa46abae881e77450466592dc0615060 | fa799896e13cdfaf40f65ff0981e7d98ad80a5f0 | refs/heads/master | 2016-09-06T14:34:11.048290 | 2011-10-22T07:12:33 | 2011-10-22T07:12:33 | 1,990,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | h | #ifndef ENGINE_H
#define ENGINE_H
#include <memory>
#include <queue>
#include <string>
#include <boost/noncopyable.hpp>
#ifdef WIN32
#include <WinSock2.h>
#else
#include <netinet/in.h>
#endif
#include "engine/luamanager.h"
#include "i18n/i18n.h"
#include "irrlicht/irrlicht.h"
#include "font/font_manager.h"
#include "state/fsmevents.h"
#include "utility/useroptions.h"
namespace Typhon
{
class Engine : boost::noncopyable
{
private:
std::unique_ptr<FontManager> fonts;
public:
bool ready;
bool terminate;
int perfScore;
irr::IrrlichtDevice *device;
irr::scene::ISceneManager *smgr;
irr::video::IVideoDriver *driver;
irr::gui::IGUIEnvironment *gui;
LuaManager lua;
std::queue<FSM::EVENT_TYPE> eventQueue;
std::shared_ptr<I18N> lang;
UserOptions options;
sockaddr_in serverIP;
bool clientIsServer;
std::shared_ptr<std::string> lobbyList;
Engine();
~Engine();
void SavePrefs();
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
6871f6f63d46c1c06caf8c3d2639e63dea50d606 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/asio/test/serial_port.cpp | 9146b590900886d4ef01405e8d6a577325f77391 | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,721 | cpp | //
// serial_port.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected])
//
// 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)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include <boost/asio/serial_port.hpp>
#include <boost/asio.hpp>
#include "unit_test.hpp"
//------------------------------------------------------------------------------
// serial_port_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all public member functions on the class
// serial_port compile and link correctly. Runtime failures are ignored.
namespace serial_port_compile {
void write_some_handler(const boost::system::error_code&, std::size_t)
{
}
void read_some_handler(const boost::system::error_code&, std::size_t)
{
}
void test()
{
#if defined(BOOST_ASIO_HAS_SERIAL_PORT)
using namespace boost::asio;
try
{
io_service ios;
char mutable_char_buffer[128] = "";
const char const_char_buffer[128] = "";
serial_port::baud_rate serial_port_option;
boost::system::error_code ec;
// basic_serial_port constructors.
serial_port port1(ios);
serial_port port2(ios, "null");
serial_port::native_type native_port1 = port1.native();
serial_port port3(ios, native_port1);
// basic_io_object functions.
io_service& ios_ref = port1.io_service();
(void)ios_ref;
// basic_serial_port functions.
serial_port::lowest_layer_type& lowest_layer = port1.lowest_layer();
(void)lowest_layer;
const serial_port& port4 = port1;
const serial_port::lowest_layer_type& lowest_layer2 = port4.lowest_layer();
(void)lowest_layer2;
port1.open("null");
port1.open("null", ec);
serial_port::native_type native_port2 = port1.native();
port1.assign(native_port2);
serial_port::native_type native_port3 = port1.native();
port1.assign(native_port3, ec);
bool is_open = port1.is_open();
(void)is_open;
port1.close();
port1.close(ec);
serial_port::native_type native_port4 = port1.native();
(void)native_port4;
port1.cancel();
port1.cancel(ec);
port1.set_option(serial_port_option);
port1.set_option(serial_port_option, ec);
port1.get_option(serial_port_option);
port1.get_option(serial_port_option, ec);
port1.send_break();
port1.send_break(ec);
port1.write_some(buffer(mutable_char_buffer));
port1.write_some(buffer(const_char_buffer));
port1.write_some(buffer(mutable_char_buffer), ec);
port1.write_some(buffer(const_char_buffer), ec);
port1.async_write_some(buffer(mutable_char_buffer), write_some_handler);
port1.async_write_some(buffer(const_char_buffer), write_some_handler);
port1.read_some(buffer(mutable_char_buffer));
port1.read_some(buffer(mutable_char_buffer), ec);
port1.async_read_some(buffer(mutable_char_buffer), read_some_handler);
}
catch (std::exception&)
{
}
#endif // defined(BOOST_ASIO_HAS_SERIAL_PORT)
}
} // namespace serial_port_compile
//------------------------------------------------------------------------------
test_suite* init_unit_test_suite(int, char*[])
{
test_suite* test = BOOST_TEST_SUITE("serial_port");
test->add(BOOST_TEST_CASE(&serial_port_compile::test));
return test;
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
131
]
]
]
|
757029a04e52256fdb524f2361656755a580307e | 1e23d293a86830184ff9d59039e4d8f2d2a8f318 | /array2d.h | e166ec1243b0f67c8b120eabc37323402d355888 | []
| no_license | beru/bitmap-font-encoder | c95a3e9641119f79cf0c93fd797a41db84685473 | 1ca6f91c440dc05db4c4ec2ac99a14ffe908209a | refs/heads/master | 2016-09-06T17:27:29.748951 | 2011-08-23T13:21:33 | 2011-08-23T13:21:33 | 33,050,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | h | #pragma once
#include <vector>
template <typename T>
class Array2D
{
public:
Array2D(T* mem)
:
values_(mem)
{
}
Array2D& operator = (const Array2D& a)
{
Resize(a.w_, a.h_);
std::copy(a.values_, a.values_ + w_*h_, values_);
return *this;
}
void Resize(size_t w, size_t h)
{
std::fill(values_, values_+w*h, T());
w_ = w;
h_ = h;
}
T* operator[] (int row) {
return &values_[row * w_];
}
const T* operator[] (int row) const {
return &values_[row * w_];
}
size_t GetWidth() const { return w_; }
size_t GetHeight() const { return h_; }
private:
size_t w_;
size_t h_;
T* values_;
};
| [
"[email protected]"
]
| [
[
[
1,
45
]
]
]
|
2c85f3f3d7d2367cb9cf265da3f5d116403e0a03 | 3ab5d507d11afdab41c8c1b509cc2a807d717897 | /src/VoIPModule/VoIPModule.h | 0da39f1d8f3272001c54406b134069b8b5745b6e | []
| no_license | mkurdej/pwtinproject | 73dd952ca7b18c36b0c68124bd4447c9741fa372 | f11afa69776c9f9b55c3c3466544ed49e56ebdff | refs/heads/master | 2016-09-05T18:39:33.692316 | 2010-01-19T10:16:55 | 2010-01-19T10:16:55 | 32,997,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | h | /**
* @file VoIPModule.h
*
* @date created 2010-01-14
* @author: Piotr Gwizda�a
*/
#ifndef VOIPMODULE_H_
#define VOIPMODULE_H_
#include <string>
#include <stdexcept>
#include <queue>
#include "../Debug/Debug.h"
#include "../Main/Config.h"
#include "../Main/Main.h"
#include "../ProtocolModule/SIP/SIPAgent.h"
#include "../ProtocolModule/RTP/RTPAgent.h"
#include "../ProtocolModule/RTP/RTPPacket.h"
#include "../VoIPPacketsManager/VoIPPacketsManager.h"
#include "../VoIPPacketsManager/NoSteg.h"
#include "../VoIPPacketsManager/StegLACK.h"
#include "../Util/Observer/Observer.h"
#include "../Util/Timer.h"
using namespace std;
/**
* \~
* \~polish
* Klasa pośrednicząca między pozostałymi modułami aplikacji VoIP.
*
* Nawiązuje połączenie korzystając z SIP i RTP, następnie pobiera pakiety
* od @ref VoIPPacketsManager i przekazuje do wysłania.
* W międzyczasie odbiera pakiety i przekazuje je do przetworzenia również do VoIPPacketsManager.
*
* \~english
* A controlling class that administers and mediates other modules of VoIP application.
*
* It makes a connection using SIP and RTP protocols, and then gets packets
* from @ref VoIPPacketsManager.
* In the meantime it receives packets and pushes them to the @ref VoIPPacketsManager.
*
* \~
*/
class VoIPModule : public Observer {
public:
VoIPModule(Config* config);
virtual ~VoIPModule();
void connect();
//@Override
void update();
private:
void processIncomingPackets();
void doSending();
void doReceiving();
void doTransport();
Config& config;
SIPAgent* sipAgent;
RTPAgent* rtpAgent;
VoIPPacketsManager* packetsManager;
CallInfo callInfo;
};
#endif /* VOIPMODULE_H_ */
| [
"marek.kurdej@f427f6ac-f01a-11de-af0a-9d584d74d99e",
"gwizdek@f427f6ac-f01a-11de-af0a-9d584d74d99e"
]
| [
[
[
1,
2
],
[
4,
5
],
[
11,
26
],
[
28,
30
],
[
33,
51
],
[
53,
53
],
[
56,
56
],
[
58,
73
]
],
[
[
3,
3
],
[
6,
10
],
[
27,
27
],
[
31,
32
],
[
52,
52
],
[
54,
55
],
[
57,
57
],
[
74,
76
]
]
]
|
d8f289d134072aa72a291534cf7c90d4ab399015 | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /NpcServer/NpcKernel/NetWork/MsgAiNpcInfo.cpp | 7db128c67da2041f656b45dc30b347ad0a47a94e | []
| no_license | cronoszeu/revresyksgpr | 78fa60d375718ef789042c452cca1c77c8fa098e | 5a8f637e78f7d9e3e52acdd7abee63404de27e78 | refs/heads/master | 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 1,136 | cpp | #include "allmsg.h"
#include "Npc.h"
#include "NpcWorld.h"
bool CMsgAiNpcInfo::Create(int nAction, OBJID idNpc, OBJID idGen, int nType, OBJID idMap, int nPosX, int nPosY)
{
CHECKF(nAction == MSGAINPCINFO_CREATENEW);
m_id = idNpc;
m_usAction = nAction;
m_usType = nType;
m_idMap = idMap;
m_usPosX = nPosX;
m_usPosY = nPosY;
m_idGen = idGen;
m_idOwner = ID_NONE;
m_ucOwnerType = OWNER_NONE;
m_nData = 0;
return true;
}
void CMsgAiNpcInfo::Process()
{
#ifdef _MYDEBUG
::LogSave("Process CMsgAiNpcInfo: ID:0x:%x, Type:%d, LookType:%d, CellX:%d, CellY:%d, Name:%s",
m_id , m_usType,
m_usLook, m_usCellX,
m_usCellY, m_szName);
#endif
//if (!pSocket)
// return;
if(NpcManager()->QuerySet()->GetObj(m_id))
{
return; //@ 已经有此NPC,如何处理?
}
CNpc* pNpc = CNpc::CreateNew();
if(pNpc)
{
if(pNpc->Create(m_id, m_usType, m_idMap, m_usPosX, m_usPosY, m_idGen,
m_idOwner, m_ucOwnerType, m_nData))
{
NpcManager()->QuerySet()->AddObj(Cast<INpc>(pNpc));
return ;
}
pNpc->ReleaseByOwner();
}
}
| [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
]
| [
[
[
1,
59
]
]
]
|
4703208533d46f4831c44c00ead6e495dbae0a57 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor-0.32/diagram/DiagramEditor/DiagramLine.cpp | a1f31c7922ad2ce3c5185c92758f9e67362dffdd | []
| no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,307 | cpp | /* ==========================================================================
CDiagramLine
Author : Johan Rosengren, Abstrakt Mekanik AB
Date : 2004-03-30
Purpose : Encapsulates a line object. Other line objects can be
derived from this class.
Description : First of all, we do not want constraints to the line
size (as we can't move the end points freely if that
is the case), so one SetRect must be modified. Second,
we need a non-rectangular body area for hit testing, a
line in this case. Third, we need only a subset of the
selection markers. All this is implemented in this
class, to serve as a model or base class for other line
objects.
Usage : Use as a model for line objects.
========================================================================*/
#include "stdafx.h"
#include "DiagramLine.h"
#include "Tokenizer.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
VOID CALLBACK HitTest( int X, int Y, LPARAM data )
/* ============================================================
Function : HitTest
Description : Checks if the coordinate in the hitParams
struct falls within +/- 1 of the x, y
coordinates of this point of the line.
Return : nothing
Parameters : int X - Current x coordinate
int Y - Current y coordinate
LPARAM data - Pointer to a hitParams
struct containing the x,y
coordinates to check. The
hit element will be set to
TRUE if the condition is
met.
Usage : LineDDA callback function. Called for each
point of the line
============================================================*/
{
hitParams* obj = ( hitParams* ) data;
if( obj->x >= X - 1 && obj->x <= X + 1 && obj->y >= Y - 1 && obj->y <= Y + 1 )
obj->hit = TRUE;
}
VOID CALLBACK HitTestRect( int X, int Y, LPARAM data )
/* ============================================================
Function : HitTestRect
Description : Checks if the x, y coordinates of the line
falls withing the hitParamsRect rectangle.
Return : nothing
Parameters : int X - Current x coordinate
int Y - Current y coordinate
LPARAM data - Pointer to a hitParamsRect
struct containing the rect
to check. The hit element
will be set to TRUE if the
condition is met.
Usage : LineDDA callback function. Called for each
point of the line.
============================================================*/
{
hitParamsRect* obj = ( hitParamsRect* ) data;
CPoint pt( X, Y );
if( obj->rect.PtInRect( pt ) )
obj->hit = TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CDiagramLine
//
CDiagramLine::CDiagramLine()
/* ============================================================
Function : CDiagramLine::CDiagramLine
Description : constructor
Return : void
Parameters : none
Usage :
============================================================*/
{
SetMinimumSize( CSize( -1, -1 ) );
SetType( _T( "line" ) );
}
CDiagramEntity* CDiagramLine::Clone()
/* ============================================================
Function : CDiagramLine::Clone
Description : Clones this object and returns a new one.
Return : CDiagramEntity* - The resulting clone
Parameters : none
Usage :
============================================================*/
{
CDiagramLine* obj = new CDiagramLine;
obj->Copy( this );
return obj;
}
void CDiagramLine::SetRect( CRect rect )
/* ============================================================
Function : CDiagramLine::SetRect
Description : Sets the rect of the object.
Return : void
Parameters : CRect rect -
Usage : Overriden to avoid normalization.
============================================================*/
{
SetLeft( rect.left );
SetTop( rect.top );
SetRight( rect.right );
SetBottom( rect.bottom );
}
BOOL CDiagramLine::BodyInRect( CRect rect ) const
/* ============================================================
Function : CDiagramLine::BodyInRect
Description : Checks if some part of the body of this
object lies inside the rectangle rect.
Return : BOOL - TRUE if any part of the
object lies inside rect.
Parameters : CRect rect - The rect to test.
Usage : Shows one way to test a non-rectangular
object body - in this case a line.
============================================================*/
{
BOOL result = FALSE;
hitParamsRect hit;
hit.rect = rect;
hit.hit = FALSE;
LineDDA( ( int ) GetLeft(),
( int ) GetTop(),
( int ) GetRight(),
( int ) GetBottom(),
HitTestRect,
( LPARAM ) &hit );
if( hit.hit )
result = TRUE;
return result;
}
int CDiagramLine::GetHitCode( CPoint point ) const
/* ============================================================
Function : CDiagramLine::GetHitCode
Description : Returns the hit point constant (DEHT_,
defined in DiagramEntity.h) for point.
Return : int - The resulting hit point
constant, DEHT_NONE if
none.
Parameters : CPoint point - The point to test.
Usage : Shows one way to hit point test a non-
rectangular area.
============================================================*/
{
int result = DEHT_NONE;
CRect rect = GetRect();
hitParams hit;
hit.hit = FALSE;
hit.x = point.x;
hit.y = point.y;
LineDDA( ( int ) GetLeft(),
( int ) GetTop(),
( int ) GetRight(),
( int ) GetBottom(),
HitTest,
(LPARAM) &hit );
if( hit.hit )
result = DEHT_BODY;
CRect rectTest;
rectTest = GetSelectionMarkerRect( DEHT_TOPLEFT, rect );
if( rectTest.PtInRect( point ) )
result = DEHT_TOPLEFT;
rectTest = GetSelectionMarkerRect( DEHT_BOTTOMRIGHT, rect );
if( rectTest.PtInRect( point ) )
result = DEHT_BOTTOMRIGHT;
return result;
}
void CDiagramLine::Draw( CDC* dc, CRect rect )
/* ============================================================
Function : CDiagramLine::Draw
Description : Draws the object.
Return : void
Parameters : CDC* dc - CDC to draw to
CRect rect - True (zoomed) rectangle to
draw to.
Usage :
============================================================*/
{
dc->SelectStockObject( BLACK_PEN );
dc->MoveTo( rect.TopLeft() );
dc->LineTo( rect.BottomRight() );
}
HCURSOR CDiagramLine::GetCursor( int hit ) const
/* ============================================================
Function : CDiagramLine::GetCursor
Description : Returns the cursor for a specific hit
point.
Return : HCURSOR - The cursor to display, or NULL
if default.
Parameters : int hit - The hit point constant (DEHT_,
defined in DiagramEntity.h) to
show a cursor for.
Usage : Shows the cursor for a subset of the hit
points. Will also show cursors different
from the standard ones.
============================================================*/
{
HCURSOR cursor = NULL;
switch( hit )
{
case DEHT_BODY:
cursor = LoadCursor( NULL, IDC_SIZEALL );
break;
case DEHT_TOPLEFT:
cursor = LoadCursor( NULL, IDC_SIZEALL );
break;
case DEHT_BOTTOMRIGHT:
cursor = LoadCursor( NULL, IDC_SIZEALL );
break;
}
return cursor;
}
void CDiagramLine::DrawSelectionMarkers( CDC* dc, CRect rect ) const
/* ============================================================
Function : CDiagramLine::DrawSelectionMarkers
Description : Draws selection markers for this object.
Return : void
Parameters : CDC* dc - CDC to draw to.
CRect rect - True object rectangle.
Usage : Draws a subset of the standard selection
markers.
============================================================*/
{
// Draw selection markers
CRect rectSelect;
dc->SelectStockObject( BLACK_BRUSH );
rectSelect = GetSelectionMarkerRect( DEHT_TOPLEFT, rect );
dc->Rectangle( rectSelect );
rectSelect = GetSelectionMarkerRect( DEHT_BOTTOMRIGHT, rect );
dc->Rectangle( rectSelect );
}
CDiagramEntity* CDiagramLine::CreateFromString( XML::Node* node )
/* ============================================================
Function : CDiagramLine::CreateFromString
Description : Static factory function to create a
CDiagramLine object from str.
Return : CDiagramEntity* - Resulting object,
NULL if str is not
a representation of
a CDiagramLine.
Parameters : const CString& str - String representation
to decode.
Usage : One proposed mechanism for loading/creating
CDiagramEntity-derived objects from a text
stream.
============================================================*/
{
CDiagramLine* obj = new CDiagramLine;
if(!obj->FromString( node ) )
{
delete obj;
obj = NULL;
}
return obj;
}
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
354
]
]
]
|
9361b4348a71f194676289b7642f2e850b781128 | 30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff | /squirrel/source/modem.cpp | 66438fab3ed9a0f92e2170a03f6eb06594523a27 | []
| no_license | inspirer/history | ed158ef5c04cdf95270821663820cf613b5c8de0 | 6df0145cd28477b23748b1b50e4264a67441daae | refs/heads/master | 2021-01-01T17:22:46.101365 | 2011-06-12T00:58:37 | 2011-06-12T00:58:37 | 1,882,931 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 10,677 | cpp |
struct mc { char st[80],ok[80]; };
struct config
{
mc init,offhook,onhook,voice,data,play,stplay,mailinit;
mc rec,strec,beep,sphone,mphone,abeep,deinit,aonreq;
char irq,dle,etx,ring; // Interrupt,DLE,ETX,AnsOnRING
unsigned int waitans,cmddelay; // Wait for answer(1/10),Delay cmd (ms)
unsigned int ioport,baud,khz; // I/O Port,Baud Rate,PCSpeaker freq.
int debuginfo,gsmframe,pln; // Debug,Use GSM,Play/Rec to/from line
char vdir[128],realcl,sallo[128]; // VoiceDIR,realclose?,sound:allo
int hear,up,RTL,rec_time,wavout; // time to listen,do off/on hook
char swait[128],sauto[128],ata[128];// sound:wait, sound:auto
unsigned int delayring,limit,wallo; // Pause RING,Limit,Wait After OffHook
int wav8bit,delay1,delay2,useaon; // 8-bit wav,AON delay1&2,use_aon
int hook,digits; // aondebug,do offhook?
long minver,auto_detect,postspace; // min ver,auto detect voice
char log[128],soundfl[128]; // log name
int loglev,frame; // debug?, frame noise level
};
config cfg;
FILE *fp;
char ch;
FILE *Log;
void ErrorExit(int code,char *str)
{
while (kbhit()) getch();
if (cfg.debuginfo){
cout << " ! Press any key to return" << endl;
while(kbhit()) getch();
long _o=time(NULL)+10;
while(kbhit()==0&&time(NULL)<=_o);
}
ExitScr();
if (cfg.realcl&&prtst==-1){
cout<< "real: ";
RealCloseComm();
} else CloseComm();
nosound;fclose(Log);
cout << str << " (ErrorLev " << code << ")" << endl << endl;
exit (code);
}
void write_log(char *lg)
{
if (cfg.log[0]!=0){
if (Log==NULL){
Log=fopen(cfg.log,"a");
if (Log==NULL) ErrorExit(82,"log appending error");
}
fprintf(Log,lg);
}
}
void write_log_num(long nm)
{
char num[20];
num[0]=0;
if (nm==0){
num[0]='0';num[1]=0;
} else while(nm>0){
num[strlen(num)+1]=0;
num[strlen(num)]=nm%10+'0';
nm/=10;
}strrev(num);
write_log(num);
}
int DetectFlag(char *fname)
{
int fhandle;
if ((fhandle=open(fname,O_RDONLY))!=-1) {
close(fhandle);return 1;
} else return 0;
}
void CreateFlag(char *fname)
{
FILE *out;
if ((out = fopen(fname,"wb"))!=NULL){ fclose(out);}
}
void SetDefault()
{
// Strings
strcpy(cfg.init.st,cfg_init_st); strcpy(cfg.init.ok,"OK");
strcpy(cfg.deinit.st,cfg_deinit_st); strcpy(cfg.deinit.ok,"OK");
strcpy(cfg.offhook.st,cfg_offhook_st); strcpy(cfg.offhook.ok,"OK");
strcpy(cfg.onhook.st,cfg_onhook_st); strcpy(cfg.onhook.ok,"OK");
strcpy(cfg.voice.st,cfg_voice_st); strcpy(cfg.voice.ok,"OK");
strcpy(cfg.data.st,cfg_data_st); strcpy(cfg.data.ok,"OK");
strcpy(cfg.play.st,cfg_play_st); strcpy(cfg.play.ok,"CONNECT");
strcpy(cfg.rec.st,cfg_rec_st); strcpy(cfg.rec.ok,"CONNECT");
strcpy(cfg.stplay.st,cfg_stplay_st); strcpy(cfg.stplay.ok,"VCON");
strcpy(cfg.strec.st,cfg_strec_st); strcpy(cfg.strec.ok,"VCON");
strcpy(cfg.beep.st,cfg_beep_st); strcpy(cfg.beep.ok,"OK");
strcpy(cfg.abeep.st,cfg_aabeep_st); strcpy(cfg.abeep.ok,"OK");
strcpy(cfg.sphone.st,cfg_sphone_st); strcpy(cfg.sphone.ok,"VCON");
strcpy(cfg.mphone.st,cfg_mphone_st); strcpy(cfg.mphone.ok,"VCON");
strcpy(cfg.mailinit.st,cfg_mailinit_st);strcpy(cfg.mailinit.ok,"OK");
strcpy(cfg.aonreq.st,AON_request); strcpy(cfg.aonreq.ok,"OK");
strcpy(cfg.sallo,cfg_file_allo);
strcpy(cfg.swait,cfg_file_wait);
strcpy(cfg.sauto,cfg_file_auto);
strcpy(cfg.ata,cfg_mailer_ata);
cfg.irq=cfg_modem_irq+8;
cfg.ioport=cfg_ioport;
cfg.baud=cfg_baud;
cfg.dle=cfg_dle;
cfg.etx=cfg_etx;
cfg.ring=cfg_ring;
cfg.waitans=cfg_wait_answer;
cfg.cmddelay=cfg_command_delay;
cfg.khz=cfg_speaker_freq;
cfg.debuginfo=show_debug_info;
cfg.gsmframe=cfg_use_gsm;
cfg.pln=cfg_play_device;
strcpy(cfg.vdir,cfg_voice_dir);
cfg.delayring=cfg_pause_ring;
cfg.limit=cfg_detect_num;
cfg.wallo=cfg_wait_offhook;
cfg.realcl=cfg_real_close;
cfg.hear=cfg_listen;
cfg.up=1;cfg.rec_time=cfg_rec_message;
cfg.RTL=cfg_ring_to_line;
cfg.wavout=WAVE_output;
cfg.wav8bit=WAV_8bit;
cfg.delay1=AON_delay_bef;
cfg.delay2=AON_delay_after;
cfg.useaon=Use_AON;
cfg.minver=AON_signal;
strcpy(cfg.log,logfile);
strcpy(cfg.soundfl,cfg_sound_flag);
cfg.hook=cfg_offhook;
cfg.digits=AON_digits;
cfg.auto_detect=cfg_auto_detect;
cfg.postspace=cfg_post_space;
cfg.frame=cfg_frame;
cfg.loglev=cfg_log_level;
}
void SendModemStr(mc *snd,char *str)
{
int wfor=0;
for(int cmdnum=1;(cmdnum<=3)&&(wfor==0);cmdnum++){
cout << " " << str << " : ";
for (int cnt=0;cnt<strlen(snd->st);cnt++){
if (snd->st[cnt]=='~') snd->st[cnt]=cfg.dle;
if (snd->st[cnt]=='!') snd->st[cnt]=cfg.etx;
}
if (cfg.cmddelay>0) Delay(cfg.cmddelay);
WriteCommStr((*snd).st);WriteComm(13);
if (cfg.debuginfo){
cout << snd->st << "(" << snd->ok << ")" << endl;FixLine();
wfor=WaitFor(snd->ok,cfg.waitans,1);
cout << endl;FixLine();
cout << " Result: ";
} else {
wfor=WaitFor(snd->ok,cfg.waitans,0);
}
if (wfor){
cout << "OK" << endl;FixLine();
} else {
cout << "ERROR" << endl;FixLine();
}
}
if (!wfor) ErrorExit(4,"Command send error");
}
char prbuf[4092];
void PlayFile(char *fname)
{
cout << " þ Playing file : " << fname << endl;FixLine();
fp=fopen(fname,"rb");
while(kbhit()) getch();
// If fileopened;
if (fp!=NULL){
if (cfg.pln)
SendModemStr(&cfg.sphone,"Phones");
else
if (cfg.up) SendModemStr(&cfg.offhook,"Offhook");
SendModemStr(&cfg.play,"Voice playback");
cout << " Playing ...";
while (fread(prbuf,1,33,fp)==33){
if (cfg.gsmframe){
WriteComm(0xFE);WriteComm(0xFE);
}
for (int buffs=0;buffs<33;buffs++){
if (prbuf[buffs]==cfg.dle) WriteComm(cfg.dle);
WriteComm(prbuf[buffs]);
}
if (cfg.gsmframe){
WriteComm(0);WriteComm(0xA5);WriteComm(0xA5);
delay(cfg_gsm_delay);
}
if (kbhit()){ cout << "(stopped)";break;}
}
cout << endl;FixLine();
SendModemStr(&cfg.stplay,"Stop");
if (!cfg.pln)
if (cfg.up) SendModemStr(&cfg.onhook,"Onhook");
fclose(fp);
} else ErrorExit(5,"File not found");
}
void RecFile(char *fname,int ttime)
{
cout << " þ Recording file : " << fname << endl;FixLine();
if (cfg.wavout&&cfg.gsmframe){
if (!Start_GSM_WAV(fname,cfg.wav8bit)) ErrorExit(122,".wav file not created");
} else {
fp=fopen(fname,"wb");
}
while(kbhit()) getch();
int ctime=0;
// If fileopened;
if (fp!=NULL||cfg.wavout){
if (cfg.pln)
SendModemStr(&cfg.mphone,"Microphone");
else
if (cfg.up) SendModemStr(&cfg.offhook,"Offhook");
SendModemStr(&cfg.rec,"Voice record");
cout << " Recording ...";
int buffs=0;
while ((ctime<ttime||ttime==0)&&(kbhit()==0)&&ctime!=-1){
delay(990);ctime++;
while(ReadComm(ch)){
// Get character
if (ch==cfg.dle){
while(!ReadComm(ch));
if (ch==cfg.dle){
prbuf[buffs]=ch;buffs++;
} else switch(ch){
case 'b': cout << "b";ctime=-1;break;
case 'd': cout << "d";ctime=-1;break;
}
} else {
prbuf[buffs]=ch;
buffs++;
}
// Save buffer?
if (cfg.gsmframe){
if (buffs==38){
if (cfg.wavout) decode_block(prbuf+2,cfg.wav8bit);
else fwrite(prbuf+2,33,1,fp);
buffs=0;
}
} else {
if (buffs==40){fwrite(prbuf,40,1,fp);buffs=0;}
}
}
}
cout << endl;FixLine();
SendModemStr(&cfg.strec,"Stop");
SendModemStr(&cfg.voice,"Voice");
if (!cfg.pln)
if (cfg.up) SendModemStr(&cfg.onhook,"Onhook");
if (cfg.wavout&&cfg.gsmframe) Close_GSM_WAV(); else fclose(fp);
} else ErrorExit(121,".gsm file not created");
}
int Detect()
{
cout << " þ Detecting" << endl;FixLine();
SendModemStr(&cfg.rec,"Prepearing");
cout << " Listening ...";
if (cfg.loglev&2){
write_log("DETECTING: ");
}
long buffs=0,blcks=0,reslt=0;
while(blcks<5*cfg.hear&&reslt>=0){
while(!ReadComm(ch));
if (ch==cfg.dle){
while(!ReadComm(ch));
if (ch==cfg.dle){
prbuf[buffs]=ch;buffs++;
} else switch(ch){
case 'b': cout << "b";reslt=-1;break;
case 'd': cout << "d";reslt=-2;break;
}
} else {
prbuf[buffs]=ch;
buffs++;
}
if (buffs==38){
gsm_decode(&gsm,prbuf+2,wavb);
blcks++;buffs=0;
// Search for max volume
int max=0;for (int _qq=0;_qq<160;_qq++) if (wavb[_qq]>max) max=wavb[_qq];
// Check for silence
reslt+=max/cfg.frame;
if (cfg.loglev&2){
write_log_num(max);write_log(" ");
}
}
}
if (cfg.loglev&2) write_log("\n");
cout << endl;FixLine();
SendModemStr(&cfg.strec,"Stop");
SendModemStr(&cfg.voice,"Voice");
cout << " ! (noise=" << reslt << ") ";
if (cfg.loglev&2){
write_log("noise=");write_log_num(reslt);write_log("\n");
}
if (reslt==-1){ cout << "BUSY" << endl;FixLine();return 3;}
else if (reslt==-2){ cout << "DIAL TONE" << endl;FixLine();return 4;}
else if (reslt>cfg.limit){ cout << "VOICE" << endl;FixLine();return 2;}
else { cout << "MODEM"<< endl;FixLine();return 1; }
}
void generate_name(char *nm)
{
char tbl[]="0123456789";
struct time t;
unsigned char _a,_b;
char nm2[128];
gettime(&t);
_a=t.ti_hour/10;_b=t.ti_hour%10;nm[0]=tbl[_a];nm[1]=tbl[_b];
_a=t.ti_min/10;_b=t.ti_min%10;nm[3]=tbl[_a];nm[4]=tbl[_b];
_a=t.ti_sec/10;_b=t.ti_sec%10;nm[6]=tbl[_a];nm[7]=tbl[_b];
nm[2]='_';nm[5]='_';nm[8]=0;
if (cfg.gsmframe){ if (cfg.wavout) strcat(nm,".wav"); else strcat(nm,".gsm"); }
else strcat(nm,".pcm");
strcpy(nm2,cfg.vdir);strcat(nm2,nm);strcpy(nm,nm2);
}
| [
"[email protected]"
]
| [
[
[
1,
369
]
]
]
|
2bd9271425a39f476faf413fc8e9835e1e199cbd | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor-0.32/TestPage.cpp | 44643a18d0ce172e3b18be69d5a7a56ae2b5d375 | []
| no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 518 | cpp | // TestPage.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "GumpEditor.h"
#include "TestPage.h"
// CTestPage 대화 상자입니다.
IMPLEMENT_DYNAMIC(CTestPage, CPropertyPage)
CTestPage::CTestPage()
: CPropertyPage(CTestPage::IDD)
{
}
CTestPage::~CTestPage()
{
}
void CTestPage::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CTestPage, CPropertyPage)
END_MESSAGE_MAP()
// CTestPage 메시지 처리기입니다.
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
31
]
]
]
|
306e58f195269c1881bb89a5a39da6dd937ed7fb | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestquery/src/bctestquerycontainer.cpp | c1759e679194d8f94fb0cfebb4279166c3b70afd | []
| 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,464 | 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 "bctestquerycontainer.h"
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// C++ default Constructor
// ---------------------------------------------------------------------------
//
CBCTestQueryContainer::CBCTestQueryContainer()
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestQueryContainer::~CBCTestQueryContainer()
{
delete iControl;
iControl = NULL;
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTestQueryContainer::ConstructL( const TRect& aRect )
{
CreateWindowL();
SetRect( aRect );
ActivateL();
}
// ----------------------------------------------------------------------------
// CBCTestQueryContainer::Draw
// Fills the window's rectangle.
// ----------------------------------------------------------------------------
//
void CBCTestQueryContainer::Draw( const TRect& aRect ) const
{
CWindowGc& gc = SystemGc();
gc.SetPenStyle( CGraphicsContext::ENullPen );
gc.SetBrushColor( KRgbGray );
gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
gc.DrawRect( aRect );
}
// ---------------------------------------------------------------------------
// CBCTestQueryContainer::CountComponentControls
// ---------------------------------------------------------------------------
//
TInt CBCTestQueryContainer::CountComponentControls() const
{
if ( iControl )
{
return 1;
}
else
{
return 0;
}
}
// ---------------------------------------------------------------------------
// CBCTestQueryContainer::ComponentControl
// ---------------------------------------------------------------------------
//
CCoeControl* CBCTestQueryContainer::ComponentControl( TInt ) const
{
return iControl;
}
// ---------------------------------------------------------------------------
// CBCTestQueryContainer::SetControl
// ---------------------------------------------------------------------------
//
void CBCTestQueryContainer::SetControl( CCoeControl* aControl )
{
iControl = aControl;
if ( iControl )
{
iControl->SetExtent( Rect().iTl, Rect().Size() );
DrawNow();
}
}
// ---------------------------------------------------------------------------
// CBCTestQueryContainer::ResetControl
// ---------------------------------------------------------------------------
//
void CBCTestQueryContainer::ResetControl()
{
delete iControl;
iControl = NULL;
}
| [
"none@none"
]
| [
[
[
1,
119
]
]
]
|
6a34a3be8fcd5c76551738769b7d0495b3a8bf2a | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/internal/XTemplateComparator.hpp | 5709dcf80bb1ffb4e336e5467d7bdfa83fe28bab | [
"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 | 11,563 | hpp | /*
* Copyright 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.
*/
/*
* $Log: XTemplateComparator.hpp,v $
* Revision 1.2 2004/09/08 13:56:14 peiyongz
* Apache License Version 2.0
*
* Revision 1.1 2003/10/29 16:14:15 peiyongz
* XObjectComparator/XTemplateComparator
*
* $Id: XTemplateComparator.hpp,v 1.2 2004/09/08 13:56:14 peiyongz Exp $
*
*/
#if !defined(XTEMPLATE_COMPARATOR_HPP)
#define XTEMPLATE_COMPARATOR_HPP
#include <xercesc/util/ValueVectorOf.hpp>
#include <xercesc/util/RefArrayVectorOf.hpp>
#include <xercesc/util/RefVectorOf.hpp>
#include <xercesc/util/RefHashTableOf.hpp>
#include <xercesc/util/RefHash2KeysTableOf.hpp>
#include <xercesc/util/RefHash3KeysIdPool.hpp>
#include <xercesc/util/NameIdPool.hpp>
#include <xercesc/framework/XMLNotationDecl.hpp>
#include <xercesc/framework/XMLRefInfo.hpp>
#include <xercesc/util/XMLNumber.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/DTD/DTDAttDef.hpp>
#include <xercesc/validators/DTD/DTDElementDecl.hpp>
#include <xercesc/validators/DTD/DTDEntityDecl.hpp>
#include <xercesc/validators/schema/SchemaAttDef.hpp>
#include <xercesc/validators/schema/SchemaElementDecl.hpp>
#include <xercesc/validators/schema/XercesGroupInfo.hpp>
#include <xercesc/validators/schema/XercesAttGroupInfo.hpp>
#include <xercesc/validators/schema/SchemaGrammar.hpp>
#include <xercesc/validators/schema/identity/IC_Field.hpp>
#include <xercesc/validators/schema/identity/IdentityConstraint.hpp>
#include <xercesc/validators/schema/identity/XercesXPath.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLUTIL_EXPORT XTemplateComparator
{
public:
/**********************************************************
*
* ValueVectorOf
*
* SchemaElementDecl*
* unsigned int
*
***********************************************************/
static bool isEquivalent(
ValueVectorOf<SchemaElementDecl*>* const lValue
, ValueVectorOf<SchemaElementDecl*>* const rValue
);
static bool isEquivalent(
ValueVectorOf<unsigned int>* const lValue
, ValueVectorOf<unsigned int>* const rValue
);
/**********************************************************
*
* RefArrayVectorOf
*
* XMLCh
*
***********************************************************/
static bool isEquivalent(
RefArrayVectorOf<XMLCh>* const lValue
, RefArrayVectorOf<XMLCh>* const rValue
);
/**********************************************************
*
* RefVectorOf
*
* SchemaAttDef
* SchemaElementDecl
* ContentSpecNode
* IC_Field
* DatatypeValidator
* IdentityConstraint
* XMLNumber
* XercesLocationPath
* XercesStep
*
***********************************************************/
static bool isEquivalent(
RefVectorOf<SchemaAttDef>* const lValue
, RefVectorOf<SchemaAttDef>* const rValue
);
static bool isEquivalent(
RefVectorOf<SchemaElementDecl>* const lValue
, RefVectorOf<SchemaElementDecl>* const rValue
);
static bool isEquivalent(
RefVectorOf<ContentSpecNode>* const lValue
, RefVectorOf<ContentSpecNode>* const rValue
);
static bool isEquivalent(
RefVectorOf<IC_Field>* const lValue
, RefVectorOf<IC_Field>* const rValue
);
static bool isEquivalent(
RefVectorOf<DatatypeValidator>* const lValue
, RefVectorOf<DatatypeValidator>* const rValue
);
static bool isEquivalent(
RefVectorOf<IdentityConstraint>* const lValue
, RefVectorOf<IdentityConstraint>* const rValue
);
static bool isEquivalent(
RefVectorOf<XMLNumber>* const lValue
, RefVectorOf<XMLNumber>* const rValue
);
static bool isEquivalent(
RefVectorOf<XercesLocationPath>* const lValue
, RefVectorOf<XercesLocationPath>* const rValue
);
static bool isEquivalent(
RefVectorOf<XercesStep>* const lValue
, RefVectorOf<XercesStep>* const rValue
);
/**********************************************************
*
* RefHashTableOf
*
* KVStringPair
* XMLAttDef
* DTDAttDef
* ComplexTypeInfo
* XercesGroupInfo
* XercesAttGroupInfo
* XMLRefInfo
* DatatypeValidator
* Grammar
*
***********************************************************/
static bool isEquivalent(
RefHashTableOf<KVStringPair>* const lValue
, RefHashTableOf<KVStringPair>* const rValue
);
static bool isEquivalent(
RefHashTableOf<XMLAttDef>* const lValue
, RefHashTableOf<XMLAttDef>* const rValue
);
static bool isEquivalent(
RefHashTableOf<DTDAttDef>* const lValue
, RefHashTableOf<DTDAttDef>* const rValue
);
static bool isEquivalent(
RefHashTableOf<ComplexTypeInfo>* const lValue
, RefHashTableOf<ComplexTypeInfo>* const rValue
);
static bool isEquivalent(
RefHashTableOf<XercesGroupInfo>* const lValue
, RefHashTableOf<XercesGroupInfo>* const rValue
);
static bool isEquivalent(
RefHashTableOf<XercesAttGroupInfo>* const lValue
, RefHashTableOf<XercesAttGroupInfo>* const rValue
);
static bool isEquivalent(
RefHashTableOf<XMLRefInfo>* const lValue
, RefHashTableOf<XMLRefInfo>* const rValue
);
static bool isEquivalent(
RefHashTableOf<DatatypeValidator>* const lValue
, RefHashTableOf<DatatypeValidator>* const rValue
);
static bool isEquivalent(
RefHashTableOf<Grammar>* const lValue
, RefHashTableOf<Grammar>* const rValue
);
/**********************************************************
*
* RefHash2KeysTableOf
*
* SchemaAttDef
* ElemVector
*
***********************************************************/
static bool isEquivalent(
RefHash2KeysTableOf<SchemaAttDef>* const lValue
, RefHash2KeysTableOf<SchemaAttDef>* const rValue
);
static bool isEquivalent(
RefHash2KeysTableOf<ElemVector>* const lValue
, RefHash2KeysTableOf<ElemVector>* const rValue
);
/**********************************************************
*
* RefHash3KeysIdPool
*
* SchemaElementDecl
*
***********************************************************/
static bool isEquivalent(
RefHash3KeysIdPool<SchemaElementDecl>* const lop
, RefHash3KeysIdPool<SchemaElementDecl>* const rop
);
/**********************************************************
*
* NameIdPool
*
* DTDElementDecl
* DTDEntityDecl
* XMLNotationDecl
*
***********************************************************/
static bool isEquivalent(
NameIdPool<DTDElementDecl>* const lValue
, NameIdPool<DTDElementDecl>* const rValue
);
static bool isEquivalent(
NameIdPool<DTDEntityDecl>* const lValue
, NameIdPool<DTDEntityDecl>* const rValue
);
static bool isEquivalent(
NameIdPool<XMLNotationDecl>* const lValue
, NameIdPool<XMLNotationDecl>* const rValue
);
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
~XTemplateComparator();
XTemplateComparator();
XTemplateComparator(const XTemplateComparator&);
XTemplateComparator& operator=(const XTemplateComparator&);
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
280
]
]
]
|
3e103f069722d9e699f2857cf0ee04c7497556ac | 6caf1a340711c6c818efc7075cc953b2f1387c04 | /client/VersionInfo.cpp | 17440bbafaaf1a646432c8db3ce152d23bf83e6c | []
| no_license | lbrucher/timelis | 35c68061bea68cc31ce1c68e3adbc23cb7f930b1 | 0fa9f8f5ef28fe02ca620c441783a1ff3fc17bde | refs/heads/master | 2021-01-01T18:18:37.988944 | 2011-08-18T19:39:19 | 2011-08-18T19:39:19 | 2,229,915 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,554 | cpp | // $Id: VersionInfo.cpp,v 1.1 2005/01/13 17:50:08 lbrucher Exp $
//
#include "stdafx.h"
#include "VersionInfo.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// ////////////////////////////////////////////////////////////////////////////
//
CVersionInfo::CVersionInfo( const CString& sFilename, const CString& sLanguageCodepage )
{
ExtractInfo(sFilename, sLanguageCodepage);
}
// ////////////////////////////////////////////////////////////////////////////
//
CVersionInfo::CVersionInfo( HINSTANCE hModuleInstance, const CString& sLanguageCodepage )
{
char pFilename[1024];
if ( ::GetModuleFileName(hModuleInstance, pFilename, 1024) > 0 )
ExtractInfo(pFilename, sLanguageCodepage);
}
// ////////////////////////////////////////////////////////////////////////////
//
void CVersionInfo::ExtractInfo( const char* pFilename, const CString& sLanguageCodepage )
{
DWORD dwDummy;
DWORD dwSize = ::GetFileVersionInfoSize((char*)pFilename, &dwDummy);
if (dwSize > 0)
{
char *pBuffer = new char[dwSize];
if ( ::GetFileVersionInfo((char*)pFilename, dwDummy, dwSize, (void *)pBuffer) )
{
// Get Version Number
//
char pBlock[512];
UINT nTempSize;
LPSTR pTempData;
wsprintf(pBlock, "\\StringFileInfo\\%s\\FileVersion", sLanguageCodepage);
VerQueryValue(pBuffer, pBlock, (LPVOID *) &pTempData, &nTempSize);
m_sFileVersion = CString(pTempData);
wsprintf(pBlock, "\\StringFileInfo\\%s\\ProductVersion", sLanguageCodepage);
VerQueryValue(pBuffer, pBlock, (LPVOID *) &pTempData, &nTempSize);
m_sProductVersion = CString(pTempData);
wsprintf(pBlock, "\\StringFileInfo\\%s\\ProductName", sLanguageCodepage);
VerQueryValue(pBuffer, pBlock, (LPVOID *) &pTempData, &nTempSize);
m_sProductName = CString(pTempData);
wsprintf(pBlock, "\\StringFileInfo\\%s\\LegalCopyright", sLanguageCodepage);
VerQueryValue(pBuffer, pBlock, (LPVOID *) &pTempData, &nTempSize);
m_sCopyright = CString(pTempData);
}
}
}
// ////////////////////////////////////////////////////////////////////////////
//
CString CVersionInfo::GetDottedProductVersion()
{
CString s(m_sProductVersion);
s.Replace(',', '.');
s.Replace(" ", "");
return s;
}
// ////////////////////////////////////////////////////////////////////////////
//
CString CVersionInfo::GetDottedFileVersion()
{
CString s(m_sFileVersion);
s.Replace(',', '.');
s.Replace(" ", "");
return s;
}
| [
"[email protected]"
]
| [
[
[
1,
89
]
]
]
|
fe78c0813be4039fde1a7ded807428c9027b435e | b4d726a0321649f907923cc57323942a1e45915b | /CODE/INETFILE/CFTP.CPP | 2ec8fbd89e9d71858a125f8223c222bc51fba745 | []
| no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,970 | cpp | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/Inetfile/CFtp.cpp $
* $Revision: 1.1.1.1 $
* $Date: 2004/08/13 22:47:41 $
* $Author: Spearhawk $
*
* FTP Client class (get only)
*
* $Log: CFTP.CPP,v $
* Revision 1.1.1.1 2004/08/13 22:47:41 Spearhawk
* no message
*
* Revision 1.1.1.1 2004/08/13 20:50:25 Darkhill
* no message
*
* Revision 2.1 2002/08/01 01:41:06 penguin
* The big include file move
*
* Revision 2.0 2002/06/03 04:02:23 penguin
* Warpcore CVS sync
*
* Revision 1.2 2002/05/08 02:35:09 mharris
* porting
*
* Revision 1.1 2002/05/02 18:03:08 mharris
* Initial checkin - converted filenames and includes to lower case
*
*
* 3 5/04/99 7:34p Dave
* Fixed slow HTTP get problem.
*
* 2 4/20/99 6:39p Dave
* Almost done with artillery targeting. Added support for downloading
* images on the PXO screen.
*
* 1 4/20/99 4:37p Dave
*
* Initial version
*
* $NoKeywords: $
*/
#include <windows.h>
#include <process.h>
#include <stdio.h>
#include "globalincs/pstypes.h"
#include "inetfile/cftp.h"
void FTPObjThread( void * obj )
{
((CFtpGet *)obj)->WorkerThread();
}
void CFtpGet::AbortGet()
{
m_Aborting = true;
while(!m_Aborted) ; //Wait for the thread to end
fclose(LOCALFILE);
}
CFtpGet::CFtpGet(char *URL,char *localfile,char *Username,char *Password)
{
SOCKADDR_IN listensockaddr;
m_State = FTP_STATE_STARTUP;
m_ListenSock = INVALID_SOCKET;
m_DataSock = INVALID_SOCKET;
m_ControlSock = INVALID_SOCKET;
m_iBytesIn = 0;
m_iBytesTotal = 0;
m_Aborting = false;
m_Aborted = false;
LOCALFILE = fopen(localfile,"wb");
if(NULL == LOCALFILE)
{
m_State = FTP_STATE_CANT_WRITE_FILE;
return;
}
if(Username)
{
strcpy(m_szUserName,Username);
}
else
{
strcpy(m_szUserName,"anonymous");
}
if(Password)
{
strcpy(m_szPassword,Password);
}
else
{
strcpy(m_szPassword,"[email protected]");
}
m_ListenSock = socket(AF_INET, SOCK_STREAM, 0);
if(INVALID_SOCKET == m_ListenSock)
{
// vint iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return;
}
else
{
listensockaddr.sin_family = AF_INET;
listensockaddr.sin_port = 0;
listensockaddr.sin_addr.s_addr = INADDR_ANY;
// Bind the listen socket
if (bind(m_ListenSock, (SOCKADDR *)&listensockaddr, sizeof(SOCKADDR)))
{
//Couldn't bind the socket
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return;
}
// Listen for the server connection
if (listen(m_ListenSock, 1))
{
//Couldn't listen on the socket
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return;
}
}
m_ControlSock = socket(AF_INET, SOCK_STREAM, 0);
if(INVALID_SOCKET == m_ControlSock)
{
m_State = FTP_STATE_SOCKET_ERROR;
return;
}
//Parse the URL
//Get rid of any extra ftp:// stuff
char *pURL = URL;
if(_strnicmp(URL,"ftp:",4)==0)
{
pURL +=4;
while(*pURL == '/')
{
pURL++;
}
}
//There shouldn't be any : in this string
if(strchr(pURL,':'))
{
m_State = FTP_STATE_URL_PARSING_ERROR;
return;
}
//read the filename by searching backwards for a /
//then keep reading until you find the first /
//when you found it, you have the host and dir
char *filestart = NULL;
char *dirstart = NULL;
for(int i = strlen(pURL);i>=0;i--)
{
if(pURL[i]== '/')
{
if(!filestart)
{
filestart = pURL+i+1;
dirstart = pURL+i+1;
strcpy(m_szFilename,filestart);
}
else
{
dirstart = pURL+i+1;
}
}
}
if((dirstart==NULL) || (filestart==NULL))
{
m_State = FTP_STATE_URL_PARSING_ERROR;
return;
}
else
{
strncpy(m_szDir,dirstart,(filestart-dirstart));
m_szDir[(filestart-dirstart)] = '\0';
strncpy(m_szHost,pURL,(dirstart-pURL));
m_szHost[(dirstart-pURL)-1] = '\0';
}
//At this point we should have a nice host,dir and filename
//if(NULL==CreateThread(NULL,0,ObjThread,this,0,&m_dwThreadId))
if(NULL==_beginthread(FTPObjThread,0,this))
{
m_State = FTP_STATE_INTERNAL_ERROR;
return;
}
m_State = FTP_STATE_CONNECTING;
}
CFtpGet::~CFtpGet()
{
if(m_ListenSock != INVALID_SOCKET)
{
shutdown(m_ListenSock,2);
closesocket(m_ListenSock);
}
if(m_DataSock != INVALID_SOCKET)
{
shutdown(m_DataSock,2);
closesocket(m_DataSock);
}
if(m_ControlSock != INVALID_SOCKET)
{
shutdown(m_ControlSock,2);
closesocket(m_ControlSock);
}
}
//Returns a value to specify the status (ie. connecting/connected/transferring/done)
int CFtpGet::GetStatus()
{
return m_State;
}
unsigned int CFtpGet::GetBytesIn()
{
return m_iBytesIn;
}
unsigned int CFtpGet::GetTotalBytes()
{
return m_iBytesTotal;
}
//This function does all the work -- connects on a blocking socket
//then sends the appropriate user and password commands
//and then the cwd command, the port command then get and finally the quit
void CFtpGet::WorkerThread()
{
ConnectControlSocket();
if(m_State != FTP_STATE_LOGGING_IN)
{
return;
}
LoginHost();
if(m_State != FTP_STATE_LOGGED_IN)
{
return;
}
GetFile();
//We are all done now, and state has the current state.
m_Aborted = true;
}
unsigned int CFtpGet::GetFile()
{
//Start off by changing into the proper dir.
char szCommandString[200];
int rcode;
sprintf(szCommandString,"TYPE I\r\n");
rcode = SendFTPCommand(szCommandString);
if(rcode >=400)
{
m_State = FTP_STATE_UNKNOWN_ERROR;
return 0;
}
if(m_Aborting)
return 0;
if(m_szDir[0])
{
sprintf(szCommandString,"CWD %s\r\n",m_szDir);
rcode = SendFTPCommand(szCommandString);
if(rcode >=400)
{
m_State = FTP_STATE_DIRECTORY_INVALID;
return 0;
}
}
if(m_Aborting)
return 0;
if(!IssuePort())
{
m_State = FTP_STATE_UNKNOWN_ERROR;
return 0;
}
if(m_Aborting)
return 0;
sprintf(szCommandString,"RETR %s\r\n",m_szFilename);
rcode = SendFTPCommand(szCommandString);
if(rcode >=400)
{
m_State = FTP_STATE_FILE_NOT_FOUND;
return 0;
}
if(m_Aborting)
return 0;
//Now we will try to determine the file size...
char *p,*s;
p = strchr(recv_buffer,'(');
p++;
if(p)
{
s = strchr(p,' ');
*s = '\0';
m_iBytesTotal = atoi(p);
}
if(m_Aborting)
return 0;
m_DataSock = accept(m_ListenSock, NULL,NULL);//(SOCKADDR *)&sockaddr,&iAddrLength);
// Close the listen socket
closesocket(m_ListenSock);
if (m_DataSock == INVALID_SOCKET)
{
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return 0;
}
if(m_Aborting)
return 0;
ReadDataChannel();
m_State = FTP_STATE_FILE_RECEIVED;
return 1;
}
unsigned int CFtpGet::IssuePort()
{
char szCommandString[200];
SOCKADDR_IN listenaddr; // Socket address structure
#ifdef unix
socklen_t iLength; // Length of the address structure
#else
int iLength; // Length of the address structure
#endif
UINT nLocalPort; // Local port for listening
UINT nReplyCode; // FTP server reply code
// Get the address for the hListenSocket
iLength = sizeof(listenaddr);
if (getsockname(m_ListenSock, (LPSOCKADDR)&listenaddr,&iLength) == SOCKET_ERROR)
{
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return 0;
}
// Extract the local port from the hListenSocket
nLocalPort = listenaddr.sin_port;
// Now, reuse the socket address structure to
// get the IP address from the control socket.
if (getsockname(m_ControlSock, (LPSOCKADDR)&listenaddr,&iLength) == SOCKET_ERROR)
{
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return 0;
}
// Format the PORT command with the correct numbers.
#ifdef WINDOWS
sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n",
listenaddr.sin_addr.S_un.S_un_b.s_b1,
listenaddr.sin_addr.S_un.S_un_b.s_b2,
listenaddr.sin_addr.S_un.S_un_b.s_b3,
listenaddr.sin_addr.S_un.S_un_b.s_b4,
nLocalPort & 0xFF,
nLocalPort >> 8);
#else
sprintf(szCommandString, "PORT %d,%d,%d,%d,%d,%d\r\n",
(listenaddr.sin_addr.s_addr & 0xff000000) >> 24,
(listenaddr.sin_addr.s_addr & 0x00ff0000) >> 16,
(listenaddr.sin_addr.s_addr & 0x0000ff00) >> 8,
(listenaddr.sin_addr.s_addr & 0x000000ff),
nLocalPort & 0xFF,
nLocalPort >> 8);
#endif
// Tell the server which port to use for data.
nReplyCode = SendFTPCommand(szCommandString);
if (nReplyCode != 200)
{
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_SOCKET_ERROR;
return 0;
}
return 1;
}
int CFtpGet::ConnectControlSocket()
{
HOSTENT *he;
SERVENT *se;
SOCKADDR_IN hostaddr;
he = gethostbyname(m_szHost);
if(he == NULL)
{
m_State = FTP_STATE_HOST_NOT_FOUND;
return 0;
}
//m_ControlSock
if(m_Aborting)
return 0;
se = getservbyname("ftp", NULL);
if(se == NULL)
{
hostaddr.sin_port = htons(21);
}
else
{
hostaddr.sin_port = se->s_port;
}
hostaddr.sin_family = AF_INET;
memcpy(&hostaddr.sin_addr,he->h_addr_list[0],4);
if(m_Aborting)
return 0;
//Now we will connect to the host
if(connect(m_ControlSock, (SOCKADDR *)&hostaddr, sizeof(SOCKADDR)))
{
// int iWinsockErr = WSAGetLastError();
m_State = FTP_STATE_CANT_CONNECT;
return 0;
}
m_State = FTP_STATE_LOGGING_IN;
return 1;
}
int CFtpGet::LoginHost()
{
char szLoginString[200];
int rcode;
sprintf(szLoginString,"USER %s\r\n",m_szUserName);
rcode = SendFTPCommand(szLoginString);
if(rcode >=400)
{
m_State = FTP_STATE_LOGIN_ERROR;
return 0;
}
sprintf(szLoginString,"PASS %s\r\n",m_szPassword);
rcode = SendFTPCommand(szLoginString);
if(rcode >=400)
{
m_State = FTP_STATE_LOGIN_ERROR;
return 0;
}
m_State = FTP_STATE_LOGGED_IN;
return 1;
}
unsigned int CFtpGet::SendFTPCommand(char *command)
{
FlushControlChannel();
// Send the FTP command
if (SOCKET_ERROR ==(send(m_ControlSock,command,strlen(command), 0)))
{
// int iWinsockErr = WSAGetLastError();
// Return 999 to indicate an error has occurred
return(999);
}
// Read the server's reply and return the reply code as an integer
return(ReadFTPServerReply());
}
unsigned int CFtpGet::ReadFTPServerReply()
{
unsigned int rcode;
unsigned int iBytesRead;
char chunk[2];
char szcode[5];
unsigned int igotcrlf = 0;
memset(recv_buffer,0,1000);
do
{
chunk[0] = '\0';
iBytesRead = recv(m_ControlSock,chunk,1,0);
if (iBytesRead == SOCKET_ERROR)
{
// int iWinsockErr = WSAGetLastError();
// Return 999 to indicate an error has occurred
return(999);
}
if((chunk[0]==0x0a) || (chunk[0]==0x0d))
{
if(recv_buffer[0] != '\0')
{
igotcrlf = 1;
}
}
else
{ chunk[1] = '\0';
strcat(recv_buffer,chunk);
}
Sleep(1);
}while(igotcrlf==0);
if(recv_buffer[3] == '-')
{
//Hack -- must be a MOTD
return ReadFTPServerReply();
}
if(recv_buffer[3] != ' ')
{
//We should have 3 numbers then a space
return 999;
}
memcpy(szcode,recv_buffer,3);
szcode[3] = '\0';
rcode = atoi(szcode);
// Extract the reply code from the server reply and return as an integer
return(rcode);
}
unsigned int CFtpGet::ReadDataChannel()
{
char sDataBuffer[4096]; // Data-storage buffer for the data channel
int nBytesRecv; // Bytes received from the data channel
m_State = FTP_STATE_RECEIVING;
if(m_Aborting)
return 0;
do
{
if(m_Aborting)
return 0;
nBytesRecv = recv(m_DataSock, (LPSTR)&sDataBuffer,sizeof(sDataBuffer), 0);
m_iBytesIn += nBytesRecv;
if (nBytesRecv > 0 )
{
fwrite(sDataBuffer,nBytesRecv,1,LOCALFILE);
//Write sDataBuffer, nBytesRecv
}
Sleep(1);
}while (nBytesRecv > 0);
fclose(LOCALFILE);
// Close the file and check for error returns.
if (nBytesRecv == SOCKET_ERROR)
{
//Ok, we got a socket error -- xfer aborted?
m_State = FTP_STATE_RECV_FAILED;
return 0;
}
else
{
//done!
m_State = FTP_STATE_FILE_RECEIVED;
return 1;
}
}
void CFtpGet::FlushControlChannel()
{
fd_set read_fds;
TIMEVAL timeout;
char flushbuff[3];
timeout.tv_sec=0;
timeout.tv_usec=0;
FD_ZERO(&read_fds);
FD_SET(m_ControlSock,&read_fds);
while(select(0,&read_fds,NULL,NULL,&timeout))
{
recv(m_ControlSock,flushbuff,1,0);
Sleep(1);
}
}
| [
"[email protected]"
]
| [
[
[
1,
598
]
]
]
|
33e0a94e4af5e3fbc664f830aa7fb189a93775fd | d7df4671497eadc8f86567ed2631bcf2cdb1cd74 | /MagicBowl/Mp3Helper.h | b52bd62a4076dbda8c29fd6b600aa8cc7e04e4c4 | []
| no_license | PSP-Archive/MagicBowl | 6081838f014ebc7941896d57b01534c71e4d0ad4 | 0790e93f8072ea7169b6fcd9f20d1b66e5066c3d | refs/heads/master | 2023-06-25T03:33:33.083679 | 2010-08-29T14:22:14 | 2010-08-29T14:22:14 | 388,950,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | h | /*
* Mp3Helper.h Helper class to enable playing MP3 sounds in
* PSP homebrew applications
*
*/
#ifndef MP3HELPER_H_
#define MP3HELPER_H_
extern "C"{
#include <stdio.h>
#include <pspkerneltypes.h>
#include <pspaudio.h>
}
class ClMp3Helper {
public:
static bool initMP3();
static void closeMP3();
static int playMP3(const char* fileName, unsigned short volume = PSP_AUDIO_VOLUME_MAX);
static void stopMP3(int mp3ID);
static void setMP3Volume(int mp3ID, unsigned short volume);
private:
static int threadId;
static int fillStreamBuffer(FILE* fileHandle, int mp3Handle);
static int playThread(SceSize args, void *argp);
protected:
ClMp3Helper();
virtual ~ClMp3Helper();
};
#endif /* MP3HELPER_H_ */
| [
"anmabagima@d0c0c054-8719-4030-88c3-0e07ff0e07ca"
]
| [
[
[
1,
34
]
]
]
|
64fc014a0349581f5bdd7cde8f022e14717855a6 | 3bfc30f7a07ce0f6eabcd526e39ba1030d84c1f3 | /BlobbyWarriors/Source/BlobbyWarriors/Model/Entity/Factory/FlamethrowerFactory.cpp | e57357a1ddeadc9b28713b3fc4e57a22ab0364b9 | []
| no_license | visusnet/Blobby-Warriors | b0b70a0b4769b60d96424b55ad7c47b256e60061 | adec63056786e4e8dfcb1ed7f7fe8b09ce05399d | refs/heads/master | 2021-01-19T14:09:32.522480 | 2011-11-29T21:53:25 | 2011-11-29T21:53:25 | 2,850,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | cpp | #include "FlamethrowerFactory.h"
IEntity* FlamethrowerFactory::create(const EntityProperties& properties)
{
b2BodyDef bodyDef = b2BodyDef();
bodyDef.position.Set(pixel2meter(properties.x), pixel2meter(properties.y));
bodyDef.angle = radian2degree(properties.angle);
bodyDef.type = b2_kinematicBody;
b2Body *body = GameWorld::getInstance()->getPhysicsWorld()->CreateBody(&bodyDef);
b2PolygonShape polygonShape;
polygonShape.SetAsBox(pixel2meter(properties.width / 2), pixel2meter(properties.height / 2));
b2FixtureDef fixtureDef;
fixtureDef.shape = &polygonShape;
fixtureDef.density = properties.density;
fixtureDef.friction = properties.friction;
fixtureDef.restitution = properties.restitution;
if (properties.special) {
fixtureDef.filter.groupIndex = -1;
}
fixtureDef.filter.categoryBits = COLLISION_BIT_WEAPON;
fixtureDef.filter.maskBits = COLLISION_BIT_OBJECT;
body->CreateFixture(&fixtureDef);
body->ResetMassData();
Flamethrower *flamethrower = new Flamethrower();
flamethrower->addBody(body);
return flamethrower;
}
EntityProperties& FlamethrowerFactory::getDefaultProperties()
{
EntityProperties *properties = new EntityProperties();
properties->density = 0.1f;
properties->friction = 0.0f;
properties->restitution = 0.0f;
properties->angle = 0.0f;
properties->radius = 0.0f;//ENTITY_PROPERTY_UNUSED;
properties->width = 40.0f; //ENTITY_PROPERTY_UNUSED;
properties->height = 19.0f; //ENTITY_PROPERTY_UNUSED;
properties->x = 0;
properties->y = 0;
return *properties;
} | [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
f5361bd0cf5b26057372e5ff92728490eaa95261 | fd792229322e4042f6e88a01144665cebdb1c339 | /src/serverWorldMap.h | a4a24eccb79979d8694d8c823197e0c76761f1ed | []
| no_license | weimingtom/mmomm | 228d70d9d68834fa2470d2cd0719b9cd60f8dbcd | cab04fcad551f7f68f99fa0b6bb14cec3b962023 | refs/heads/master | 2021-01-10T02:14:31.896834 | 2010-03-15T16:15:43 | 2010-03-15T16:15:43 | 44,764,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | h | #ifndef SERVER_WORLD_MAP_H_
#define SERVER_WORLD_MAP_H_
#include <boost/multi_array.hpp>
#include <boost/unordered_map.hpp>
#include <RakNet/NativeTypes.h>
#include "tileTypes.h"
#include "vector2D.h"
class ServerWorldMap {
public:
~ServerWorldMap();
// Saves/loads tile data from/to a given (possibly new) cell and returns it.
typedef std::vector<TileType> TileDataVector;
void loadCell(const IVector2D& v, const TileDataVector& tileData);
void saveCell(const IVector2D& v, TileDataVector& buffer);
// Removes the given cell from memory, if it exists.
void discardCell(const IVector2D& v);
// Directly access the correct tile of the underlying cell at the given position.
TileType getTile(const IVector2D& v) const;
void setTile(const IVector2D& v, TileType type);
// Figure out the time that the cell was last updated.
double getUpdateTime(const IVector2D& cell) const;
private:
typedef boost::multi_array< TileType, 2 > Cell;
typedef boost::unordered_map< IVector2D, Cell* > CellMap;
CellMap _cellMap;
typedef boost::unordered_map< IVector2D, double > UpdateMap;
mutable UpdateMap _updateMap;
TileType& getTile(const IVector2D& v);
Cell& getCell(const IVector2D& v);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
f161ac3bc12a705b9601db6aba6d17f8d9b4a691 | c0a577ec612a721b324bb615c08882852b433949 | /englishplayer/EnTranscription/Mfcc.cpp | 9a152b00eecb470e5c895c6c3e82159c53fa16c1 | []
| no_license | guojerry/cppxml | ca87ca2e3e62cbe2a132d376ca784f148561a4cc | a4f8b7439e37b6f1f421445694c5a735f8beda71 | refs/heads/master | 2021-01-10T10:57:40.195940 | 2010-04-21T13:25:29 | 2010-04-21T13:25:29 | 52,403,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,041 | cpp | #include "StdAfx.h"
#include "AudioDoc.h"
#include "Mfcc.h"
#include "fe_warp.h"
int32 fe_start_utt(fe_t * fe)
{
fe->num_overflow_samps = 0;
memset(fe->overflow_samps, 0, fe->frame_size * sizeof(int16));
fe->start_flag = 1;
fe->prior = 0;
return 0;
}
CMfcc::CMfcc(void)
{
m_fe = new fe_t;
//Do parameters initialization
m_fe->sampling_rate = SAMPLE_RATE;
m_fe->frame_rate = 100;
m_fe->dither = 1; //Do dither
m_fe->seed = -1; //For dither random data seed, -1 using defaults: time()
m_fe->swap = 0; //WORDS_LITTLEENDIAN
m_fe->window_length = float32(SAMPLE_INTERVAL*1.0 / 1000);
m_fe->pre_emphasis_alpha = float32(0.97); //Pre emphasis alpha
m_fe->num_cepstra = MFCCVECTOR; //13 spectra components
m_fe->fft_size = 512; //For 10ms samples, it will be 441, fft size must greater than it.
/* Check FFT size, compute FFT order (log_2(n)) */
int j = m_fe->fft_size;
m_fe->fft_order = 0;
for(; j > 1; j >>= 1, m_fe->fft_order++)
{
if (((j % 2) != 0) || (m_fe->fft_size <= 0))
{
TRACE("fft: number of points must be a power of 2 (is %d)\n", m_fe->fft_size);
goto error;
}
}
/* Verify that FFT size is greater or equal to window length. */
if(m_fe->fft_size < (int)(m_fe->window_length * m_fe->sampling_rate))
{
TRACE("FFT: Number of points must be greater or equal to frame size (%d samples)\n",
(int)(m_fe->window_length * m_fe->sampling_rate));
goto error;
}
m_fe->remove_dc = 1;
m_fe->transform = LEGACY_DCT;
m_fe->log_spec = 0;//SMOOTH_LOG_SPEC;
//End parameter initialization
/* compute remaining fe parameters */
/* We add 0.5 so approximate the float with the closest
* integer. E.g., 2.3 is truncate to 2, whereas 3.7 becomes 4
*/
m_fe->frame_shift = (int32) (m_fe->sampling_rate / m_fe->frame_rate + 0.5);
m_fe->frame_size = (int32) (m_fe->window_length * m_fe->sampling_rate + 0.5);
m_fe->prior = 0;
m_fe->frame_counter = 0;
if (m_fe->frame_size > (m_fe->fft_size))
{
TRACE("Number of FFT points has to be a power of 2 higher than %d\n", (m_fe->frame_size));
goto error;
}
if(m_fe->dither)
fe_init_dither(m_fe->seed);
/* establish buffers for overflow samps and hamming window */
m_fe->overflow_samps = new int16[m_fe->frame_size];
m_fe->hamming_window = new window_t[m_fe->frame_size/2];
/* create hamming window */
fe_create_hamming(m_fe->hamming_window, m_fe->frame_size);
/* init and fill appropriate filter structure */
m_fe->mel_fb = new melfb_t;
//Init mel fb
m_fe->mel_fb->sampling_rate = m_fe->sampling_rate;
m_fe->mel_fb->fft_size = m_fe->fft_size;
m_fe->mel_fb->num_cepstra = m_fe->num_cepstra;
m_fe->mel_fb->num_filters = 80;
if(m_fe->log_spec == RAW_LOG_SPEC)
m_fe->feature_dimension = m_fe->mel_fb->num_filters;
else
m_fe->feature_dimension = m_fe->num_cepstra;
m_fe->mel_fb->upper_filt_freq = float32(6855.4976);
m_fe->mel_fb->lower_filt_freq = float32(133.33334);
m_fe->mel_fb->doublewide = 0;
m_fe->mel_fb->warp_type = "inverse_linear";
m_fe->mel_fb->warp_params = NULL;
m_fe->mel_fb->lifter_val = 0;
m_fe->mel_fb->unit_area = 1;
m_fe->mel_fb->round_filters = 1;
if (fe_warp_set(m_fe->mel_fb, m_fe->mel_fb->warp_type) != FE_SUCCESS)
{
E_ERROR("Failed to initialize the warping function.\n");
goto error;
}
fe_warp_set_parameters(m_fe->mel_fb, m_fe->mel_fb->warp_params, m_fe->mel_fb->sampling_rate);
/* transfer params to mel fb */
fe_build_melfilters(m_fe->mel_fb);
fe_compute_melcosine(m_fe->mel_fb);
/* Create temporary FFT, spectrum and mel-spectrum buffers. */
/* FIXME: Gosh there are a lot of these. */
m_fe->spch = new int16[m_fe->frame_size];
m_fe->frame = new frame_t[m_fe->fft_size];
m_fe->spec = new powspec_t[m_fe->fft_size];
m_fe->mfspec = new powspec_t[m_fe->mel_fb->num_filters];
/* create twiddle factors */
m_fe->ccc = new frame_t[m_fe->fft_size / 4];
m_fe->sss = new frame_t[m_fe->fft_size / 4];
fe_create_twiddle(m_fe);
/*** Z.A.B. ***/
/*** Initialize the overflow buffers ***/
fe_start_utt(m_fe);
return;
error:
fe_free(m_fe);
m_fe = NULL;
}
CMfcc::~CMfcc(void)
{
fe_free(m_fe);
m_fe = NULL;
}
int CMfcc::fe_free(fe_t * fe)
{
if (fe == NULL)
return 0;
/* kill FE instance - free everything... */
if (fe->mel_fb)
{
if (fe->mel_fb->mel_cosine)
delete [] fe->mel_fb->mel_cosine;
delete [] fe->mel_fb->lifter;
delete [] fe->mel_fb->spec_start;
delete [] fe->mel_fb->filt_start;
delete [] fe->mel_fb->filt_width;
delete [] fe->mel_fb->filt_coeffs;
delete [] fe->mel_fb;
}
delete [] fe->spch;
delete [] fe->frame;
delete [] fe->ccc;
delete [] fe->sss;
delete [] fe->spec;
delete [] fe->mfspec;
delete [] fe->overflow_samps;
delete [] fe->hamming_window;
delete fe;
return 0;
}
int32 CMfcc::fe_process_frame(int16 const *spch, int32 nsamps, mfcc_t* fr_cep)
{
fe_read_frame(m_fe, spch, nsamps);
return fe_write_frame(m_fe, fr_cep);
}
| [
"oeichenwei@0e9f5f58-6d57-11de-950b-9fccee66d0d9"
]
| [
[
[
1,
176
]
]
]
|
2c1458c0e45bf18b3b5d45a5400b6ba3c25f988d | 23e1deafd7805287ca582e6f5d1a9ba408e058a6 | /MN1-RaizFuncao/src/MetodoNewtonRaphson.cpp | e4c02801463adb69a1c92ff15967eea86219d4b8 | []
| no_license | lucaseduardo101/NumericalMethods | 8ddc7e907dc5f47a0a848ddfd515d715482616e2 | ce2e38401bb36bf702c53142d398dd56c632de0f | refs/heads/master | 2021-01-21T21:38:38.976852 | 2010-09-11T00:24:18 | 2010-09-11T00:24:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | cpp | /*
* MetodoNewtonRaphson.cpp
*
* Created on: 22/10/2009
* Author: Rafael Sales
*/
#include <iostream>
#include <math.h>
#include "MetodoNewtonRaphson.h"
using namespace std;
double MetodoNewtonRaphson::encontrarRaiz(double intervaloA, double intervaloB) {
cout << "\n=> Raiz de função - Método Newton-Raphson" << endl;
double raiz;
double fRaiz;
int k = 0;
//Exibe o cabeçalho da tabela dos dados das iterações do método:
cout << "k \t Xk \t f(Xk)" << endl;
do {
//Neste método o valor da raíz na primeira iteração é um chute:
if (k == 0) {
//O chute que escolhemos é meio do intervalo dado:
raiz = (intervaloA + intervaloB) / 2;
} else {
//Calcula a raiz a aproximada:
raiz = raiz - (this->funcao.f(raiz) / this->funcaoDerivada.f(raiz));
}
//Calcula f(raiz):
fRaiz = this->funcao.f(raiz);
//Exibe os dados da iteração:
cout << k++ << " \t " << raiz << " \t " << fRaiz << " \t " << endl;
} while (fabs(fRaiz) > this->erro);
return raiz;
}
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
81eafd2db3ca0a50dd9bea3e2420371414d1456f | 63c17f092bf95bc9daaf92ee05f6a823623f2f9b | /src/PlugInSDK/BeckyApi.h | 4492ab1d93265fbfdb2247b38e5eb1ffa704663d | []
| no_license | sodiumda250/bkhdpnl | ba9d36b9b77d23c6cac004ce3c4818d19564eed4 | 52e628f3bc70f38bea4c6287778c3a3d765f37bf | refs/heads/master | 2020-03-31T11:59:52.220401 | 2009-10-20T05:50:43 | 2009-10-20T05:50:43 | 3,039,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,018 | h | ///////////////////////////////////////////////////////////////////////////
// Becky! API header file
//
// You can modify and redistribute this file without any permission.
#ifndef _BECKY_API
#define _BECKY_API
#define BKC_MENU_MAIN 0
#define BKC_MENU_LISTVIEW 1
#define BKC_MENU_TREEVIEW 2
#define BKC_MENU_MSGVIEW 3
#define BKC_MENU_MSGEDIT 4
#define BKC_MENU_TASKTRAY 5
#define BKC_MENU_COMPOSE 10
#define BKC_MENU_COMPEDIT 11
#define BKC_MENU_COMPREF 12
#define BKC_BITMAP_ADDRESSBOOKICON 1
#define BKC_BITMAP_ADDRESSPERSON 2
#define BKC_BITMAP_ANIMATION 3
#define BKC_BITMAP_FOLDERCOLOR 4
#define BKC_BITMAP_FOLDERICON 5
#define BKC_BITMAP_LISTICON 6
#define BKC_BITMAP_PRIORITYSTAMP 7
#define BKC_BITMAP_RULETREEICON 8
#define BKC_BITMAP_TEMPLATEFOLDER 9
#define BKC_BITMAP_WHATSNEWLIST 10
#define BKC_ICON_ADDRESSBOOK 101
#define BKC_ICON_ANIMATION1_SMALL 102
#define BKC_ICON_ANIMATION2_SMALL 103
#define BKC_ICON_COMPOSEFRAME 104
#define BKC_ICON_MAINFRAME 105
#define BKC_ICON_NEWARRIVAL1_SMALL 106
#define BKC_ICON_NEWARRIVAL2_SMALL 107
#define BKC_TOOLBAR_ADDRESSBOOK 201
#define BKC_TOOLBAR_COMPOSEFRAME 202
#define BKC_TOOLBAR_HTMLEDITOR 203
#define BKC_TOOLBAR_MAINFRAME 204
#define BKC_ONSEND_ERROR -1
#define BKC_ONSEND_PROCESSED -2
#define BKC_FILTER_DEFAULT 0
#define BKC_FILTER_PASS 1
#define BKC_FILTER_DONE 2
#define BKC_FILTER_NEXT 3
#define ACTION_NOTHING -1
#define ACTION_MOVEFOLDER 0
#define ACTION_COLORLABEL 1
#define ACTION_SETFLAG 2
#define ACTION_SOUND 3
#define ACTION_RUNEXE 4
#define ACTION_REPLY 5
#define ACTION_FORWARD 6
#define ACTION_LEAVESERVER 7
#define ACTION_ADDHEADER 8
#define MESSAGE_READ 0x00000001
#define MESSAGE_FORWARDED 0x00000002
#define MESSAGE_REPLIED 0x00000004
#define MESSAGE_ATTACHMENT 0x00000008
#define MESSAGE_PARTIAL 0x00000100
#define MESSAGE_REDIRECT 0x00000200
#define COMPOSE_MODE_COMPOSE1 0
#define COMPOSE_MODE_COMPOSE2 1
#define COMPOSE_MODE_COMPOSE3 2
#define COMPOSE_MODE_TEMPLATE 3
#define COMPOSE_MODE_REPLY1 5
#define COMPOSE_MODE_REPLY2 6
#define COMPOSE_MODE_REPLY3 7
#define COMPOSE_MODE_FORWARD1 10
#define COMPOSE_MODE_FORWARD2 11
#define COMPOSE_MODE_FORWARD3 12
#define BKMENU_CMDUI_DISABLED 1
#define BKMENU_CMDUI_CHECKED 2
class CBeckyAPI
{
public:
CBeckyAPI()
{
m_hInstBecky = NULL;
}
~CBeckyAPI()
{
if (m_hInstBecky) {
//::FreeLibrary(m_hInstBecky);
}
}
BOOL InitAPI();
LPCTSTR (WINAPI* GetVersion)();
void (WINAPI* Command)(HWND hWnd, LPCTSTR lpCmd);
BOOL (WINAPI* GetWindowHandles)(HWND* lphMain, HWND* lphTree, HWND* lphList, HWND* lphView);
UINT (WINAPI* RegisterCommand)(LPCTSTR lpszComment, int nTarget, void (CALLBACK* lpCallback)(HWND, LPARAM));
UINT (WINAPI* RegisterUICallback)(UINT nID, UINT (CALLBACK* lpCallback)(HWND, LPARAM));
LPCTSTR (WINAPI* GetDataFolder)();
LPCTSTR (WINAPI* GetTempFolder)();
LPCTSTR (WINAPI* GetTempFileName)(LPCTSTR lpType);
LPCTSTR (WINAPI* GetCurrentMailBox)();
void (WINAPI* SetCurrentMailBox)(LPCTSTR lpMailBox);
LPCTSTR (WINAPI* GetCurrentFolder)();
void (WINAPI* SetCurrentFolder)(LPCTSTR lpFolderID);
LPCTSTR (WINAPI* GetFolderDisplayName)(LPCSTR lpFolderID);
void (WINAPI* SetMessageText)(HWND hWnd, LPCSTR lpszMsg);
LPCTSTR (WINAPI* GetCurrentMail)();
void (WINAPI* SetCurrentMail)(LPCTSTR lpMailID);
int (WINAPI* GetNextMail)(int nStart, LPSTR lpszMailID, int nBuf, BOOL bSelected);
void (WINAPI* SetSel)(LPCTSTR lpMailID, BOOL bSel);
BOOL (WINAPI* AppendMessage)(LPCTSTR lpFolderID, LPCTSTR lpszData);
BOOL (WINAPI* MoveSelectedMessages)(LPCTSTR lpFolderID, BOOL bCopy);
DWORD (WINAPI* GetStatus)(LPCTSTR lpMailID);
DWORD (WINAPI* SetStatus)(LPCTSTR lpMailID, DWORD dwSet, DWORD dwReset);
HWND (WINAPI* ComposeMail)(LPCTSTR lpURL);
int (WINAPI* GetCharSet)(LPCTSTR lpMailID, LPSTR lpszCharSet, int nBuf);
LPSTR (WINAPI* GetSource)(LPCTSTR lpMailID);
void (WINAPI* SetSource)(LPCTSTR lpMailID, LPCTSTR lpSource);
LPSTR (WINAPI* GetHeader)(LPCTSTR lpMailID);
LPSTR (WINAPI* GetText)(LPSTR lpszMimeType, int nBuf);
void (WINAPI* SetText)(int nMode, LPCTSTR lpText);
void (WINAPI* GetSpecifiedHeader)(LPCTSTR lpHeader, LPSTR lpszData, int nBuf);
void (WINAPI* SetSpecifiedHeader)(LPCTSTR lpHeader, LPCTSTR lpszData);
int (WINAPI* CompGetCharSet)(HWND hWnd, LPSTR lpszCharSet, int nBuf);
LPSTR (WINAPI* CompGetSource)(HWND hWnd);
void (WINAPI* CompSetSource)(HWND hWnd, LPCTSTR lpSource);
LPSTR (WINAPI* CompGetHeader)(HWND hWnd);
void (WINAPI* CompGetSpecifiedHeader)(HWND hWnd, LPCTSTR lpHeader, LPSTR lpszData, int nBuf);
void (WINAPI* CompSetSpecifiedHeader)(HWND hWnd, LPCTSTR lpHeader, LPCTSTR lpszData);
LPSTR (WINAPI* CompGetText)(HWND hWnd, LPSTR lpszMimeType, int nBuf);
void (WINAPI* CompSetText)(HWND hWnd, int nMode, LPCTSTR lpText);
void (WINAPI* CompAttachFile)(HWND hWnd, LPCTSTR lpAttachFile, LPCTSTR lpMimeType);
LPVOID (WINAPI* Alloc)(DWORD dwSize);
LPVOID (WINAPI* ReAlloc)(LPVOID lpVoid, DWORD dwSize);
void (WINAPI* Free)(LPVOID lpVoid);
LPSTR (WINAPI* ISO_2022_JP)(LPCTSTR lpSrc, BOOL bEncode);
LPSTR (WINAPI* ISO_2022_KR)(LPCTSTR lpSrc, BOOL bEncode);
LPSTR (WINAPI* HZ_GB2312)(LPCTSTR lpSrc, BOOL bEncode);
LPSTR (WINAPI* ISO_8859_2)(LPCTSTR lpSrc, BOOL bEncode);
LPSTR (WINAPI* EUC_JP)(LPCTSTR lpSrc, BOOL bEncode);
LPSTR (WINAPI* UTF_7)(LPCTSTR lpSrc, BOOL bEncode);
LPSTR (WINAPI* UTF_8)(LPCTSTR lpSrc, BOOL bEncode);
BOOL (WINAPI* B64Convert)(LPCTSTR lpszOutFile, LPCTSTR lpszInFile, BOOL bEncode);
BOOL (WINAPI* QPConvert)(LPCTSTR lpszOutFile, LPCTSTR lpszInFile, BOOL bEncode);
LPSTR (WINAPI* MIMEHeader)(LPCTSTR lpszIn, LPSTR lpszCharSet, int nBuf, BOOL bEncode);
LPSTR (WINAPI* SerializeRcpts)(LPCTSTR lpAddresses);
BOOL (WINAPI* Connect)(BOOL bConnect);
BOOL (WINAPI* NextUnread)(BOOL bBackScroll, BOOL bGoNext);
protected:
HINSTANCE m_hInstBecky;
};
#endif
| [
"woods@e212b10a-3bbd-de11-b494-001ec944baf4"
]
| [
[
[
1,
159
]
]
]
|
f5d34ca8865c74ba031c17f87be7e6e076a4ff1d | 2e5fd1fc05c0d3b28f64abc99f358145c3ddd658 | /deps/quickfix/src/.NET/PostgreSQLStore.cpp | 909e6a17e6c7f0e405d829d48e3534147d4d8844 | [
"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 | 51 | cpp | #include "stdafx.h"
#include "PostgreSQLStore.h"
| [
"[email protected]"
]
| [
[
[
1,
2
]
]
]
|
920be660e06c0b32014652dd3bedad7777efe68c | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/partition.hpp | d949d92fcf94bfb1acb481e672a1532127cf501e | []
| no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,211 | hpp |
#ifndef BOOST_MPL_PARTITION_HPP_INCLUDED
#define BOOST_MPL_PARTITION_HPP_INCLUDED
// Copyright Eric Friedman 2002-2003
// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/partition.hpp,v $
// $Date: 2006/04/17 23:49:40 $
// $Revision: 1.1 $
#include <boost/mpl/stable_partition.hpp>
#include <boost/mpl/aux_/inserter_algorithm.hpp>
namespace boost { namespace mpl {
namespace aux {
template <
typename Sequence
, typename Pred
, typename In1
, typename In2
>
struct partition_impl
: stable_partition_impl<Sequence,Pred,In1,In2>
{
};
template <
typename Sequence
, typename Pred
, typename In1
, typename In2
>
struct reverse_partition_impl
: reverse_stable_partition_impl<Sequence,Pred,In1,In2>
{
};
} // namespace aux
BOOST_MPL_AUX_INSERTER_ALGORITHM_DEF(4, partition)
}}
#endif // BOOST_MPL_PARTITION_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
53
]
]
]
|
cde2e7015fb6f73e0a56acd66f6736b0564dcc3b | 909e422494d7c012c2bc89c79eabdceb53c721a5 | /icpcLibrary/Heap_UsingSTL.cpp | 79d7bbfc6692aa2539d45dd84f18460864a3a1bf | []
| no_license | aviramagen/menglin-icpc-code-library | f14cc303a3fd05992a1a40b9bcd7a0b09657f21c | c8375f39ed13312f705fb42c20ce83f5194bd297 | refs/heads/master | 2021-01-10T14:00:32.605726 | 2011-12-03T11:39:50 | 2011-12-03T11:39:50 | 54,555,734 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 747 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
struct type
{
int x, y;
bool operator< ( const type &a )
{
return x < a.x;
}
};
int main()
{
int B[10] = {0, 112, 23, 354, 45, 878, 66, 87, 9898, 459 };
type A[10];
for ( int i = 0; i < 10; i++ ) A[i].x = A[i].y = B[i];
make_heap ( A, A + 9 );
push_heap ( A, A + 10 ); //瑕佹眰[first,last-1)宸茬粡鏄爢
int i;
for ( i = 9; i >= 0; i-- )
{
pop_heap ( A, A + i + 1 );
cout << A[i].x << endl;
}
while ( 1 );
}
| [
"bluebird498@localhost"
]
| [
[
[
1,
107
]
]
]
|
16ec074d8ca3fe135a64d3eee8a9ab635f31f045 | 629e4fdc23cb90c0144457e994d1cbb7c6ab8a93 | /lib/graphics/viewport.cpp | ed01a2f09a80094e42a782f0bdf4ad11f4a553d3 | []
| 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 | 754 | cpp | /*
* viewport.cpp
*
* Created on: 5.8.2011
* Author: akin
*/
#include "viewport.h"
#include <glm/transform>
namespace ice
{
Viewport::Viewport()
{
}
Viewport::~Viewport()
{
}
glm::mat4x4& Viewport::getProjectionMatrix()
{
return projection;
}
glm::mat4x4& Viewport::getModelMatrix()
{
return model;
}
// Lenses:
void Viewport::setOrtho( float width , float height , float near , float far )
{
projection = glm::ortho( 0.0f , width , height , 0.0f , near , far );
}
void Viewport::setFrustum( float left , float right , float bottom , float top , float near , float far )
{
projection = glm::frustum( left , right , bottom , top , near , far );
}
} /* namespace ice */
| [
"akin@lich"
]
| [
[
[
1,
41
]
]
]
|
c70badb1d32cbfc95493009156f8eaf8695d1de7 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor/dyndroptarget.cpp | 4b7bd1eaf1da49b18b57730bd121d7a956a349ea | []
| no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,025 | cpp | // Copyright ?2002 Oink!
// FILE NAME : DynDropTarget.cpp
// DESCRIPTION : Provides basic member variables and functions for all
// : CWnd objects to act as drop target for control dragged from
// : toolbar
//
// PROGRAMMER DATE PATCH DESCRIPTION
// ============ =========== ======= ===============================================
#include "stdafx.h"
#include "gumpeditor.h"
#include "dyndroptarget.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static UINT uiCursorID[] =
{
IDC_EDITCURSOR, //DYN_EDIT,
IDC_EDITCURSOR, //DYN_MULTIEDIT,
IDC_LABELCURSOR,//DYN_LABEL,
IDC_GROUPCURSOR,//DYN_GROUP,
IDC_COMBOCURSOR,//DYN_COMBO,
IDC_CHECKCURSOR,//DYN_CHECK,
IDC_CHECKCURSOR,//DYN_DATE,
IDC_DATECURSOR, //DYN_RADIO,
IDC_PICTURECURSOR,//DYN_PICTURE,
IDC_LISTCURSOR,//DYN_LIST,
IDC_BUTTONCURSOR,//DYN_BUTTON,
};
SCODE CDynDropSource::GiveFeedback(DROPEFFECT dropEffect)
{
UINT cursorID = IDC_EDITCURSOR;
if (0 <= nControlType && nControlType < sizeof(uiCursorID)/sizeof(uiCursorID[0]))
cursorID = uiCursorID[nControlType];
SetCursor(AfxGetApp()->LoadCursor(cursorID));
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// CDynDropTarget
IMPLEMENT_DYNCREATE(CDynDropTarget, CCmdTarget)
CDynDropTarget::CDynDropTarget()
{
}
CDynDropTarget::~CDynDropTarget()
{
}
BEGIN_MESSAGE_MAP(CDynDropTarget, COleDropTarget)
//{{AFX_MSG_MAP(CDynDropTarget)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDynDropTarget message handlers
BOOL CDynDropTarget::OnDrop(CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect,CPoint point)
{
// Detects a drop and adds a new control to the screen
if (!(pDataObject->IsDataAvailable(m_nIDClipFormat)))
return FALSE;
STGMEDIUM stgmedium;
int nType;
if (pDataObject->GetData(m_nIDClipFormat, &stgmedium))
{
HGLOBAL hGlobal = stgmedium.hGlobal;
LPCTSTR pText = (LPCTSTR)GlobalLock(hGlobal);
nType = atoi(pText);
// free memory
GlobalUnlock(hGlobal);
GlobalFree(hGlobal);
pWnd->SendMessage(WM_ADDCONTROL,(WPARAM)nType,(LPARAM)MAKELONG(point.y,point.x));
}
return FALSE;
}
DROPEFFECT CDynDropTarget::OnDragEnter( CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point )
{
// Determines if data is available to drop
if (pDataObject->IsDataAvailable(m_nIDClipFormat))
return DROPEFFECT_COPY;
return DROPEFFECT_NONE;
}
DROPEFFECT CDynDropTarget::OnDragOver( CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point )
{
// Determines if data is available to drop
CString strPos;
strPos.Format(" x: %d, y: %d ",point.x,point.y);
if (pDataObject->IsDataAvailable(m_nIDClipFormat))
return DROPEFFECT_COPY;
return DROPEFFECT_NONE;
}
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
117
]
]
]
|
b220ebf68c731a758177bfbb8fafb278cec1e1d7 | 99d3989754840d95b316a36759097646916a15ea | /tags/2011_09_07_to_baoxin_gpd_0.1/ferrylibs/src/ferry/cv_geometry/CvMatUtil.cpp | 77c09bdb572fe40458a449379c298b11be698e84 | []
| no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,300 | cpp | #include ".\cvmatutil.h"
namespace ferry {
namespace cv_mat {
void svd(CvMat* A, CvMat** W, CvMat** U, CvMat** V) {
*U = cvCreateMat(A->rows, A->rows, A->type);
*V = cvCreateMat(A->cols, A->cols, A->type);
*W = cvCreateMat(A->rows, A->cols, A->type);
cvSVD(A, *W, *U, *V);
}
CvMat* null(CvMat* A) {
CvMat* X = cvCreateMat(A->cols, 1, A->type);
int n = MIN(A->rows, A->cols);
CvMat* u = cvCreateMat(A->rows, A->rows, A->type);
CvMat* v = cvCreateMat(A->cols, A->cols, A->type);
CvMat* w = cvCreateMat(A->rows, A->cols, A->type);
cvSVD(A, w, u, v);
for (int i = 0; i < v->rows; i++) X->data.db[i] = v->data.db[(i + 1)*v->cols - 1];
cvReleaseMat(&w);
cvReleaseMat(&u);
cvReleaseMat(&v);
return X;
}
CvMat* leftNull(CvMat* A) {
CvMat* At = transpose(A);
CvMat* n = null(At);
cvReleaseMat(&At);
return n;
}
CvMat* transpose(const CvMat* A) {
CvMat* At = cvCreateMat(A->cols, A->rows, A->type);
cvT(A, At);
return At;
}
CvMat* inv(const CvMat* A) {
CvMat* inv_A = cvCreateMat(A->cols, A->rows, A->type);
cvInvert(A, inv_A);
return inv_A;
}
CvMat* matMul(const CvMat* A, const CvMat* B) {
assert(A->cols == B->rows);
CvMat* M = cvCreateMat(A->rows, B->cols, A->type);
cvMatMul(A, B, M);
return M;
}
CvMat* matMul(const CvMat* A, const CvMat* B, const CvMat* C) {
assert(A->cols == B->rows && B->cols == C->rows);
CvMat* AB = matMul(A, B);
CvMat* ABC = matMul(AB, C);
cvReleaseMat(&AB);
return ABC;
}
//diagonal
CvMat* diagpseudoinverse(const CvMat* D) {
//assert(D->rows == D->cols);
CvMat* DI = cvCreateMat(D->cols, D->rows, D->type);
cvZero(DI);
int n = MIN(D->rows, D->cols);
for (int i = 0; i < n; i++) {
double d = cvmGet(D, i, i);
if (abs(d) > 0.000001) cvmSet(DI, i, i, 1 /d );
}
return DI;
}
//return A+ such that AA+ = I
//suppose A = UWV', then A+ = VW+U'
CvMat* pseudoinverse(CvMat* A) {
int n = MIN(A->rows, A->cols);
CvMat* u = cvCreateMat(A->rows, n, A->type);
CvMat* v = cvCreateMat(A->cols, A->cols, A->type);
CvMat* w = cvCreateMat(n, A->cols, A->type);
cvSVD(A, w, u, v);
CvMat* AP = cvCreateMat(A->cols, A->rows, A->type);
CvMat* wp = diagpseudoinverse(w);
CvMat* vwp = cvCreateMat(v->rows, wp->cols, v->type);
CvMat* ut = cvCreateMat(u->cols, u->rows, u->type);
//==DEBUG
/* cout<<"w: "<<matString(w)<<endl;
cout<<"wp: "<<matString(wp)<<endl;
CvMat* wwp = matMul(w, wp);
cout<<"w * wp: "<<matString(wwp)<<endl;
CvMat* vt = cvCreateMat(v->cols, v->rows, v->type);
CvMat* vtv = cvCreateMat(v->cols, v->cols, v->type);
cvT(v, vt);
cvMatMul(vt, v, vtv);
cout<<"vtv: "<<matString(vtv)<<endl;
CvMat* ut2 = cvCreateMat(u->cols, u->rows, u->type);
CvMat* uut = cvCreateMat(u->rows, u->rows, u->type);
cvT(u, ut2);
cvMatMul(u, ut2, uut);
cout<<"uut: "<<matString(uut)<<endl;
CvMat* A1 = matMul(u, w, vt);
cout<<"A1: "<<matString(A1)<<endl;
CvMat* AP1 = matMul(v, wp, ut2);
cout<<"AP1: "<<matString(AP1)<<endl;
CvMat* A1AP1 = matMul(A1, AP1);
cout<<"A1 * AP1: "<<matString(A1AP1)<<endl;
*/
//==
cvMatMul(v, wp, vwp);
cvTranspose(u, ut);
cvMatMul(vwp, ut, AP);
cvReleaseMat(&u);
cvReleaseMat(&v);
cvReleaseMat(&w);
cvReleaseMat(&wp);
cvReleaseMat(&vwp);
cvReleaseMat(&ut);
return AP;
}
// v: n x 1 matrix
// v = v / ||v||
void normalizeVector(CvMat* v) {
double d = cvNorm(v);
for (int i = 0; i < v->rows; i++) {
v->data.db[i] /= d;
}
}
// v: 3 x 1 matrix
CvMat* getCrossMatrix(CvMat* v) {
assert(v->rows == 3 && v->cols == 1);
CvMat* ex = cvCreateMat(3, 3, v->type);
cvZero(ex);
cvmSet(ex, 0, 1, -cvmGet(v, 2, 0));
cvmSet(ex, 0, 2, cvmGet(v, 1, 0));
cvmSet(ex, 1, 0, cvmGet(v, 2, 0));
cvmSet(ex, 1, 2, -cvmGet(v, 0, 0));
cvmSet(ex, 2, 0, -cvmGet(v, 1, 0));
cvmSet(ex, 2, 1, cvmGet(v, 0, 0));
return ex;
}
void setSubRect(CvMat* dst, const CvMat* submat, const CvRect& rect) {
assert(submat->width == rect.width && submat->height == rect.height);
CvMat stub;
cvGetSubRect(dst, &stub, rect);
cvCopy(submat, &stub);
}
void copySubRect(const CvMat* src, CvMat* submat, const CvRect& rect) {
assert(submat->width == rect.width && submat->height == rect.height);
for (int i = 0; i < rect.height; i++) {
for (int j = 0; j < rect.width; j++) {
cvmSet(submat, i, j, cvmGet(src, rect.y + i, rect.x + j));
}
}
}
void copyCols(CvMat* dst, CvMat* submat, int start, int end) {
copySubRect(dst, submat, cvRect(start, 0, end - start, dst->height));
}
void copyCol(CvMat* dst, CvMat* submat, int index) {
copyCols(dst, submat, index, index + 1);
}
void setCols(CvMat* dst, const CvMat* submat, int start, int end) {
setSubRect(dst, submat, cvRect(start, 0, end - start, dst->height));
}
void setCol(CvMat* dst, const CvMat* submat, int col) {
setSubRect(dst, submat, cvRect(col, 0, 1, dst->height));
}
CvMat* getRows(const CvMat* src, int start, int end) {
CvMat* submat = cvCreateMat(end - start, src->cols, src->type);
copySubRect(src, submat, cvRect(0, start, src->cols, end - start));
return submat;
}
CvMat* getRow(const CvMat* src, int index) {
return getRows(src, index, index + 1);
}
void setRow(CvMat* dst, const CvMat* submat, int row) {
setSubRect(dst, submat, cvRect(0, row, dst->width, 1));
}
CvMat* getCols(CvMat* src, int start, int end) {
CvMat* submat = cvCreateMat(src->rows, end - start, src->type);
copySubRect(src, submat, cvRect(start, 0, end - start, src->rows));
return submat;
}
CvMat* getCol(CvMat* src, int index) {
return getCols(src, index, index + 1);
}
//===== BEGIN ==== Transformation between Point and Matrix ==========================/
//homogeneous vector <- point2d
CvMat* hmatFromPoint2D(const CvPoint2D32f& p) {
CvMat* m = cvCreateMat(3, 1, CV_64FC1);
m->data.db[0] = p.x;
m->data.db[1] = p.y;
m->data.db[2] = 1.0;
return m;
}
//homogeneous vector -> point2d
CvPoint2D32f hmatToPoint2D(CvMat* m) {
CvPoint2D32f p;
p.x = (float)(m->data.db[0] / m->data.db[2]);
p.y = (float)(m->data.db[1] / m->data.db[2]);
return p;
}
//homogeneous vector <- point3d
CvMat* hmatFromPoint3D(const CvPoint3D32f& p) {
CvMat* m = cvCreateMat(4, 1, CV_64FC1);
m->data.db[0] = p.x;
m->data.db[1] = p.y;
m->data.db[2] = p.z;
m->data.db[3] = 1.0;
return m;
}
//homogeneous vector -> point3d
CvPoint3D32f hmatToPoint3D(CvMat* m) {
CvPoint3D32f p;
p.x = m->data.db[0] / m->data.db[3];
p.y = m->data.db[1] / m->data.db[3];
p.z = m->data.db[2] / m->data.db[3];
return p;
}
//unhomogeneous vector <- point3d
CvMat* matFromPoint3D(const CvPoint3D32f& p) {
CvMat* m = cvCreateMat(3, 1, CV_64FC1);
m->data.db[0] = p.x;
m->data.db[1] = p.y;
m->data.db[2] = p.z;
return m;
}
//unhomogeneous vector -> point3d
CvPoint3D32f matToPoint3D(CvMat* m) {
CvPoint3D32f p;
p.x = m->data.db[0];
p.y = m->data.db[1];
p.z = m->data.db[2];
return p;
}
CvMat* hmatFromMat(const CvMat* m) {
assert(m->cols == 1);
CvMat* hm = cvCreateMat(m->rows + 1, m->cols, m->type);
setSubRect(hm, m, cvRect(0, 0, m->width, m->height));
cvmSet(hm, m->rows, 0, 1.0);
return hm;
}
CvMat* hmatToMat(const CvMat* hm) {
assert(hm->cols == 1);
CvMat* m = cvCreateMat(hm->rows - 1, hm->cols, hm->type);
double d = cvmGet(hm, hm->rows - 1, 0);
for (int i = 0; i < m->rows; i++) {
cvmSet(m, i, 0, cvmGet(hm, i, 0) / d);
}
return m;
}
//homogeneous vector <- point2d
vector<CvMat*> vectorHmatFromPoint2D(const vector<CvPoint2D32f>& ps) {
vector<CvMat*> mps;
for (int i = 0; i < (int)ps.size(); i++) {
mps.push_back(hmatFromPoint2D(ps[i]));
}
return mps;
}
//homogeneous vector -> point2d
vector<CvPoint2D32f> vectorHmatToPoint2D(const vector<CvMat*>& mps) {
vector<CvPoint2D32f> ps;
for (int i = 0; i < (int)mps.size(); i++) {
ps.push_back(hmatToPoint2D(mps[i]));
}
return ps;
}
//homogeneous vector <- point3d
vector<CvMat*> vectorHmatFromPoint3D(const vector<CvPoint3D32f>& ps) {
vector<CvMat*> mps;
for (int i = 0; i < (int)ps.size(); i++) {
mps.push_back(hmatFromPoint3D(ps[i]));
}
return mps;
}
//homogeneous vector -> point3d
vector<CvPoint3D32f> vectorHmatToPoint3D(const vector<CvMat*>& mps) {
vector<CvPoint3D32f> ps;
for (int i = 0; i < (int)mps.size(); i++) {
ps.push_back(hmatToPoint3D(mps[i]));
}
return ps;
}
vector<CvPoint3D32f> initXs(float pts[][3], int num) {
vector<CvPoint3D32f> Xs;
for (int i = 0; i < num; i++) {
Xs.push_back(cvPoint3D32f(pts[i][0], pts[i][1], pts[i][2]));
}
return Xs;
}
//===== END ==== Transformation between Point and Matrix ==========================/
string matString(const CvMat* M) {
ostringstream oss;
oss<<M->rows<<" x "<<M->cols<<endl;
double* data = (double*)M->data.db;
for (int i = 0; i < M->rows; i++) {
for (int j = 0; j < M->cols; j++) {
oss<<data[i * M->cols + j]<<" ";
}
oss<<endl;
}
return oss.str();
}
//assert M : 3 x 1
void assertH3(const CvMat* M) {
assert(M->rows == 3 && M->cols == 1);
}
//assert M : 4 x 1
void assertH4(const CvMat* M) {
assert(M->rows == 4 && M->cols == 1);
}
CvMat* getIdentity() {
CvMat* I = cvCreateMat(3, 3, CV_64FC1);
cvSetIdentity(I);
return I;
}
CvMat* getZero(int rows, int cols) {
CvMat* M = cvCreateMat(rows, cols, CV_64FC1);
cvZero(M);
return M;
}
CvMat* cloneMat(const CvMat* M) {
CvMat* nM = cvCreateMat(M->rows, M->cols, M->type);
cvCopy(M, nM);
return nM;
}
CvMat* sub(const CvMat* A, const CvMat* B) {
CvMat* C = cvCreateMat(A->rows, A->cols, A->type);
cvSub(A, B, C);
return C;
}
CvMat* scale(const CvMat* M, double s) {
CvMat* nM = cvCreateMat(M->rows, M->cols, M->type);
cvScale(M, nM, s);
return nM;
}
void clearMat(CvMat** M) {
if (*M != NULL) {
cvReleaseMat(M);
*M = NULL;
}
}
}
} | [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
]
| [
[
[
1,
408
]
]
]
|
e465fb6a539004751bb6ec955655434adccc949d | 67298ca8528b753930a3dc043972dceab5e45d6a | /Asteroids/src/SocketInterface.cpp | 1cfb62799c0b23f8ebabdaa91e570ed861c1385e | []
| no_license | WhyKay92/cs260assignment3 | 3cf28dd92b9956b2cd4f850652651cb11f25c753 | 77ad90cd2dc0b44f3ba0a396dc8399021de4faa5 | refs/heads/master | 2021-05-30T14:59:21.297733 | 2010-12-13T09:18:17 | 2010-12-13T09:18:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,568 | cpp | #include "SocketInterface.hpp"
void iSocket::SetIP( char *IP )
{
socketAddress_.sin_addr.s_addr = inet_addr( IP );
}
void iSocket::SetPortNumber( u32 port )
{
socketAddress_.sin_port = htons( port );
}
void iSocket::Shutdown( void )
{
Sleep( 100 );
int eCode = shutdown( socket_, SD_BOTH );
if( eCode == SOCKET_ERROR )
{
throw( SockErr( WSAGetLastError(), "Failed to shutdown on sending socket." ) );
}
}
void iSocket::Close( void )
{
int eCode = closesocket( socket_ );
if( eCode == SOCKET_ERROR )
{
throw( SockErr( WSAGetLastError(), "Failure to close socket" ) );
}
}
bool iSocket::ReceiveUntil( char *buffer, u32 recvCount, u32 bufferSize, u32 bufferOffset /* = 0 */ )
{
u32 writeCount = bufferSize - bufferOffset;
if( recvCount > writeCount )
// to do: throw something
return false;
buffer += bufferOffset;
u32 totalBytesRead = 0;
u32 bytesRead = 0;
while( totalBytesRead < recvCount )
{
int eCode = recv( socket_, buffer, writeCount, 0 );
if( eCode == 0 )
{
disconnect_ = true;
throw( SockErr( 0, "Remote end point has shutdown the connection." ) );
}
else if( eCode == SOCKET_ERROR )
{
eCode = WSAGetLastError();
if( eCode == WSAEWOULDBLOCK )
return false;
throw( SockErr( WSAGetLastError(), "Failure to receive." ) );
}
bytesRead = eCode;
totalBytesRead += bytesRead;
buffer += bytesRead;
writeCount -= bytesRead;
}
/*
if( totalBytesRead > recvCount )
return false;
else if( totalBytesRead < recvCount )
// to do: this is bad, throw something
return false;
else
return true;
*/
return true;
}
u32 iSocket::PendingBytes( void )
{
ULONG count = 0;
if( ioctlsocket( socket_, FIONREAD, &count ) == 0 )
return count;
else
return 333333;
}
iSocket::SocketErrExcep::SocketErrExcep( int eCode, char const *msg, std::string const &socketName )
: WinSockErrExcep( eCode, msg_ ), socketName_( socketName )
{
}
iSocket::SocketErrExcep::SocketErrExcep( int eCode, std::string const &msg, std::string const &socketName )
: WinSockErrExcep( eCode, msg ), socketName_( socketName )
{
}
void iSocket::SocketErrExcep::Print( void )
{
if( socketName_ == "" )
{
printf("A socket generated an error. ");
}
else
{
printf("Socket %s generated an error. ", socketName_.c_str() );
}
WinSockErrExcep::Print();
}
| [
"[email protected]"
]
| [
[
[
1,
125
]
]
]
|
2f0631ff45b921fa43f5222a52d3bbbe1d450d1b | bfbe6667ce1a0b7b2772f4de57829d8760a0f55c | /var.3/Текстовые файлы.CPP | fc01fb8a0768d349e256c47b369538de134eeff7 | []
| no_license | buger/CPP-Labs | 50333a317657d495ad5a3f120441ed5988ea16d5 | f413c505af4a9f612c597214ab68384b588f5389 | refs/heads/master | 2023-07-12T11:41:10.793947 | 2009-10-17T16:00:24 | 2009-10-17T16:00:24 | 339,804 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 470 | cpp | #include <stdio.h>
#include <stdlib.h>
void main()
{ FILE*ft,*zp;
int c='a',d,ch,j;
ft=fopen("inp.txt","w");
if(!ft) { puts("ne cozdat fail\n");
exit(1);
}
fprintf(ft,"fhjhhahfjahwiuoweiitudbcanvczxccdfee");
fclose(ft);
zp=fopen("g.txt","w");
for(j=0;j<5;j++)
{
d=0;
ft=fopen("inp.txt","r");
while((ch=fgetc(ft))!=EOF)
{if(c==ch)
{ d++;
printf("===%c",c);
}
}
fclose(ft);
fprintf(zp,"bykv(%c)-%d\n",c,d);
c++;
}
fclose(zp);
}
| [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
503d6cb3d40dbbf5ce9080b8df2e491be18fd83f | 842997c28ef03f8deb3422d0bb123c707732a252 | /src/moaicore/MOAIBlocker.h | 452dff54985827bea05884e1f34b9c6895862f81 | []
| no_license | bjorn/moai-beta | e31f600a3456c20fba683b8e39b11804ac88d202 | 2f06a454d4d94939dc3937367208222735dd164f | refs/heads/master | 2021-01-17T11:46:46.018377 | 2011-06-10T07:33:55 | 2011-06-10T07:33:55 | 1,837,561 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#ifndef MOAIBLOCKER_H
#define MOAIBLOCKER_H
//================================================================//
// MOAIBlocker
//================================================================//
class MOAIBlocker :
public virtual USLuaObject {
private:
MOAIBlocker* mBlocker;
MOAIBlocker* mBlockedList;
MOAIBlocker* mNextBlocked;
//----------------------------------------------------------------//
void AddBlocked ( MOAIBlocker* blocked );
virtual void OnUnblock ();
void RemoveBlocked ( MOAIBlocker* blocked );
public:
friend class MOAIAction;
//----------------------------------------------------------------//
bool IsBlocked ();
MOAIBlocker ();
virtual ~MOAIBlocker ();
void SetBlocker ( MOAIBlocker* blocker );
void UnblockAll ();
void UnblockSelf ();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
2c66e6a03acf985637d0a97634e62e732a3a1c30 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/Dialogs.h | 8c624ba2af198b3998676a6eedf4130a56d41eff | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,039 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WAYFINDER_DIALOGS_H
#define WAYFINDER_DIALOGS_H
#include <e32def.h>
#include <e32std.h>
#include <coemain.h>
namespace WFDialog{
/**\defgroup g1 ShowConfirmationL
* Displays an information note containing an animated checkbox.
* The dialog has no buttons, but closes automatically.
* @{
*/
/** @param aText the text to be displayed.
*/
void ShowConfirmationL( TDesC const &aText );
/** @param aResourceId the id of a resource containing a string.
* @param aCoeEnv pointer to the application instance of CCoeEnv.
* Used for reading the resource. If no CCoeEnv pointer
* is available, use <code>ShowConfirmationL(TInt)</code>
* instead.
*/
void ShowConfirmationL( TInt aResourceId, class CCoeEnv* aCoeEnv );
/** This method calls <code>CCoeEnv::Static()</code> for resource access.
* If a <code>CCoeENv</code> pointer is available, prefer
* <code>ShowConfirmationL(TInt, CCoeEnv*)</code>.
* @param aResourceId the resource id of the text to be displayed.
*/
inline void ShowConfirmationL( TInt aResourceId )
{
ShowConfirmationL(aResourceId, CCoeEnv::Static());
}
/**@}*/
/** \defgroup g2 ShowErrorDialogL
* Display an error dialog containing an red exclamation mark.
* The dialog has an OK button.
* A tone is played when the dialog opens.
*@{
*/
/** @param aText the string to display.
*/
void ShowErrorDialogL( const TDesC &aText );
/** @param aResourceId the resource identifier of the test to be displayed.
* @param aCoeEnv pointer to the application instance of CCoeEnv.
* Used for reading the resource. If no CCoeEnv pointer
* is available, use <code>ShowErrorDialogL(TInt)</code>
* instead.
*/
void ShowErrorDialogL( TInt aResourceId, class CCoeEnv* coeEnv );
/** This method calls <code>CCoeEnv::Static()</code> for resource access.
* If a <code>CCoeENv</code> pointer is available, prefer
* <code>ShowErrorDialogL(TInt, CCoeEnv*)</code>.
* @param aResourceId the resource identifier of the test to be displayed.
*/
inline void ShowErrorDialogL( TInt aResourceId )
{
ShowErrorDialogL(aResourceId, CCoeEnv::Static());
}
/**@}*/
/**\defgroup g3 ShowWarningDialogL
* Displays a warning dialog containing an exclamation mark.
* Has an OK button. Plays a tone when opening.
* @{*/
/** @param aText the text to display.
*/
void ShowWarningDialogL( const TDesC &aText );
/** @param aResourceId the resource identifier of the test to be displayed.
* @param aCoeEnv pointer to the application instance of CCoeEnv.
* Used for reading the resource. If no CCoeEnv pointer
* is available, use <code>ShowWarningDialogL(TInt)</code>
* instead.
*/
void ShowWarningDialogL( TInt aResourceId, class CCoeEnv* aCoeEnv);
/** This method calls <code>CCoeEnv::Static()</code> for resource access.
* If a <code>CCoeENv</code> pointer is available, prefer
* <code>ShowWarningDialogL(TInt, CCoeEnv*)</code>.
* @param aResourceId the resource identifier of the test to be displayed.
*/
inline void ShowWarningDialogL( TInt aResourceId)
{
ShowWarningDialogL(aResourceId, CCoeEnv::Static());
}
/**\defgroup g3 ShowInfoDialogL
* Displays a info dialog.
* Has an OK button. Plays no tone when opening.
* @{*/
/** @param aText the text to display.
*/
void ShowInfoDialogL( const TDesC &aText, TBool aAutoClose );
/** @param aResourceId the resource identifier of the text to be displayed.
* @param aCoeEnv pointer to the application instance of CCoeEnv.
* Used for reading the resource. If no CCoeEnv pointer
* is available, use <code>ShowInfoDialogL(TInt)</code>
* instead.
*/
void ShowInfoDialogL( TInt aResourceId, class CCoeEnv* aCoeEnv, TBool aAutoClose);
//TInt ShowRoamingDialogL(const TDesC& aText, MCoeControlObserver* aObserver);
//TInt ShowRoamingDialogL(TInt aResourceId, class CCoeEnv* aCoeEnv, MCoeControlObserver* aObserver);
/**@}*/
/**\defgroup g4 ShowDebugDialogL
* When compiled in debug mode, this function displays a query
* dialog containg the text in the parameter. It makes no
* difference whether the user chooses Yes or No.
* Note! MAX 128 chars!
* @{
*/
/** @param str a C-style string to be displayed.
* It may be max 128 characters long.
*/
void ShowDebugDialogL( const char *str );
/** @param aText the text to display.
*/
void ShowDebugDialogL( const TDesC &aText);
/**@}*/
/**\defgroup g5 ShowScrollingWarningDialogL
* Displays a scrolling dialog with a header saying "Warning" and
* an OK button.
* @{
*/
/** @param aText the text to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowScrollingWarningDialogL(const TDesC &aText,
class CCoeEnv *aCoeEnv);
/** If a CCoeEnv pointer is available, prefer
* <code>ShowScrollingWarningDialogL(const TDesC, CCoeEnv*)</code>.
* @param aText the text to display.
*/
inline void ShowScrollingWarningDialogL( const TDesC& aText)
{
ShowScrollingWarningDialogL(aText, CCoeEnv::Static());
}
/** @param aResourceId the resource id for the string to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowScrollingWarningDialogL( TInt aResourceId, class CCoeEnv* coeEnv );
/** If a CCoeEnv pointer is available, prefer
* <code>ShowScrollingWarningDialogL(const TDesC, CCoeEnv*)</code>.
* @param aResourceId the resource id for the string to display.
*/
inline void ShowScrollingWarningDialogL( TInt aResourceId )
{
ShowScrollingWarningDialogL(aResourceId, CCoeEnv::Static());
}
/**@}*/
/**\defgroup g6 ShowScrollingErrorDialogL
* Displays a scrolling dialog with a header saying "Error" and an
* OK button.
* @{
*/
/** @param aText the text to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowScrollingErrorDialogL( const TDesC &aText, class CCoeEnv*aCoeEnv );
/** If a CCoeEnv pointer is available, prefer
* <code>ShowScrollingErrorDialogL(const TDesC, CCoeEnv*)</code>.
* @param aText the text to display.
*/
inline void ShowScrollingErrorDialogL( const TDesC &aText )
{
ShowScrollingErrorDialogL( aText, CCoeEnv::Static() );
}
/** @param aResourceId the resource id for the string to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowScrollingErrorDialogL( TInt aResourceId, class CCoeEnv* coeEnv );
/** If a CCoeEnv pointer is available, prefer
* <code>ShowScrollingErrorDialogL(const TDesC, CCoeEnv*)</code>.
* @param aResourceId the resource id for the string to display.
*/
inline void ShowScrollingErrorDialogL( TInt aResourceId )
{
ShowScrollingErrorDialogL(aResourceId, CCoeEnv::Static());
}
/**@}*/
//*****ShowScrollingInfoDialogL*****
void ShowScrollingInfoDialogL( const TDesC &aText, class CCoeEnv* coeEnv );
void ShowScrollingInfoDialogL( TInt aResourceId, class CCoeEnv* coeEnv );
inline void ShowScrollingInfoDialogL( const TDesC &aText )
{
ShowScrollingInfoDialogL( aText, CCoeEnv::Static() );
}
inline void ShowScrollingInfoDialogL( TInt aResourceId )
{
ShowScrollingInfoDialogL(aResourceId, CCoeEnv::Static());
}
/**\defgroup g7 ShowScrollingDialogL
* Displays a scrolling dialog with a user defined header,
* and an OK button.
*@{
*/
/** @param aHeader the header string.
* @param aText the text to display.
* @param aTone play tone when opening or not.
* @param aBitmap unused
* @param aMask unused
*/
void ShowScrollingDialogL( const TDesC &aHeader, const TDesC &aText,
TBool aTone, TInt32 aBitmap = -1,
TInt32 aMask = -1 );
/** @param aCoeEnv a pointer to a CCoeEnv object used to read resources.
* @param aHeader a resource id identifying the header string.
* @param aText a resource id identifying the message string.
* @param aTone play tone when opening or not.
* @param aBitmap unused
* @param aMask unused
*/
void ShowScrollingDialogL(class CCoeEnv* aCoeEnv, TInt aHeader, TInt aText,
TBool aTone, TInt32 aBitmap = -1,
TInt32 aMask = -1);
/** If a CCoeEnv pointer is available, prefer
* <code>ShowScrollingDialogL(CCoeEnv*, TInt, TInt, TBool,
* TInt32, TInt32)</code>.
* @param aHeader a resource id identifying the header string.
* @param aText a resource id identifying the message string.
* @param aTone play tone when opening or not.
* @param aBitmap unused
* @param aMask unused
*/
inline void ShowScrollingDialogL( TInt aHeader, TInt aText, TBool aTone,
TInt32 aBitmap = -1, TInt32 aMask = -1)
{
ShowScrollingDialogL(CCoeEnv::Static(), aHeader, aText, aTone, aBitmap,
aMask);
}
TBool ShowScrollingQueryL(class CCoeEnv* coeEnv,
TInt aHeader, TInt aText, TBool aTone,
TInt32 aBitmap = -1, TInt32 aMask = -1);
TBool ShowScrollingQueryL( const TDesC &aHeader, const TDesC &aText,
TBool aTone, TInt32 aBitmap = -1, TInt32 aMask = -1);
TBool ShowScrollingQueryL(TInt aResourceId,
const TDesC &aHeader, const TDesC &aText,
TBool aTone);
inline TBool ShowScrollingQueryL( TInt aHeader, TInt aText, TBool aTone,
TInt32 aBitmap = -1, TInt32 aMask = -1)
{
return ShowScrollingQueryL(CCoeEnv::Static(),
aHeader, aText, aTone, aBitmap, aMask);
}
/**@}*/
/**\defgroup ginfo ShowInformationL
* Display an information note containing an animated 'i'.
* @{
*/
/** @param aText the test to display*/
void ShowInformationL( const TDesC &aText );
/** @param aResourceId a resource id identifying the string to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowInformationL( TInt aResourceId, class CCoeEnv* coeEnv );
/** If a CCoeEnv pointer is available, prefer
* <code>ShowInformationL(TInt, CCoeEnv*)</code>.
* @param aResourceId a resource id identifying the string to display.
*/
inline void ShowInformationL( TInt aResourceId )
{
ShowInformationL(aResourceId, CCoeEnv::Static());
}
/**@}*/
/** \defgroup gwarn ShowWarningL
* Display a warning note containing an image of an exclamation mark.
* @{
*/
/** @param aText the test to display*/
void ShowWarningL( const TDesC &aText );
/** @param aResourceId a resource id identifying the string to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowWarningL( TInt aResourceId, class CCoeEnv* coeEnv );
/** If a CCoeEnv pointer is available, prefer
* <code>ShowWarningL(TInt, CCoeEnv*)</code>.
* @param aResourceId a resource id identifying the string to display.
*/
inline void ShowWarningL( TInt aResourceId )
{
ShowWarningL(aResourceId, CCoeEnv::Static());
}
/**@}*/
/** \defgroup gwarn ShowErrorL
* Display a error note containing an image of an exclamation mark.
* @{
*/
/** @param aText the test to display*/
void ShowErrorL( const TDesC &aText );
/** @param aResourceId a resource id identifying the string to display.
* @param aCoeEnv a pointer to a CCoeEnv instance used to read resources.
*/
void ShowErrorL( TInt aResourceId, class CCoeEnv* coeEnv );
/** If a CCoeEnv pointer is available, prefer
* <code>ShowErrorL(TInt, CCoeEnv*)</code>.
* @param aResourceId a resource id identifying the string to display.
*/
inline void ShowErrorL( TInt aResourceId )
{
ShowErrorL(aResourceId, CCoeEnv::Static());
}
/**@}*/
/**\defgroup gquery ShowQueryL
* Display a yes no dialog. Contains an image of a question mark.
* @{
*/
/** @param aText the test to display.
* @return ETrue if the user selected Yes, EFalse if the user selected No.
*/
TBool ShowQueryL( const TDesC &aText );
/** @param aResourceId a resource id identifying the string to display.
* @param aCoeEnv a pointer to an CCoeEnv instance used for reading
* resources.
* @return ETrue if the user selected Yes, EFalse if the user selected No.
*/
TBool ShowQueryL( TInt aResourceId, class CCoeEnv* coeenv );
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
350
]
]
]
|
66c7f40e9544a38af1ffae0874fa43088c9927fd | 9d58409162a450f5dd162c43cfe0dc7c12c00e14 | /src/BeatDetectView.cpp | fbf79eb2948d9c541fe6251800e863e2d7b8d64d | []
| no_license | robharper/beat-detect | 0f8e9c6feb64e52409972117bed9417795057c76 | 2f0905d3b657155521c1f4c354b1f75d48d63b04 | refs/heads/master | 2021-01-01T20:06:05.435288 | 2011-08-07T17:48:07 | 2011-08-07T17:48:07 | 2,169,522 | 17 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,877 | cpp | // BeatDetectView.cpp : implementation of the CBeatDetectView class
//
#include "stdafx.h"
#include "BeatDetect.h"
#include "MainFrm.h"
#include "BeatDetectDoc.h"
#include "BeatDetectView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define RULER_HEIGHT 20
/////////////////////////////////////////////////////////////////////////////
// CBeatDetectView
IMPLEMENT_DYNCREATE(CBeatDetectView, CScrollView)
BEGIN_MESSAGE_MAP(CBeatDetectView, CScrollView)
//{{AFX_MSG_MAP(CBeatDetectView)
ON_COMMAND(ID_VIEW_ZOOMIN, OnViewZoomIn)
ON_COMMAND(ID_VIEW_ZOOMOUT, OnViewZoomOut)
ON_BN_CLICKED(IDC_VIEW_INPUT_CHECK, OnViewStreamChange)
ON_WM_SIZE()
ON_BN_CLICKED(IDC_VIEW_ONSET_CHECK, OnViewStreamChange)
ON_BN_CLICKED(IDC_VIEW_ONSET2_CHECK, OnViewStreamChange)
ON_BN_CLICKED(IDC_VIEW_BEATOUT_CHECK, OnViewStreamChange)
ON_BN_CLICKED(IDC_VIEW_TEMPOOUT_CHECK, OnViewStreamChange)
ON_BN_CLICKED(IDC_VIEW_PERIODOUT_CHECK, OnViewStreamChange)
ON_BN_CLICKED(IDC_VIEW_INFOOUT_CHECK, OnViewStreamChange)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CBeatDetectView construction/destruction
CBeatDetectView::CBeatDetectView() : m_dZoom(0.016)
{
// TODO: add construction code here
}
CBeatDetectView::~CBeatDetectView()
{
}
BOOL CBeatDetectView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CScrollView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CBeatDetectView drawing
void CBeatDetectView::OnDraw(CDC* pDC)
{
CBeatDetectDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
RECT rcView;
GetViewRect( &rcView );
CList<CDataStream*,CDataStream*> lstStream;
HRESULT hr = CreateStreamsList( &lstStream );
if( S_OK == hr )
{
//////////////////
// Draw Time Ruler
RECT rcRuler = rcView;
rcRuler.bottom = rcRuler.top + RULER_HEIGHT;
rcView.top = rcRuler.bottom;
DrawTimeRuler( pDC, &rcRuler );
//////////////////
// Draw Data Streams
// Determine rects for drawing streams
INT32 nStreams = lstStream.GetCount();
INT32 nStreamHeight = rcView.bottom/nStreams;
RECT rcStream = rcView;
rcStream.bottom = rcStream.top + nStreamHeight;
POSITION pos = lstStream.GetHeadPosition();
while( pos != NULL )
{
CDataStream* pStrm = lstStream.GetNext(pos);
// Draw
DrawStream( pDC, pStrm, &rcStream );
// Offset stream rect
OffsetRect( &rcStream, 0, nStreamHeight );
}
}
//////////////////
}
void CBeatDetectView::OnInitialUpdate()
{
CScrollView::OnInitialUpdate();
CMainFrame* pMainFrm = (CMainFrame*)AfxGetApp()->GetMainWnd();
CDialogBar* pDlgBar = pMainFrm->GetDialogBar();
((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_INPUT_CHECK))->SetCheck(TRUE);
((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_ONSET_CHECK))->SetCheck(TRUE);
((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_BEATOUT_CHECK))->SetCheck(TRUE);
((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_TEMPOOUT_CHECK))->SetCheck(TRUE);
((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_PERIODOUT_CHECK))->SetCheck(TRUE);
OnViewStreamChange();
}
/////////////////////////////////////////////////////////////////////////////
// CBeatDetectView diagnostics
#ifdef _DEBUG
void CBeatDetectView::AssertValid() const
{
CScrollView::AssertValid();
}
void CBeatDetectView::Dump(CDumpContext& dc) const
{
CScrollView::Dump(dc);
}
CBeatDetectDoc* CBeatDetectView::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CBeatDetectDoc)));
return (CBeatDetectDoc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CBeatDetectView message handlers
void CBeatDetectView::OnViewZoomIn()
{
// Messy crap, but this is not a pro app...
if( m_dZoom > 0.0001 )
{
m_dZoom = m_dZoom / 2;
OnViewStreamChange();
}
}
void CBeatDetectView::OnViewZoomOut()
{
// Messy crap, but this is not a pro app...
if( m_dZoom < 0.1 )
{
m_dZoom = m_dZoom * 2;
OnViewStreamChange();
}
}
HRESULT CBeatDetectView::CreateStreamsList
(
CList<CDataStream*,CDataStream*> *pList
)
{
CBeatDetectDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if( NULL == pList )
return E_INVALIDARG;
CMainFrame* pMainFrm = (CMainFrame*)AfxGetApp()->GetMainWnd();
CDialogBar* pDlgBar = pMainFrm->GetDialogBar();
// Clear out list
while( !pList->IsEmpty() )
pList->RemoveTail();
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_INPUT_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_ASInput );
}
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_ONSET_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_StrmOnsetOutput );
}
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_ONSET2_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_StrmOnsetInternal );
}
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_BEATOUT_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_StrmBeatOutput );
}
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_TEMPOOUT_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_StrmBeatTempo );
}
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_PERIODOUT_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_StrmBeatPeriod );
}
if( ((CButton*)pDlgBar->GetDlgItem(IDC_VIEW_INFOOUT_CHECK))->GetCheck() )
{
pList->AddTail( &pDoc->m_StrmBeatInfo );
}
if( !pList->IsEmpty() )
return S_OK;
else
return S_FALSE;
}
void CBeatDetectView::OnViewStreamChange()
{
// Update the view with changes in the streams we are to show
CList<CDataStream*,CDataStream*> lstStream;
DOUBLE dDuration = 0;
HRESULT hr = CreateStreamsList( &lstStream );
if( S_OK == hr )
{
POSITION pos = lstStream.GetHeadPosition();
while( pos != NULL )
{
CDataStream* pStrm = lstStream.GetNext(pos);
if( pStrm->GetDuration() > dDuration )
dDuration = pStrm->GetDuration();
}
}
// Set View Size
RECT rcWnd;
GetClientRect(&rcWnd);
SIZE sz;
sz.cx = max((INT32)(dDuration/m_dZoom), rcWnd.right-rcWnd.left);
sz.cy = rcWnd.bottom-rcWnd.top;
SetScrollSizes(MM_TEXT, sz);
Invalidate( TRUE );
////////////////////
// Scroll Error Crap
// Scrollbars suck and can't go higher than 32767, so warn if this happens
m_fScrollError = (sz.cx > 32767);
return;
}
void CBeatDetectView::OnSize
(
UINT nType,
int cx,
int cy
)
{
CScrollView::OnSize(nType, cx, cy);
//////////
// Make vertical dimension equal to client size...
SIZE szTotal;
RECT rcView;
GetViewRect(&rcView);
szTotal.cx = rcView.right;
RECT rcWnd;
GetClientRect(&rcWnd);
szTotal.cy = rcWnd.bottom-rcWnd.top;
SetScrollSizes(MM_TEXT, szTotal);
//////////
}
void CBeatDetectView::GetViewRect
(
RECT *prc
)
{
INT32 nTemp;
SIZE szTotal, szTemp1, szTemp2;
GetDeviceScrollSizes( nTemp, szTotal, szTemp1, szTemp2 );
prc->top = 0;
prc->left = 0;
prc->bottom = szTotal.cy;
prc->right = szTotal.cx;
}
void CBeatDetectView::DrawStream
(
CDC * pDC,
CDataStream *pStrm,
LPRECT lprc
)
{
INT32 nCentreLine = (lprc->top + lprc->bottom)/2;
// Draw horizontal line at zero
CBrush Brush;
Brush.CreateSolidBrush( 0x0000FF00 );
RECT rcDraw = *lprc;
rcDraw.top = nCentreLine;
rcDraw.bottom = nCentreLine + 1;
pDC->FillRect( &rcDraw, &Brush );
Brush.DeleteObject();
// Hurt Casting! ***************************************************************
// Assume Float
FLOAT* pData = (FLOAT*)pStrm->GetData();
RECT rcClip;
pDC->GetClipBox( &rcClip );
InflateRect( &rcClip, 2, 0 );
// Create Draw Brush - Blue
if( m_fScrollError )
Brush.CreateSolidBrush( 0x000000FF );
else
Brush.CreateSolidBrush( 0x00CC0000 );
CBrush BrushSpike;
BrushSpike.CreateSolidBrush( 0x00009900 );
// Calculate draw region
INT32 nSampleScale = (INT32)((lprc->bottom - lprc->top)/2);
// Calculate Sample Offsets
INT32 nStartSample = max((INT32)((DOUBLE)rcClip.left*m_dZoom*pStrm->GetSampleRate()), 0);
INT32 nEndSample = min((INT32)((DOUBLE)rcClip.right*m_dZoom*pStrm->GetSampleRate()), pStrm->GetNumSamples());
DOUBLE dSamplesPerPixel = m_dZoom*pStrm->GetSampleRate();
DOUBLE dSamCurPixel = nStartSample;
DOUBLE dSamNextPixel = dSamCurPixel + dSamplesPerPixel;
// Loop through all samples
INT32 ix = rcClip.left;
FLOAT flMin = 1;
FLOAT flMax = -1;
BOOL fNext = FALSE;
for( INT32 iSam = nStartSample; iSam < nEndSample; iSam++ )
{
// Draw and go to the next pixel
while( iSam > (INT32)dSamNextPixel )
{
// Draw this pixel
RECT rcDraw;
rcDraw.left = ix;
rcDraw.right = ix+1;
rcDraw.top = nCentreLine - (INT32)(flMax*nSampleScale);
rcDraw.bottom = nCentreLine - (INT32)(flMin*nSampleScale) + 1;
if( flMax > 1 )
pDC->FillRect( &rcDraw, &BrushSpike );
else
pDC->FillRect( &rcDraw, &Brush );
// Next pixel
dSamNextPixel += dSamplesPerPixel;
ix += 1;
fNext = TRUE;
}
if( fNext )
{
// Swap min and max to make continuous plot for next set of samples
// Only do this after drawing all pixels for current samples because
// we need to make sure to draw situations where samples/pixel is less
// than one
FLOAT flTemp = flMin;
flMin = flMax;
flMax = flTemp;
fNext = FALSE;
}
if( pData[iSam] > flMax )
flMax = pData[iSam];
if( pData[iSam] < flMin )
flMin = pData[iSam];
}
// Clean Up
Brush.DeleteObject();
BrushSpike.DeleteObject();
}
void CBeatDetectView::DrawTimeRuler
(
CDC * pDC,
LPRECT lprc
)
{
// Draw Background
CBrush Brush;
Brush.CreateSolidBrush( 0x00BBBBBB );
pDC->FillRect( lprc, &Brush );
Brush.DeleteObject();
// Draw horizontal marker lines
Brush.CreateSolidBrush( 0x00000000 );
RECT rcClip;
pDC->GetClipBox( &rcClip );
INT32 nStartPixel = rcClip.left;
INT32 nEndPixel = rcClip.right+2;
FLOAT flTicks = (FLOAT)(1/m_dZoom);
INT32 nTickHeight = lprc->bottom - lprc->top - 1;
while( flTicks > 25 )
{
FLOAT fli = (INT32)(nStartPixel/flTicks) * flTicks;
for(; fli<nEndPixel; fli+=flTicks)
{
RECT rcTick;
rcTick.bottom = lprc->bottom;
rcTick.top = rcTick.bottom - nTickHeight;
rcTick.left = (LONG)fli;
rcTick.right = (LONG)fli+1;
pDC->FillRect( &rcTick, &Brush );
}
nTickHeight = (nTickHeight * 2) / 3;
flTicks /= 2;
}
Brush.DeleteObject();
}
| [
"[email protected]"
]
| [
[
[
1,
444
]
]
]
|
647386d94e5d4900ae47785dd519ebf70e28a87d | 5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd | /EngineSource/dpslim/dpslim/Simulation/Source/MSDatabaseMethods.CPP | cca088385a83d5194cd620dd41bfd82889790437 | []
| no_license | karakots/dpresurrection | 1a6f3fca00edd24455f1c8ae50764142bb4106e7 | 46725077006571cec1511f31d314ccd7f5a5eeef | refs/heads/master | 2016-09-05T09:26:26.091623 | 2010-02-01T11:24:41 | 2010-02-01T11:24:41 | 32,189,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,013 | cpp | #pragma once
#define _CRT_SECURE_NO_WARNINGS
// MSDatabaseMethods.cpp
//
// Copyright 2004 DecisionPower, Inc.
//
// Database calls for the microsegment
// Created by Vicki de Mey 4/16/04
#ifndef WINVER
#define WINVER 0x0501
#endif
#include "CMicroSegment.h"
#include "MSDatabase.h"
#include <stdlib.h>
#include <math.h>
#include "DBModel.h"
#include "DBProdAttr.h"
#include "DBProductTree.h"
#include "ProductTree.h"
#include "SegmentWriter.h"
#include "RepurchaseModel.h"
#include "DBProdSize.h"
#include "DBSimLog.h"
#include "Product.h"
#include "Channel.h"
#include "InitialCondition.h"
#include "PopObject.h"
#include "ChoiceModel.h"
// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
void CMicroSegment::write_purchase_info_to_file(void)
{
for(Pcn_iter iter = iProductsAvailable.begin(); iter != iProductsAvailable.end(); iter++)
{
accumlate_data(GetPcn(iter));
}
}
// ------------------------------------------------------------------------------
// Write to Database - writes directly to m_SegData structure directly
// SSN 3/29/2005
// ------------------------------------------------------------------------------
void CMicroSegment::accumlate_data(Pcn pcn)
{
SegmentDataAcc* currData;
if (iSegmentMap.find(pcn) == iSegmentMap.end())
{
iSegmentMap[pcn] = new SegmentDataAcc(iModelInfo->start_date);
}
currData = iSegmentMap[pcn];
currData->AddInfo(this, pcn);
}
void CMicroSegment::DBOutput(MSDatabase* database)
{
for(Pcn_iter iter = iProductsAvailable.begin(); iter != iProductsAvailable.end(); iter++)
{
Pcn pcn = GetPcn(iter);
SegmentDataAcc* currData = iSegmentMap[pcn];
currData->getInfo(database->NewSegData());
currData->reset(Current_Time);
}
}
void CMicroSegment::ReadSegmentAndModel(SegmentRecordset* segment, ModelRecordset* model, bool isNimo)
{
iModelInfo = model;
iSegmentID = segment->m_SegmentID;
iNameString = segment->m_SegmentName;
//NIMO BRANCH
if(isNimo)
{
repurchaseModel->type = kRepurchaseModel_TaskBased_NBDrate;
iShareAwarenessWithSibs = true;
iRejectSibs = true;
iUseACVDistribution = false;
iDisplayUtility = segment->m_display_utility;
}
else
{
repurchaseModel->type = kRepurchaseModel_NBD;
iShareAwarenessWithSibs = false;
iRejectSibs = false;
iUseACVDistribution = true;
iDisplayUtility = 0.0;
}
//Repurchase Model (NIMO and MS)
repurchaseModel->iRepurchase = true;
repurchaseModel->iRepurchaseFrequencyDuration = segment->m_repurchase_period_frequency;
repurchaseModel->iNBDstddev = segment->m_repurchase_frequency_variation;
repurchaseModel->iGammaA = segment->m_gamma_location_parameter_a;
repurchaseModel->iGammaK = segment->m_gamma_shape_parameter_k;
repurchaseModel->iAverageMaxUnits = segment->m_avg_max_units_purch;
//Choice Model
if(segment->m_price_value.CompareNoCase("Relative") == 0)
{
choiceModel->iGCMf8_PriceValueSource = kGCMf8_RelativePrice;
}
else if(segment->m_price_value.CompareNoCase("Base") == 0)
{
choiceModel->iGCMf8_PriceValueSource = kGCMf8_ReferencePrice;
}
else
{
choiceModel->iGCMf8_PriceValueSource = kGCMf8_AbsolutePrice;
}
if(segment->m_persuasion_value_computation.CompareNoCase("Share of Voice") == 0)
{
choiceModel->iGCMf2_PersuasionValComp = kGCMf2_ShareOfVoice;
}
else if(segment->m_persuasion_value_computation.CompareNoCase("Exponential") == 0)
{
choiceModel->iGCMf2_PersuasionValComp = kGCMf2_squareRoot;
}
else if(segment->m_persuasion_value_computation.CompareNoCase("Base 10 Log") == 0)
{
choiceModel->iGCMf2_PersuasionValComp = kGCMf2_base10log;
}
else
{
choiceModel->iGCMf2_PersuasionValComp = kGCMf2_Absolute;
}
choiceModel->iGCM_ErrorTermUserValue = segment->m_units_desired_trigger;
//Choice Math Sensitivities
iPriceSensitivity = segment->m_price_disutility;
iMessageSensitivity = segment->m_persuasion_scaling;
//Loyalties
iChannelLoyalty = segment->m_loyalty;
iBrandLoyalty = segment->m_inertia;
//Message Model
iPersuasionDecayRatePostUse = segment->m_persuasion_decay_rate_post;
iPersuasionDecayRatePreUse = segment->m_persuasion_decay_rate_pre;
iAwarenessDecayRatePostUse = segment->m_awareness_decay_rate_post;
iAwarenessDecayRatePreUse = segment->m_awareness_decay_rate_pre;
iDiversityPercent = segment->m_variability;
iMaxDisplayHits = (int)segment->m_max_display_hits_per_trip;
long segment_size = (segment->m_segment_size*model->pop_size*model->scale_factor)/10000;
// cannot have zero consumers
if (segment_size < 1)
{
segment_size = 1;
}
iPopulation->iGroupSize = segment_size;
}
void CMicroSegment::LoadDataFromDatabase( map<int, Product*> & products,
map<int, Channel*> & channels,
map<int, double> & channel_choice,
vector<pair<int,int>> & tree,
map<int, Attribute*> & attributes,
map<pair<int, int>, double> & product_sizes,
map<pair<int, int>, double> & prerequistes,
map<int, InitialCondition*> & initial_conditions)
{
read_product_attributes(attributes);
read_product_and_channels(products, channels, channel_choice);
read_product_tree(tree);
read_product_size(product_sizes);
read_product_dependencies(prerequistes);
read_initial_share_and_penetration(initial_conditions);
}
void CMicroSegment::read_product_and_channels(map<int, Product*> & products, map<int, Channel*> & channels, map<int, double> & channel_choice)
{
iProducts.clear();
iChannels.clear();
map<int, Product*>::const_iterator p_iter;
map<int, Channel*>::const_iterator c_iter;
map<int, double>::const_iterator cc_iter;
int product_index = 0;
for(p_iter = products.begin(); p_iter != products.end(); ++p_iter)
{
iProducts.push_back(new Product(p_iter->second));
iProducts[product_index]->iProductIndex = product_index;
product_index++;
}
int channel_index = 0;
for(c_iter = channels.begin(); c_iter != channels.end(); ++c_iter)
{
iChannels.push_back(new Channel(c_iter->second));
iChannels[channel_index]->iChannelIndex = channel_index;
channel_index++;
}
pcn_key::NumProducts = iProducts.size();
build_product_channel_list();
for(cc_iter = channel_choice.begin(); cc_iter != channel_choice.end(); ++cc_iter)
{
iChannels[ChanIndex(cc_iter->first)]->iPctChanceChosen = cc_iter->second;
}
compute_cumulative_channel_percents();
}
void CMicroSegment::read_product_tree(vector<pair<ID,ID>> & tree)
{
if(ProductTree::theTree->LeafNodes()->size() == 0)
{
ProductTree::theTree->SetSize(iProducts.size());
for(size_t i = 0; i < tree.size(); ++i)
{
ID parent_id = tree[i].first;
ID child_id = tree[i].second;
Index p_pn = ProdIndex(parent_id);
Index c_pn = ProdIndex(child_id);
ProductTree::theTree->SetParent(p_pn, c_pn);
}
}
iProdTree = ProductTree::theTree;
}
void CMicroSegment::read_product_dependencies(map<pair<int, int>, double> & prerequistes)
{
//First initial the prerequiste array for each product
for(Pn_iter pn_iter = iProducts.begin(); pn_iter != iProducts.end(); ++pn_iter)
{
(*pn_iter)->iPrerequisiteNum = vector<Index>();
(*pn_iter)->iInCompatibleNum = vector<Index>();
}
map<pair<int, int>, double>::const_iterator iter;
int parent;
int child;
for(iter = prerequistes.begin(); iter != prerequistes.end(); ++iter)
{
parent = ProdIndex(iter->first.first);
child = ProdIndex(iter->first.second);
if(iter->second > 0)
{
iProducts[child]->iPrerequisiteNum.push_back(parent);
}
if(iter->second < 0)
{
iProducts[child]->iInCompatibleNum.push_back(parent);
}
}
}
void CMicroSegment::read_product_size(map<pair<int, int>, double> & product_sizes)
{
map<pair<int, int>, double>::const_iterator iter;
for(iter = product_sizes.begin(); iter != product_sizes.end(); ++iter)
{
Pcn pcn = Pcn(ProdIndex(iter->first.first), ChanIndex(iter->first.second));
iProductsAvailable[pcn]->iSize = iter->second;
}
}
void CMicroSegment::read_product_attributes(map<int, Attribute*> & attributes)
{
iAttributes.insert(attributes.begin(), attributes.end());
}
void CMicroSegment::read_initial_share_and_penetration(map<int, InitialCondition*> & initial_conditions)
{
int ID;
for(Pn_iter pn_iter = iProducts.begin(); pn_iter != iProducts.end(); ++pn_iter)
{
ID = (*pn_iter)->iProductID;
if(initial_conditions.find(ID) != initial_conditions.end())
{
(*pn_iter)->iInitialSharePct = initial_conditions[ID]->GetShare();
(*pn_iter)->iInitialPenetrationPct = initial_conditions[ID]->GetPenetration();
(*pn_iter)->iInitialAwareness = initial_conditions[ID]->GetAwareness();
(*pn_iter)->iInitialPersuasion = initial_conditions[ID]->GetPersuasion();
}
}
} | [
"Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c"
]
| [
[
[
1,
301
]
]
]
|
8c073b0e9eb116d1ef5a4e0698d3d13fe7490851 | 563e71cceb33a518f53326838a595c0f23d9b8f3 | /v2/POC/POC/TerrainMng.h | 4308972dfb8bcd2dd402a035ab9ea64bd0402592 | []
| no_license | fabio-miranda/procedural | 3d937037d63dd16cd6d9e68fe17efde0688b5a0a | e2f4b9d34baa1315e258613fb0ea66d1235a63f0 | refs/heads/master | 2021-05-28T18:13:57.833985 | 2009-10-07T21:09:13 | 2009-10-07T21:09:13 | 39,636,279 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 303 | h | #ifndef TerrainMng_H
#define TerrainMng_H
#include "Random.h"
#include "Vector3.h"
#include "Node.h"
#include "GL/glew.h"
#include "GL/glfw.h"
class TerrainMng{
public:
TerrainMng();
void Update(Vector3<float>);
void Render();
private:
Node* m_sceneGraph;
};
#endif | [
"fabiom@01b71de8-32d4-11de-96ab-f16d9912eac9"
]
| [
[
[
1,
25
]
]
]
|
eff35f3b8f8233c6c9aa0f25a32860aa784604e1 | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/HHVClientDemo/HHVClientDemo/Dlg_Playback_Download_Bytime.h | fba89e75e0dfe85d3a3aa360fa9d198865022cd6 | []
| no_license | 080278/dvrmd-filter | 176f4406dbb437fb5e67159b6cdce8c0f48fe0ca | b9461f3bf4a07b4c16e337e9c1d5683193498227 | refs/heads/master | 2016-09-10T21:14:44.669128 | 2011-10-17T09:18:09 | 2011-10-17T09:18:09 | 32,274,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,084 | h | #if !defined(AFX_DLG_PLAYBACK_DOWNLOAD_BYTIME_H__086A5B12_0518_4591_A15C_3CD0E90D1107__INCLUDED_)
#define AFX_DLG_PLAYBACK_DOWNLOAD_BYTIME_H__086A5B12_0518_4591_A15C_3CD0E90D1107__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Dlg_Playback_Download_Bytime.h : header file
#include "TextProgressCtrl.h"
#include "struct_TCPServ.h"
/////////////////////////////////////////////////////////////////////////////
// CDlg_Playback_Download_Bytime dialog
class CDlg_Playback_Download_Bytime : public CDialog
{
// Construction
public:
CDlg_Playback_Download_Bytime(CWnd* pParent = NULL); // standard constructor
DATE_INFO Playback_BeginTime_DateInfo;
TIME_INFO Playback_BeginTime_TimeInfo;
DATE_INFO Playback_EndTime_DateInfo;
TIME_INFO Playback_EndTime_TimeInfo;
LONG m_lPlayback_Bytime_Handle;
// Dialog Data
//{{AFX_DATA(CDlg_Playback_Download_Bytime)
enum { IDD = IDD_DLG_PLAYBACK_BYTIME };
CSliderCtrl m_slider_playback_bytime;
CSliderCtrl m_slider_mute_bytime;
CTextProgressCtrl m_progress_present;
CDateTimeCtrl m_dEndYear_Bytime;
CDateTimeCtrl m_dEndTime_Bytime;
CDateTimeCtrl m_dBeginYear_Bytime;
CDateTimeCtrl m_dBeginTime_Bytime;
CComboBox m_cmb_channel;
CStatic m_sPlayback_Bytime;
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlg_Playback_Download_Bytime)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDlg_Playback_Download_Bytime)
afx_msg void OnBtnDownloadBytime();
virtual BOOL OnInitDialog();
afx_msg void OnBtnPlaybackPlayBytime();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DLG_PLAYBACK_DOWNLOAD_BYTIME_H__086A5B12_0518_4591_A15C_3CD0E90D1107__INCLUDED_)
| [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
]
| [
[
[
1,
66
]
]
]
|
d93f998ffd2450f2f7034b0d6fc31bc9f7230c01 | 913f43ef4d03bd5d6b42b9e31b1048ae54493f59 | /CraterRacer/CraterRacer/Source_Code/Vehicle Files/VehicleAI.cpp | a6916b31a2e79ffe6b9864b1baf7d03e1a88bb19 | []
| no_license | GreenAdept/cpsc585 | bfba6ea333c2857df0822dd7d00768df6a010a73 | c66745e77be4c78e435da1a59ae94ac2a61228cf | refs/heads/master | 2021-01-10T16:42:03.804213 | 2010-04-27T00:13:52 | 2010-04-27T00:13:52 | 48,024,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,197 | cpp | /*
The Vehicle's AI class.
*/
#include "VehicleAI.h"
#include "EntityManager.h"
#include "MessageManager.h"
#include <cmath>
VehicleAI::VehicleAI (bool canModify) {
this->canModify = canModify;
path = 0;
currentLap = 1;
passedWPs = 0;
passedWPsLB;
}
//------------------------------------------------------
// Function: think
// Checks if the vehicle has reached its destination
// waypoint, and updates the destination waypoint and
// lap count.
//------------------------------------------------------
#define WAYPOINT_RADIUS 60
void VehicleAI::think (EntityManager *em, int myList, int myIndex) {
if (state == AI::STOPPED) return;
Vehicle* myEntity = (Vehicle*) (*em)[myList][myIndex];
Vec3 myPos = myEntity->getPosition ();
if (state == AI::WAITING) {
Terrain* terrain = em->getTerrain( 0 );
if (terrain == 0) return;
path = terrain->getTrack();
elapsed = 0.0f;
state = AI::MOVING;
}
//Check if the destination has been reached
if (path->reachedWaypoint (myPos, passedWPsLB-1, WAYPOINT_RADIUS)) {
passedWPsLB--;
while (path->reachedWaypoint (myPos, passedWPsLB-1, WAYPOINT_RADIUS)) {
passedWPsLB--;
}
passedWPs = passedWPsLB;
while (path->reachedWaypoint (myPos, passedWPs+1, WAYPOINT_RADIUS)) {
passedWPs++;
}
}
else if (path->reachedWaypoint (myPos, passedWPs+1, WAYPOINT_RADIUS)) {
elapsed = 0.0f;
passedWPs++;
while (path->reachedWaypoint (myPos, passedWPs+1, WAYPOINT_RADIUS)) {
passedWPs++;
}
passedWPsLB = passedWPs;
while (path->reachedWaypoint (myPos, passedWPsLB-1, WAYPOINT_RADIUS)) {
passedWPsLB--;
}
}
//Modify count of remaining laps, if needed
int newLap = path->findCurrentLap (passedWPs);
if (newLap > path->getNumberOfLaps()) {
state = AI::STOPPED;
//if (m_iPlayerNum >= 0)
Emit (Events::EPlayerFinished, m_iPlayerNum);
return;
}
if (newLap > currentLap) {
currentLap = newLap;
if (m_iPlayerNum >= 0)
Emit (Events::ELapFinished, m_iPlayerNum, newLap);
}
if (myList == PLAYERS) {
Vec3 currentDir = myEntity->getDirection ();
bool wrongway = path->goingWrongWay (myPos, currentDir, passedWPs);
if (wrongway)
Emit( Events::EWrongWay, m_iPlayerNum );
else
Emit( Events::EWrongWayCancel, m_iPlayerNum );
}
}
Vec3 VehicleAI::getLastPassedWaypoint (Vec3 myPos) {
if (path == 0)
return Vec3 (0, 0, 0);
else
return path->getPositionOfWP (myPos, passedWPs);
}
Vec3 VehicleAI::getNextWaypoint (Vec3 myPos) {
if (path == 0)
return Vec3 (0, 0, 0);
else
return path->getPositionOfWP (myPos, passedWPs+1);
}
float VehicleAI::getDistanceToNextWP (Vec3 myPos) {
if (path == 0)
return 0;
else
return path->getDistanceToWP (myPos, passedWPs+1);
}
int VehicleAI::getCurrentLapNumber () {
if (path == 0)
return 1;
else
return path->findCurrentLap (passedWPs);
}
//------------------------------------------------------
// Function: think
// Sets the input for the AI vehicle based on its
// desired destination.
//------------------------------------------------------
void CompVehicleAI::think (EntityManager *em, int myList, int myIndex) {
VehicleAI::think (em, myList, myIndex);
if (state == AI::STOPPED || state == AI::WAITING) return;
Vehicle* myEntity = (Vehicle*) (*em)[myList][myIndex];
Vec3 myPos = myEntity->getPosition();
Input* input = myEntity->getInputObj();
//Find the current direction of travel
Vec3 currentDir = myEntity->getDirection ();
vector<Entity*> obstacles = em->getObstacles();
for (int i=0; i<obstacles.size(); i++) {
Vec3 obstacle = obstacles[i]->getPosition();
if (distSquared (myPos, obstacle) < 400.0f) {
Vec3 dirOfObstacle = obstacle - myPos;
D3DXVec3Normalize (&dirOfObstacle, &dirOfObstacle);
if (avoid (currentDir, dirOfObstacle, input))
return;
}
}
//Find the desired direction of travel and steer there
Vec3 desiredDir = path->getDirectionToWP (myPos, passedWPs+1);
steer (currentDir, desiredDir, input);
}
//------------------------------------------------------
// Function: steer
// Sets the input for the AI vehicle based on the
// difference between its current and desired directions.
//------------------------------------------------------
void CompVehicleAI::steer (Vec3& currentDir, Vec3& desiredDir, Input* input) {
//Find the sine of the angle between the two directions
Vec3 temp;
D3DXVec3Cross (&temp, ¤tDir, &desiredDir);
float cosTheta = D3DXVec3Dot (¤tDir, &desiredDir);
float sinTheta = D3DXVec3Length (&temp);
//Set input based on angle
if (cosTheta >= 0.0f) {
input->setDir (Input::UP, true);
if (sinTheta > 0.2f) {
if (temp.y > 0.0) input->setInput (Input::RIGHT, true);
else input->setInput (Input::LEFT, true);
}
}
else {
input->setDir (Input::DOWN, true);
if (temp.y > 0.0) input->setInput (Input::LEFT, true);
else input->setInput (Input::RIGHT, true);
}
//respawn if 7 seconds have passed since the last waypoint was passed
if (elapsed > 7.0f) {
elapsed = 0.0f;
input->setKey (Input::D_KEY, true);
}
}
//------------------------------------------------------
// Function: avoid
// Sets the input for the AI vehicle to avoid an obstacle
// based on the difference between its current direction
// and the direction of the obstacle. Returns true if the
// vehicle is steering to avoid the obstacle.
//------------------------------------------------------
bool CompVehicleAI::avoid (Vec3& currentDir, Vec3& dirOfObstacle, Input* input) {
//Find the sine of the angle between the two directions
Vec3 temp;
D3DXVec3Cross (&temp, ¤tDir, &dirOfObstacle);
float cosTheta = D3DXVec3Dot (¤tDir, &dirOfObstacle);
//Set input based on angle
if (cosTheta >= 0.866f) {
input->setInput (Input::UP, true);
if (temp.y < 0.0) input->setInput (Input::RIGHT, true);
else input->setInput (Input::LEFT, true);
return true;
}
else
return false;
}
void VehicleAI::incWP() {
if (canModify) {
passedWPs++;
}
} | [
"wshnng@b92cab1e-0213-11df-804c-772d9fe11005",
"tfalders@b92cab1e-0213-11df-804c-772d9fe11005",
"amber.wetherill@b92cab1e-0213-11df-804c-772d9fe11005",
"[email protected]"
]
| [
[
[
1,
4
],
[
8,
8
],
[
170,
170
],
[
177,
177
],
[
187,
187
],
[
205,
205
]
],
[
[
5,
5
],
[
7,
7
],
[
16,
32
],
[
34,
67
],
[
69,
83
],
[
85,
85
],
[
87,
169
],
[
171,
176
],
[
178,
186
],
[
188,
204
],
[
206,
211
]
],
[
[
6,
6
],
[
33,
33
],
[
84,
84
],
[
86,
86
]
],
[
[
9,
15
],
[
68,
68
],
[
212,
218
]
]
]
|
f89333dff857dfbcecebcdafd780cb147ff48c7a | d9d498167237f41a9cf47f4ec2d444a49da4b23b | /zhangxin/example2/SettingMsgDlg.cpp | 0593682e27c75b9e9a54e26d981f931c32e5605c | []
| no_license | wangluyi1982/piggypic | d81cf15a6b58bbb5a9cde3d124333348419c9663 | d173e3acc6c3e57267733fb7b80b1b07cb21fa01 | refs/heads/master | 2021-01-10T20:13:42.615324 | 2010-03-17T13:44:49 | 2010-03-17T13:44:49 | 32,907,995 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,352 | cpp | // SettingMsgDlg.cpp : インプリメンテーション ファイル
//
#include "stdafx.h"
#include "NECTestPattern.h"
#include "SettingMsgDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CSettingMsgDlg ダイアログ
CSettingMsgDlg::CSettingMsgDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSettingMsgDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CSettingMsgDlg)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_DATA_INIT
}
void CSettingMsgDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CSettingMsgDlg)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CSettingMsgDlg, CDialog)
//{{AFX_MSG_MAP(CSettingMsgDlg)
// メモ - ClassWizard はこの位置にマッピング用のマクロを追加または削除します。
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSettingMsgDlg メッセージ ハンドラ
void CSettingMsgDlg::OnCancel(){
}
void CSettingMsgDlg::OnOK(){
}
| [
"zhangxin.sanjin@fa8d6de2-2387-11df-88d9-3f628f631586"
]
| [
[
[
1,
50
]
]
]
|
ecaf26161b61d9b7ccc4ff3610c94f66fd9f580d | 115cdd77595f80aa6870893657f26f6b4e7cdd2b | /src/include/MouseMotionEventHandler.hpp | e5f822fb79236e2df0f566433a7e8e5ad40c7988 | []
| no_license | douglyuckling/peek | 0bc036906bab49fec63944e4c23e3b0c6935d820 | 9d7c3022366290a43830be5f19a47bd406038f3c | refs/heads/master | 2021-01-23T07:21:11.076300 | 2010-07-09T04:48:33 | 2010-07-09T04:48:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | hpp | /**
* @file MouseMotionEventHandler.hpp
*/
#pragma once
#include "Peek_base.hpp"
namespace peek {
/**
* @interface MouseMotionEventHandler
* @brief Handles mouse motion events
*/
class MouseMotionEventHandler {
public:
/** Handles a mouse motion event */
virtual void handleMouseMotionEvent(const SDL_MouseMotionEvent &motionEvent) = 0;
};
} | [
"douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9"
]
| [
[
[
1,
22
]
]
]
|
bb6326a811f60e5be294fc72cdaaf5c7d82a9ed3 | cd07acbe92f87b59260478f62a6f8d7d1e218ba9 | /src/SpermView.h | f202cc286a8925b3d819547b9c4dc51a97de56a7 | []
| no_license | niepp/sperm-x | 3a071783e573d0c4bae67c2a7f0fe9959516060d | e8f578c640347ca186248527acf82262adb5d327 | refs/heads/master | 2021-01-10T06:27:15.004646 | 2011-09-24T03:33:21 | 2011-09-24T03:33:21 | 46,690,957 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 5,194 | h | // SpermView.h : interface of the CSpermView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_SPERMVIEW_H__5E420D3D_4A9A_4202_BE82_1146A85F23AC__INCLUDED_)
#define AFX_SPERMVIEW_H__5E420D3D_4A9A_4202_BE82_1146A85F23AC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "StdAfx.h"
#include <qedit.h>
#include "SpermDoc.h"
#include "LiveDetectDLG.h"
class CSpermView : public CScrollView
{
protected: // create from serialization only
CSpermView();
DECLARE_DYNCREATE(CSpermView)
public:
// BOOL csIsInRect(CPoint c, int r, CPoint p);
// Attributes
public:
static BOOL IsInRect(CPoint c,int r,CPoint p);
CSpermDoc* GetDocument();
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSpermView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual void OnInitialUpdate();
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//}}AFX_VIRTUAL
// Implementation
public:
enum{
VIDEO_PLAY, // 视频播放状态
FRAME_ADJUST_RESULT, // 显示实时调整结果状态
VIDEO_RESULT, // 视频分析结果显示状态
MORPHA_IMAGE, // 形态学图像打开显示状态
MORPHA_RESULT, // 形态学图像结果显示状态
INITIAL // 初始态
}m_eViewShowMode; // 视图区显示模式
CBrush m_brushBackground;// 背景画刷
// 形态学
BOOL m_bAnalyseFinished;
int m_nOpenOpt; // 2 形态学 1 活力分析
int m_nPos; // 形态学,当前选中精子编号
CvvImage m_imgMorphaImg; // 形态学分析图像
// 处理中的序列图
LPBYTE m_lpImage[FRAME_NUM]; // 序列帧数据区指针
LPBITMAPINFOHEADER m_lpBMIH[FRAME_NUM]; // 序列帧信息头的指针
// 轨迹跟踪结果图
LPBYTE m_lpTrackResultBmData; // 轨迹跟踪结果图数据区指针
LPBITMAPINFOHEADER m_lpTrackResultBmInfo; // 轨迹跟踪结果图信息头的指针
// 手工调整图
LPBYTE m_lpAdjustBmData;
LPBITMAPINFOHEADER m_lpAdjustBmInfo;
virtual ~CSpermView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
afx_msg void OnContextMenu(CWnd*, CPoint point);
// Generated message map functions
//protected:
public:
//{{AFX_MSG(CSpermView)
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnImage();
afx_msg void OnPrintTable( ) ;
afx_msg void OnPrintPreview( );
afx_msg void OnPrintSetup();
afx_msg void OnDataOption();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
afx_msg void OnFileOpen();
afx_msg void OnButtonLeftarrow();
afx_msg void OnButtonRightarrow();
afx_msg void OnUpdateButtonLeftarrow(CCmdUI* pCmdUI);
afx_msg void OnUpdateButtonRightarrow(CCmdUI* pCmdUI);
afx_msg void OnDeleteSperm();
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnSpermMorset();
afx_msg void OnSpermNormal();
afx_msg void OnUpdateFileOpenS(CCmdUI* pCmdUI);
afx_msg void OnSpermDel();
afx_msg void OnSpermAddA();
afx_msg void OnSpermAddB();
afx_msg void OnSpermAddC();
afx_msg void OnSpermAddD();
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnMenuAddNormal2DB();
afx_msg void OnMenuAddAbnormal2DB();
// afx_msg void OnMenuDbVerdict();
//}}AFX_MSG
afx_msg LRESULT OnCapFrmFinished(WPARAM wParam,LPARAM lParam);
DECLARE_MESSAGE_MAP()
void AddContrast(int x);
int ChoosePoint(int x);
//控制各项按钮的有效状态
public:
void PreviewResult(int reprottype,CString detectno);
void GuoPing();
void UserShowSperm();
int GetSpermIndex(CPoint pt); // pt为屏幕坐标
void DrawMemResImg(CDC* pDC);
void DrawMemDCImage(CDC *pDC1,const CRect rect);
void DrawImage(CDC* pDC);
static double dist(CPoint p, CPoint q);
void FileOpenMorphaImage();
void FileOpenDiskVideoFile();
// { 2008_8_31
CFile *m_pFile;
BOOL ReadImageFromDisk(int i, CFile *pFile);
BOOL WriteImageToDisk(int i, CFile *pFile);
// } 2008_8_31
int m_nDeviceID;
bool m_bMenuItemFileOpen;
int m_Indx;
CPoint m_pt;
// { 2009_3_31
UINT mMoveShowTimer;
int mFrm;
void markTheNewSperm(const POINT& pt, COLORTYPE ct);
CPoint mClick_pt;
// } 2009_3_31
};
#ifndef _DEBUG // debug version in SpermView.cpp
inline CSpermDoc* CSpermView::GetDocument()
{ return (CSpermDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SPERMVIEW_H__5E420D3D_4A9A_4202_BE82_1146A85F23AC__INCLUDED_)
| [
"harithchen@e030fd90-5f31-5877-223c-63bd88aa7192"
]
| [
[
[
1,
179
]
]
]
|
beebf289cae6d6f444bcd82b0bce09513c3fe189 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientShellDLL/ClientShellShared/DeathFX.h | b7d4bd582fd09660c952306a56cc8a11d28ad7f3 | []
| 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 | 1,695 | h | // ----------------------------------------------------------------------- //
//
// MODULE : DeathFX.h
//
// PURPOSE : Death special fx class - Definition
//
// CREATED : 6/14/98
//
// ----------------------------------------------------------------------- //
#ifndef __DEATH_FX_H__
#define __DEATH_FX_H__
#include "SpecialFX.h"
#include "ContainerCodes.h"
#include "CharacterAlignment.h"
#include "GibFX.h"
struct DEATHCREATESTRUCT : public SFXCREATESTRUCT
{
DEATHCREATESTRUCT();
ModelId eModelId;
uint8 nDeathType;
LTVector vPos;
LTVector vDir;
};
inline DEATHCREATESTRUCT::DEATHCREATESTRUCT()
{
eModelId = eModelIdInvalid;
nDeathType = 0;
vPos.Init();
vDir.Init();
}
class CDeathFX : public CSpecialFX
{
public :
CDeathFX() : CSpecialFX()
{
m_eCode = CC_NO_CONTAINER;
m_nDeathType = 0;
m_eModelId = eModelIdInvalid;
VEC_INIT(m_vPos);
VEC_INIT(m_vDir);
}
virtual LTBOOL Init(SFXCREATESTRUCT* psfxCreateStruct);
virtual LTBOOL CreateObject(ILTClient* pClientDE);
virtual LTBOOL Update() { return LTFALSE; }
virtual uint32 GetSFXID() { return SFX_DEATH_ID; }
protected :
ContainerCode m_eCode; // Container effect is in
LTVector m_vPos; // Effect position
LTVector m_vDir; // Direction damage came from
uint8 m_nDeathType; // Type of death
ModelId m_eModelId; // Model
void CreateDeathFX();
void CreateVehicleDeathFX();
void CreateHumanDeathFX();
void SetupGibTypes(GIBCREATESTRUCT & gib);
};
#endif // __DEATH_FX_H__ | [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
8ae3833fe29a6310c15942851aa73cbb71cab40e | cfa667b1f83649600e78ea53363ee71dfb684d81 | /code/render/terrain/terrainrenderer.cc | ac93896eeff11223df6cb46a5034a5fd14e3f75f | []
| no_license | zhouxh1023/nebuladevice3 | c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f | 3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241 | refs/heads/master | 2021-01-23T08:56:15.823698 | 2011-08-26T02:22:25 | 2011-08-26T02:22:25 | 32,018,644 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cc | //------------------------------------------------------------------------------
// terrainrenderer.cc
// (C) 2011 xiongyouyi
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "terrain/terrainrenderer.h"
namespace Terrain
{
__ImplementClass(Terrain::TerrainRenderer, 'TERR', Core::RefCounted);
__ImplementSingleton(Terrain::TerrainRenderer);
//------------------------------------------------------------------------------
/**
*/
TerrainRenderer::TerrainRenderer()
{
__ConstructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
TerrainRenderer::~TerrainRenderer()
{
__DestructSingleton;
}
} // namespace Terrain | [
"[email protected]"
]
| [
[
[
1,
31
]
]
]
|
4867c30e04ee1a7090bdb077443b285c362841ab | 6fbf3695707248bfb00e3f8c4a0f9adf5d8a3d4c | /java/jniutil/include/jvm/virtual_machine.hpp | 2482ef2da169dedc6496d8f71e1844f59f28cd00 | []
| no_license | ochafik/cppjvm | c554a2f224178bc3280f03919aff9287bd912024 | e1feb48eee3396d3a5ecb539de467c0a8643cba0 | refs/heads/master | 2020-12-25T16:02:38.582622 | 2011-11-17T00:11:35 | 2011-11-17T00:11:35 | 2,790,123 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,094 | hpp | #ifndef JVM_VIRTUAL_MACHINE_INCLUDED
#define JVM_VIRTUAL_MACHINE_INCLUDED
#include <stdexcept>
#include <jni.h>
namespace jvm
{
class virtual_machine
{
JavaVM *m_jvm;
public:
virtual_machine()
: m_jvm(0) {}
virtual_machine(const std::string &classPath)
: m_jvm(0) { create(classPath); }
~virtual_machine()
{ destroy(); }
void create(const std::string &classPath);
void destroy();
JNIEnv *env(JNIEnv *e = 0) const;
jstring string(const std::string &v, JNIEnv *e = 0) const;
jstring string(const std::wstring &v, JNIEnv *e = 0) const;
std::wstring wstring(jstring v, JNIEnv *e = 0) const;
std::string string(jstring v, JNIEnv *e = 0) const;
void check_exception(JNIEnv *e = 0) const;
void throw_exception(const std::string &msg, JNIEnv *e = 0) const;
void throw_exception(const std::wstring &msg, JNIEnv *e = 0) const;
};
virtual_machine &global_vm();
void create_global_vm(const std::string &classPath);
virtual_machine *swap_global_vm(virtual_machine *vm);
bool global_vm_available();
}
#endif
| [
"danielearwicker@ubuntu.(none)"
]
| [
[
[
1,
44
]
]
]
|
bf1da980d39e7bb172ce49ab8d58a71c767fc60b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/tools/inspect/long_name_check.hpp | ffa4cb97520588fb9dc18b948afd753229a1ffc5 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,486 | hpp | // long_name_check header --------------------------------------------------//
// (main class renamed to: file_name_check) - gps
// Copyright Beman Dawes 2002.
// Copyright Gennaro Prota 2006.
//
// 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_FILE_NAME_CHECK_HPP
#define BOOST_FILE_NAME_CHECK_HPP
#include "inspector.hpp"
namespace boost
{
namespace inspect
{
class file_name_check : public inspector
{
long m_name_errors;
// ISO 9660 Level 3
//
struct iso_9660_limits
{
enum { max_directory_depth = 8 };
enum { max_dirname_length = 31 };
enum { max_filename_length = 31 }; // > level 2!
static const char name[];
};
public:
typedef iso_9660_limits limits;
file_name_check();
virtual ~file_name_check();
virtual const char * name() const { return "*N*"; }
virtual const char * desc() const { return "file/directory names issues"; }
virtual void inspect(
const string & library_name,
const path & full_path );
virtual void inspect(
const string &, // "filesystem"
const path &, // "c:/foo/boost/filesystem/path.hpp"
const string &)
{ /* empty */ }
};
}
}
#endif // BOOST_FILE_NAME_CHECK_HPP
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
61
]
]
]
|
45a1aade561948147bf14522d37412427088c410 | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /plugins/gs/zerogs/opengl/rasterfont.cpp | 787ee47b5f238be84101d4aa31cdd7cb4e6f1db2 | []
| no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,274 | cpp |
#ifdef _WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
#include <string.h>
#include "rasterfont.h"
// globals
GLubyte rasters[][13] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36},
{0x00, 0x00, 0x00, 0x66, 0x66, 0xff, 0x66, 0x66, 0xff, 0x66, 0x66, 0x00, 0x00},
{0x00, 0x00, 0x18, 0x7e, 0xff, 0x1b, 0x1f, 0x7e, 0xf8, 0xd8, 0xff, 0x7e, 0x18},
{0x00, 0x00, 0x0e, 0x1b, 0xdb, 0x6e, 0x30, 0x18, 0x0c, 0x76, 0xdb, 0xd8, 0x70},
{0x00, 0x00, 0x7f, 0xc6, 0xcf, 0xd8, 0x70, 0x70, 0xd8, 0xcc, 0xcc, 0x6c, 0x38},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x1c, 0x0c, 0x0e},
{0x00, 0x00, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0c},
{0x00, 0x00, 0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x18, 0x30},
{0x00, 0x00, 0x00, 0x00, 0x99, 0x5a, 0x3c, 0xff, 0x3c, 0x5a, 0x99, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0xff, 0xff, 0x18, 0x18, 0x18, 0x00, 0x00},
{0x00, 0x00, 0x30, 0x18, 0x1c, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x38, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x60, 0x60, 0x30, 0x30, 0x18, 0x18, 0x0c, 0x0c, 0x06, 0x06, 0x03, 0x03},
{0x00, 0x00, 0x3c, 0x66, 0xc3, 0xe3, 0xf3, 0xdb, 0xcf, 0xc7, 0xc3, 0x66, 0x3c},
{0x00, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x38, 0x18},
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x03, 0xe7, 0x7e},
{0x00, 0x00, 0x7e, 0xe7, 0x03, 0x03, 0x07, 0x7e, 0x07, 0x03, 0x03, 0xe7, 0x7e},
{0x00, 0x00, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0xff, 0xcc, 0x6c, 0x3c, 0x1c, 0x0c},
{0x00, 0x00, 0x7e, 0xe7, 0x03, 0x03, 0x07, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0xff},
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc7, 0xfe, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e},
{0x00, 0x00, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x06, 0x03, 0x03, 0x03, 0xff},
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xe7, 0x7e, 0xe7, 0xc3, 0xc3, 0xe7, 0x7e},
{0x00, 0x00, 0x7e, 0xe7, 0x03, 0x03, 0x03, 0x7f, 0xe7, 0xc3, 0xc3, 0xe7, 0x7e},
{0x00, 0x00, 0x00, 0x38, 0x38, 0x00, 0x00, 0x38, 0x38, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x30, 0x18, 0x1c, 0x1c, 0x00, 0x00, 0x1c, 0x1c, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06},
{0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x03, 0x06, 0x0c, 0x18, 0x30, 0x60},
{0x00, 0x00, 0x18, 0x00, 0x00, 0x18, 0x18, 0x0c, 0x06, 0x03, 0xc3, 0xc3, 0x7e},
{0x00, 0x00, 0x3f, 0x60, 0xcf, 0xdb, 0xd3, 0xdd, 0xc3, 0x7e, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0x66, 0x3c, 0x18},
{0x00, 0x00, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe},
{0x00, 0x00, 0x7e, 0xe7, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e},
{0x00, 0x00, 0xfc, 0xce, 0xc7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc7, 0xce, 0xfc},
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xc0, 0xff},
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfc, 0xc0, 0xc0, 0xc0, 0xff},
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xcf, 0xc0, 0xc0, 0xc0, 0xc0, 0xe7, 0x7e},
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xff, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3},
{0x00, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7e},
{0x00, 0x00, 0x7c, 0xee, 0xc6, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06},
{0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xe0, 0xf0, 0xd8, 0xcc, 0xc6, 0xc3},
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0},
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xdb, 0xff, 0xff, 0xe7, 0xc3},
{0x00, 0x00, 0xc7, 0xc7, 0xcf, 0xcf, 0xdf, 0xdb, 0xfb, 0xf3, 0xf3, 0xe3, 0xe3},
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xe7, 0x7e},
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe},
{0x00, 0x00, 0x3f, 0x6e, 0xdf, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0x66, 0x3c},
{0x00, 0x00, 0xc3, 0xc6, 0xcc, 0xd8, 0xf0, 0xfe, 0xc7, 0xc3, 0xc3, 0xc7, 0xfe},
{0x00, 0x00, 0x7e, 0xe7, 0x03, 0x03, 0x07, 0x7e, 0xe0, 0xc0, 0xc0, 0xe7, 0x7e},
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xff},
{0x00, 0x00, 0x7e, 0xe7, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3},
{0x00, 0x00, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3},
{0x00, 0x00, 0xc3, 0xe7, 0xff, 0xff, 0xdb, 0xdb, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3},
{0x00, 0x00, 0xc3, 0x66, 0x66, 0x3c, 0x3c, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3},
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3},
{0x00, 0x00, 0xff, 0xc0, 0xc0, 0x60, 0x30, 0x7e, 0x0c, 0x06, 0x03, 0x03, 0xff},
{0x00, 0x00, 0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c},
{0x00, 0x03, 0x03, 0x06, 0x06, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x60, 0x60},
{0x00, 0x00, 0x3c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3c},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc3, 0x66, 0x3c, 0x18},
{0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x38, 0x30, 0x70},
{0x00, 0x00, 0x7f, 0xc3, 0xc3, 0x7f, 0x03, 0xc3, 0x7e, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xfe, 0xc3, 0xc3, 0xc3, 0xc3, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0},
{0x00, 0x00, 0x7e, 0xc3, 0xc0, 0xc0, 0xc0, 0xc3, 0x7e, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x7f, 0xc3, 0xc3, 0xc3, 0xc3, 0x7f, 0x03, 0x03, 0x03, 0x03, 0x03},
{0x00, 0x00, 0x7f, 0xc0, 0xc0, 0xfe, 0xc3, 0xc3, 0x7e, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x30, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x33, 0x1e},
{0x7e, 0xc3, 0x03, 0x03, 0x7f, 0xc3, 0xc3, 0xc3, 0x7e, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xc3, 0xfe, 0xc0, 0xc0, 0xc0, 0xc0},
{0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x18, 0x00},
{0x38, 0x6c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x00, 0x00, 0x0c, 0x00},
{0x00, 0x00, 0xc6, 0xcc, 0xf8, 0xf0, 0xd8, 0xcc, 0xc6, 0xc0, 0xc0, 0xc0, 0xc0},
{0x00, 0x00, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78},
{0x00, 0x00, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xdb, 0xfe, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xfc, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00},
{0xc0, 0xc0, 0xc0, 0xfe, 0xc3, 0xc3, 0xc3, 0xc3, 0xfe, 0x00, 0x00, 0x00, 0x00},
{0x03, 0x03, 0x03, 0x7f, 0xc3, 0xc3, 0xc3, 0xc3, 0x7f, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xe0, 0xfe, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xfe, 0x03, 0x03, 0x7e, 0xc0, 0xc0, 0x7f, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x1c, 0x36, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x30, 0x00},
{0x00, 0x00, 0x7e, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x18, 0x3c, 0x3c, 0x66, 0x66, 0xc3, 0xc3, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xc3, 0xe7, 0xff, 0xdb, 0xc3, 0xc3, 0xc3, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xc3, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0xc3, 0x00, 0x00, 0x00, 0x00},
{0xc0, 0x60, 0x60, 0x30, 0x18, 0x3c, 0x66, 0x66, 0xc3, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xff, 0x60, 0x30, 0x18, 0x0c, 0x06, 0xff, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x0f, 0x18, 0x18, 0x18, 0x38, 0xf0, 0x38, 0x18, 0x18, 0x18, 0x0f},
{0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18},
{0x00, 0x00, 0xf0, 0x18, 0x18, 0x18, 0x1c, 0x0f, 0x1c, 0x18, 0x18, 0x18, 0xf0},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x8f, 0xf1, 0x60, 0x00, 0x00, 0x00}
};
RasterFont::RasterFont()
{
// set GL modes
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// create the raster font
fontOffset = glGenLists (128);
for (int i = 32; i < 127; i++) {
glNewList(i+fontOffset, GL_COMPILE);
glBitmap(8, 13, 0.0f, 2.0f, 10.0f, 0.0f, rasters[i-32]);
glEndList();
}
}
RasterFont::~RasterFont()
{
glDeleteLists(fontOffset, 128);
}
void RasterFont::printString(const char *s, double x, double y, double z)
{
// go to the right spot
glRasterPos3d(x, y, z);
glPushAttrib (GL_LIST_BIT);
glListBase(fontOffset);
glCallLists(strlen(s), GL_UNSIGNED_BYTE, (GLubyte *) s);
glPopAttrib ();
}
void RasterFont::printCenteredString(const char *s, double y, int screen_width, double z)
{
int length = strlen(s);
int x = int(screen_width/2.0 - (length/2.0)*char_width);
printString(s, x, y, z);
}
| [
"zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84"
]
| [
[
[
1,
147
]
]
]
|
b98d625290b0a85ac43b42263b09c590ed9886de | df5277b77ad258cc5d3da348b5986294b055a2be | /Spaceships/IWeapon.h | db1dfa0ffde80b3dd8c17e512c69468727f635aa | []
| no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | h | #pragma once
class IWeapon
{
public:
virtual void Fire(const float x, const float y, const float rotation, Controller* controller) = 0;
virtual void Update() = 0;
virtual void SetFireDuration(const int duration) = 0;
//virtual void CeaseFire() = 0;
;
};
| [
"ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
]
| [
[
[
1,
14
]
]
]
|
2e513e2287e5ef361634fc5a9e021de9d6d9d69e | 918c8a14d31946cef59d68420d0f4a8ed4752001 | /waveletshadow/inc/CWavelet.h | df60a19b566df5725815921c24ed48b4bfdec5af | []
| no_license | rroc/ibrproject | a67b2565402c1eed0c14363633a52c0a81974c0b | 69dbaea6e2de7c00e82d9d08fab20341ba21fac5 | refs/heads/master | 2021-01-01T16:06:46.943270 | 2009-04-03T20:14:15 | 2009-04-03T20:14:15 | 34,713,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,765 | h | #pragma once
#include "basic.h"
#include "THashtable.h"
#include "CMatrix.h"
#include "CMatrixNoColors.h"
class CWavelet
{
public:
CWavelet();
CWavelet( CMatrixNoColors* aMatrix ,int aRows, int aCols);
CWavelet( CMatrix* aMatrix ,int aRows, int aCols);
~CWavelet();
void nonStandardDeconstruction();
void nonStandardReconstruction();
void standardDeconstruction();
void standardReconstruction();
void print();
//void operator /(float aValue);
//void operator *(float aValue);
//non-standard steps- with/without colors
CMatrix* nonStandardDeconstructionStep(CMatrix *aMatrix);
CMatrix* nonStandardReconstructionStep(CMatrix *aMatrix);
CMatrixNoColors* nonStandardDeconstructionStep(CMatrixNoColors *aMatrix);
CMatrixNoColors* nonStandardReconstructionStep(CMatrixNoColors *aMatrix);
//standard steps- with/without colors
/*CMatrix* standardDeconstructionStep(CMatrix *aMatrix);
CMatrix* standardReconstructionStep(CMatrix *aMatrix);
CMatrixNoColors* standardDeconstructionStep(CMatrixNoColors *aMatrix);
CMatrixNoColors* standardReconstructionStep(CMatrixNoColors *aMatrix);*/
float* returnFloat();
float* returnScaledFloat();
private:
float ComputeParentSum( CWavelet aF, TSquare aS);
void ComputeChildrenSums( CWavelet aG, CWavelet aH );
float Product( CWavelet aG, CWavelet aH, TSquare aS, int aM);
float F(int aM, int aL, int aX, int aY );
int sign( int aM, int aX, int aY );
public:
CMatrix *iWavelet;
CMatrixNoColors *iWaveletNoColors;
private:
int iRows;
int iCols;
TSquareHashTable iParentSum;
TSquareHashTable iChildSum;
public:
bool withColors;
bool decomposed;
bool recomposed;
};
| [
"onnepoika@5699bb8f-202d-0410-a568-af645a74364e",
"natha.yamuna.ramanuja.parampara@5699bb8f-202d-0410-a568-af645a74364e"
]
| [
[
[
1,
4
],
[
7,
10
],
[
14,
14
],
[
16,
16
],
[
43,
43
],
[
45,
52
],
[
60,
62
],
[
67,
68
]
],
[
[
5,
6
],
[
11,
13
],
[
15,
15
],
[
17,
42
],
[
44,
44
],
[
53,
59
],
[
63,
66
]
]
]
|
0d5f0c42cc9b864a49ebc12012dd63f8385e68a9 | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /SendMail/凸包.cpp | f0702d3b4948afca34f196782b4e368a577de3a2 | []
| 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 | 3,360 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct CPoint
{
double x, y;
}Point;
const int MAXSIZE = 10000;
const double EPS = 1E-6;
int stack[MAXSIZE]; //数组模拟堆栈,存放凸包的逆序顶点
int top; //凸包顶点数p[stack[0]...stack[top]]
Point p[MAXSIZE];
void GrahamScan(const int &n); //Graham扫描法求凸包
double Dist(const Point &arg1, const Point &arg2); //两点距离
double Length(const int &n); //多边形周长
double Area(const int &n); //多边形面积
void Swap(const int &i, const int &j); //交换两个点
double Multi(const Point &p0, const Point &p1, const Point &p2); //叉积运算
int cmp(const void *arg1, const void *arg2); //自定义排序:按照极角
int main(void)
{
int n;
// freopen("Input.txt", "r", stdin);
while( scanf("%d", &n), n )
{
int i;
for( i=0; i < n; ++i )
{
scanf("%lf %lf", &p[i].x, &p[i].y);
}
if( n == 1 )
{
printf("周长: 0.00\t面积: 0.00\n");
}
else if( n == 2 )
{
printf("周长: %.2lf\t面积: 0.00\n", Dist(p[0], p[1]));
}
else
{
GrahamScan(n);
for( int k=0; k <= top; ++k )
{
printf("%lf %lf\n", p[stack[k]].x, p[stack[k]].y);
}
printf("周长: %.2lf\t面积: %.2lf\n", Length(top+1), Area(top+1));
}
}
return 0;
}
double Length(const int &n)
{
double sum = Dist( p[stack[n-1]], p[stack[0]] );
for( int i = 0; i < n-1; ++i )
{
sum += Dist( p[stack[i]], p[stack[i+1]] );
}
return sum;
}
double Area(const int &n)
{
double area = 0;
for( int i=0; i < n-1; ++i )
{
area += (p[stack[i]].x*p[stack[i+1]].y) - (p[stack[i+1]].x*p[stack[i]].y);
}
area = fabs(area) / 2;
return area;
}
double Dist(const Point &arg1, const Point &arg2)
{
return sqrt( (arg1.x - arg2.x)*(arg1.x - arg2.x) + (arg1.y - arg2.y)*(arg1.y - arg2.y) );
}
void Swap(const int &i, const int &j)
{
Point temp = p[i];
p[i] = p[j];
p[j] = temp;
}
//通过矢量叉积求极角关系(p0p1)(p0p2)
//P*Q > 0,P在Q的顺时针方向... ...
double Multi(const Point &p0, const Point &p1, const Point &p2)
{
return (p1.x-p0.x)*(p2.y-p0.y) - (p2.x-p0.x)*(p1.y-p0.y);
}
int cmp(const void *arg1, const void *arg2)
{
Point a = *(Point*)arg1;
Point b = *(Point*)arg2;
double k = Multi(p[0], a, b);
if( k < -EPS ) return 1;
else if( fabs(k) < EPS && (Dist(a, p[0]) - Dist(b, p[0])) > EPS ) return 1;
else return -1;
}
void GrahamScan(const int &n)
{
int i, u = 0;
for( i = 1; i < n; ++i )
{
//找到最左下的顶点, 令其为p[0]
if( ( p[i].y < p[u].y ) || ( p[i].y == p[u].y && p[i].x < p[u].x ) )
u = i;
}
i = 0;
Swap(i, u); //只交换一次
//将点按照相对p[0]的极角从小到大排序, 用qsort
qsort( p+1, n-1, sizeof(p[0]), cmp );
//将每一个点逐一检验, 是凸包点放入栈中, 不是则弹出栈。
//注意: 排序后, p[0]和p[1]一定是凸包的顶点
stack[0] = 0; stack[1] = 1; stack[2] = 2;
top = 2;
for( int j = 3; j < n; ++j )
{
while( Multi( p[j], p[stack[top]], p[stack[top-1]] ) > 0 )
{
--top;
if( top == 0 ) break;
}
stack[++top] = j;
}
}
//本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Fandywang_jlu/archive/2008/03/20/2201350.aspx | [
"[email protected]"
]
| [
[
[
1,
136
]
]
]
|
eccf4db0e297c6978ab1efb90a53dce5066ab0b4 | 90aa2eebb1ab60a2ac2be93215a988e3c51321d7 | /castor/branches/boost/libs/castor/test/test_reduce.cpp | c86c8104b15316ed408e8174b522da3400eef206 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | roshannaik/castor | b9f4ea138a041fe8bccf2d8fc0dceeb13bcca5a6 | e86e2bf893719bf3164f9da9590217c107cbd913 | refs/heads/master | 2021-04-18T19:24:38.612073 | 2010-08-18T05:10:39 | 2010-08-18T05:10:39 | 126,150,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include <boost/castor.h>
#include <boost/test/minimal.hpp>
using namespace castor;
int test_main(int, char * [])
{
{ // multiple values in input
lref<int> j;
relation r = range(j, 1, 10) >>= reduce(j, std::multiplies<int>());
BOOST_CHECK(r() && j.defined());
BOOST_CHECK(*j == 3628800);
BOOST_CHECK(!r());
BOOST_CHECK(!j.defined());
}
{ // single input
lref<int> j;
relation r = range(j, 1, 1) >>= reduce(j, std::multiplies<int>());
BOOST_CHECK(r() && j.defined());
BOOST_CHECK(*j == 1);
BOOST_CHECK(!r());
BOOST_CHECK(!j.defined());
}
{ // no inputs
lref<int> j;
relation r = range(j, 2, 1) >>= reduce(j, std::plus<int>());
BOOST_CHECK(!r() || !j.defined());
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
d1acbd0db725148975fb1afcf4063adccc1c8ed7 | 221e3e713891c951e674605eddd656f3a4ce34df | /core/OUE/Core.cpp | 0169fac633de4be633ea564e7d5f205c4b0c6b02 | [
"MIT"
]
| permissive | zacx-z/oneu-engine | da083f817e625c9e84691df38349eab41d356b76 | d47a5522c55089a1e6d7109cebf1c9dbb6860b7d | refs/heads/master | 2021-05-28T12:39:03.782147 | 2011-10-18T12:33:45 | 2011-10-18T12:33:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | cpp | /*
This source file is part of OneU Engine.
Copyright (c) 2011 Ladace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "Matrix.h"
namespace OneU
{
ONEU_API const matrix& GetIdentityMatrix(){
static matrix a(matrix::IDENTITY);
return a;
}
} | [
"[email protected]@d30a3831-f586-b1a3-add9-2db6dc386f9c"
]
| [
[
[
1,
30
]
]
]
|
ef379d9aaff08adabeeac9f5a3d84d5155197e8a | acd999f7078cf4fb5545b6fcbd2b6e514af6e29b | /tests/tester/tester.cpp | 053d751a490ebac3b9aa3ffb9483783b410aee2b | []
| no_license | joshuaeckroth/CSE202 | 5239c8bdd9ad48289d6a3bea459158696af095f4 | 57ac830f9ca3ca3d8b737c7da93e2aa1918284c9 | refs/heads/master | 2016-09-01T23:29:54.227011 | 2010-09-10T12:59:43 | 2010-09-10T12:59:43 | 448,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,985 | cpp | #include <iostream>
#include <fstream>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
using namespace std;
#define READ 0
#define WRITE 1
bool run_test(char *program, string test, string input, string output);
void expand_string_array(string *&str_array, int oldsize, int newsize);
pid_t mypopen(const char *program, int *infp, int *outfp);
int main(int argc, char *argv[])
{
if(argc != 3)
{
cerr << "*** Usage: " << argv[0] << " <test file> <program file>" << endl;
return EXIT_FAILURE;
}
char *test_file = argv[1];
char *program_file = argv[2];
ifstream test_file_stream(test_file, ios::in);
if(!test_file_stream.good())
{
cerr << "*** Test file " << test_file << " cannot be opened." << endl;
cerr << "*** Unable to proceed." << endl;
return EXIT_FAILURE;
}
int test_count = 0;
int successful_tests = 0;
string *tests = NULL;
string *inputs = NULL;
string *outputs = NULL;
string *tmp = NULL;
string line;
bool inside_input = false;
bool inside_output = false;
while(!test_file_stream.eof())
{
getline(test_file_stream, line);
if(line.substr(0, 3) == "===")
{
inside_input = false;
inside_output = false;
expand_string_array(tests, test_count, test_count + 1);
expand_string_array(inputs, test_count, test_count + 1);
expand_string_array(outputs, test_count, test_count + 1);
test_count++;
tests[test_count - 1] = line.substr(4);
}
else if(line.substr(0, 9) == "--- Input")
{
inside_input = true;
inside_output = false;
}
else if(line.substr(0, 10) == "--- Output")
{
inside_input = false;
inside_output = true;
}
else
{
if(inside_input)
{
inputs[test_count - 1] += line;
inputs[test_count - 1] += "\n";
}
else if(inside_output)
{
outputs[test_count - 1] += line;
outputs[test_count - 1] += "\n";
}
}
}
cout << endl;
cout << "** Running " << test_count << " tests..." << endl << endl;
for(int i = 0; i < test_count; i++)
{
if(run_test(program_file, tests[i], inputs[i], outputs[i]))
successful_tests++;
}
double successful_percent = 100 * static_cast<double>(successful_tests) / static_cast<double>(test_count);
cout << endl;
cout << "** " << successful_tests << " of " << test_count << " (";
cout.setf(ios::fixed, ios::floatfield);
cout.precision(0);
cout << successful_percent;
cout << "%) successful." << endl;
return EXIT_SUCCESS;
}
bool run_test(char *program, string test, string input, string output)
{
int infp, outfp, status, pos, substr_length, read_length;
pid_t pid, w;
const int bufsize = 100;
char buf[bufsize];
string program_output, program_output_stripped, output_stripped;
if((pid = mypopen(program, &infp, &outfp)) <= 0)
{
cerr << "*** Error executing " << program << endl;
return false;
}
pos = 0;
while(pos < input.size())
{
if((input.size() - pos) > bufsize)
substr_length = bufsize;
else
substr_length = input.size() - pos;
memset(buf, 0x0, bufsize);
strncpy(buf, input.substr(pos, substr_length).c_str(), substr_length);
pos += substr_length;
write(infp, buf, substr_length);
}
close(infp);
waitpid(pid, &w, 0);
if(w == -1)
{
cerr << "*** Error waiting for program to finish." << endl;
return false;
}
fcntl(outfp, F_SETFL, O_NONBLOCK);
while((read_length = read(outfp, buf, bufsize)) > 0)
{
buf[read_length] = '\0';
program_output += buf;
}
// strip newlines, spaces, and tabs in both program_output and output
program_output_stripped = program_output;
output_stripped = output;
while((pos = program_output_stripped.find(' ')) != -1)
program_output_stripped.erase(pos, 1);
while((pos = program_output_stripped.find('\t')) != -1)
program_output_stripped.erase(pos, 1);
while((pos = program_output_stripped.find('\n')) != -1)
program_output_stripped.erase(pos, 1);
while((pos = program_output_stripped.find('\r')) != -1)
program_output_stripped.erase(pos, 1);
while((pos = output_stripped.find(' ')) != -1)
output_stripped.erase(pos, 1);
while((pos = output_stripped.find('\t')) != -1)
output_stripped.erase(pos, 1);
while((pos = output_stripped.find('\n')) != -1)
output_stripped.erase(pos, 1);
while((pos = output_stripped.find('\r')) != -1)
output_stripped.erase(pos, 1);
if(program_output_stripped == output_stripped)
{
cout << "** Success! " << test << endl;
return true;
}
else
{
cout << endl;
cout << "** Failed " << test << endl;
cout << endl;
cout << "--> Desired output (ignore spaces):" << endl << output << endl;
cout << "--> Program output (ignore spaces):" << endl << program_output << endl;
cout << endl << endl;
return false;
}
}
// from: http://www.unix.com/unix-dummies-questions-answers/63311-how-write-stdin-another-program-program-stdin-program-b.html
pid_t mypopen(const char *program, int *infp, int *outfp)
{
int p_to_program[2], p_from_program[2];
pid_t pid;
if(pipe(p_to_program) != 0 || pipe(p_from_program) != 0)
return -1;
pid = fork();
if(pid < 0)
return pid;
else if(pid == 0)
{
close(p_to_program[WRITE]);
dup2(p_to_program[READ], READ);
close(p_from_program[READ]);
dup2(p_from_program[WRITE], WRITE);
execl(program, program, NULL);
cerr << "*** Error executing " << program << endl;
exit(EXIT_FAILURE);
}
if(infp == NULL)
close(p_to_program[WRITE]);
else
*infp = p_to_program[WRITE];
if(outfp == NULL)
close(p_from_program[READ]);
else
*outfp = p_from_program[READ];
return pid;
}
void expand_string_array(string *&str_array, int oldsize, int newsize)
{
string *tmp = str_array;
str_array = new string[newsize];
for(int i = 0; i < oldsize; i++)
{
str_array[i] = tmp[i];
}
delete [] tmp;
}
| [
"[email protected]"
]
| [
[
[
1,
235
]
]
]
|
935bd80dc956e70e8fc75d20fbcf9b7431e10bce | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/CTaiKlineDlgEditScreenStock.cpp | 7fbd1b133e3afae8b32ad99a84bc6e85657631f7 | []
| no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | GB18030 | C++ | false | false | 39,195 | cpp | // TechDlgEditScreenStock.cpp : implementation file
//
#include "stdafx.h"
#include "CTaiShanApp.h"
#include "CTaiKlineDlgEditScreenStock.h"
#include "CTaiShanDoc.h"
#include "MainFrm.h"
#include "CFormularCompute.h"
#include "DIAEDITZBGSHS.h"
#include "CFormularContent.h"
#include "CTaiScreenParent.h"
#include "CTaiKlineDlgCanUsedPeriod.h"
#include "CTaiKlineDlgParamExplain.h"
#include "DIALOGXZZB.h"
#include "DIAGSGLMM.h"
#include "CTaiKlineIndicatorsManage.h"
#include "CTaiScreenParent.h"
#include "CTaiKlineDlgChangeIndexParam.h"
#include "KEYBRODEANGEL.h"
#include "DIALOGGSSM.h"
#include "CwdSelectFormu.h"
#include "CwdShowFormu.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTaiKlineDlgEditScreenStock dialog
bool g_bInitDlgEdit = false;
/////////////////////////////////////////////////////////////////////////////
// CTaiKlineDlgEditScreenStock message handlers
CTaiKlineDlgEditScreenStock::CTaiKlineDlgEditScreenStock(int nID,CWnd* pParent)
: CDialog(nID, pParent)
{
m_bShowFromMouse = false;
m_nKlineType = -1;
m_nTabPre = 0;
m_maxChars = 30;
jishunow = NULL;
m_bInit = false;//CFloatEdit
//{{AFX_DATA_INIT(CTaiKlineDlgEditScreenStock)
m_checkmm = FALSE;
m_checkOften = FALSE;
m_explainbrief = _T("");
m_myhelp = _T("");
m_name = _T("");
m_password = _T("");
m_xline = _T("");
m_sTestInfo = _T("");
m_sKindTime = _T("中期");
m_sKindFormu = _T("");
//}}AFX_DATA_INIT
for(int i=0;i<8;i++)
{
for(int j=0;j<4;j++)
m_editParam[i][j] = _T("");
}
m_strPeriodPre ="日线";
memset(m_nPeriodsUsed,1,16);
m_strParamExplain = "";
m_nID[0][0] = IDC_EDIT11;
m_nID[0][1] = IDC_EDIT12;
m_nID[0][2] = IDC_EDIT13;
m_nID[0][3] = IDC_EDIT14;
m_nID[1][0] = IDC_EDIT21;
m_nID[1][1] = IDC_EDIT22;
m_nID[1][2] = IDC_EDIT23;
m_nID[1][3] = IDC_EDIT24;
m_nID[2][0] = IDC_EDIT31;
m_nID[2][1] = IDC_EDIT32;
m_nID[2][2] = IDC_EDIT33;
m_nID[2][3] = IDC_EDIT34;
m_nID[3][0] = IDC_EDIT41;
m_nID[3][1] = IDC_EDIT42;
m_nID[3][2] = IDC_EDIT43;
m_nID[3][3] = IDC_EDIT44;
AfxInitRichEdit( );
}
CTaiKlineDlgEditScreenStock::~CTaiKlineDlgEditScreenStock()
{
}
void CTaiKlineDlgEditScreenStock::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTaiKlineDlgEditScreenStock)
DDX_Control(pDX, IDOK, m_ok);
DDX_Control(pDX, IDCANCEL, m_cancel);
DDX_Control(pDX, IDC_DYHS, m_dyhs);
DDX_Control(pDX, IDC_CSGS, m_csgs);
DDX_Control(pDX, IDC_BUTTON2, m_button2);
DDX_Control(pDX, IDC_BUTTON1, m_button1);
DDX_Control(pDX, IDC_BUTTON_CAN_USED, m_canused);
DDX_Control(pDX, IDC_EDIT12, m_floatEdit12);
DDX_Control(pDX, IDC_EDIT13, m_floatEdit13);
DDX_Control(pDX, IDC_EDIT14, m_floatEdit14);
DDX_Control(pDX, IDC_EDIT22, m_floatEdit22);
DDX_Control(pDX, IDC_EDIT23, m_floatEdit23);
DDX_Control(pDX, IDC_EDIT24, m_floatEdit24);
DDX_Control(pDX, IDC_EDIT32, m_floatEdit32);
DDX_Control(pDX, IDC_EDIT33, m_floatEdit33);
DDX_Control(pDX, IDC_EDIT34, m_floatEdit34);
DDX_Control(pDX, IDC_EDIT42, m_floatEdit42);
DDX_Control(pDX, IDC_EDIT43, m_floatEdit43);
DDX_Control(pDX, IDC_EDIT44, m_floatEdit44);
DDX_Control(pDX, IDC_TAB1, m_tabParam);
DDX_Control(pDX, IDC_NAME, m_namecor);
DDX_Control(pDX, IDC_PASSWORD, m_passwordcor);
DDX_Control(pDX, IDC_HFQS, m_hfqs);
DDX_Control(pDX, IDC_INPUT, m_inputcor);
DDX_Check(pDX, IDC_CHECKMM, m_checkmm);
DDX_Check(pDX, IDC_CHECK1, m_checkOften);
DDX_Text(pDX, IDC_EXPLAINBRIEF, m_explainbrief);
DDX_Text(pDX, IDC_MYHELP, m_myhelp);
DDX_Text(pDX, IDC_NAME, m_name);
DDX_Text(pDX, IDC_PASSWORD, m_password);
DDX_Control(pDX, IDC_XLINE, m_xlinecor);
DDX_Text(pDX, IDC_XLINE, m_xline);
DDX_Text(pDX, IDC_STATIC_TEST_INFO, m_sTestInfo);
DDX_CBString(pDX, IDC_COMBO_KIND_TIME, m_sKindTime);
DDX_Text(pDX, IDC_EDIT1, m_sKindFormu);
//}}AFX_DATA_MAP
if(this->iskline == 2) DDV_MaxChars(pDX, m_name, 10);
}
BEGIN_MESSAGE_MAP(CTaiKlineDlgEditScreenStock, CDialog)
//{{AFX_MSG_MAP(CTaiKlineDlgEditScreenStock)
ON_BN_CLICKED(IDC_HFQS, OnRestoreDefault)
ON_BN_CLICKED(IDC_CSGS, OnTestFormula)
ON_BN_CLICKED(IDC_DYHS, OnAddFunc)
ON_BN_CLICKED(IDC_BUTTON2, OnImportFormula)
ON_WM_PAINT()
ON_BN_CLICKED(IDC_CHECKMM, OnCheckmm)
ON_WM_CTLCOLOR()
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, OnSelchangeTab1)
ON_BN_CLICKED(IDC_BUTTON_CAN_USED, OnButtonCanUsed)
ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
ON_CBN_SELCHANGE(IDC_COMBO_KIND_TIME, OnSelchangeComboKindTime)
ON_WM_HELPINFO()
ON_EN_CHANGE(IDC_INPUT, OnChangeInput)
ON_WM_SIZE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTaiKlineDlgEditScreenStock message handlers
///////////////////////////////////////////////////////////////////
//
// 入口参数:无
// 返回参数:无
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnTestFormula()
{
bool errpram=false;
UpdateData();
CString input="" ;
m_inputcor.GetWindowText(input);
// m_inputcor.SetRedraw(FALSE);
int i,j;
for(int flag=0;flag<1;flag++)
{
int n = m_tabParam.GetCurSel();
if(n==0)
{
for(i=0;i<4;i++)
for(j=0;j<4;j++)
m_editParam[i][j]=GetStringParam(i,j);//m_edit[i][j];
}
else
{
for(i=0;i<4;i++)
for(j=0;j<4;j++)
m_editParam[i+4][j]=GetStringParam(i,j);//m_edit[i][j];
// SetStringParam(i,j,m_editParam[i+4][j]);//=m_edit[i][j];
}
for(i=0;i<8;i++)
{
bool bEmpty = true;
for(j=1;j<4;j++)
{
if(m_editParam[i][j] != "")
{
bEmpty = false;
break;
}
}
//test name
if(bEmpty == false)
{
if(m_editParam[i][0]=="")
{
errorposition=2000+(i+1)*10+1;
errormessage="参数名不能空";
errpram=true;
break;
}
else if(!CheckParmNameInput(m_editParam[i][0],errormessage))
{
errorposition=2000+(i+1)*10+1;
errpram=true;
break;
}
}
else
{
m_editParam[i][0]=="";
for(int k=i+1;k<8;k++)
{
for(int l=0;l<4;l++)
m_editParam[k][l]=="";
}
break;
}
//test param
for(j=1;j<4;j++)
{
if(m_editParam[i][j] == "")
{
errorposition=2000+(i+1)*10+1+j;
errormessage="输入值不能空";
errpram=true;
break;
}
else
{
if(!CheckParmInput(m_editParam[i][j]))
{
errorposition=2000+(i+1)*10+1+j;
errormessage="输入值不合法";
errpram=true;
break;
}
}
//
if(j==3)
{
if(StringToFloat(m_editParam[i][3])>StringToFloat(m_editParam[i][1])||StringToFloat(m_editParam[i][3])<StringToFloat(m_editParam[i][2]))
{
errorposition=2014;
errormessage="缺省值不在合法的范围";
errpram=true;
break;
}
}
}
}
}
//----------------------
if(iskline>1)
{
m_xline.Remove(' ');
int strstart=0;
CString xpos;
int j=0;
for(int i=0;i<m_xline.GetLength();i++)
{
char test=m_xline.GetAt(i);
bool isreturn=false;
bool isfinish=(test==';');
bool isdot=(test=='.');
if(test==13&&m_xline.GetAt(i+1)==10)
{
isreturn=true;
}
if(!(isdot||isreturn||isfinish||isdot||(test>='0'&&test<='9'||test=='-')))
{
errormessage="指标水平位置设置错误";
errorposition=3000+i;
errpram=true;
break;
}
if(isfinish||isreturn||i==m_xline.GetLength()-1)
{
xpos=m_xline.Mid(strstart,i-strstart);
if(xpos!="")
{
if(j<7)
{
// jishunow->posX[j]=atof(xpos);
j++;
for(int k=i+1;k<m_xline.GetLength();k++)
{
char test=m_xline.GetAt(k);
if(test>='0'&&test<='9')
{
strstart=k;
break;
}
}
}
else
{
errorposition=3000+i;
errormessage="水平线位置太多";
errpram=true;
break;
}
}
}
if(isreturn)
i++;
}
}//end XLINE
CString formal=input;
formal.Remove(' ');
if(formal.GetLength()==0)
{
errormessage="公式内容不能为空";
m_inputcor.SetFocus();
// m_inputcor.SetRedraw();
UpdateData(FALSE);
return;
}
else
{
formal=input;
}
if(formal.GetAt(formal.GetLength()-1)==';')
formal.Delete(formal.GetLength()-1);
formal.MakeLower();
Kline kline;
CFormularCompute *equation=new CFormularCompute(0,0,&kline,formal);
for(i=0;i<8;i++)
{
if(m_editParam[i][0]!=""&&m_editParam[i][3]!="")
{
float fpram=StringToFloat(m_editParam[i][3]);
m_editParam[i][0].MakeLower();
int addpra=equation->AddPara(m_editParam[i][0],fpram);
switch(addpra)
{
case(1):
errorposition=2011;
errpram=true;
errormessage="参数个数太多";
break;
case(2):
errorposition=2011;
errpram=true;
errormessage="参数名重复或是系统关键字";
break;
}
if(errpram == true)
break;
}
}
if(errpram)
{
errorposition-=2000;
switch(errorposition)
{
case 11:
GetDlgItem(IDC_EDIT11)->SetFocus();
break;
case 12:
GetDlgItem(IDC_EDIT12)->SetFocus();
break;
case 13:
GetDlgItem(IDC_EDIT13)->SetFocus();
break;
case 14:
GetDlgItem(IDC_EDIT14)->SetFocus();
break;
case 21:
GetDlgItem(IDC_EDIT21)->SetFocus();
break;
case 22:
GetDlgItem(IDC_EDIT22)->SetFocus();
break;
case 23:
GetDlgItem(IDC_EDIT23)->SetFocus();
break;
case 24:
GetDlgItem(IDC_EDIT24)->SetFocus();
break;
case 31:
GetDlgItem(IDC_EDIT31)->SetFocus();
break;
case 32:
GetDlgItem(IDC_EDIT32)->SetFocus();
break;
case 33:
GetDlgItem(IDC_EDIT33)->SetFocus();
break;
case 34:
GetDlgItem(IDC_EDIT34)->SetFocus();
break;
case 41:
GetDlgItem(IDC_EDIT41)->SetFocus();
break;
case 42:
GetDlgItem(IDC_EDIT42)->SetFocus();
break;
case 43:
GetDlgItem(IDC_EDIT43)->SetFocus();
break;
case 44:
GetDlgItem(IDC_EDIT44)->SetFocus();
break;
default:
if(iskline>1)//技术指标
{
m_xlinecor.SetFocus();
m_xlinecor.SetSel(errorposition-1000,errorposition-1000);
}
break;
}
if(errorposition==-1)
m_sTestInfo="测试通过!";
else
m_sTestInfo=errormessage;
UpdateData(FALSE);
return;
}
equation->Devide();
if(iskline<2)
{
if(equation->m_RlineNum!=1)
{
if(equation->m_errpos==-1)
{
if(equation->m_RlineNum==0)
{
equation->m_errmsg="公式必须有一个返回值";
equation->m_errpos=formal.GetLength();
}
else
{
int k=0,j=0;
int formallength=formal.GetLength();
char test;
for(int i=formallength-1;i>=0;i--)
{
test=formal.GetAt(i);
if(test==' '||test==';'||test=='\t'||test=='\n'||test=='\r')
continue;
else
break;
}
for( j=i+1;j<formal.GetLength();j++)
formal.Delete(j);
formal.Insert(i+1,';');
for( i=0;i<formal.GetLength();i++)
{
char test=formal.GetAt(i);
if(test==':'&&formal.GetAt(i+1)=='=')
{
k++;
}
if(test==';')
{
k--;
if(k<-1)
break;
else
j=i;
}
}
if(equation->m_errpos==-1&&k<-1)
{
equation->m_errpos=j;
equation->m_errmsg="公式只能有一个表达式";
}
}
}
}
errorposition=equation->m_errpos;
errormessage=equation->m_errmsg;
}
else
{
errorposition=equation->m_errpos;
errormessage=equation->m_errmsg;
if(errorposition==-1)
{
if(equation->m_RlineNum==0)
{
errorposition=formal.GetLength();
errormessage="公式必须至少画一条线";
}
else if(equation->m_RlineNum>NUM_LINE_TOT)
{
errorposition=formal.GetLength();
errormessage="公式最多只能计算32条线";
}
}
}
delete equation;
// return;
if(errorposition!=-1)
{
m_inputcor.SetSel(errorposition,errorposition);
long lng = m_inputcor.LineFromChar(errorposition);
if(lng>=0)
{
int nln = m_inputcor.GetFirstVisibleLine();
if(nln>lng)
m_inputcor.LineScroll(lng-nln , 0 );
else if(nln<lng)
{
m_inputcor.LineScroll(lng-nln-1 , 0 );
}
}
}
if(errorposition==-1)
m_sTestInfo="测试通过!";
else
m_sTestInfo=errormessage;
m_inputcor.SetFocus();
UpdateData(FALSE);
}
//--------------
void CTaiKlineDlgEditScreenStock::OnOK()
{
UpdateData();
if(jishunow)
if(jishunow->sellStr != "")
return;
CTaiShanDoc* pDoc=CMainFrame::m_taiShanDoc ;//(CTaiShanDoc*)pchildfram->GetActiveDocument();
CString name=m_name;
CString input="" ;
m_inputcor.GetWindowText(input);
name.Remove(' ');
bool isnameok=true;
for(int i=0;i<m_name.GetLength();i++)
{
char test=m_name.GetAt(i);
if((test&0x80)!=0)
{
i=i+1;
continue;
}
// if(!((test>='a'&&test<='z')||test=='#'||test=='_'||test=='%'||test == '(' || test == ')'||(test>='A'&&test<='Z')||(test>='0'&&test<='9')))
{
}
//
{
}
}
if(!isnameok||name==""||name=="STOCKMODEKLINE"||name=="STOCKFILTER")
{
AfxMessageBox("指标名为空或非法,\n请重新输入",MB_OK);
m_namecor.SetFocus();
return;
}
OnTestFormula();
//-----------
if(errorposition!=-1)
if(AfxMessageBox("您编辑的公式没有通过\n语法检查,系统将强制存储,\n\
要继续吗?",MB_OKCANCEL|MB_ICONQUESTION)==IDCANCEL)
return;
CFormularContent *jishunew = NULL;
if(item == -1)
{
jishunew=new CFormularContent();
jishunow=jishunew;
}
else
{
if(iskline == 1)
jishunow =pDoc->m_formuar_kline.GetAt(item);
else if(iskline == 0)
jishunow =pDoc->m_formuar_choose.GetAt(item);
else
{
jishunow =pDoc->m_formuar_index.GetAt(item);
CString namepre=jishunow->name;
CTaiKeyBoardAngelDlg::DeleteIndicatorName(namepre);
}
int nKind = 0;
if(iskline == 1)
nKind =1;
else if(iskline == 0)
nKind =2;
if(FindIndicator(nKind, m_name,jishunow))
{
AfxMessageBox(m_name+" 公式已存在,请重新选择!");
return;
}
}
if(item == -1)
{
if(iskline == 1)
{
int length=pDoc->m_formuar_kline.GetSize();
if(length>0)
{
int k;
for(k=0;k<length;k++)
{
if(m_name.Compare(pDoc->m_formuar_kline.GetAt(k)->name)<=0)
break;
}
if(k>=length)
{
pDoc->m_formuar_kline.Add(jishunew);
addpos=length;
}
else
{
if(m_name.Compare(pDoc->m_formuar_kline.GetAt(k)->name)==0)
{
AfxMessageBox(m_name+"K线组合公式已存在,请重新选择!");
m_namecor.SetFocus();
delete jishunew;
return ;
}
else
{
pDoc->m_formuar_kline.InsertAt(k,jishunew);
addpos=k;
}
}
}
else
{
addpos=0;
pDoc->m_formuar_kline.Add(jishunew);
}
}
else if(iskline == 0)
{
int length=pDoc->m_formuar_choose.GetSize();
if(length>0)
{
int k;
for(k=0;k<length;k++)
{
if(m_name.Compare(pDoc->m_formuar_choose.GetAt(k)->name)<=0)
break;
}
if(k>=length)
{
pDoc->m_formuar_choose.Add(jishunew);
addpos=length;
}
else
{
if(m_name.Compare(pDoc->m_formuar_choose.GetAt(k)->name)==0)
{
AfxMessageBox(m_name+"条件选股公式已存在,请重新选择!");
m_namecor.SetFocus();
delete jishunew;
return ;
}
else
{
pDoc->m_formuar_choose.InsertAt(k,jishunew);
addpos=k;
}
}
}
else
{
addpos=0;
pDoc->m_formuar_choose.Add(jishunew);
}
}
else
{
int length=pDoc->m_formuar_index.GetSize();
if(length>0)
{
int k;
for(k=0;k<length;k++)
{
if(m_name.Compare(pDoc->m_formuar_index.GetAt(k)->name)<=0)
break;
}
if(k>=length)
{
pDoc->m_formuar_index.Add(jishunew);
addpos=length;
}
else
{
if(m_name.Compare(pDoc->m_formuar_index.GetAt(k)->name)==0)
{
AfxMessageBox(m_name+"指标公式已存在,请重新选择!");
delete jishunew;
return ;
}
else
{
pDoc->m_formuar_index.InsertAt(k,jishunew);
addpos=k;
}
}
}
else
{
pDoc->m_formuar_index.Add(jishunew);
addpos=0;
}
}
}
if(iskline == 2)
{
//-----------------------
for(int k=0;k<7;k++)
{
jishunow->posX[k]=-10e20;
}
CString xpos;
int j=0,strstart=0;
for(int i=0;i<m_xline.GetLength();i++)
{
char test=m_xline.GetAt(i);
bool isreturn=false;
bool isfinish=(test==';');
if(test==13&&m_xline.GetAt(i+1)==10)
{
isreturn=true;
}
if(isfinish||isreturn||i==m_xline.GetLength()-1)
{
xpos=m_xline.Mid(strstart,i-strstart);
if(xpos!="")
{
jishunow->posX[j]=atof(xpos);
j++;
for(int k=i+1;k<m_xline.GetLength();k++)
{
char test=m_xline.GetAt(k);
if(test>='0'&&test<='9'||test == '-')
{
strstart=k;
break;
}
}
}
}
if(isreturn)
i++;
}
//--------------------
int itemid;
itemid=GetCheckedRadioButton(IDC_ZTDJ,IDC_FT);
if(itemid==IDC_ZTDJ)
jishunow->isMainFiguer=true;
else
jishunow->isMainFiguer=false;
}
//--------------
int pramnum=0;
for(int i=0;i<8;i++)
{
if(m_editParam[i][0]!=""&&m_editParam[i][3]!="")
pramnum++;
else
break;
}
jishunow->numPara=pramnum;
for(int i=0;i<pramnum;i++)
{
jishunow->namePara[i]=m_editParam[i][0];
jishunow->namePara[i].MakeLower ();
jishunow->max[i]=StringToFloat(m_editParam[i][1]);
jishunow->min[i]=StringToFloat(m_editParam[i][2]);
float f = StringToFloat(m_editParam[i][3]);
if(m_nKlineType!=-1)
CTaiKlineDlgChangeIndexParam::SetParamLjishu(jishunow,m_nKlineType,i,(CMainFrame::m_taiShanDoc)->m_propertyInitiate.bSaveParam,f);
else
jishunow->defaultVal[i]=f;
}
//temp initiate
jishunow->InitDefaultValArray();
//------------------------
jishunow->fomular=input;
if((m_checkmm==TRUE))
jishunow->password=m_password;
jishunow->explainBrief=m_explainbrief;
jishunow->name=m_name;
jishunow->isProtected=m_checkmm;
jishunow->help=m_myhelp;
if(m_sKindTime!="长期"&&m_sKindTime!="中期"&&m_sKindTime!="短期")
m_sKindTime = "中期";
jishunow->subKindIndexTime = m_sKindTime;
memcpy(jishunow->nPeriodsUsed , m_nPeriodsUsed,11);
// CComboBox* pCombo = (CComboBox* )GetDlgItem(IDC_COMBO_KIND_TIME)->GetWindowText();
jishunow->explainParam = m_strParamExplain ;
jishunow->subKindIndex = m_sKindFormu;
jishunow->isOfen = m_checkOften;
if(pramnum!=jishunow->defaultValArray.GetSize())
jishunow->AddDefaultValToArray();
CFormularCompute::FanEach(jishunow);
CDialog::OnOK();
}
///////////////////////////////////////////////////////////////////
// 功能说明:增加函数
// 入口参数:无
// 返回参数:无
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnAddFunc()
{
UpdateData();
CDialogEDITZBGSHS m_diazbgshs;
if(m_diazbgshs.DoModal()==IDOK)
{
m_inputcor.SetFocus();
functionstr=m_diazbgshs.m_selectedstr;
int length=functionstr.GetLength();
int i;
for(i=0;i<length;i++)
{
char test=functionstr.GetAt(i);
if(test=='-'&&functionstr.GetAt(i+1)=='-')
break;
}
if(i==length)
functionstr="";
else
functionstr=functionstr.Left(i);
m_inputcor.ReplaceSel(functionstr);
}
}
BOOL CTaiKlineDlgEditScreenStock::OnInitDialog()
{
CDialog::OnInitDialog();
CTaiShanDoc* pDoc=(CMainFrame::m_taiShanDoc );
if(m_nKlineType!=-1)
{
CString sTl ;
GetWindowText(sTl);
CString s2 = CTaiScreenParent::GetPeriodName(m_nKlineType);
sTl+="(";
sTl+=s2;
sTl+=")";
SetWindowText(sTl);
}
if(m_bInit == false)
{
m_tabParam.InsertItem (0,"参数1-4");
m_tabParam.InsertItem (1,"参数5-8");
m_bInit = true;
}
if(item!=-1)
{
//
}
if(iskline<2)
{
if(iskline==0)
this->SetWindowText("条件选股公式编辑器");
else
this->SetWindowText("K线组合公式编辑器");
if(item!=-1)
{
if(iskline==0)
jishunow=pDoc->m_formuar_choose.GetAt(item);
if(iskline==1)
jishunow=pDoc->m_formuar_kline.GetAt(item);
m_name=jishunow->name;
m_myhelp=jishunow->help;
m_checkOften = jishunow->isOfen ;
// m_namecor.SetReadOnly(TRUE);
m_explainbrief=jishunow->explainBrief;
if(jishunow->isProtected)
{
m_checkmm=true;
m_password=jishunow->password;
}
else
m_passwordcor.EnableWindow(FALSE);
m_inputcor.SetWindowText(jishunow->fomular);
m_inputcor.SetFocus();
numPara = jishunow->numPara ;
//temp initiate
jishunow->InitDefaultValArray();
ParamIntoOther(0);
ParamIntoOther(2);
// m_strPeriodPre ="";
memcpy(m_nPeriodsUsed,jishunow->nPeriodsUsed,16);
m_sKindTime=jishunow->subKindIndexTime ;
this->m_sKindFormu = jishunow->subKindIndex ;
m_strParamExplain = jishunow->explainParam ;
UpdateData(FALSE);
}
else
{
m_checkmm=false;
m_hfqs.EnableWindow(FALSE);
UpdateData(FALSE);
}
}
else
{
if(item!=-1)
{
jishunow=pDoc->m_formuar_index.GetAt(item);
m_name=jishunow->name;
// m_namecor.SetReadOnly(TRUE);
if(pDoc->m_formuar_index.GetAt(item)->isMainFiguer==1)
CheckRadioButton(IDC_ZTDJ,IDC_FT,IDC_ZTDJ);
else
CheckRadioButton(IDC_ZTDJ,IDC_FT,IDC_FT);
CString strxline;
for(int k=0;k<7;k++)
{
if(jishunow->posX[k]>=-10e19)
{
CString test;
test.Format("%.2f",jishunow->posX[k]);
strxline+=test;
strxline+=';';
}
else
break;
}
m_xline=strxline;
m_explainbrief=jishunow->explainBrief;
if(jishunow->isProtected)
{
m_checkmm=true;
m_password=jishunow->password;
}
else
{
m_checkmm=false;
m_passwordcor.EnableWindow(FALSE);
}
if(jishunow->isSystem)
m_namecor.SetReadOnly(TRUE);
//---------------------
m_myhelp=jishunow->help;
m_inputcor.SetWindowText(pDoc->m_formuar_index.GetAt(item)->fomular);
m_inputcor.SetFocus();
//temp initiate
jishunow->InitDefaultValArray();
m_checkOften = jishunow->isOfen ;
ParamIntoOther(0);
ParamIntoOther(2);
memcpy(m_nPeriodsUsed,jishunow->nPeriodsUsed,16);
m_sKindTime=jishunow->subKindIndexTime ;
this->m_sKindFormu = jishunow->subKindIndex ;
m_strParamExplain = jishunow->explainParam ;
UpdateData(FALSE);
}
else
{
m_myhelp="";
CheckRadioButton(IDC_ZTDJ,IDC_FT,IDC_FT);
m_checkmm=false;
m_hfqs.EnableWindow(FALSE);
UpdateData(FALSE);
}
// m_xlinecor.ShowWindow (SW_SHOW);
;
}
if(jishunow)
if(jishunow->sellStr != "")
{
m_inputcor.SetWindowText("");
}
g_bInitDlgEdit = false;
OnChangeInput2() ;
m_inputcor.SetEventMask(m_inputcor.GetEventMask() |
ENM_CHANGE);
g_bInitDlgEdit = true;
DoMoveWindow();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
///////////////////////////////////////////////////////////////////
// 功能说明:浮点数转换为字符串
// 入口参数:fdata:浮点数
// 返回参数:str:返回字符串
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::ShowData(CString &str, float fdata)
{
if(fdata==-1000)
str="";
else
{
str.Format("%.4f",fdata);
int strlength=str.GetLength();
str.TrimRight ("0");
str.TrimRight (".");
}
}
///////////////////////////////////////////////////////////////////
// 功能说明:字符串转换为浮点数
// 入口参数:str:字符串
// 返回参数:返回浮点数
/////////////////////////////////////////////////////////////////////////////
float CTaiKlineDlgEditScreenStock::StringToFloat(CString str)
{
char * test;
int length=str.GetLength();
test=str.GetBuffer(length);
return (float)atof(test);
}
void CTaiKlineDlgEditScreenStock::OnPaint()
{
CDialog::OnPaint();
// Do not call CDialog::OnPaint() for painting messages
}
///////////////////////////////////////////////////////////////////
// 功能说明:测试参数数据是否合法
// 入口参数:parminput:参数数据
// 返回参数:返回是否正确
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnCheckmm()
{
if(IsDlgButtonChecked(IDC_CHECKMM))
m_passwordcor.EnableWindow(TRUE);
else
m_passwordcor.EnableWindow(FALSE);
}
///////////////////////////////////////////////////////////////////
// 功能说明:测试参数数据是否合法
// 入口参数:parminput:参数数据
// 返回参数:返回是否正确
/////////////////////////////////////////////////////////////////////////////
BOOL CTaiKlineDlgEditScreenStock::CheckParmInput(CString parminput)
{
int inputlength=parminput.GetLength();
char test;
for(int i=0;i<inputlength;i++)
{
test=parminput.GetAt(i);
if(!(test=='-'||test=='+'||test=='.'||(test>='0'&&test<='9')))
{
return FALSE;
}
}
return TRUE;
}
///////////////////////////////////////////////////////////////////
// 功能说明:检测参数名称是否合法
// 入口参数:parname:参数名称,errmessage:错误信息
// 返回参数:返回是否正确
/////////////////////////////////////////////////////////////////////////////
BOOL CTaiKlineDlgEditScreenStock::CheckParmNameInput(CString parname, CString &errmessage)
{
parname.Remove(' ');
char test=parname.GetAt(0);
if(test&0x80 == 0 && (test<'A'||test>'z'||test=='_'))
{
errormessage="参数名必须以字母开头";
return FALSE;
}
int length=parname.GetLength();
for(int i=1;i<length;i++)
{
test=parname.GetAt(i);
if((test>='0'&&test<='9')||(test>='A'&&test<='z')||test=='_'||((BYTE)test)>=0x80 )
continue;
else
{
errormessage="参数名组成非法";
return FALSE;
}
}
return TRUE;
}
///////////////////////////////////////////////////////////////////
// 功能说明:恢复缺省数据
// 入口参数:无
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnRestoreDefault()
{
// TODO: Add your control notification handler code here
((CComboBox*)GetDlgItem(IDC_COMBO_KIND_TIME))->ResetContent( );
OnInitDialog();
}
///////////////////////////////////////////////////////////////////
// 功能说明:引入技术指标公式
// 入口参数:无
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnImportFormula()
{
// TODO: Add your control notification handler code here
CFxjSelectFormu dlg;
if(dlg.DoModal () == IDOK)
{
CFxjShowFormu dlg2 (this);
dlg2.m_s =dlg.GetJishu() ->fomular ;
if(dlg.GetJishu() ->sellStr != "")
return;
dlg2.m_title = dlg.GetJishu() ->name ;
if(dlg2.DoModal () == IDOK)
{
// m_inputcor.Paste ();
}
}
return;
CDialogLOGXZZB mdiaxzzb(this);
int item2 = -1;
if(mdiaxzzb.DoModal() == IDOK)
{
CString s = mdiaxzzb.result;
CTaiShanDoc* pDoc = CMainFrame::m_taiShanDoc ;
int n = pDoc->m_formuar_index .GetSize ();
for(int i=0;i<n;i++)
{
if(s == pDoc->m_formuar_index.GetAt (i)->name )
{
item2 = i;
break;
}
}
if(item2==-1)
return;
//test
if(pDoc->m_formuar_index.GetAt (item2)->isProtected !=0)
{
CDialogGSGLMM mdiagsglmm;
mdiagsglmm.password=pDoc->m_formuar_index.GetAt (item2)->password;
if(mdiagsglmm.DoModal()!=IDOK)
return;
}
ASSERT(item==-1);
item = item2;
int temp = iskline;
iskline = 2;
CString s2 = this->m_sKindFormu ;
((CComboBox*)GetDlgItem(IDC_COMBO_KIND_TIME))->ResetContent( );
this->OnInitDialog ();
this->m_sKindFormu = s2;
UpdateData(FALSE);
iskline = temp;
item = -1;
}
}
void CTaiKlineDlgEditScreenStock::OnCancel()
{
// TODO: Add extra cleanup here
CDialog::OnCancel();
}
///////////////////////////////////////////////////////////////////
// 功能说明:改变标签的字体的颜色
// 入口参数:参阅msdn帮助文件
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
HBRUSH CTaiKlineDlgEditScreenStock::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
if (pWnd->GetDlgCtrlID() == IDC_STATIC_TEST_INFO )
{
if(errorposition==-1)
pDC->SetTextColor(RGB(255,0,0));
else
pDC->SetTextColor(RGB(0,0,255));
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
///////////////////////////////////////////////////////////////////
// 功能说明:参数1-4与参数5-8之间的切换处理
// 入口参数:无
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnSelchangeTab1(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
UpdateData();
// static int nTabPre = 0;
int n = m_tabParam.GetCurSel();
int i,j;
if(m_nTabPre!=n)
{
if(n==0)
{//把参数信息(5-8)保存到m_editParam中,把参数信息(1-4)从m_editParam中恢复到m_edit
for(i=0;i<4;i++)
for(j=0;j<4;j++)
m_editParam[4+i][j]=GetStringParam(i,j);//m_edit[i][j];
for(i=0;i<4;i++)
for(j=0;j<4;j++)
SetStringParam(i,j,m_editParam[i][j]);
}
else if(n==1)//
{
if(GetStringParam(0,0)==""||GetStringParam(1,0)==""||GetStringParam(2,0)==""||GetStringParam(3,0)=="")
{
m_tabParam.SetCurSel(0);
n=0;
}
else//把参数信息(1-4)保存到m_editParam中,把参数信息(5-8)从m_editParam中恢复到m_edit
{
for(i=0;i<4;i++)
for(j=0;j<4;j++)
m_editParam[i][j]=GetStringParam(i,j);//m_edit[i][j];
for(i=0;i<4;i++)
for(j=0;j<4;j++)
SetStringParam(i,j,m_editParam[i+4][j]);
}
}
UpdateData(FALSE);
}
m_nTabPre = n;
*pResult = 0;
}
///////////////////////////////////////////////////////////////////
// 功能说明:参数转换
// 入口参数:nFlag=0:前四个参数输出到编辑框,nFlag=1:后四个参数输出到编辑框,nFlag=2:所有参数输出到缓存
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::ParamIntoOther(int nFlag)//
{
int i,j;
if(nFlag >1)
{
if(jishunow->numPara>8)
jishunow->numPara = 0;
for(i=0;i<8;i++)
{
if(i<jishunow->numPara)
{
m_editParam[i][0]=jishunow->namePara[i];
ShowData(m_editParam[i][1],jishunow->max[i]);
ShowData(m_editParam[i][2],jishunow->min[i]);
float f = jishunow->defaultVal[i];
if(m_nKlineType!=-1)
f = CFormularContent::GetParamDataEach(i,m_nKlineType,jishunow);
ShowData(m_editParam[i][3],f);
}
else
{
for(j=0;j<4;j++)
m_editParam[i][j]="";
}
;
}
}
else
{
if(jishunow->numPara>8)
jishunow->numPara = 0;
int nBegin = 0;
if(nFlag==1&&jishunow->numPara>4)
nBegin = 4;
for(i=nBegin;i<4+nBegin;i++)
{
if(i<jishunow->numPara-nBegin)
{
SetStringParam(i,0,jishunow->namePara[i]);
CString s;
ShowData(s,jishunow->max[i]);
SetStringParam(i,1,s);
ShowData(s,jishunow->min[i]);
SetStringParam(i,2,s);
float f = jishunow->defaultVal[i];
if(m_nKlineType!=-1)
f = CFormularContent::GetParamDataEach(i,m_nKlineType,jishunow);
ShowData(s,f);
SetStringParam(i,3,s);
}
else
for(j=0;j<4;j++)
SetStringParam(i,j,"");
}
}
}
///////////////////////////////////////////////////////////////////
// 功能说明:改变技术指标数据的指标可用时间周期的内容
// 入口参数:无
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnButtonCanUsed()
{
// TODO: Add your control notification handler code here
CTaiKlineDlgCanUsedPeriod dlgCanUsed;
dlgCanUsed.InputString(m_nPeriodsUsed);
if(dlgCanUsed.DoModal ()==IDOK)
dlgCanUsed.OutSetting (m_nPeriodsUsed);
}
///////////////////////////////////////////////////////////////////
// 功能说明:改变指标公式数据的指标参数注释内容
// 入口参数:无
// 返回参数:无返回数
/////////////////////////////////////////////////////////////////////////////
void CTaiKlineDlgEditScreenStock::OnButton1()
{
// TODO: Add your control notification handler code here
UpdateData();
CDialogLOGGSSM mdiagssm;
mdiagssm.m_bReadOnly = false;
mdiagssm.m_edit=m_strParamExplain;
if(mdiagssm.DoModal()==IDOK)
m_strParamExplain=mdiagssm.m_edit;
UpdateData(FALSE);
}
void CTaiKlineDlgEditScreenStock::OnSelchangeComboKindTime()
{
// TODO: Add your control notification handler code here
}
void CTaiKlineDlgEditScreenStock::ChangePeriodParamData(bool bSave)
{
}
CString CTaiKlineDlgEditScreenStock::GetStringParam(int x, int y)
{
CString s ="";
GetDlgItem(m_nID[x][y])->GetWindowText(s);
return s;
}
void CTaiKlineDlgEditScreenStock::SetStringParam(int x, int y, CString sIn)
{
GetDlgItem(m_nID[x][y])->SetWindowText(sIn);
}
BOOL CTaiKlineDlgEditScreenStock::OnHelpInfo(HELPINFO* pHelpInfo)
{
// TODO: Add your message handler code here and/or call default
// HtmlHelp(m_hWnd,"stock.chm",HH_HELP_CONTEXT,CTaiKlineIndicatorsManage::IDD);
// return TRUE;//
DoHtmlHelp(this);return TRUE;
}
bool CTaiKlineDlgEditScreenStock::FindIndicator(int nKind, CString sName,CFormularContent *jishunow)
{
CTaiShanDoc* pDoc=CMainFrame::m_taiShanDoc ;//(CTaiShanDoc*)pchildfram->GetActiveDocument();
Formu_Array1* pArray[3] = {&(pDoc->m_formuar_index ),&(pDoc->m_formuar_choose),&(pDoc->m_formuar_kline )};
int length=pArray[nKind]->GetSize();
if(length>0)
{
for(int k=0;k<length;k++)
{
if(sName.Compare(pArray[nKind]->GetAt(k)->name)==0 && jishunow!=pArray[nKind]->GetAt(k))
return true;
}
}
else return false;
return false;
}
void CTaiKlineDlgEditScreenStock::OnChangeInput()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialog::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
UpdateData();
if(g_bInitDlgEdit)
OnChangeInput2();
}
void CTaiKlineDlgEditScreenStock::OnChangeInput2()
{
// TODO: Add your control notification handler code here
CString formal="" ;
m_inputcor.GetWindowText(formal);
if(formal.GetLength()==0)
{
return;
}
formal.MakeLower();
Kline kline;
CFormularCompute equation(0,0,&kline,formal);
equation.m_bShowColor = true;
bool errpram = false;
for(int i=0;i<8;i++)
{
if(m_editParam[i][0]!=""&&m_editParam[i][3]!="")
{
float fpram=StringToFloat(m_editParam[i][3]);
m_editParam[i][0].MakeLower();
int addpra=equation.AddPara(m_editParam[i][0],fpram);
switch(addpra)
{
case(1):
case(2):
errpram=true;
break;
}
if(errpram == true)
{
AfxMessageBox("请先设置正确参数!");
return;
}
}
}
equation.Devide();
//取得位置颜色信息
if(equation.m_errpos==-1 && equation.m_pKindPos )
{
//formal;
COLORREF clr[10] = {RGB(0,0,255),RGB(0,150,0),
RGB(120,0,0),RGB(255,0,0),
RGB(0,255,255),RGB(0,0,120)};
m_inputcor.SetRedraw(FALSE);
CPoint pt = GetCaretPos( );
long nStartChar;
long nEndChar;
m_inputcor.GetSel( nStartChar, nEndChar ) ;
static int iii = 0;
iii++;
TRACE("iii = %d",iii);
for(int k = 0;k<equation.m_nSizeKindPos ;k++)
{
int b = equation.m_pKindPos[k].m_nPos;
int e ;
if(k == equation.m_nSizeKindPos -1)
e = formal.GetLength ()-1;
else
e = equation.m_pKindPos[k+1].m_nPos;
if(e<0) e = 0;
if(e>formal.GetLength ()-1)
e = formal.GetLength ()-1;
if(b<0) b = 0;
if(b>formal.GetLength ()-1)
b = formal.GetLength ()-1;
m_inputcor.SetSel(b,e);
if(equation.m_pKindPos[k].m_nKind<10
&&equation.m_pKindPos[k].m_nKind>=0)
m_inputcor.SetSelectColor( clr[equation.m_pKindPos[k].m_nKind]);
}
m_inputcor.SetSel( nStartChar, nEndChar ) ;
// m_inputcor.HideSelection(TRUE, FALSE);
//SetSel(-1,-1);
SetCaretPos( pt );
m_inputcor.SetRedraw();
m_inputcor.RedrawWindow();
}
}
void CTaiKlineDlgEditScreenStock::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
CRect r;
if(m_inputcor.m_hWnd )
{
GetDlgItem (IDC_EDIT41)->GetWindowRect(r);
this->ScreenToClient (r);
// m_inputcor.GetWindowRect(r);
CRect r2(5,r.bottom+12,cx-5,cy-5);
m_inputcor.MoveWindow(r2);
}
}
void CTaiKlineDlgEditScreenStock::DoMoveWindow()
{
if(m_bShowFromMouse)
{
CPoint p;
GetCursorPos(&p);
CRect r;
GetWindowRect(r);
this->SetWindowPos(NULL,p.x,p.y,r.Width (),r.Height (),SWP_NOREDRAW);
}
}
| [
"[email protected]"
]
| [
[
[
1,
1644
]
]
]
|
6f74d66ce04af1d0b371e1b766829fb532d5e7ec | be7eef50e21e11340134d150f78db8d6f5423e66 | /D2/D2.cpp | 566a62ae4378d40aa3528311efc2eeb8d3fd768c | []
| no_license | Maciej-Poleski/Algorytmika | 8023aef976c1087e25a4f9079de65769cf690ae3 | 3a3818f82738d9ea42aba24dea89e9280d504f00 | refs/heads/master | 2023-07-06T03:57:54.430947 | 2011-05-26T15:57:11 | 2011-05-26T15:57:11 | 395,015,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,059 | cpp | #include <vector>
#include <algorithm>
#include <cstdio>
#include <climits>
using namespace std;
struct w
{
int v;
int p;
};
w *tab;
int n;
bool cmp(int a,int b)
{
return tab[a].v<tab[b].v;
}
int main()
{
int z;
scanf("%d\n",&z);
while(z--)
{
scanf("%d\n",&n);
tab=new w[n+1];
for(int i=1;i<=n;++i)
scanf("%d ",&tab[i].v);
vector<int> wynik;
wynik.push_back(1);
tab[1].p=0;
tab[0].v=INT_MIN;
tab[0].p=0;
for(int i=2;i<=n;++i)
{
vector<int>::iterator ttt=lower_bound(wynik.begin(),wynik.end(),i,cmp);
int p=ttt-wynik.begin();
if(ttt==wynik.end())
{
wynik.push_back(i);
tab[i].p=wynik[p-1];
continue;
}
wynik[p]=i;
if(p!=0)
tab[i].p=wynik[p-1];
else
tab[i].p=0;
}
int *ww=new int[n];
int *p=ww;
int i=wynik.back();
while(i!=0)
{
*p++=i;
i=tab[i].p;
}
delete [] tab;
printf("%d\n",p-ww);
while(p!=ww)
printf("%d ",*--p);
printf("\n");
delete [] ww;
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
3a70da5f17b61c3074d14c5fb6d5d816250528b6 | ab41c2c63e554350ca5b93e41d7321ca127d8d3a | /glm/gtc/quaternion.hpp | c2d36e784d95e098e05cdd0059eab44a2ad4a2f1 | []
| no_license | burner/e3rt | 2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e | 775470cc9b912a8c1199dd1069d7e7d4fc997a52 | refs/heads/master | 2021-01-11T08:08:00.665300 | 2010-04-26T11:42:42 | 2010-04-26T11:42:42 | 337,021 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,265 | hpp | ///////////////////////////////////////////////////////////////////////////////////////////////////
// OpenGL Mathematics Copyright (c) 2005 - 2009 G-Truc Creation (www.g-truc.net)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Created : 2009-05-21
// Updated : 2009-06-04
// Licence : This source is under MIT License
// File : glm/gtc/quaternion.hpp
///////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency:
// - GLM core
///////////////////////////////////////////////////////////////////////////////////////////////////
// ToDo:
// - Study constructors with angles and axis
// - Study constructors with vec3 that are the imaginary component of quaternion
///////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef glm_gtc_quaternion
#define glm_gtc_quaternion
// Dependency:
#include "../glm.hpp"
namespace glm
{
namespace detail
{
//! \brief Template for quaternion.
//! From GLM_GTC_quaternion extension.
template <typename valType>
class tquat
{
public:
valType x, y, z, w;
// Constructors
tquat();
explicit tquat(valType const & s, tvec3<valType> const & v);
explicit tquat(valType const & w, valType const & x, valType const & y, valType const & z);
// Convertions
//explicit tquat(valType const & pitch, valType const & yaw, valType const & roll);
//! pitch, yaw, roll
explicit tquat(tvec3<valType> const & eulerAngles);
explicit tquat(tmat3x3<valType> const & m);
explicit tquat(tmat4x4<valType> const & m);
// Accesses
valType& operator[](int i);
valType operator[](int i) const;
// Operators
tquat<valType>& operator*=(valType const & s);
tquat<valType>& operator/=(valType const & s);
};
template <typename valType>
detail::tquat<valType> operator- (
detail::tquat<valType> const & q);
template <typename valType>
detail::tvec3<valType> operator* (
detail::tquat<valType> const & q,
detail::tvec3<valType> const & v);
template <typename valType>
detail::tvec3<valType> operator* (
detail::tvec3<valType> const & v,
detail::tquat<valType> const & q);
template <typename valType>
detail::tvec4<valType> operator* (
detail::tquat<valType> const & q,
detail::tvec4<valType> const & v);
template <typename valType>
detail::tvec4<valType> operator* (
detail::tvec4<valType> const & v,
detail::tquat<valType> const & q);
template <typename valType>
detail::tquat<valType> operator* (
detail::tquat<valType> const & q,
valType const & s);
template <typename valType>
detail::tquat<valType> operator* (
valType const & s,
detail::tquat<valType> const & q);
template <typename valType>
detail::tquat<valType> operator/ (
detail::tquat<valType> const & q,
valType const & s);
} //namespace detail
namespace gtc{
//! GLM_GTC_quaternion extension: Quaternion types and functions
namespace quaternion
{
//! Returns the length of the quaternion x.
//! From GLM_GTC_quaternion extension.
template <typename valType>
valType length(
detail::tquat<valType> const & q);
//! Returns the normalized quaternion of from x.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> normalize(
detail::tquat<valType> const & q);
//! Returns dot product of q1 and q2, i.e., q1[0] * q2[0] + q1[1] * q2[1] + ...
//! From GLM_GTC_quaternion extension.
template <typename valType>
valType dot(
detail::tquat<valType> const & q1,
detail::tquat<valType> const & q2);
//! Returns the cross product of q1 and q2.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> cross(
detail::tquat<valType> const & q1,
detail::tquat<valType> const & q2);
//! Returns a LERP interpolated quaternion of x and y according a.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> mix(
detail::tquat<valType> const & x,
detail::tquat<valType> const & y,
valType const & a);
//! Returns the q conjugate.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> conjugate(
detail::tquat<valType> const & q);
//! Returns the q inverse.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> inverse(
detail::tquat<valType> const & q);
//! Rotates a quaternion from an vector of 3 components axis and an angle expressed in degrees.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> rotate(
detail::tquat<valType> const & q,
valType const & angle,
detail::tvec3<valType> const & v);
//! Converts a quaternion to a 3 * 3 matrix.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tmat3x3<valType> mat3_cast(
detail::tquat<valType> const & x);
//! Converts a quaternion to a 4 * 4 matrix.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tmat4x4<valType> mat4_cast(
detail::tquat<valType> const & x);
//! Converts a 3 * 3 matrix to a quaternion.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> quat_cast(
detail::tmat3x3<valType> const & x);
//! Converts a 4 * 4 matrix to a quaternion.
//! From GLM_GTC_quaternion extension.
template <typename valType>
detail::tquat<valType> quat_cast(
detail::tmat4x4<valType> const & x);
//! Quaternion of floating-point numbers.
//! From GLM_GTC_quaternion extension.
typedef detail::tquat<float> quat;
}//namespace quaternion
}//namespace gtc
} //namespace glm
#define GLM_GTC_quaternion namespace gtc::quaternion
#ifndef GLM_GTC_GLOBAL
namespace glm {using GLM_GTC_quaternion;}
#endif//GLM_GTC_GLOBAL
#include "quaternion.inl"
#endif//glm_gtc_quaternion
| [
"[email protected]"
]
| [
[
[
1,
194
]
]
]
|
b6cbe5a8a4882ba81a0291c3152d7f20f1bd6b9f | 6fa6532d530904ba3704da72327072c24adfc587 | /SCoder/SCoder/keys/prskey.cpp | 2b128c496481ea19d6f477a9234da58ca935d4e0 | []
| no_license | photoguns/code-hnure | 277b1c0a249dae75c66e615986fb1477e6e0f938 | 92d6ab861a9de3f409c5af0a46ed78c2aaf13c17 | refs/heads/master | 2020-05-20T08:56:07.927168 | 2009-05-29T16:49:34 | 2009-05-29T16:49:34 | 35,911,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | cpp | ////////////////////////////////////////////////////////////////////////////////
#include "prskey.h"
////////////////////////////////////////////////////////////////////////////////
PRSKey::PRSKey( const std::string& _string, Key::KeyType _type )
:Key(_string, _type)
{
}
////////////////////////////////////////////////////////////////////////////////
PRSKey::~PRSKey()
{
}
////////////////////////////////////////////////////////////////////////////////
std::string PRSKey::ApplyPRSKey( const std::string& _message ) const
{
// Get key hash
std::string keyHash = GetKeyHash();
// Key hash length
size_t hashLength = keyHash.length();
// Message + key
std::string mixedMessage(_message);
for (size_t i = 0; i < _message.length(); ++i)
mixedMessage[i] = _message[i] ^ keyHash[i % hashLength];
return mixedMessage;
}
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]@8592428e-0b6d-11de-9036-69e38a880166"
]
| [
[
[
1,
42
]
]
]
|
4a3a8875e31b2a0ec25466b4b7a686271bece3f1 | cb1c6c586d769f919ed982e9364d92cf0aa956fe | /examples/TRTSampleUtils/include/Timer.h | 25ceb663e802ea380a0a8ec7cbcfe381cc5f7a2c | []
| no_license | jrk/tinyrt | 86fd6e274d56346652edbf50f0dfccd2700940a6 | 760589e368a981f321e5f483f6d7e152d2cf0ea6 | refs/heads/master | 2016-09-01T18:24:22.129615 | 2010-01-07T15:19:44 | 2010-01-07T15:19:44 | 462,454 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | h | //=====================================================================================================================
//
// Timer.h
//
// Simple timer class for benchmarking
//
// Part of the TinyRT Raytracing Library.
// Author: Joshua Barczak
//
// Copyright 2009 Joshua Barczak. All rights reserved.
// See Doc/LICENSE.txt for terms and conditions.
//
//=====================================================================================================================
#ifndef _TIMER_H_
#define _TIMER_H_
class Timer
{
public:
Timer();
~Timer();
/// Returns the number of milliseconds elapsed since this object was created, or since the last reset
inline unsigned int Tick() const { return m_pImpl->Tick(); };
/// Same as tick, but in microseconds
inline unsigned long TickMicroSeconds() const { return m_pImpl->TickMicroSeconds(); };
/// Resets the timer
inline void Reset() { return m_pImpl->Reset(); };
// Windows and linux need to use different member types, so we use the PIMPL idiom here to avoid
// including that dastardly windows.h header on Win32 builds
class TimerImpl
{
public:
virtual unsigned int Tick() const = 0;
virtual unsigned long TickMicroSeconds() const = 0;
virtual void Reset() = 0;
};
private:
TimerImpl* m_pImpl;
};
#endif
| [
"jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809"
]
| [
[
[
1,
56
]
]
]
|
b0305c7c97d674e485ccc28aa9a0a37d93e5fc8b | 9c62af23e0a1faea5aaa8dd328ba1d82688823a5 | /rl/tags/techdemo2/engine/rules/include/EigenschaftenStateSet.h | 8e668bcf080b942e4c6599bbab029e93a1a6ab34 | [
"ClArtistic",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
]
| 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 | ISO-8859-1 | C++ | false | false | 1,663 | h | /* This source file is part of Rastullahs Lockenpracht.
* Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not you can get it here
* http://www.jpaulmorrison.com/fbp/artistic2.htm.
*/
#ifndef __EIGENSCHAFTENSTATESET_H__
#define __EIGENSCHAFTENSTATESET_H__
#include "StateSet.h"
namespace rl
{
class _RlRulesExport EigenschaftenStateSet : public StateSet
{
public:
EigenschaftenStateSet();
~EigenschaftenStateSet();
int getStartValue();
void setStartValue( int newStartValue );
int getPermanentModifier();
void setPermanentModifier( int newPermanentModifier );
int getModifierWithoutRecalculation();
void setModifierWithoutRecalculation( int newModifierWithoutRecalculation );
int getValue( bool getUnmodifiedValue = false );
int getValueForBasiswertCalculation();
protected:
// Der Wert bei Charaktererschaffung ohne Rassen-, Kultur- und Vorteilsboni/ -mali
int mStartValue;
// Rassen-, Kultur- und Vor-/Nachteils modifikatoren
int mPermanentModifier;
// Modifikatoren durch Effekte. Bei einer Neubereuchnung der Grundwerte (AT-Basis, AE etc) wird dieser Modifikator ignoriert
// @todo Aussagekräftigeren Namen finden.
int mModifierWithoutRecalculation;
};
}
#endif //__EIGENSCHAFTENSTATESET_H__
| [
"tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013"
]
| [
[
[
1,
49
]
]
]
|
5ad0b36d7a9a7860258561602d31d2c0c5aafcd5 | b236da3776ea1085448f6d8669e1f36189ad3a3b | /public-ro/common/h/common_types.hpp | 0fc243aa04cc7a4d562363489381b49643310c39 | []
| no_license | jirihelmich/mlaskal | f79a9461b9bbf00d0c9c8682ac52811e397a0c5d | 702cb0e1e81dc3524719d361ba48e7ec9e68cf91 | refs/heads/master | 2021-01-13T01:40:09.443603 | 2010-12-14T18:33:02 | 2010-12-14T18:33:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,666 | hpp | #ifndef GUARD_MLASKAL_COMMON_TYPES_HPP_
#define GUARD_MLASKAL_COMMON_TYPES_HPP_
/*
common_types.hpp
Common types
Kuba, 2006
*/
#include <iostream>
namespace mlaskal {
/// function kind
enum fnc_signature_type { FNCSIG_PROGRAM, FNCSIG_PROC, FNCSIG_FNC };
/// variable kind
enum fnc_signature_var_type { FNCSIG_LOCVAR, FNCSIG_GLOBVAR };
/// physical type
enum physical_type { PTYPE_UNDEF, PTYPE_ADDR, PTYPE_BOOL, PTYPE_INTEGER, PTYPE_REAL, PTYPE_STRING, PTYPE_ANY };
/// @cond INTERNAL
inline std::ostream &operator<<(std::ostream &os, physical_type ptype) {
static const char *ptypes[] = {
"UNDEF", "ADDR", "BOOLEAN", "INTEGER", "REAL", "STRING", "ANY"
};
os << ptypes[ptype];
return os;
}
/// @endcond
// types for instruction parameters
/// @cond INTERNAL
typedef int ICRELNUM;
/// @endcond
typedef int ICSTKOFFS; ///< stack offset
typedef unsigned ICABSNUM; ///< unsigned integer
/// @cond INTERNAL
typedef ICABSNUM ICLITIDX;
/// @endcond
typedef ICABSNUM ICREGNUM; ///< register number
/*************************************************************************/
/// limited-feature pointer to \p T
/** \internal **/
template< typename T> class dumb_pointer
{
public:
dumb_pointer() : ptr_( 0) {}
explicit dumb_pointer( T * p) : ptr_( p) {}
template< typename T2>
dumb_pointer( const dumb_pointer< T2> & b) : ptr_( b.ptr_) {}
T * operator->() const { return ptr_; }
bool operator!() const { return ! ptr_; }
private:
T * ptr_;
template< typename T2>
friend class dumb_pointer;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
5c23b1b341c9a49e062b229a7b0416e4fa3d08a9 | eec70a1718c685c0dbabeee59eb7267bfaece58c | /Sense Management Irrlicht AI/SoundModality.h | c739bff7afd33c1e0a01f709c474aaad2db65aaf | []
| no_license | mohaider/sense-management-irrlicht-ai | 003939ee770ab32ff7ef3f5f5c1b77943a4c7489 | c5ef02f478d00a4957a294254fc4f3920037bd7a | refs/heads/master | 2020-12-24T14:44:38.254964 | 2011-05-19T14:29:53 | 2011-05-19T14:29:53 | 32,393,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | h | #ifndef SOUND_MODALITY_H
#define SOUND_MODALITY_H
#include "Modality.h"
#include "Singleton.h"
class SoundModality : public Modality
{
public:
virtual void Load();
virtual bool ExtraChecks(Signal* signal, Sensor* sensor);
private:
SoundModality();
friend class Singleton<SoundModality>;
};
typedef Singleton<SoundModality> TheSoundModality;
#endif | [
"[email protected]@2228f7ce-bb98-ac94-67a7-be962254a327"
]
| [
[
[
1,
22
]
]
]
|
b49585827cdaab00c3de23045bcce87a8600e2ee | 028d6009f3beceba80316daa84b628496a210f8d | /uidesigner/com.nokia.sdt.referenceprojects.test/data/lists_3_0/reference/src/lists_3_0ListBox.cpp | f854704196f53f13f540f1d17be9159a3b9a9e80 | []
| no_license | JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp | fa50cafa69d3e317abf0db0f4e3e557150fd88b3 | 4420f338bc4e522c563f8899d81201857236a66a | refs/heads/master | 2020-12-30T16:45:28.474973 | 2010-10-20T16:19:31 | 2010-10-20T16:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,764 | cpp | // [[[ begin generated region: do not modify [Generated System Includes]
#include <barsread.h>
#include <stringloader.h>
#include <aknlists.h>
#include <eikenv.h>
#include <akniconarray.h>
#include <eikclbd.h>
#include <aknviewappui.h>
#include <eikappui.h>
#include <lists_3_0.mbg>
#include <lists_3_0.rsg>
// ]]] end generated region [Generated System Includes]
// [[[ begin generated region: do not modify [Generated User Includes]
#include "lists_3_0ListBox.h"
#include "lists_3_0ListBoxView.h"
#include "lists_3_0.hrh"
// ]]] end generated region [Generated User Includes]
// [[[ begin generated region: do not modify [Generated Constants]
_LIT( Klists_3_0File, "\\resource\\apps\\lists_3_0.mbm" );
// ]]] end generated region [Generated Constants]
/**
* First phase of Symbian two-phase construction. Should not
* contain any code that could leave.
*/
CLists_3_0ListBox::CLists_3_0ListBox()
{
// [[[ begin generated region: do not modify [Generated Contents]
iListBox = NULL;
// ]]] end generated region [Generated Contents]
}
/**
* Destroy child controls.
*/
CLists_3_0ListBox::~CLists_3_0ListBox()
{
// [[[ begin generated region: do not modify [Generated Contents]
delete iListBox;
iListBox = NULL;
// ]]] end generated region [Generated Contents]
}
/**
* Construct the control (first phase).
* Creates an instance and initializes it.
* Instance is not left on cleanup stack.
* @param aRect bounding rectangle
* @param aParent owning parent, or NULL
* @param aCommandObserver command observer
* @return initialized instance of CLists_3_0ListBox
*/
CLists_3_0ListBox* CLists_3_0ListBox::NewL(
const TRect& aRect,
const CCoeControl* aParent,
MEikCommandObserver* aCommandObserver )
{
CLists_3_0ListBox* self = CLists_3_0ListBox::NewLC(
aRect,
aParent,
aCommandObserver );
CleanupStack::Pop( self );
return self;
}
/**
* Construct the control (first phase).
* Creates an instance and initializes it.
* Instance is left on cleanup stack.
* @param aRect The rectangle for this window
* @param aParent owning parent, or NULL
* @param aCommandObserver command observer
* @return new instance of CLists_3_0ListBox
*/
CLists_3_0ListBox* CLists_3_0ListBox::NewLC(
const TRect& aRect,
const CCoeControl* aParent,
MEikCommandObserver* aCommandObserver )
{
CLists_3_0ListBox* self = new ( ELeave ) CLists_3_0ListBox();
CleanupStack::PushL( self );
self->ConstructL( aRect, aParent, aCommandObserver );
return self;
}
/**
* Construct the control (second phase).
* Creates a window to contain the controls and activates it.
* @param aRect bounding rectangle
* @param aCommandObserver command observer
* @param aParent owning parent, or NULL
*/
void CLists_3_0ListBox::ConstructL(
const TRect& aRect,
const CCoeControl* aParent,
MEikCommandObserver* aCommandObserver )
{
if ( aParent == NULL )
{
CreateWindowL();
}
else
{
SetContainerWindowL( *aParent );
}
iFocusControl = NULL;
iCommandObserver = aCommandObserver;
InitializeControlsL();
SetRect( aRect );
ActivateL();
// [[[ begin generated region: do not modify [Post-ActivateL initializations]
// ]]] end generated region [Post-ActivateL initializations]
}
/**
* Return the number of controls in the container (override)
* @return count
*/
TInt CLists_3_0ListBox::CountComponentControls() const
{
return ( int ) ELastControl;
}
/**
* Get the control with the given index (override)
* @param aIndex Control index [0...n) (limited by #CountComponentControls)
* @return Pointer to control
*/
CCoeControl* CLists_3_0ListBox::ComponentControl( TInt aIndex ) const
{
// [[[ begin generated region: do not modify [Generated Contents]
switch ( aIndex )
{
case EListBox:
return iListBox;
}
// ]]] end generated region [Generated Contents]
// handle any user controls here...
return NULL;
}
/**
* Handle resizing of the container. This implementation will lay out
* full-sized controls like list boxes for any screen size, and will layout
* labels, editors, etc. to the size they were given in the UI designer.
* This code will need to be modified to adjust arbitrary controls to
* any screen size.
*/
void CLists_3_0ListBox::SizeChanged()
{
CCoeControl::SizeChanged();
LayoutControls();
// [[[ begin generated region: do not modify [Generated Contents]
// ]]] end generated region [Generated Contents]
}
// [[[ begin generated function: do not modify
/**
* Layout components as specified in the UI Designer
*/
void CLists_3_0ListBox::LayoutControls()
{
iListBox->SetExtent( TPoint( 0, 0 ), iListBox->MinimumSize() );
}
// ]]] end generated function
/**
* Handle key events.
*/
TKeyResponse CLists_3_0ListBox::OfferKeyEventL(
const TKeyEvent& aKeyEvent,
TEventCode aType )
{
// [[[ begin generated region: do not modify [Generated Contents]
if ( aKeyEvent.iCode == EKeyLeftArrow
|| aKeyEvent.iCode == EKeyRightArrow )
{
// Listbox takes all events even if it doesn't use them
return EKeyWasNotConsumed;
}
// ]]] end generated region [Generated Contents]
if ( iFocusControl != NULL
&& iFocusControl->OfferKeyEventL( aKeyEvent, aType ) == EKeyWasConsumed )
{
return EKeyWasConsumed;
}
return CCoeControl::OfferKeyEventL( aKeyEvent, aType );
}
// [[[ begin generated function: do not modify
/**
* Initialize each control upon creation.
*/
void CLists_3_0ListBox::InitializeControlsL()
{
iListBox = new ( ELeave ) CAknDoubleLargeStyleListBox;
iListBox->SetContainerWindowL( *this );
{
TResourceReader reader;
iEikonEnv->CreateResourceReaderLC( reader, R_LISTS_3_0_LIST_BOX_LIST_BOX );
iListBox->ConstructFromResourceL( reader );
CleanupStack::PopAndDestroy(); // reader internal state
}
// the listbox owns the items in the list and will free them
iListBox->Model()->SetOwnershipType( ELbmOwnsItemArray );
// setup the icon array so graphics-style boxes work
SetupListBoxIconsL();
// add list items
AddListBoxResourceArrayItemL( R_LISTS_3_0_LIST_BOX_LISTBOX_ITEM1,
EListBoxLists_3_0List_iconIndex );
AddListBoxResourceArrayItemL( R_LISTS_3_0_LIST_BOX_LISTBOX_ITEM2,
EListBoxLists_3_0List_iconIndex );
iListBox->SetFocus( ETrue );
iFocusControl = iListBox;
}
// ]]] end generated function
/**
* Handle global resource changes, such as scalable UI or skin events (override)
*/
void CLists_3_0ListBox::HandleResourceChange( TInt aType )
{
CCoeControl::HandleResourceChange( aType );
SetRect( iAvkonViewAppUi->View( TUid::Uid( ELists_3_0ListBoxViewId ) )->ClientRect() );
// [[[ begin generated region: do not modify [Generated Contents]
// ]]] end generated region [Generated Contents]
}
/**
* Draw container contents.
*/
void CLists_3_0ListBox::Draw( const TRect& aRect ) const
{
// [[[ begin generated region: do not modify [Generated Contents]
CWindowGc& gc = SystemGc();
gc.Clear( aRect );
// ]]] end generated region [Generated Contents]
}
// [[[ begin generated function: do not modify
/**
* Add a list box item to a list.
*/
void CLists_3_0ListBox::AddListBoxItemL(
CEikTextListBox* aListBox,
const TDesC& aString )
{
CTextListBoxModel* model = aListBox->Model();
CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
itemArray->AppendL( aString );
aListBox->HandleItemAdditionL();
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Get the array of selected item indices, with respect to the list model.
* The array is sorted in ascending order.
* The array should be destroyed with two calls to CleanupStack::PopAndDestroy(),
* the first with no argument (referring to the internal resource) and the
* second with the array pointer.
* @return newly allocated array, which is left on the cleanup stack;
* or NULL for empty list.
*/
RArray< TInt >* CLists_3_0ListBox::GetSelectedListBoxItemsLC( CEikTextListBox* aListBox )
{
CAknFilteredTextListBoxModel* model =
static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
if ( model->NumberOfItems() == 0 )
return NULL;
// get currently selected indices
const CListBoxView::CSelectionIndexArray* selectionIndexes =
aListBox->SelectionIndexes();
TInt selectedIndexesCount = selectionIndexes->Count();
if ( selectedIndexesCount == 0 )
return NULL;
// copy the indices and sort numerically
RArray<TInt>* orderedSelectedIndices =
new (ELeave) RArray< TInt >( selectedIndexesCount );
// push the allocated array
CleanupStack::PushL( orderedSelectedIndices );
// dispose the array resource
CleanupClosePushL( *orderedSelectedIndices );
// see if the search field is enabled
CAknListBoxFilterItems* filter = model->Filter();
if ( filter != NULL )
{
// when filtering enabled, translate indices back to underlying model
for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
{
TInt filteredItem = ( *selectionIndexes ) [ idx ];
TInt actualItem = filter->FilteredItemIndex ( filteredItem );
orderedSelectedIndices->InsertInOrder( actualItem );
}
}
else
{
// the selection indices refer directly to the model
for ( TInt idx = 0; idx < selectedIndexesCount; idx++ )
orderedSelectedIndices->InsertInOrder( ( *selectionIndexes ) [ idx ] );
}
return orderedSelectedIndices;
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Delete the selected item or items from the list box.
*/
void CLists_3_0ListBox::DeleteSelectedListBoxItemsL( CEikTextListBox* aListBox )
{
CAknFilteredTextListBoxModel* model =
static_cast< CAknFilteredTextListBoxModel *> ( aListBox->Model() );
if ( model->NumberOfItems() == 0 )
return;
RArray< TInt >* orderedSelectedIndices = GetSelectedListBoxItemsLC( aListBox );
if ( !orderedSelectedIndices )
return;
// Delete selected items from bottom up so indices don't change on us
CDesCArray* itemArray = static_cast< CDesCArray* > ( model->ItemTextArray() );
TInt currentItem = 0;
for ( TInt idx = orderedSelectedIndices->Count(); idx-- > 0; )
{
currentItem = ( *orderedSelectedIndices )[ idx ];
itemArray->Delete ( currentItem );
}
// dispose the array resources
CleanupStack::PopAndDestroy();
// dispose the array pointer
CleanupStack::PopAndDestroy( orderedSelectedIndices );
// refresh listbox's cursor now that items are deleted
AknListBoxUtils::HandleItemRemovalAndPositionHighlightL(
aListBox, currentItem, ETrue );
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Get the listbox.
*/
CAknDoubleLargeStyleListBox* CLists_3_0ListBox::ListBox()
{
return iListBox;
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Create a list box item with the given column values.
*/
void CLists_3_0ListBox::CreateListBoxItemL( TDes& aBuffer,
TInt aIconIndex,
const TDesC& aMainText,
const TDesC& aSecondaryText )
{
_LIT ( KStringHeader, "%d\t%S\t%S" );
aBuffer.Format( KStringHeader(), aIconIndex, &aMainText, &aSecondaryText );
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Add an item to the list by reading the text items from the array resource
* and setting a single image property (if available) from an index
* in the list box's icon array.
* @param aResourceId id of an ARRAY resource containing the textual
* items in the columns
* @param aIconIndex the index in the icon array, or -1
*/
void CLists_3_0ListBox::AddListBoxResourceArrayItemL( TInt aResourceId, TInt aIconIndex )
{
CDesCArray* array = iCoeEnv->ReadDesCArrayResourceL( aResourceId );
CleanupStack::PushL( array );
// This is intended to be large enough, but if you get
// a USER 11 panic, consider reducing string sizes.
TBuf<512> listString;
CreateListBoxItemL( listString, aIconIndex, ( *array ) [ 0 ],
( *array ) [ 1 ] );
AddListBoxItemL( iListBox, listString );
CleanupStack::PopAndDestroy( array );
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Set up the list's icon array.
*/
void CLists_3_0ListBox::SetupListBoxIconsL()
{
CArrayPtr< CGulIcon >* icons = NULL;
icons = new (ELeave) CAknIconArray( 1 );
CleanupStack::PushL( icons );
CGulIcon* icon;
// for EListBoxLists_3_0List_iconIndex
icon = LoadAndScaleIconL(
Klists_3_0File, EMbmLists_3_0List_icon, EMbmLists_3_0List_icon_mask,
NULL, EAspectRatioPreserved );
CleanupStack::PushL( icon );
icons->AppendL( icon );
CleanupStack::Pop( icon );
CleanupStack::Pop( icons );
if ( icons != NULL )
{
iListBox->ItemDrawer()->ColumnData()->SetIconArray( icons );
}
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* This routine loads and scales a bitmap or icon.
*
* @param aFileName the MBM or MIF filename
* @param aBitmapId the bitmap id
* @param aMaskId the mask id or -1 for none
* @param aSize the TSize for the icon, or NULL to use real size
* @param aScaleMode one of the EAspectRatio* enums when scaling
*
*/
CGulIcon* CLists_3_0ListBox::LoadAndScaleIconL(
const TDesC& aFileName,
TInt aBitmapId,
TInt aMaskId,
TSize* aSize,
TScaleMode aScaleMode )
{
CFbsBitmap* bitmap;
CFbsBitmap* mask;
AknIconUtils::CreateIconL( bitmap, mask, aFileName, aBitmapId, aMaskId );
TSize size;
if ( aSize == NULL )
{
// Use size from the image header. In case of SVG,
// we preserve the image data for a while longer, since ordinarily
// it is disposed at the first GetContentDimensions() or SetSize() call.
AknIconUtils::PreserveIconData( bitmap );
AknIconUtils::GetContentDimensions( bitmap, size );
}
else
{
size = *aSize;
}
AknIconUtils::SetSize( bitmap, size, aScaleMode );
AknIconUtils::SetSize( mask, size, aScaleMode );
if ( aSize == NULL )
{
AknIconUtils::DestroyIconData( bitmap );
}
return CGulIcon::NewL( bitmap, mask );
}
// ]]] end generated function
// [[[ begin generated function: do not modify
/**
* Handle commands relating to markable lists.
*/
TBool CLists_3_0ListBox::HandleMarkableListCommandL( TInt aCommand )
{
return EFalse;
}
// ]]] end generated function
| [
"[email protected]"
]
| [
[
[
1,
507
]
]
]
|
fa44f40ec53954d66659903cdcbec0064cfc8e47 | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/1346.cpp | 832668729570532d8e00400be726e51ec2345524 | []
| no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,654 | cpp | #include<iostream>
#include<map>
#include<cstdlib>
#include<string>
using namespace std;
enum {
InitValue = 0x00ffff,
};
int heromask[16] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768};
typedef struct {
int num;
int degree;
int nextnode[16];
} Node ;
Node matrix[20];
int heronum;
map<int,int> table;
map<string, int> heroname;
int fetch(string &s){
int ret;
if(heroname.find(s) == heroname.end()){
ret = heronum ++;
heroname[s] = ret;
} else {
ret = heroname[s];
}
return ret;
}
int init(){
heronum = 0;
int compnum;
if(!( cin>>compnum) ){
return 0;
}
table.clear();
heroname.clear();
int first, second;
string sf,sn;
memset(matrix,0,sizeof(Node) * 20);
while(compnum--){
cin>> sf >> sn;
first = fetch(sf);
second = fetch(sn);
matrix[first].nextnode[matrix[first].num ++] = second;
matrix[second].degree ++;
}
return 1;
}
int fun(int bitmask, int num){
if(num == 1){
return 1;
}
if(table.find(bitmask) != table.end()){
return table[bitmask];
}
int i,j,t;
int sum = 0;
for(i=0;i<heronum;i++){
if(matrix[i].degree == 0){
for(j=0;j<matrix[i].num;j++){
t = matrix[i].nextnode[j];
matrix[t].degree--;
}
matrix[i].degree = -1;
sum += fun(bitmask - heromask[i],num-1);
matrix[i].degree = 0;
for(j=0;j<matrix[i].num;j++){
t = matrix[i].nextnode[j];
matrix[t].degree++;
}
}
}
table[bitmask] = sum;
return sum;
}
int main(){
while(init()){
cout<<fun(InitValue,heronum)<<endl;
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
ec5d9ae82a894fe842898458ec0b8b2083559c72 | a7a890e753c6f69e8067d16a8cd94ce8327f80b7 | /tserver/server.cpp | a11af31d4a866c1bc734a29f61a9677dfe45d8d1 | []
| 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 | 8,506 | cpp | /******************************************/
/* MMOG programmer's guide */
/* Tutorial game server */
/* Programming: */
/* Teijo Hakala */
/******************************************/
#include "server.h"
#include <fstream>
#include <math.h>
#include <malloc.h>
#include <stdlib.h>
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
float VectorLength(VECTOR2D *vec)
{
return (float) sqrt(vec->x*vec->x + vec->y*vec->y);
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
VECTOR2D VectorSubstract(VECTOR2D *vec1, VECTOR2D *vec2)
{
VECTOR2D vec;
vec.x = vec1->x - vec2->x;
vec.y = vec1->y - vec2->y;
return vec;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
CArmyWarServer::CArmyWarServer()
{
networkServer = new dreamServer;
clientList = NULL;
clients = 0;
realtime = 0;
servertime = 0;
index = 0;
next = NULL;
framenum = 0;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
CArmyWarServer::~CArmyWarServer()
{
delete networkServer;
}
//-----------------------------------------------------------------------------
// Name: InitNetwork()
// Desc: Initialize network
//-----------------------------------------------------------------------------
int CArmyWarServer::InitNetwork()
{
if(dreamSock_Initialize() != 0)
{
LogString("Error initialising Communication Library!");
return 1;
}
LogString("Initialising game");
// Create the game servers on new ports, starting from 30004
int ret = networkServer->Initialise("", 30004);
if(ret == DREAMSOCK_SERVER_ERROR)
{
#ifdef WIN32
char text[64];
sprintf(text, "Could not open server on port %d", networkServer->GetPort());
MessageBox(NULL, text, "Error", MB_OK);
#else
LogString("Could not open server on port %d", networkServer->GetPort());
#endif
return 1;
}
return 0;
}
//-----------------------------------------------------------------------------
// Name: ShutdownNetwork()
// Desc: Shutdown network
//-----------------------------------------------------------------------------
void CArmyWarServer::ShutdownNetwork(void)
{
LogString("Shutting down game server...");
RemoveClients();
networkServer->Uninitialise();
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWarServer::CalculateVelocity(command_t *command, float frametime)
{
float multiplier = 17.0f;
command->vel.x = 0.0f;
command->vel.y = 0.0f;
if(command->key & KEY_UP)
{
command->vel.y += multiplier * frametime;
}
if(command->key & KEY_DOWN)
{
command->vel.y += -multiplier * frametime;
}
if(command->key & KEY_LEFT)
{
command->vel.x += -multiplier * frametime;
}
if(command->key & KEY_RIGHT)
{
command->vel.x += multiplier * frametime;
}
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWarServer::MovePlayer(clientData *client)
{
float clientFrametime;
float multiplier = 17.0f;
clientFrametime = client->command.msec / 1000.0f;;
CalculateVelocity(&client->command, clientFrametime);
// Move the client based on the commands
client->command.origin.x += client->command.vel.x;
client->command.origin.y += client->command.vel.y;
int f = client->netClient->GetIncomingSequence() & (COMMAND_HISTORY_SIZE-1);
client->processedFrame = f;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWarServer::AddClient(void)
{
// First get a pointer to the beginning of client list
clientData *list = clientList;
clientData *prev;
dreamClient *netList = networkServer->GetClientList();
// No clients yet, adding the first one
if(clientList == NULL)
{
LogString("App: Server: Adding first client");
clientList = (clientData *) calloc(1, sizeof(clientData));
clientList->netClient = netList;
memcpy(&clientList->address,
clientList->netClient->GetSocketAddress(), sizeof(struct sockaddr));
if(clients % 2 == 0)
{
//clientList->startPos.x = 46.0f * 32.0f + ((clients/2) * 32.0f);
//clientList->startPos.y = 96.0f * 32.0f;
clientList->startPos.x = 00.0f;
clientList->startPos.y = 00.0f;;
}
else
{
//clientList->startPos.x = 46.0f * 32.0f + ((clients/2) * 32.0f);
//clientList->startPos.y = 4.0f * 32.0f;
clientList->startPos.x = 00.0f;
clientList->startPos.y = 00.0f;;
}
clientList->command.origin.x = clientList->startPos.x;
clientList->command.origin.y = clientList->startPos.y;
clientList->next = NULL;
}
else
{
LogString("App: Server: Adding another client");
prev = list;
list = clientList->next;
netList = netList->next;
while(list != NULL)
{
prev = list;
list = list->next;
netList = netList->next;
}
list = (clientData *) calloc(1, sizeof(clientData));
list->netClient = netList;
memcpy(&list->address,
list->netClient->GetSocketAddress(), sizeof(struct sockaddr));
if(clients % 2 == 0)
{
//list->startPos.x = 46.0f * 32.0f + ((clients/2) * 32.0f);
//list->startPos.y = 96.0f * 32.0f;
list->startPos.x = 00.0f;
list->startPos.y = 00.0f;;
}
else
{
//list->startPos.x = 46.0f * 32.0f + ((clients/2) * 32.0f);
//list->startPos.y = 4.0f * 32.0f;
list->startPos.x = 00.0f;
list->startPos.y = 00.0f;;
}
list->command.origin.x = list->startPos.x;
list->command.origin.y = list->startPos.y;
list->next = NULL;
prev->next = list;
}
clients++;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWarServer::RemoveClient(struct sockaddr *address)
{
clientData *list = clientList;
clientData *prev = NULL;
clientData *next = NULL;
for( ; list != NULL; list = list->next)
{
if(memcmp(&list->address, address, sizeof(address)) == 0)
{
if(prev != NULL)
{
prev->next = list->next;
}
break;
}
prev = list;
}
if(list == clientList)
{
if(list)
{
next = list->next;
free(list);
}
list = NULL;
clientList = next;
}
else
{
if(list)
{
next = list->next;
free(list);
}
list = next;
}
clients--;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWarServer::RemoveClients(void)
{
clientData *list = clientList;
clientData *next;
while(list != NULL)
{
if(list)
{
next = list->next;
free(list);
}
list = next;
}
clientList = NULL;
clients = 0;
}
//-----------------------------------------------------------------------------
// Name: empty()
// Desc:
//-----------------------------------------------------------------------------
void CArmyWarServer::Frame(int msec)
{
realtime += msec;
frametime = msec / 1000.0f;
// Read packets from clients
ReadPackets();
// Wait full 100 ms before allowing to send
if(realtime < servertime)
{
// never let the time get too far off
if(servertime - realtime > 100)
{
realtime = servertime - 100;
}
return;
}
// Bump frame number, and calculate new servertime
framenum++;
servertime = framenum * 100;
if(servertime < realtime)
realtime = servertime;
SendCommand();
}
| [
"jbreslin33@localhost"
]
| [
[
[
1,
366
]
]
]
|
9a9e880cb5ab5e4345d9d444eddf7bbf6e94f162 | a1534c845538131e30363237cdcf131ce2440c6f | /Source/C/VfrCompile/VfrFormPkg.cpp | a0c39c4ab3291e55a718b4d25a17852da00c9e38 | []
| no_license | mcb30/basetools | d570873e063edeb4b790b3f365bd209b19959faf | 2762e82bdf9161aaf6781489a8cf5ba5cc81cb93 | refs/heads/master | 2020-11-28T00:01:58.361792 | 2008-09-03T01:49:49 | 2008-09-03T01:49:49 | 229,654,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,744 | cpp | /** @file
The definition of CFormPkg's member function
Copyright (c) 2004 - 2008, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "stdio.h"
#include "VfrFormPkg.h"
/*
* The definition of CFormPkg's member function
*/
SPendingAssign::SPendingAssign (
IN CHAR8 *Key,
IN VOID *Addr,
IN UINT32 Len,
IN UINT32 LineNo,
IN CHAR8 *Msg
)
{
mKey = NULL;
mAddr = Addr;
mLen = Len;
mFlag = PENDING;
mLineNo = LineNo;
mMsg = NULL;
mNext = NULL;
if (Key != NULL) {
mKey = new CHAR8[strlen (Key) + 1];
if (mKey != NULL) {
strcpy (mKey, Key);
}
}
if (Msg != NULL) {
mMsg = new CHAR8[strlen (Msg) + 1];
if (mMsg != NULL) {
strcpy (mMsg, Msg);
}
}
}
SPendingAssign::~SPendingAssign (
VOID
)
{
if (mKey != NULL) {
delete mKey;
}
mAddr = NULL;
mLen = 0;
mLineNo = 0;
if (mMsg != NULL) {
delete mMsg;
}
mNext = NULL;
}
VOID
SPendingAssign::SetAddrAndLen (
IN VOID *Addr,
IN UINT32 LineNo
)
{
mAddr = Addr;
mLineNo = LineNo;
}
VOID
SPendingAssign::AssignValue (
IN VOID *Addr,
IN UINT32 Len
)
{
memcpy (mAddr, Addr, (mLen < Len ? mLen : Len));
mFlag = ASSIGNED;
}
CHAR8 *
SPendingAssign::GetKey (
VOID
)
{
return mKey;
}
CFormPkg::CFormPkg (
IN UINT32 BufferSize = 4096
)
{
CHAR8 *BufferStart;
CHAR8 *BufferEnd;
SBufferNode *Node;
mPkgLength = 0;
mBufferNodeQueueHead = NULL;
mCurrBufferNode = NULL;
Node = new SBufferNode;
if (Node == NULL) {
return ;
}
BufferStart = new CHAR8[BufferSize];
if (BufferStart == NULL) {
return;
}
BufferEnd = BufferStart + BufferSize;
memset (BufferStart, 0, BufferSize);
Node->mBufferStart = BufferStart;
Node->mBufferEnd = BufferEnd;
Node->mBufferFree = BufferStart;
Node->mNext = NULL;
mBufferSize = BufferSize;
mBufferNodeQueueHead = Node;
mBufferNodeQueueTail = Node;
mCurrBufferNode = Node;
}
CFormPkg::~CFormPkg ()
{
SBufferNode *pBNode;
SPendingAssign *pPNode;
while (mBufferNodeQueueHead != NULL) {
pBNode = mBufferNodeQueueHead;
mBufferNodeQueueHead = mBufferNodeQueueHead->mNext;
if (pBNode->mBufferStart != NULL) {
delete pBNode->mBufferStart;
delete pBNode;
}
}
mBufferNodeQueueTail = NULL;
mCurrBufferNode = NULL;
while (PendingAssignList != NULL) {
pPNode = PendingAssignList;
PendingAssignList = PendingAssignList->mNext;
delete pPNode;
}
PendingAssignList = NULL;
}
CHAR8 *
CFormPkg::IfrBinBufferGet (
IN UINT32 Len
)
{
CHAR8 *BinBuffer = NULL;
if ((Len == 0) || (Len > mBufferSize)) {
return NULL;
}
if ((mCurrBufferNode->mBufferFree + Len) <= mCurrBufferNode->mBufferEnd) {
BinBuffer = mCurrBufferNode->mBufferFree;
mCurrBufferNode->mBufferFree += Len;
} else {
SBufferNode *Node;
Node = new SBufferNode;
if (Node == NULL) {
return NULL;
}
Node->mBufferStart = new CHAR8[mBufferSize];
if (Node->mBufferStart == NULL) {
delete Node;
return NULL;
} else {
memset (Node->mBufferStart, 0, mBufferSize);
Node->mBufferEnd = Node->mBufferStart + mBufferSize;
Node->mBufferFree = Node->mBufferStart;
Node->mNext = NULL;
}
if (mBufferNodeQueueTail == NULL) {
mBufferNodeQueueHead = mBufferNodeQueueTail = Node;
} else {
mBufferNodeQueueTail->mNext = Node;
mBufferNodeQueueTail = Node;
}
mCurrBufferNode = Node;
//
// Now try again.
//
BinBuffer = mCurrBufferNode->mBufferFree;
mCurrBufferNode->mBufferFree += Len;
}
mPkgLength += Len;
return BinBuffer;
}
inline
UINT32
CFormPkg::GetPkgLength (
VOID
)
{
return mPkgLength;
}
VOID
CFormPkg::Open (
VOID
)
{
mReadBufferNode = mBufferNodeQueueHead;
mReadBufferOffset = 0;
}
VOID
CFormPkg::Close (
VOID
)
{
mReadBufferNode = NULL;
mReadBufferOffset = 0;
}
UINT32
CFormPkg::Read (
IN CHAR8 *Buffer,
IN UINT32 Size
)
{
UINT32 Index;
if ((Size == 0) || (Buffer == NULL)) {
return 0;
}
if (mReadBufferNode == NULL) {
return 0;
}
for (Index = 0; Index < Size; Index++) {
if ((mReadBufferNode->mBufferStart + mReadBufferOffset) < mReadBufferNode->mBufferFree) {
Buffer[Index] = mReadBufferNode->mBufferStart[mReadBufferOffset++];
} else {
if ((mReadBufferNode = mReadBufferNode->mNext) == NULL) {
return Index;
} else {
mReadBufferOffset = 0;
Buffer[Index] = mReadBufferNode->mBufferStart[mReadBufferOffset++];
}
}
}
return Size;
}
EFI_VFR_RETURN_CODE
CFormPkg::BuildPkgHdr (
OUT EFI_HII_PACKAGE_HEADER **PkgHdr
)
{
if (PkgHdr == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
if (((*PkgHdr) = new EFI_HII_PACKAGE_HEADER) == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
(*PkgHdr)->Type = EFI_HII_PACKAGE_FORM;
(*PkgHdr)->Length = mPkgLength + sizeof (EFI_HII_PACKAGE_HEADER);
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CFormPkg::BuildPkg (
OUT PACKAGE_DATA &TBuffer
)
{
CHAR8 *Temp;
UINT32 Size;
CHAR8 Buffer[1024];
if (TBuffer.Buffer != NULL) {
delete TBuffer.Buffer;
}
TBuffer.Size = mPkgLength;
TBuffer.Buffer = NULL;
if (TBuffer.Size != 0) {
TBuffer.Buffer = new CHAR8[TBuffer.Size];
} else {
return VFR_RETURN_SUCCESS;
}
Temp = TBuffer.Buffer;
Open ();
while ((Size = Read (Buffer, 1024)) != 0) {
memcpy (Temp, Buffer, Size);
Temp += Size;
}
Close ();
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CFormPkg::BuildPkg (
IN FILE *Output,
IN PACKAGE_DATA *PkgData
)
{
EFI_VFR_RETURN_CODE Ret;
CHAR8 Buffer[1024];
UINT32 Size;
EFI_HII_PACKAGE_HEADER *PkgHdr;
if (Output == NULL) {
return VFR_RETURN_FATAL_ERROR;
}
if ((Ret = BuildPkgHdr(&PkgHdr)) != VFR_RETURN_SUCCESS) {
return Ret;
}
fwrite (PkgHdr, sizeof (EFI_HII_PACKAGE_HEADER), 1, Output);
delete PkgHdr;
if (PkgData == NULL) {
Open ();
while ((Size = Read (Buffer, 1024)) != 0) {
fwrite (Buffer, Size, 1, Output);
}
Close ();
} else {
fwrite (PkgData->Buffer, PkgData->Size, 1, Output);
}
return VFR_RETURN_SUCCESS;
}
VOID
CFormPkg::_WRITE_PKG_LINE (
IN FILE *pFile,
IN UINT32 LineBytes,
IN CHAR8 *LineHeader,
IN CHAR8 *BlkBuf,
IN UINT32 BlkSize
)
{
UINT32 Index;
if ((pFile == NULL) || (LineHeader == NULL) || (BlkBuf == NULL)) {
return;
}
for (Index = 0; Index < BlkSize; Index++) {
if ((Index % LineBytes) == 0) {
fprintf (pFile, "\n%s", LineHeader);
}
fprintf (pFile, "0x%02X, ", (UINT8)BlkBuf[Index]);
}
}
VOID
CFormPkg::_WRITE_PKG_END (
IN FILE *pFile,
IN UINT32 LineBytes,
IN CHAR8 *LineHeader,
IN CHAR8 *BlkBuf,
IN UINT32 BlkSize
)
{
UINT32 Index;
if ((BlkSize == 0) || (pFile == NULL) || (LineHeader == NULL) || (BlkBuf == NULL)) {
return;
}
for (Index = 0; Index < BlkSize - 1; Index++) {
if ((Index % LineBytes) == 0) {
fprintf (pFile, "\n%s", LineHeader);
}
fprintf (pFile, "0x%02X, ", (UINT8)BlkBuf[Index]);
}
if ((Index % LineBytes) == 0) {
fprintf (pFile, "\n%s", LineHeader);
}
fprintf (pFile, "0x%02X\n", (UINT8)BlkBuf[Index]);
}
#define BYTES_PRE_LINE 0x10
EFI_VFR_RETURN_CODE
CFormPkg::GenCFile (
IN CHAR8 *BaseName,
IN FILE *pFile,
IN PACKAGE_DATA *PkgData
)
{
EFI_VFR_RETURN_CODE Ret;
CHAR8 Buffer[BYTES_PRE_LINE * 8];
EFI_HII_PACKAGE_HEADER *PkgHdr;
UINT32 PkgLength = 0;
UINT32 ReadSize = 0;
if ((BaseName == NULL) || (pFile == NULL)) {
return VFR_RETURN_FATAL_ERROR;
}
fprintf (pFile, "\nunsigned char %sBin[] = {\n", BaseName);
if ((Ret = BuildPkgHdr(&PkgHdr)) != VFR_RETURN_SUCCESS) {
return Ret;
}
fprintf (pFile, " // ARRAY LENGTH\n");
PkgLength = PkgHdr->Length + sizeof (UINT32);
_WRITE_PKG_LINE(pFile, BYTES_PRE_LINE, " ", (CHAR8 *)&PkgLength, sizeof (UINT32));
fprintf (pFile, "\n\n // PACKAGE HEADER\n");
_WRITE_PKG_LINE(pFile, BYTES_PRE_LINE, " ", (CHAR8 *)PkgHdr, sizeof (EFI_HII_PACKAGE_HEADER));
PkgLength = sizeof (EFI_HII_PACKAGE_HEADER);
fprintf (pFile, "\n\n // PACKAGE DATA\n");
if (PkgData == NULL) {
Open ();
while ((ReadSize = Read ((CHAR8 *)Buffer, BYTES_PRE_LINE * 8)) != 0) {
PkgLength += ReadSize;
if (PkgLength < PkgHdr->Length) {
_WRITE_PKG_LINE (pFile, BYTES_PRE_LINE, " ", Buffer, ReadSize);
} else {
_WRITE_PKG_END (pFile, BYTES_PRE_LINE, " ", Buffer, ReadSize);
}
}
Close ();
} else {
if (PkgData->Size % BYTES_PRE_LINE != 0) {
PkgLength = PkgData->Size - (PkgData->Size % BYTES_PRE_LINE);
_WRITE_PKG_LINE (pFile, BYTES_PRE_LINE, " ", PkgData->Buffer, PkgLength);
_WRITE_PKG_END (pFile, BYTES_PRE_LINE, " ", PkgData->Buffer + PkgLength, PkgData->Size % BYTES_PRE_LINE);
} else {
PkgLength = PkgData->Size - BYTES_PRE_LINE;
_WRITE_PKG_LINE (pFile, BYTES_PRE_LINE, " ", PkgData->Buffer, PkgLength);
_WRITE_PKG_END (pFile, BYTES_PRE_LINE, " ", PkgData->Buffer + PkgLength, BYTES_PRE_LINE);
}
}
delete PkgHdr;
fprintf (pFile, "\n};\n");
return VFR_RETURN_SUCCESS;
}
EFI_VFR_RETURN_CODE
CFormPkg::AssignPending (
IN CHAR8 *Key,
IN VOID *ValAddr,
IN UINT32 ValLen,
IN UINT32 LineNo,
IN CHAR8 *Msg
)
{
SPendingAssign *pNew;
pNew = new SPendingAssign (Key, ValAddr, ValLen, LineNo, Msg);
if (pNew == NULL) {
return VFR_RETURN_OUT_FOR_RESOURCES;
}
pNew->mNext = PendingAssignList;
PendingAssignList = pNew;
return VFR_RETURN_SUCCESS;
}
VOID
CFormPkg::DoPendingAssign (
IN CHAR8 *Key,
IN VOID *ValAddr,
IN UINT32 ValLen
)
{
SPendingAssign *pNode;
if ((Key == NULL) || (ValAddr == NULL)) {
return;
}
for (pNode = PendingAssignList; pNode != NULL; pNode = pNode->mNext) {
if (strcmp (pNode->mKey, Key) == 0) {
pNode->AssignValue (ValAddr, ValLen);
}
}
}
bool
CFormPkg::HavePendingUnassigned (
VOID
)
{
SPendingAssign *pNode;
for (pNode = PendingAssignList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mFlag == PENDING) {
return TRUE;
}
}
return FALSE;
}
VOID
CFormPkg::PendingAssignPrintAll (
VOID
)
{
SPendingAssign *pNode;
for (pNode = PendingAssignList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mFlag == PENDING) {
gCVfrErrorHandle.PrintMsg (pNode->mLineNo, pNode->mKey, "Error", pNode->mMsg);
}
}
}
EFI_VFR_RETURN_CODE
CFormPkg::DeclarePendingQuestion (
IN CVfrVarDataTypeDB &lCVfrVarDataTypeDB,
IN CVfrDataStorage &lCVfrDataStorage,
IN CVfrQuestionDB &lCVfrQuestionDB,
IN EFI_GUID *LocalFormSetGuid,
IN UINT32 LineNo
)
{
SPendingAssign *pNode;
CHAR8 *VarStr;
UINT32 ArrayIdx;
CHAR8 FName[MAX_NAME_LEN];
EFI_VFR_RETURN_CODE ReturnCode;
EFI_VFR_VARSTORE_TYPE VarStoreType = EFI_VFR_VARSTORE_INVALID;
for (pNode = PendingAssignList; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mFlag == PENDING) {
//
// declare this question as Numeric in SuppressIf True
//
// SuppressIf
CIfrSuppressIf SIObj;
SIObj.SetLineNo (LineNo);
//TrueOpcode
CIfrTrue TObj (LineNo);
//Numeric qeustion
CIfrNumeric CNObj;
EFI_VARSTORE_INFO Info;
EFI_QUESTION_ID QId = EFI_QUESTION_ID_INVALID;
CNObj.SetLineNo (LineNo);
CNObj.SetPrompt (0x0);
CNObj.SetHelp (0x0);
//
// Register this question, assume it is normal question, not date or time question
//
VarStr = pNode->mKey;
ReturnCode = lCVfrQuestionDB.RegisterQuestion (NULL, VarStr, QId);
if (ReturnCode != VFR_RETURN_SUCCESS) {
gCVfrErrorHandle.HandleError (ReturnCode, pNode->mLineNo, pNode->mKey);
return ReturnCode;
}
#ifdef VFREXP_DEBUG
printf ("Undefined Question name is %s and Id is 0x%x\n", VarStr, QId);
#endif
//
// Get Question Info, framework vfr VarName == StructName
//
ReturnCode = lCVfrVarDataTypeDB.ExtractFieldNameAndArrary (VarStr, FName, ArrayIdx);
if (ReturnCode != VFR_RETURN_SUCCESS) {
gCVfrErrorHandle.PrintMsg (pNode->mLineNo, pNode->mKey, "Error", "Var string is not the valid C variable");
return ReturnCode;
}
//
// Get VarStoreType
//
ReturnCode = lCVfrDataStorage.GetVarStoreType (FName, VarStoreType);
if (ReturnCode == VFR_RETURN_UNDEFINED) {
lCVfrDataStorage.DeclareBufferVarStore (
FName,
LocalFormSetGuid,
&lCVfrVarDataTypeDB,
FName,
EFI_VARSTORE_ID_INVALID,
FALSE
);
ReturnCode = lCVfrDataStorage.GetVarStoreType (FName, VarStoreType);
}
if (ReturnCode != VFR_RETURN_SUCCESS) {
gCVfrErrorHandle.PrintMsg (pNode->mLineNo, FName, "Error", "Var Store Type is not defined");
return ReturnCode;
}
ReturnCode = lCVfrDataStorage.GetVarStoreId (FName, &Info.mVarStoreId);
if (ReturnCode != VFR_RETURN_SUCCESS) {
gCVfrErrorHandle.PrintMsg (pNode->mLineNo, FName, "Error", "Var Store Type is not defined");
return ReturnCode;
}
if (*VarStr == '\0' && ArrayIdx != INVALID_ARRAY_INDEX) {
ReturnCode = lCVfrDataStorage.GetNameVarStoreInfo (&Info, ArrayIdx);
} else {
if (VarStoreType == EFI_VFR_VARSTORE_EFI) {
ReturnCode = lCVfrDataStorage.GetEfiVarStoreInfo (&Info);
} else if (VarStoreType == EFI_VFR_VARSTORE_BUFFER) {
VarStr = pNode->mKey;
ReturnCode = lCVfrVarDataTypeDB.GetDataFieldInfo (VarStr, Info.mInfo.mVarOffset, Info.mVarType, Info.mVarTotalSize);
} else {
ReturnCode = VFR_RETURN_UNSUPPORTED;
}
}
if (ReturnCode != VFR_RETURN_SUCCESS) {
gCVfrErrorHandle.HandleError (ReturnCode, pNode->mLineNo, pNode->mKey);
return ReturnCode;
}
CNObj.SetQuestionId (QId);
CNObj.SetVarStoreInfo (&Info);
CNObj.SetFlags (0, Info.mVarType);
//
// For undefined Efi VarStore type question
// Append the extended guided opcode to contain VarName
//
if (VarStoreType == EFI_VFR_VARSTORE_EFI) {
CIfrVarEqName CVNObj (QId, Info.mInfo.mVarName);
CVNObj.SetLineNo (LineNo);
}
//
// End for Numeric
//
CIfrEnd CEObj;
CEObj.SetLineNo (LineNo);
//
// End for SuppressIf
//
CIfrEnd SEObj;
SEObj.SetLineNo (LineNo);
}
}
return VFR_RETURN_SUCCESS;
}
CFormPkg gCFormPkg;
SIfrRecord::SIfrRecord (
VOID
)
{
mIfrBinBuf = NULL;
mBinBufLen = 0;
mLineNo = 0xFFFFFFFF;
mOffset = 0xFFFFFFFF;
mNext = NULL;
}
SIfrRecord::~SIfrRecord (
VOID
)
{
if (mIfrBinBuf != NULL) {
//
// IfrRecord to point to form data buffer.
//
mIfrBinBuf = NULL;
}
mLineNo = 0xFFFFFFFF;
mOffset = 0xFFFFFFFF;
mBinBufLen = 0;
mNext = NULL;
}
CIfrRecordInfoDB::CIfrRecordInfoDB (
VOID
)
{
mSwitch = TRUE;
mRecordCount = EFI_IFR_RECORDINFO_IDX_START;
mIfrRecordListHead = NULL;
mIfrRecordListTail = NULL;
}
CIfrRecordInfoDB::~CIfrRecordInfoDB (
VOID
)
{
SIfrRecord *pNode;
while (mIfrRecordListHead != NULL) {
pNode = mIfrRecordListHead;
mIfrRecordListHead = mIfrRecordListHead->mNext;
delete pNode;
}
}
SIfrRecord *
CIfrRecordInfoDB::GetRecordInfoFromIdx (
IN UINT32 RecordIdx
)
{
UINT32 Idx;
SIfrRecord *pNode = NULL;
if (RecordIdx == EFI_IFR_RECORDINFO_IDX_INVALUD) {
return NULL;
}
for (Idx = (EFI_IFR_RECORDINFO_IDX_START + 1), pNode = mIfrRecordListHead;
(Idx != RecordIdx) && (pNode != NULL);
Idx++, pNode = pNode->mNext)
;
return pNode;
}
UINT32
CIfrRecordInfoDB::IfrRecordRegister (
IN UINT32 LineNo,
IN CHAR8 *IfrBinBuf,
IN UINT8 BinBufLen,
IN UINT32 Offset
)
{
SIfrRecord *pNew;
if (mSwitch == FALSE) {
return EFI_IFR_RECORDINFO_IDX_INVALUD;
}
if ((pNew = new SIfrRecord) == NULL) {
return EFI_IFR_RECORDINFO_IDX_INVALUD;
}
if (mIfrRecordListHead == NULL) {
mIfrRecordListHead = pNew;
mIfrRecordListTail = pNew;
} else {
mIfrRecordListTail->mNext = pNew;
mIfrRecordListTail = pNew;
}
mRecordCount++;
return mRecordCount;
}
VOID
CIfrRecordInfoDB::IfrRecordInfoUpdate (
IN UINT32 RecordIdx,
IN UINT32 LineNo,
IN CHAR8 *BinBuf,
IN UINT8 BinBufLen,
IN UINT32 Offset
)
{
SIfrRecord *pNode;
if ((pNode = GetRecordInfoFromIdx (RecordIdx)) == NULL) {
return;
}
pNode->mLineNo = LineNo;
pNode->mOffset = Offset;
pNode->mBinBufLen = BinBufLen;
pNode->mIfrBinBuf = BinBuf;
}
VOID
CIfrRecordInfoDB::IfrRecordOutput (
OUT PACKAGE_DATA &TBuffer
)
{
CHAR8 *Temp;
SIfrRecord *pNode;
if (TBuffer.Buffer != NULL) {
delete TBuffer.Buffer;
}
TBuffer.Size = 0;
TBuffer.Buffer = NULL;
if (mSwitch == FALSE) {
return;
}
for (pNode = mIfrRecordListHead; pNode != NULL; pNode = pNode->mNext) {
TBuffer.Size += pNode->mBinBufLen;
}
if (TBuffer.Size != 0) {
TBuffer.Buffer = new CHAR8[TBuffer.Size];
} else {
return;
}
Temp = TBuffer.Buffer;
for (pNode = mIfrRecordListHead; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mIfrBinBuf != NULL) {
memcpy (Temp, pNode->mIfrBinBuf, pNode->mBinBufLen);
Temp += pNode->mBinBufLen;
}
}
return;
}
VOID
CIfrRecordInfoDB::IfrRecordOutput (
IN FILE *File,
IN UINT32 LineNo
)
{
SIfrRecord *pNode;
UINT8 Index;
UINT32 TotalSize;
if (mSwitch == FALSE) {
return;
}
if (File == NULL) {
return;
}
TotalSize = 0;
for (pNode = mIfrRecordListHead; pNode != NULL; pNode = pNode->mNext) {
if (pNode->mLineNo == LineNo || LineNo == 0) {
fprintf (File, ">%08X: ", pNode->mOffset);
TotalSize += pNode->mBinBufLen;
if (pNode->mIfrBinBuf != NULL) {
for (Index = 0; Index < pNode->mBinBufLen; Index++) {
fprintf (File, "%02X ", (UINT8) pNode->mIfrBinBuf[Index]);
}
}
fprintf (File, "\n");
}
}
if (LineNo == 0) {
fprintf (File, "\nTotal Size of all record is 0x%08X\n", TotalSize);
}
}
//
// for framework vfr file
// adjust opcode sequence for uefi IFR format
// adjust inconsistent and varstore into the right position.
//
BOOLEAN
CIfrRecordInfoDB::CheckQuestionOpCode (
IN UINT8 OpCode
)
{
switch (OpCode) {
case EFI_IFR_CHECKBOX_OP:
case EFI_IFR_NUMERIC_OP:
case EFI_IFR_PASSWORD_OP:
case EFI_IFR_ONE_OF_OP:
case EFI_IFR_ACTION_OP:
case EFI_IFR_STRING_OP:
case EFI_IFR_DATE_OP:
case EFI_IFR_TIME_OP:
case EFI_IFR_ORDERED_LIST_OP:
return TRUE;
default:
return FALSE;
}
}
BOOLEAN
CIfrRecordInfoDB::CheckIdOpCode (
IN UINT8 OpCode
)
{
switch (OpCode) {
case EFI_IFR_EQ_ID_VAL_OP:
case EFI_IFR_EQ_ID_ID_OP:
case EFI_IFR_EQ_ID_LIST_OP:
case EFI_IFR_QUESTION_REF1_OP:
return TRUE;
default:
return FALSE;
}
}
EFI_QUESTION_ID
CIfrRecordInfoDB::GetOpcodeQuestionId (
IN EFI_IFR_OP_HEADER *OpHead
)
{
EFI_IFR_QUESTION_HEADER *QuestionHead;
QuestionHead = (EFI_IFR_QUESTION_HEADER *) (OpHead + 1);
return QuestionHead->QuestionId;
}
EFI_VFR_RETURN_CODE
CIfrRecordInfoDB::IfrRecordAdjust (
VOID
)
{
SIfrRecord *pNode, *preNode;
SIfrRecord *uNode, *tNode;
EFI_IFR_OP_HEADER *OpHead, *tOpHead;
EFI_QUESTION_ID QuestionId;
UINT32 StackCount;
UINT32 QuestionScope;
UINT32 OpcodeOffset;
CHAR8 ErrorMsg[MAX_STRING_LEN] = {0, };
EFI_VFR_RETURN_CODE Status;
//
// Init local variable
//
Status = VFR_RETURN_SUCCESS;
pNode = mIfrRecordListHead;
preNode = pNode;
QuestionScope = 0;
while (pNode != NULL) {
OpHead = (EFI_IFR_OP_HEADER *) pNode->mIfrBinBuf;
//
// make sure the inconsistent opcode in question scope
//
if (QuestionScope > 0) {
QuestionScope += OpHead->Scope;
if (OpHead->OpCode == EFI_IFR_END_OP) {
QuestionScope --;
}
}
if (CheckQuestionOpCode (OpHead->OpCode)) {
QuestionScope = 1;
}
//
// for the inconsistent opcode not in question scope, adjust it
//
if (OpHead->OpCode == EFI_IFR_INCONSISTENT_IF_OP && QuestionScope == 0) {
//
// for inconsistent opcode not in question scope
//
//
// Count inconsistent opcode Scope
//
StackCount = OpHead->Scope;
QuestionId = EFI_QUESTION_ID_INVALID;
tNode = pNode;
while (tNode != NULL && StackCount > 0) {
tNode = tNode->mNext;
tOpHead = (EFI_IFR_OP_HEADER *) tNode->mIfrBinBuf;
//
// Calculate Scope Number
//
StackCount += tOpHead->Scope;
if (tOpHead->OpCode == EFI_IFR_END_OP) {
StackCount --;
}
//
// by IdEqual opcode to get QuestionId
//
if (QuestionId == EFI_QUESTION_ID_INVALID &&
CheckIdOpCode (tOpHead->OpCode)) {
QuestionId = *(EFI_QUESTION_ID *) (tOpHead + 1);
}
}
if (tNode == NULL || QuestionId == EFI_QUESTION_ID_INVALID) {
//
// report error; not found
//
sprintf (ErrorMsg, "Inconsistent OpCode Record list invalid QuestionId is 0x%X", QuestionId);
gCVfrErrorHandle.PrintMsg (0, NULL, "Error", ErrorMsg);
Status = VFR_RETURN_MISMATCHED;
break;
}
//
// extract inconsistent opcode list
// pNode is Incosistent opcode, tNode is End Opcode
//
//
// insert inconsistent opcode list into the right question scope by questionid
//
for (uNode = mIfrRecordListHead; uNode != NULL; uNode = uNode->mNext) {
tOpHead = (EFI_IFR_OP_HEADER *) uNode->mIfrBinBuf;
if (CheckQuestionOpCode (tOpHead->OpCode) &&
(QuestionId == GetOpcodeQuestionId (tOpHead))) {
break;
}
}
//
// insert inconsistent opcode list and check LATE_CHECK flag
//
if (uNode != NULL) {
if ((((EFI_IFR_QUESTION_HEADER *)(tOpHead + 1))->Flags & 0x20) != 0) {
//
// if LATE_CHECK flag is set, change inconsistent to nosumbit
//
OpHead->OpCode = EFI_IFR_NO_SUBMIT_IF_OP;
}
//
// skip the default storage for Date and Time
//
if ((uNode->mNext != NULL) && (*uNode->mNext->mIfrBinBuf == EFI_IFR_DEFAULT_OP)) {
uNode = uNode->mNext;
}
preNode->mNext = tNode->mNext;
tNode->mNext = uNode->mNext;
uNode->mNext = pNode;
//
// reset pNode to head list, scan the whole list again.
//
pNode = mIfrRecordListHead;
preNode = pNode;
QuestionScope = 0;
continue;
} else {
//
// not found matched question id, report error
//
sprintf (ErrorMsg, "QuestionId required by Inconsistent OpCode is not found. QuestionId is 0x%X", QuestionId);
gCVfrErrorHandle.PrintMsg (0, NULL, "Error", ErrorMsg);
Status = VFR_RETURN_MISMATCHED;
break;
}
} else if (OpHead->OpCode == EFI_IFR_VARSTORE_OP ||
OpHead->OpCode == EFI_IFR_VARSTORE_EFI_OP) {
//
// for new added group of varstore opcode
//
tNode = pNode;
while (tNode->mNext != NULL) {
tOpHead = (EFI_IFR_OP_HEADER *) tNode->mNext->mIfrBinBuf;
if (tOpHead->OpCode != EFI_IFR_VARSTORE_OP &&
tOpHead->OpCode != EFI_IFR_VARSTORE_EFI_OP) {
break;
}
tNode = tNode->mNext;
}
if (tNode->mNext == NULL) {
//
// invalid IfrCode, IfrCode end by EndOpCode
//
gCVfrErrorHandle.PrintMsg (0, NULL, "Error", "No found End Opcode in the end");
Status = VFR_RETURN_MISMATCHED;
break;
}
if (tOpHead->OpCode != EFI_IFR_END_OP) {
//
// not new added varstore, which are not needed to be adjust.
//
preNode = tNode;
pNode = tNode->mNext;
continue;
} else {
//
// move new added varstore opcode to the position befor form opcode
// varstore opcode between pNode and tNode
//
//
// search form opcode from begin
//
for (uNode = mIfrRecordListHead; uNode->mNext != NULL; uNode = uNode->mNext) {
tOpHead = (EFI_IFR_OP_HEADER *) uNode->mNext->mIfrBinBuf;
if (tOpHead->OpCode == EFI_IFR_FORM_OP) {
break;
}
}
//
// Insert varstore opcode beform form opcode if form opcode is found
//
if (uNode->mNext != NULL) {
preNode->mNext = tNode->mNext;
tNode->mNext = uNode->mNext;
uNode->mNext = pNode;
//
// reset pNode to head list, scan the whole list again.
//
pNode = mIfrRecordListHead;
preNode = pNode;
QuestionScope = 0;
continue;
} else {
//
// not found form, continue scan IfrRecord list
//
preNode = tNode;
pNode = tNode->mNext;
continue;
}
}
}
//
// next node
//
preNode = pNode;
pNode = pNode->mNext;
}
//
// Update Ifr Opcode Offset
//
if (Status == VFR_RETURN_SUCCESS) {
OpcodeOffset = 0;
for (pNode = mIfrRecordListHead; pNode != NULL; pNode = pNode->mNext) {
pNode->mOffset = OpcodeOffset;
OpcodeOffset += pNode->mBinBufLen;
}
}
return Status;
}
CIfrRecordInfoDB gCIfrRecordInfoDB;
VOID
CIfrObj::_EMIT_PENDING_OBJ (
VOID
)
{
CHAR8 *ObjBinBuf = NULL;
//
// do nothing
//
if (!mDelayEmit || !gCreateOp) {
return;
}
mPkgOffset = gCFormPkg.GetPkgLength ();
//
// update data buffer to package data
//
ObjBinBuf = gCFormPkg.IfrBinBufferGet (mObjBinLen);
if (ObjBinBuf != NULL) {
memcpy (ObjBinBuf, mObjBinBuf, mObjBinLen);
}
//
// update bin buffer to package data buffer
//
if (mObjBinBuf != NULL) {
delete mObjBinBuf;
mObjBinBuf = ObjBinBuf;
}
mDelayEmit = FALSE;
}
/*
* The definition of CIfrObj's member function
*/
static struct {
UINT8 mSize;
UINT8 mScope;
} gOpcodeSizesScopeTable[] = {
{ 0, 0 }, // EFI_IFR_INVALID - 0x00
{ sizeof (EFI_IFR_FORM), 1 }, // EFI_IFR_FORM_OP
{ sizeof (EFI_IFR_SUBTITLE), 1 }, // EFI_IFR_SUBTITLE_OP
{ sizeof (EFI_IFR_TEXT), 0 }, // EFI_IFR_TEXT_OP
{ sizeof (EFI_IFR_IMAGE), 0 }, // EFI_IFR_IMAGE_OP
{ sizeof (EFI_IFR_ONE_OF), 1 }, // EFI_IFR_ONE_OF_OP - 0x05
{ sizeof (EFI_IFR_CHECKBOX), 1}, // EFI_IFR_CHECKBOX_OP
{ sizeof (EFI_IFR_NUMERIC), 1 }, // EFI_IFR_NUMERIC_OP
{ sizeof (EFI_IFR_PASSWORD), 1 }, // EFI_IFR_PASSWORD_OP
{ sizeof (EFI_IFR_ONE_OF_OPTION), 0 }, // EFI_IFR_ONE_OF_OPTION_OP
{ sizeof (EFI_IFR_SUPPRESS_IF), 1 }, // EFI_IFR_SUPPRESS_IF - 0x0A
{ sizeof (EFI_IFR_LOCKED), 0 }, // EFI_IFR_LOCKED_OP
{ sizeof (EFI_IFR_ACTION), 1 }, // EFI_IFR_ACTION_OP
{ sizeof (EFI_IFR_RESET_BUTTON), 1 }, // EFI_IFR_RESET_BUTTON_OP
{ sizeof (EFI_IFR_FORM_SET), 1 }, // EFI_IFR_FORM_SET_OP -0xE
{ sizeof (EFI_IFR_REF), 0 }, // EFI_IFR_REF_OP
{ sizeof (EFI_IFR_NO_SUBMIT_IF), 1}, // EFI_IFR_NO_SUBMIT_IF_OP -0x10
{ sizeof (EFI_IFR_INCONSISTENT_IF), 1 }, // EFI_IFR_INCONSISTENT_IF_OP
{ sizeof (EFI_IFR_EQ_ID_VAL), 0 }, // EFI_IFR_EQ_ID_VAL_OP
{ sizeof (EFI_IFR_EQ_ID_ID), 0 }, // EFI_IFR_EQ_ID_ID_OP
{ sizeof (EFI_IFR_EQ_ID_LIST), 0 }, // EFI_IFR_EQ_ID_LIST_OP - 0x14
{ sizeof (EFI_IFR_AND), 0 }, // EFI_IFR_AND_OP
{ sizeof (EFI_IFR_OR), 0 }, // EFI_IFR_OR_OP
{ sizeof (EFI_IFR_NOT), 0 }, // EFI_IFR_NOT_OP
{ sizeof (EFI_IFR_RULE), 1 }, // EFI_IFR_RULE_OP
{ sizeof (EFI_IFR_GRAY_OUT_IF), 1 }, // EFI_IFR_GRAYOUT_IF_OP - 0x19
{ sizeof (EFI_IFR_DATE), 1 }, // EFI_IFR_DATE_OP
{ sizeof (EFI_IFR_TIME), 1 }, // EFI_IFR_TIME_OP
{ sizeof (EFI_IFR_STRING), 1 }, // EFI_IFR_STRING_OP
{ sizeof (EFI_IFR_REFRESH), 1 }, // EFI_IFR_REFRESH_OP
{ sizeof (EFI_IFR_DISABLE_IF), 1 }, // EFI_IFR_DISABLE_IF_OP - 0x1E
{ 0, 0 }, // 0x1F
{ sizeof (EFI_IFR_TO_LOWER), 0 }, // EFI_IFR_TO_LOWER_OP - 0x20
{ sizeof (EFI_IFR_TO_UPPER), 0 }, // EFI_IFR_TO_UPPER_OP - 0x21
{ 0, 0 }, // 0x22
{ sizeof (EFI_IFR_ORDERED_LIST), 1 }, // EFI_IFR_ORDERED_LIST_OP - 0x23
{ sizeof (EFI_IFR_VARSTORE), 0 }, // EFI_IFR_VARSTORE_OP
{ sizeof (EFI_IFR_VARSTORE_NAME_VALUE), 0 }, // EFI_IFR_VARSTORE_NAME_VALUE_OP
{ sizeof (EFI_IFR_VARSTORE_EFI), 0 }, // EFI_IFR_VARSTORE_EFI_OP
{ sizeof (EFI_IFR_VARSTORE_DEVICE), 1 }, // EFI_IFR_VARSTORE_DEVICE_OP
{ sizeof (EFI_IFR_VERSION), 0 }, // EFI_IFR_VERSION_OP - 0x28
{ sizeof (EFI_IFR_END), 0 }, // EFI_IFR_END_OP
{ sizeof (EFI_IFR_MATCH), 1 }, // EFI_IFR_MATCH_OP - 0x2A
{ 0, 0 }, { 0, 0} , { 0, 0} , { 0, 0} , // 0x2B ~ 0x2E
{ sizeof (EFI_IFR_EQUAL), 0 }, // EFI_IFR_EQUAL_OP - 0x2F
{ sizeof (EFI_IFR_NOT_EQUAL), 0 }, // EFI_IFR_NOT_EQUAL_OP
{ sizeof (EFI_IFR_GREATER_THAN), 0 }, // EFI_IFR_GREATER_THAN_OP
{ sizeof (EFI_IFR_GREATER_EQUAL), 0 }, // EFI_IFR_GREATER_EQUAL_OP
{ sizeof (EFI_IFR_LESS_THAN), 0 }, // EFI_IFR_LESS_THAN_OP
{ sizeof (EFI_IFR_LESS_EQUAL), 0 }, // EFI_IFR_LESS_EQUAL_OP - 0x34
{ sizeof (EFI_IFR_BITWISE_AND), 0 }, // EFI_IFR_BITWISE_AND_OP
{ sizeof (EFI_IFR_BITWISE_OR), 0 }, // EFI_IFR_BITWISE_OR_OP
{ sizeof (EFI_IFR_BITWISE_NOT), 0 }, // EFI_IFR_BITWISE_NOT_OP
{ sizeof (EFI_IFR_SHIFT_LEFT), 0 }, // EFI_IFR_SHIFT_LEFT_OP
{ sizeof (EFI_IFR_SHIFT_RIGHT), 0 }, // EFI_IFR_SHIFT_RIGHT_OP
{ sizeof (EFI_IFR_ADD), 0 }, // EFI_IFR_ADD_OP - 0x3A
{ sizeof (EFI_IFR_SUBTRACT), 0 }, // EFI_IFR_SUBTRACT_OP
{ sizeof (EFI_IFR_MULTIPLY), 0 }, // EFI_IFR_MULTIPLY_OP
{ sizeof (EFI_IFR_DIVIDE), 0 }, // EFI_IFR_DIVIDE_OP
{ sizeof (EFI_IFR_MODULO), 0 }, // EFI_IFR_MODULO_OP - 0x3E
{ sizeof (EFI_IFR_RULE_REF), 0 }, // EFI_IFR_RULE_REF_OP
{ sizeof (EFI_IFR_QUESTION_REF1), 0 }, // EFI_IFR_QUESTION_REF1_OP
{ sizeof (EFI_IFR_QUESTION_REF2), 0 }, // EFI_IFR_QUESTION_REF2_OP - 0x41
{ sizeof (EFI_IFR_UINT8), 0}, // EFI_IFR_UINT8
{ sizeof (EFI_IFR_UINT16), 0}, // EFI_IFR_UINT16
{ sizeof (EFI_IFR_UINT32), 0}, // EFI_IFR_UINT32
{ sizeof (EFI_IFR_UINT64), 0}, // EFI_IFR_UTNT64
{ sizeof (EFI_IFR_TRUE), 0 }, // EFI_IFR_TRUE_OP - 0x46
{ sizeof (EFI_IFR_FALSE), 0 }, // EFI_IFR_FALSE_OP
{ sizeof (EFI_IFR_TO_UINT), 0 }, // EFI_IFR_TO_UINT_OP
{ sizeof (EFI_IFR_TO_STRING), 0 }, // EFI_IFR_TO_STRING_OP
{ sizeof (EFI_IFR_TO_BOOLEAN), 0 }, // EFI_IFR_TO_BOOLEAN_OP
{ sizeof (EFI_IFR_MID), 0 }, // EFI_IFR_MID_OP
{ sizeof (EFI_IFR_FIND), 0 }, // EFI_IFR_FIND_OP
{ sizeof (EFI_IFR_TOKEN), 0 }, // EFI_IFR_TOKEN_OP
{ sizeof (EFI_IFR_STRING_REF1), 0 }, // EFI_IFR_STRING_REF1_OP - 0x4E
{ sizeof (EFI_IFR_STRING_REF2), 0 }, // EFI_IFR_STRING_REF2_OP
{ sizeof (EFI_IFR_CONDITIONAL), 0 }, // EFI_IFR_CONDITIONAL_OP
{ sizeof (EFI_IFR_QUESTION_REF3), 0 }, // EFI_IFR_QUESTION_REF3_OP
{ sizeof (EFI_IFR_ZERO), 0 }, // EFI_IFR_ZERO_OP
{ sizeof (EFI_IFR_ONE), 0 }, // EFI_IFR_ONE_OP
{ sizeof (EFI_IFR_ONES), 0 }, // EFI_IFR_ONES_OP
{ sizeof (EFI_IFR_UNDEFINED), 0 }, // EFI_IFR_UNDEFINED_OP
{ sizeof (EFI_IFR_LENGTH), 0 }, // EFI_IFR_LENGTH_OP
{ sizeof (EFI_IFR_DUP), 0 }, // EFI_IFR_DUP_OP - 0x57
{ sizeof (EFI_IFR_THIS), 0 }, // EFI_IFR_THIS_OP
{ sizeof (EFI_IFR_SPAN), 0 }, // EFI_IFR_SPAN_OP
{ sizeof (EFI_IFR_VALUE), 1 }, // EFI_IFR_VALUE_OP
{ sizeof (EFI_IFR_DEFAULT), 0 }, // EFI_IFR_DEFAULT_OP
{ sizeof (EFI_IFR_DEFAULTSTORE), 0 }, // EFI_IFR_DEFAULTSTORE_OP - 0x5C
{ 0, 0}, // 0x5D
{ sizeof (EFI_IFR_CATENATE), 0 }, // EFI_IFR_CATENATE_OP
{ sizeof (EFI_IFR_GUID), 0 }, // EFI_IFR_GUID_OP
};
#ifdef CIFROBJ_DEUBG
static struct {
CHAR8 *mIfrName;
} gIfrObjPrintDebugTable[] = {
"EFI_IFR_INVALID", "EFI_IFR_FORM", "EFI_IFR_SUBTITLE", "EFI_IFR_TEXT", "EFI_IFR_IMAGE", "EFI_IFR_ONE_OF",
"EFI_IFR_CHECKBOX", "EFI_IFR_NUMERIC", "EFI_IFR_PASSWORD", "EFI_IFR_ONE_OF_OPTION", "EFI_IFR_SUPPRESS_IF", "EFI_IFR_LOCKED",
"EFI_IFR_ACTION", "EFI_IFR_RESET_BUTTON", "EFI_IFR_FORM_SET", "EFI_IFR_REF", "EFI_IFR_NO_SUBMIT_IF", "EFI_IFR_INCONSISTENT_IF",
"EFI_IFR_EQ_ID_VAL", "EFI_IFR_EQ_ID_ID", "EFI_IFR_EQ_ID_LIST", "EFI_IFR_AND", "EFI_IFR_OR", "EFI_IFR_NOT",
"EFI_IFR_RULE", "EFI_IFR_GRAY_OUT_IF", "EFI_IFR_DATE", "EFI_IFR_TIME", "EFI_IFR_STRING", "EFI_IFR_REFRESH",
"EFI_IFR_DISABLE_IF", "EFI_IFR_INVALID", "EFI_IFR_TO_LOWER", "EFI_IFR_TO_UPPER", "EFI_IFR_INVALID", "EFI_IFR_ORDERED_LIST",
"EFI_IFR_VARSTORE", "EFI_IFR_VARSTORE_NAME_VALUE", "EFI_IFR_VARSTORE_EFI", "EFI_IFR_VARSTORE_DEVICE", "EFI_IFR_VERSION", "EFI_IFR_END",
"EFI_IFR_MATCH", "EFI_IFR_INVALID", "EFI_IFR_INVALID", "EFI_IFR_INVALID", "EFI_IFR_INVALID", "EFI_IFR_EQUAL",
"EFI_IFR_NOT_EQUAL", "EFI_IFR_GREATER_THAN", "EFI_IFR_GREATER_EQUAL", "EFI_IFR_LESS_THAN", "EFI_IFR_LESS_EQUAL", "EFI_IFR_BITWISE_AND",
"EFI_IFR_BITWISE_OR", "EFI_IFR_BITWISE_NOT", "EFI_IFR_SHIFT_LEFT", "EFI_IFR_SHIFT_RIGHT", "EFI_IFR_ADD", "EFI_IFR_SUBTRACT",
"EFI_IFR_MULTIPLY", "EFI_IFR_DIVIDE", "EFI_IFR_MODULO", "EFI_IFR_RULE_REF", "EFI_IFR_QUESTION_REF1", "EFI_IFR_QUESTION_REF2",
"EFI_IFR_UINT8", "EFI_IFR_UINT16", "EFI_IFR_UINT32", "EFI_IFR_UINT64", "EFI_IFR_TRUE", "EFI_IFR_FALSE",
"EFI_IFR_TO_UINT", "EFI_IFR_TO_STRING", "EFI_IFR_TO_BOOLEAN", "EFI_IFR_MID", "EFI_IFR_FIND", "EFI_IFR_TOKEN",
"EFI_IFR_STRING_REF1","EFI_IFR_STRING_REF2", "EFI_IFR_CONDITIONAL", "EFI_IFR_QUESTION_REF3", "EFI_IFR_ZERO", "EFI_IFR_ONE",
"EFI_IFR_ONES", "EFI_IFR_UNDEFINED", "EFI_IFR_LENGTH", "EFI_IFR_DUP", "EFI_IFR_THIS", "EFI_IFR_SPAN",
"EFI_IFR_VALUE", "EFI_IFR_DEFAULT", "EFI_IFR_DEFAULTSTORE", "EFI_IFR_INVALID", "EFI_IFR_CATENATE", "EFI_IFR_GUID",
};
VOID
CIFROBJ_DEBUG_PRINT (
IN UINT8 OpCode
)
{
printf ("======Create IFR [%s]\n", gIfrObjPrintDebugTable[OpCode].mIfrName);
}
#else
#define CIFROBJ_DEBUG_PRINT(OpCode)
#endif
bool gCreateOp = TRUE;
CIfrObj::CIfrObj (
IN UINT8 OpCode,
OUT CHAR8 **IfrObj,
IN UINT8 ObjBinLen,
IN BOOLEAN DelayEmit
)
{
mDelayEmit = DelayEmit;
mPkgOffset = gCFormPkg.GetPkgLength ();
mObjBinLen = (ObjBinLen == 0) ? gOpcodeSizesScopeTable[OpCode].mSize : ObjBinLen;
mObjBinBuf = ((DelayEmit == FALSE) && (gCreateOp == TRUE)) ? gCFormPkg.IfrBinBufferGet (mObjBinLen) : new CHAR8[EFI_IFR_MAX_LENGTH];
mRecordIdx = (gCreateOp == TRUE) ? gCIfrRecordInfoDB.IfrRecordRegister (0xFFFFFFFF, mObjBinBuf, mObjBinLen, mPkgOffset) : EFI_IFR_RECORDINFO_IDX_INVALUD;
if (IfrObj != NULL) {
*IfrObj = mObjBinBuf;
}
CIFROBJ_DEBUG_PRINT (OpCode);
}
CIfrObj::~CIfrObj (
VOID
)
{
if ((mDelayEmit == TRUE) && ((gCreateOp == TRUE))) {
_EMIT_PENDING_OBJ ();
}
gCIfrRecordInfoDB.IfrRecordInfoUpdate (mRecordIdx, mLineNo, mObjBinBuf, mObjBinLen, mPkgOffset);
}
/*
* The definition of CIfrObj's member function
*/
UINT8 gScopeCount = 0;
CIfrOpHeader::CIfrOpHeader (
IN UINT8 OpCode,
IN VOID *StartAddr,
IN UINT8 Length
) : mHeader ((EFI_IFR_OP_HEADER *)StartAddr)
{
mHeader->OpCode = OpCode;
mHeader->Length = (Length == 0) ? gOpcodeSizesScopeTable[OpCode].mSize : Length;
mHeader->Scope = (gOpcodeSizesScopeTable[OpCode].mScope + gScopeCount > 0) ? 1 : 0;
}
CIfrOpHeader::CIfrOpHeader (
IN CIfrOpHeader &OpHdr
)
{
mHeader = OpHdr.mHeader;
}
UINT32 CIfrForm::FormIdBitMap[EFI_FREE_FORM_ID_BITMAP_SIZE] = {0, };
| [
"lgao4@7335b38e-4728-0410-8992-fb3ffe349368",
"jwang36@7335b38e-4728-0410-8992-fb3ffe349368",
"jljusten@7335b38e-4728-0410-8992-fb3ffe349368",
"qhuang8@7335b38e-4728-0410-8992-fb3ffe349368"
]
| [
[
[
1,
15
],
[
282,
314
],
[
318,
318
],
[
321,
322
],
[
339,
347
],
[
409,
410
],
[
438,
454
],
[
456,
458
],
[
539,
667
],
[
686,
688
],
[
701,
701
],
[
788,
824
],
[
826,
827
],
[
830,
832
],
[
842,
842
],
[
852,
853
],
[
855,
855
],
[
857,
857
],
[
860,
860
],
[
866,
1144
],
[
1155,
1161
],
[
1163,
1167
],
[
1171,
1174
],
[
1177,
1177
],
[
1179,
1180
],
[
1349,
1350
]
],
[
[
16,
23
],
[
25,
26
],
[
29,
30
],
[
38,
38
],
[
40,
43
],
[
51,
62
],
[
66,
88
],
[
90,
281
],
[
315,
317
],
[
319,
320
],
[
323,
338
],
[
348,
356
],
[
359,
379
],
[
382,
407
],
[
411,
413
],
[
415,
430
],
[
432,
433
],
[
435,
437
],
[
455,
455
],
[
459,
469
],
[
471,
472
],
[
475,
478
],
[
480,
490
],
[
492,
533
],
[
535,
538
],
[
668,
685
],
[
689,
700
],
[
702,
787
],
[
825,
825
],
[
828,
829
],
[
833,
841
],
[
843,
851
],
[
854,
854
],
[
856,
856
],
[
858,
859
],
[
861,
865
],
[
1145,
1154
],
[
1162,
1162
],
[
1168,
1170
],
[
1175,
1176
],
[
1178,
1178
],
[
1181,
1286
],
[
1288,
1348
],
[
1351,
1376
]
],
[
[
24,
24
],
[
39,
39
],
[
89,
89
],
[
357,
358
],
[
380,
381
],
[
408,
408
],
[
414,
414
],
[
431,
431
],
[
434,
434
],
[
470,
470
],
[
491,
491
],
[
1287,
1287
]
],
[
[
27,
28
],
[
31,
37
],
[
44,
50
],
[
63,
65
],
[
473,
474
],
[
479,
479
],
[
534,
534
]
]
]
|
79932e0cfe09c12b1beea665279b378257f7c224 | 59e65cbfec1c3ab8c2c79881e275864e47c45fe4 | /osgi_bundle/AliasColumn.h | 2cb348585fa992cdb657fff6179b0de5aee7a8d9 | []
| no_license | RaphaelK12/Windows-Explorer-OSGi-Shell-Extensions | 3fd8d39c48c2021631a31487386942a5234d6dbd | 04e65a0c39b4454e798f402fe68b0a965c015f6c | refs/heads/master | 2021-05-27T03:30:58.935453 | 2011-10-14T17:35:47 | 2011-10-14T17:35:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | h | #pragma once
/**
Serves as an alias for another column, just with other FMTID and PID.
@author_philk
*/
class AliasColumn : public Column {
public:
AliasColumn(const Column& other,
FMTID formatId,
DWORD propertyId) :
Column(formatId,
propertyId,
other.getInfo().vt,
other.getInfo().csFlags,
other.getInfo().cChars),
columnRef(other) {
}
/**
Calls the referenced columns visit method.
*/
void visit(const org::osgi::framework::Bundle& bundle, ATL::CComVariant& result) {
columnRef.visit(bundle, result);
}
private:
const Column& columnRef;
}; | [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
05d36c2c058affdb60553588c021221cef9490dc | 9fb229975cc6bd01eb38c3e96849d0c36985fa1e | /Tools/ObjExp/main.cpp | b0790a228e6bf5a891c96e0747a467c6f9c11129 | []
| no_license | Danewalker/ahr | 3758bf3219f407ed813c2bbed5d1d86291b9237d | 2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6 | refs/heads/master | 2016-09-13T08:03:43.040624 | 2010-07-21T15:44:41 | 2010-07-21T15:44:41 | 56,323,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,997 | cpp | #include <windows.h>
#include <stdio.h>
#include <io.h>
#include <math.h>
#include <assert.h>
#pragma warning(disable : 4996)
#define OUTPUT_LIGHTS_VERTICES
#define USE_OGL // export object for OpenGL
#define MAX_VERTEX 4000
#define MATERIAL_MAX 100
#define SECTION_VERT 9
typedef struct
{
unsigned short nb_vert;
unsigned short nb_face;
} OBJ_HEADER;
typedef struct
{
#ifdef USE_OGL
unsigned short idx0, idx1, idx2; // low part of idx
unsigned short idx; // 2bits high part of idx + matidx (ii) |ii001122|
#else
unsigned char idx0, idx1, idx2; // low part of idx
unsigned char idx; // 2bits high part of idx + matidx (ii) |ii001122|
#endif // USE_OGL
unsigned char u0, v0, u1, v1, u2, v2;
} OBJ_FACE;
typedef struct
{
unsigned char u, v;
} OBJ_TV;
#define ARGUMENT_INDEX_ASE 1
#define ARGUMENT_INDEX_OBJ 2
#define ARGUMENT_INDEX_CONFIG 3
#define ARGUMENT_INDEX_CFG 4
#define OPTION_TRAFIC (1 << 0)
#define OPTION_KEEP_VERTEX_ORDER (1 << 1)
#define OPTION_NORMALS (1 << 2)
#define OPTION_SIMPLE_MESH (1 << 3)
#define OPTION_CAR (1 << 4)
bool FileSkipToToken(FILE *fin, char *token, char *stopToken)
{
bool bFound = false;
char txt[512];
while (!feof(fin) && fscanf(fin, "%s", txt) > 0)
{
if (stopToken != NULL && strcmp(txt, stopToken) == 0)
break;
if (strcmp(txt, token) == 0)
{
bFound = true;
break;
}
}
return bFound;
}
void showUsage(int argc)
{
printf("%d arguments\n", argc);
printf("Usage : OBJEXP inputAS2filename outputOBJfilename [config.txt config.cfg] [-trafic -keepVertexOrder -normals] \n\n");
exit(1);
}
// Car axis:
// X - to right
// Y - depth
// Z - up
// Compensate flipping X and changing Y with Z
int main( int argc, char** argv )
{
char *fileAseName = NULL;
char *fileObjName = NULL;
char *fileConfigName = NULL;
char *fileCfgName = NULL;
if (argc <= 2)
{
showUsage(argc);
}
fileAseName = argv[ARGUMENT_INDEX_ASE];
fileObjName = argv[ARGUMENT_INDEX_OBJ];
int options = 0;
int k = 0;
int c = ARGUMENT_INDEX_CONFIG;
while (c < argc)
{
if (!strcmp(argv[c], "-trafic"))
options |= OPTION_TRAFIC;
else if (!strcmp(argv[c], "-keepVertexOrder"))
options |= OPTION_KEEP_VERTEX_ORDER;
else if (!strcmp(argv[c], "-normals"))
options |= OPTION_NORMALS;
else if (!strcmp(argv[c], "-simpleMesh"))
options |= OPTION_SIMPLE_MESH;
else if (!strcmp(argv[c], "-car"))
options |= OPTION_CAR;
else
{
if (k == 0)
fileConfigName = argv[c];
else if (k == 1)
fileCfgName = argv[c];
k++;
}
c++;
}
if (fileConfigName != NULL && fileCfgName == NULL)
{
showUsage(argc);
}
const int texturewidth = 256;
//if (texturewidth > 256)
//{
// printf("== FILE : %s == ", fileAseName );
// printf("Input texture size Error (must be <= 256)!\n\n");
// return -1;
//}
FILE* fin = fopen( fileAseName, "rt" );
if (fin == NULL)
{
printf("== FILE : %s == ", fileAseName );
printf("Input File Error!\n");
return -1;
}
// find mesh
char txt[512];
int nbv, nbf, tmp;
txt[0] = 0;
while (strcmp( txt, "*MESH" ) )
fscanf( fin, "\t%s\t{\n", txt );
fscanf( fin, "\t%s\t%d\n", txt, &tmp );
fscanf( fin, "\t%s\t%d\n", txt, &nbv );
fscanf( fin, "\t%s\t%d\n", txt, &nbf );
fscanf( fin, "\t%s\t{\n", txt );
//----------------------------------
// VERTEX
if (nbv >= MAX_VERTEX)
{
printf("== FILE : %s == ", fileAseName );
printf("Input nb vertex Error (must be < %d)!\n\n", MAX_VERTEX);
return -1;
}
short *datav = (short*)malloc( 3 * 2 * nbv );
short *pv = datav;
short n = nbv;
#define BIG_INT 0x7FFFFFFF
long minx = BIG_INT, maxx = -BIG_INT;
long miny = BIG_INT, maxy = -BIG_INT;
long minz = BIG_INT, maxz = -BIG_INT;
while (n--)
{
float x, y, z;
int idx;
fscanf( fin, "\t*MESH_VERTEX\t%d\t%f\t%f\t%f\n", &idx, &x, &y, &z );
long xl, yl, zl;
xl = (long)(x * 50 / 100); // scale (1cm = 2cm in engine)
yl = (long)(y * 50 / 100);
zl = (long)(z * 50 / 100);
if ((abs(xl)&0xFFFF0000) || (abs(yl)&0xFFFF0000) || (abs(zl)&0xFFFF0000))
{
printf("== FILE : %s == ", fileAseName );
printf("Overflow -> to big !!!\n\n" );
return -1;
}
if (maxx < xl) maxx = xl;
if (maxy < yl) maxy = yl;
if (maxz < zl) maxz = zl;
if (minx > yl) minx = xl;
if (miny > xl) miny = yl;
if (minz > zl) minz = zl;
if (options & OPTION_SIMPLE_MESH)
{
*pv++ = (short)xl;
*pv++ = (short)zl;
*pv++ = (short)(-yl);
}
else
{
*pv++ = (short)(-xl); // change X axis
*pv++ = (short)zl;
*pv++ = (short)yl;
}
}
fscanf( fin, "\t}\n", txt );
fscanf( fin, "\t%s\t{\n", txt );
//printf("\tMIN: %d, %d, %d\n", minx, miny, minz);
//printf("\tMAX: %d, %d, %d\n", maxx, maxy, maxz);
//----------------------------------
// FACES
// to tag vert to find isolated vertices
int tagvert[MAX_VERTEX];
memset( tagvert, 0, MAX_VERTEX * 4 );
OBJ_FACE *dataf = (OBJ_FACE*)malloc( sizeof(OBJ_FACE) * nbf );
OBJ_FACE *pf = dataf;
n = nbf;
while (n--)
{
char str[256];
int a, b, c;
int idx;
fscanf( fin, "\t*MESH_FACE\t%d:\tA:\t%d\tB:\t%d\tC:\t%d", &idx, &a, &b, &c );
str[0] = 0;
while (strcmp( str, "*MESH_MTLID" ))
fscanf( fin, "%s", str );
fscanf( fin, "\t%d", &idx );
// save indexes (8 low bits in idx? and 2 higher bits in idx012) + material idx
#ifdef USE_OGL
pf->idx0 = a;
pf->idx1 = b;
pf->idx2 = c;
pf->idx = idx;
#else
pf->idx0 = a&0xFF;
pf->idx1 = b&0xFF;
pf->idx2 = c&0xFF;
pf->idx012 = (((a&0xF00)>>8)<<4) | (((b&0xF00)>>8)<<2) | ((c&0xF00)>>8) | (idx<<6);
#endif // USE_OGL
pf++;
tagvert[ a ] = 1;
tagvert[ b ] = 1;
tagvert[ c ] = 1;
}
//----------------------------------
// TVERT
int nbtv;
fscanf( fin, "\t}\n"/*, txt*/ );
fscanf( fin, "\t%s\t%d\n", txt, &nbtv );
fscanf( fin, "\t%s\t{\n", txt );
OBJ_TV *datatv = (OBJ_TV*)malloc( sizeof(OBJ_TV) * nbtv );
OBJ_TV *ptv = datatv;
n = nbtv;
while (n--)
{
float u, v, w;
int idx;
fscanf( fin, "\t*MESH_TVERT\t%d\t%f\t%f\t%f\n", &idx, &u, &v, &w );
int ui, vi;
ui = (int)((u * texturewidth) + 0.5f);
if (ui < 0)
ui = 0;
if (ui > 255)
ui = 255;
vi = (int)((v * texturewidth) + 0.5f);
if (vi > texturewidth + 0.5)
vi -= texturewidth;
if (vi < 0)
vi = 0;
if (vi > 255)
vi = 255;
ptv->u = (unsigned char)ui;
ptv->v = (unsigned char)vi;
ptv++;
}
//----------------------------------
// TFACE
int nbtf;
fscanf( fin, "\t}\n", txt );
fscanf( fin, "\t%s\t%d\n", txt, &nbtf );
fscanf( fin, "\t%s\t{\n", txt );
if (nbtf != nbf)
{
printf("== FILE : %s == ", fileAseName );
printf("Error : nb tface != nb face\n\n");
return -1;
}
pf = dataf;
n = nbf;
while (n--)
{
int a, b, c;
int idx;
fscanf( fin, "\t*MESH_TFACE\t%d\t%d\t%d\t%d\n", &idx, &a, &b, &c );
pf->u0 = datatv[a].u;
pf->v0 = datatv[a].v;
pf->u1 = datatv[b].u;
pf->v1 = datatv[b].v;
pf->u2 = datatv[c].u;
pf->v2 = datatv[c].v;
pf++;
}
//----------------------------------
// NORMALS
signed short *normals = NULL;
int nNormals = 0;
if ((options & OPTION_NORMALS) != 0)
{
bool bReadNormals = false;
if (FileSkipToToken(fin, "*MESH_NORMALS", NULL))
{
bReadNormals = true;
}
if (bReadNormals)
{
int k = 0;
float a, b, c;
int idx;
nNormals = 9 * nbf;
normals = new signed short[nNormals];
while (FileSkipToToken(fin, "*MESH_VERTEXNORMAL", "}"))
{
int res = fscanf( fin, "%d %f %f %f\n", &idx, &a, &b, &c );
float t = sqrt(a * a + b * b + c * c);
if ( t != 0)
{
a /= t;
b /= t;
c /= t;
}
if (k < nNormals)
{
normals[k++] = (signed short)((a) * 4096);
normals[k++] = (signed short)((-c) * 4096); // Z in max
normals[k++] = (signed short)((-b) * 4096); // Y in max
}
else
k += 3;
}
if (k > nNormals)
{
// Shouldn't happen :)
printf("Warning: there are more than 9 * nbFaces normals (normals: %d vs 9 * faces: %d) !\n", k, nNormals);
}
}
}
fclose( fin );
// -------------- FRONT/BACK/SIREN LIGHTS AND TIRES ISOLATED VERTICE -----------------------
int light_FL = 0; // front left light
int light_FR = 0; // front right light
int light_SL = 0; // siren left
int light_SR = 0; // siren right
int light_BL = 0; // back left light
int light_BR = 0; // back right light
int tire_FL = 0; // front left tire
int tire_FR = 0; // front right tire
int tire_BL = 0; // back left tire
int tire_BR = 0; // back right tire
int lights[6];
int lights_count = 0;
int tires_count = 0;
{
for (int i = 0; i < nbv; i++)
{
// if isolated vertice
if (tagvert[i] == 0)
{
int y = datav[i*3+1];
// tire if near ground
if (y < 5)
{
// find which tire
int x = - datav[i*3]; // flip X again
int z = datav[i*3 + 2];
if (x < 0)
{
if (z < 0)
tire_FL = i;
else
tire_BL = i;
}
else
{
if (z < 0)
tire_FR = i;
else
tire_BR = i;
}
// rax - tire above the ground
datav[i*3 + 1] = 1;
tires_count++;
}
else
{
// store lights vertecies here, decide what vertex what light is later
if (lights_count >= 6)
{
printf ("Error: there are more than 6 lights verices!\n");
}
else
{
lights[lights_count++] = i;
}
}
}
}
// sort by z so we can deside if this is front,siren or stop light
for (int i = 0; i < lights_count - 1; i++)
{
for (int j = i+1; j < lights_count; j++)
{
if (datav[lights[i]*3+2] > datav[lights[j]*3+2])
{
int temp = lights[i];
lights[i] = lights[j];
lights[j] = temp;
}
}
}
if (lights_count == 2)
{
light_FL = lights[0];
light_BL = lights[1];
}
else if (lights_count == 3)
{
light_FL = lights[0];
light_SL = lights[1];
light_BL = lights[2];
}
else if (lights_count == 4)
{
if (datav[lights[0]*3] < 0)
{
light_FL = lights[0];
light_FR = lights[1];
}
else
{
light_FL = lights[1];
light_FR = lights[0];
}
if (datav[lights[2]*3] < 0)
{
light_BL = lights[2];
light_BR = lights[3];
}
else
{
light_BL = lights[3];
light_BR = lights[2];
}
}
// 2 headlights, 2 stops and 1 sireen
else if (lights_count == 5)
{
if (datav[lights[0]*3] < 0)
{
light_FL = lights[0];
light_FR = lights[1];
}
else
{
light_FL = lights[1];
light_FR = lights[0];
}
light_SL = lights[2];
light_SR = lights[2];
if (datav[lights[3]*3] < 0)
{
light_BL = lights[3];
light_BR = lights[4];
}
else
{
light_BL = lights[4];
light_BR = lights[3];
}
}
else if (lights_count == 6)
{
if (datav[lights[0]*3] < 0)
{
light_FL = lights[0];
light_FR = lights[1];
}
else
{
light_FL = lights[1];
light_FR = lights[0];
}
if (datav[lights[2]*3] < 0)
{
light_SL = lights[2];
light_SR = lights[3];
}
else
{
light_SL = lights[3];
light_SR = lights[2];
}
if (datav[lights[4]*3] < 0)
{
light_BL = lights[4];
light_BR = lights[5];
}
else
{
light_BL = lights[5];
light_BR = lights[4];
}
}
}
#ifdef OUTPUT_LIGHTS_VERTICES
if ((options & OPTION_SIMPLE_MESH) == 0)
{
printf("\tLights: %d\n", lights_count);
printf("\t\tFront %d (%d, %d, %d), %d (%d, %d, %d)\n", light_FL, datav[light_FL*3+0], datav[light_FL*3+1], datav[light_FL*3+2],
light_FR, datav[light_FR*3+0], datav[light_FR*3+1], datav[light_FR*3+2]);
printf("\t\tBack %d (%d, %d, %d), %d (%d, %d, %d)\n", light_BL, datav[light_BL*3+0], datav[light_BL*3+1], datav[light_BL*3+2],
light_BR, datav[light_BR*3+0], datav[light_BR*3+1], datav[light_BR*3+2]);
printf("\t\tSiren %d (%d, %d, %d), %d (%d, %d, %d)\n", light_SL, datav[light_SL*3+0], datav[light_SL*3+1], datav[light_SL*3+2],
light_SR, datav[light_SR*3+0], datav[light_SR*3+1], datav[light_SR*3+2]);
printf("\tTires:\n");
printf("\t\tFront %d (%d, %d, %d), %d (%d, %d, %d)\n", tire_FL, datav[tire_FL*3+0], datav[tire_FL*3+1], datav[tire_FL*3+2],
tire_FR, datav[tire_FR*3+0], datav[tire_FR*3+1], datav[tire_FR*3+2]);
printf("\t\tBack %d (%d, %d, %d), %d (%d, %d, %d)\n", tire_BL, datav[tire_BL*3+0], datav[tire_BL*3+1], datav[tire_BL*3+2],
tire_BR, datav[tire_BR*3+0], datav[tire_BR*3+1], datav[tire_BR*3+2]);
}
#endif // OUTPUT_LIGHTS_VERTICES
//===================================
#ifdef USE_OGL
// Create lights, tires vectors
short vLights[6 * 3];
memset(vLights, 0, sizeof(vLights));
short *v = vLights;
*v++ = datav[light_FL * 3 + 0];
*v++ = datav[light_FL * 3 + 1];
*v++ = datav[light_FL * 3 + 2];
if (light_FR > 0)
{
*v++ = datav[light_FR * 3 + 0];
*v++ = datav[light_FR * 3 + 1];
*v++ = datav[light_FR * 3 + 2];
}
else v += 3;
*v++ = datav[light_BL * 3 + 0];
*v++ = datav[light_BL * 3 + 1];
*v++ = datav[light_BL * 3 + 2];
if (light_BR > 0)
{
*v++ = datav[light_BR * 3 + 0];
*v++ = datav[light_BR * 3 + 1];
*v++ = datav[light_BR * 3 + 2];
}
else v += 3;
if (light_SL > 0)
{
*v++ = datav[light_SL * 3 + 0];
*v++ = datav[light_SL * 3 + 1];
*v++ = datav[light_SL * 3 + 2];
}
else v += 3;
if (light_SR > 0)
{
*v++ = datav[light_SR * 3 + 0];
*v++ = datav[light_SR * 3 + 1];
*v++ = datav[light_SR * 3 + 2];
}
else v += 3;
short vTires[4 * 3];
v = vTires;
*v++ = datav[tire_FL * 3 + 0];
*v++ = datav[tire_FL * 3 + 1];
*v++ = datav[tire_FL * 3 + 2];
if (tire_FR > 0)
{
*v++ = datav[tire_FR * 3 + 0];
*v++ = datav[tire_FR * 3 + 1];
*v++ = datav[tire_FR * 3 + 2];
}
else v += 3;
*v++ = datav[tire_BL * 3 + 0];
*v++ = datav[tire_BL * 3 + 1];
*v++ = datav[tire_BL * 3 + 2];
if (tire_BR > 0)
{
*v++ = datav[tire_BR * 3 + 0];
*v++ = datav[tire_BR * 3 + 1];
*v++ = datav[tire_BR * 3 + 2];
}
else v += 3;
OBJ_FACE* df = dataf;
short* dv = datav;
short* vA[3];
short* nA[3];
unsigned char* tA[3];
int nVertex = 0;
int pIndicesNum[MATERIAL_MAX];
memset(pIndicesNum, 0, sizeof(pIndicesNum));
short *pVertex = new short[nbf * 3 * 3];
unsigned char *pTex = new unsigned char[nbf * 3 * 2];
unsigned short *pIndices[MATERIAL_MAX];
for (int i=0; i<MATERIAL_MAX; ++i)
pIndices[i] = new unsigned short[nbf * 3];
short *pNormals = NULL;
if (normals > 0)
pNormals = new short[nbf * 3 * 3];
int nMaterials = 1;
for (int i=0; i<nbf; ++i)
{
const int a = df->idx0;// | (((df[3]>>4)&0x3)<<8);
const int b = df->idx1;//| (((df[3]>>2)&0x3)<<8);
const int c = df->idx2;// | (((df[3])&0x3)<<8);
const int matId = df->idx;// >> 6;
assert(matId < MATERIAL_MAX);
if (matId + 1 > nMaterials)
nMaterials = matId + 1;
int &nIndices = pIndicesNum[matId];
vA[0] = dv + 3 * a;
vA[1] = dv + 3 * b;
vA[2] = dv + 3 * c;
tA[0] = &df->u0;
tA[1] = &df->u1;
tA[2] = &df->u2;
if (normals)
{
nA[0] = normals + (i * 9);
nA[1] = normals + (i * 9 + 3);
nA[2] = normals + (i * 9 + 6);
}
bool bCheckNormals = normals &&
// If car, do not check normals for anvelope (needed for wheel rotation)
((options & OPTION_CAR) == 0 || matId != 3);
for (int k=0; k<3; k++)
{
int index = -1;
short *v = pVertex;
short *norm = pNormals;
unsigned char *t = pTex;
if ((options & OPTION_KEEP_VERTEX_ORDER) == 0)
{
// check if pair (vA[k], tA[k]) is unique
for (int l=0; l<nVertex; ++l)
{
if (vA[k][0] == v[0] &&
vA[k][1] == v[1] &&
vA[k][2] == v[2] &&
tA[k][0] == t[0] &&
tA[k][1] == t[1])
{
if (bCheckNormals)
{
if (nA[k][0] == norm[0] &&
nA[k][1] == norm[1] &&
nA[k][2] == norm[2])
{
index = l;
break;
}
}
else
{
index = l;
break;
}
}
v += 3;
t += 2;
norm += 3;
}
}
if (index >= 0)
{
pIndices[matId][nIndices++] = index;
}
else
{
// add vA, tA to vertex, tex
index = nVertex;
v = pVertex + index * 3;
t = pTex + index * 2;
norm = pNormals + index * 3;
v[0] = vA[k][0];
v[1] = vA[k][1];
v[2] = vA[k][2];
t[0] = tA[k][0];
t[1] = tA[k][1];
if (pNormals)
{
norm[0] = nA[k][0];
norm[1] = nA[k][1];
norm[2] = nA[k][2];
}
nVertex++;
pIndices[matId][nIndices++] = index;
}
}
df++;
}
// Write file
FILE* fout = fopen( fileObjName, "wb" );
if (fout == NULL)
{
printf("== FILE : %s == ", fileObjName );
printf("Error opening output file\n\n");
return -1;
}
unsigned char idx = nMaterials;
fwrite( &idx, 1, 1, fout );
fwrite( &nVertex, 4, 1, fout );
fwrite( pVertex, nVertex * 3 * 2, 1, fout );
fwrite( pTex, nVertex * 2, 1, fout );
if (pNormals)
{
idx = 1;
fwrite( &idx, 1, 1, fout );
fwrite( pNormals, nVertex * 3 * 2, 1, fout );
}
else
{
idx = 0;
fwrite( &idx, 1, 1, fout );
}
int nIndices = 0;
for (int i=0; i<nMaterials; ++i)
{
fwrite( &pIndicesNum[i], 4, 1, fout );
if (pIndicesNum[i] > 0)
fwrite( pIndices[i], pIndicesNum[i] * 2, 1, fout);
nIndices += pIndicesNum[i];
}
fwrite(vLights, 6 * 3 * 2, 1, fout);
fwrite(vTires, 4 * 3 * 2, 1, fout);
printf("Indices: %d, vertices: %d\n", nIndices, nVertex);
delete[] pVertex;
delete[] pTex;
if (pNormals)
delete[] pNormals;
for (int i=0; i<MATERIAL_MAX; ++i)
delete[] pIndices[i];
#else // USE_OGL
//===================================
OBJ_HEADER header;
header.nb_vert = nbv;
header.nb_face = nbf;
FILE* fout = fopen( fileObjName, "wb" );
if (fout == NULL)
{
printf("== FILE : %s == ", fileObjName );
printf("Error opening output file\n\n");
return -1;
}
fwrite( &header.nb_vert, 2, 1, fout );
fwrite( &header.nb_face, 2, 1, fout );
fwrite( datav, nbv*3*2, 1, fout );
fwrite( dataf, nbf*sizeof(OBJ_FACE), 1, fout );
// save lights data
fwrite( &lights_count, 1, 1, fout );
if (lights_count)
{
unsigned short tmp_arr[6];
tmp_arr[0] = light_FL;
tmp_arr[1] = light_FR;
tmp_arr[2] = light_BL;
tmp_arr[3] = light_BR;
tmp_arr[4] = light_SL;
tmp_arr[5] = light_SR;
fwrite( tmp_arr, 6, 2, fout );
}
// save tires data
fwrite( &tires_count, 1, 1, fout );
if (tires_count)
{
unsigned short tmp_arr[4];
tmp_arr[0] = tire_FL;
tmp_arr[1] = tire_FR;
tmp_arr[2] = tire_BL;
tmp_arr[3] = tire_BR;
fwrite( tmp_arr, 4, 2, fout );
}
#endif // USE_OGL
fclose(fout);
free( datatv );
free( datav );
free( dataf );
// ===============================================
// CONFIG
// ===============================================
if (fileConfigName != NULL && (options & OPTION_TRAFIC) == 0)
{
// cars
fin = fopen( fileConfigName, "rt" );
if (fin == NULL)
{
printf("== FILE : %s == ", fileConfigName );
printf("Input File Error!\n\n");
return -1;
}
txt[0] = 0;
// find config
while (strcmp( txt, "[ENGINE]" ) )
fscanf( fin, "%s\n", txt );
int gear_nb = 0;
int gear[10][5];
while (1)
{
fscanf( fin, "%s\n", txt );
if (strcmp( txt, "[END]" ) == 0)
break;
// get gear config
sscanf_s( txt, "%d", &gear[gear_nb][0] );
float f;
fscanf( fin, "%f %d %d %d\n", &f, &gear[gear_nb][2], &gear[gear_nb][3], &gear[gear_nb][4] );
gear[gear_nb][1] = (int)(f * 100);
gear_nb++;
}
// find SIZE
while (strcmp( txt, "[SIZE]" ) )
fscanf( fin, "%s\n", txt );
int size[3];
fscanf( fin, "%d %d %d\n", &size[0], &size[1], &size[2] );
// find BREAK
while (strcmp( txt, "[BREAK]" ) )
fscanf( fin, "%s\n", txt );
int breakforce[2];
fscanf( fin, "%d %d\n", &breakforce[0], &breakforce[1] );
// find SLIDING
while (strcmp( txt, "[SLIDING]" ) )
fscanf( fin, "%s\n", txt );
int sliding[4];
fscanf( fin, "%d %d %d %d\n", &sliding[0], &sliding[1], &sliding[2], &sliding[3] );
// find DIRECTION
while (strcmp( txt, "[DIRECTION]" ) )
fscanf( fin, "%s\n", txt );
int direction[2];
float f[2];
fscanf( fin, "%f %f\n", &f[0], &f[1] );
direction[0] = (int)(f[0] * 100 );
direction[1] = (int)(f[1] * 100 );
// find BREAKLIGHT
/* while (strcmp( txt, "[BREAKLIGHT]" ) )
fscanf( fin, "%s\n", txt );
int breaklight[8];
fscanf( fin, "%d %d %d %d %d %d %d %d\n", &breaklight[0], &breaklight[1], &breaklight[2], &breaklight[3], &breaklight[4], &breaklight[5], &breaklight[6], &breaklight[7] );
*/
/* while (strcmp( txt, "[BREAKLIGHT]" ) )
fscanf( fin, "%s\n", txt );
int breaklight_nb = 0;
int breaklight[16][8];
while (1)
{
fscanf( fin, "%s\n", txt );
if (strcmp( txt, "[END]" ) == 0)
break;
sscanf( txt, "%d", &breaklight[breaklight_nb][0] );
fscanf( fin, "%d %d %d %d %d %d %d\n",
&breaklight[breaklight_nb][1], &breaklight[breaklight_nb][2],
&breaklight[breaklight_nb][3], &breaklight[breaklight_nb][4],
&breaklight[breaklight_nb][5], &breaklight[breaklight_nb][6],
&breaklight[breaklight_nb][7] );
breaklight_nb++;
}*/
// find TEXTURES
while (strcmp( txt, "[TEXTURES]" ) )
fscanf( fin, "%s\n", txt );
int text_nb = 0;
char text[128][128];
while (1)
{
fscanf( fin, "%s\n", text[text_nb] );
if (strcmp( text[text_nb], "[END]" ) == 0)
break;
text_nb++;
}
// find MESHES
while (strcmp( txt, "[MESHES]" ) )
fscanf( fin, "%s\n", txt );
int mesh_nb = 0;
char mesh[128][128];
int mesh_mirror[128];
while (1)
{
fscanf( fin, "%s", mesh[mesh_nb] );
if (strcmp( mesh[mesh_nb], "[END]" ) == 0)
break;
fscanf( fin, "%d\n", &mesh_mirror[mesh_nb] );
mesh_nb++;
}
// find SUSPENSION
while (strcmp( txt, "[SUSPENSION]" ) )
fscanf( fin, "%s\n", txt );
int suspension[4];
fscanf( fin, "%d %d %d %d\n", &suspension[0], &suspension[1], &suspension[2], &suspension[3] );
// find CAMERA
while (strcmp( txt, "[CAMERA]" ) )
fscanf( fin, "%s\n", txt );
int camera[9];
fscanf( fin, "%d %d %d\n", &camera[0], &camera[1], &camera[2] );
fscanf( fin, "%d %d %d\n", &camera[3], &camera[4], &camera[5] );
fscanf( fin, "%d %d %d\n", &camera[6], &camera[7], &camera[8] );
// find JUMP
while (strcmp( txt, "[JUMP]" ) )
fscanf( fin, "%s\n", txt );
int jump[2];
fscanf( fin, "%d %d\n", &jump[0], &jump[1] );
// find CLUTCH
while (strcmp( txt, "[CLUTCH]" ) )
fscanf( fin, "%s\n", txt );
int clutch[2];
fscanf( fin, "%d %d\n", &clutch[0], &clutch[1] );
// find SPEED_BOOST if any
bool missing = false;
while (strcmp( txt, "[SPEED_BOOST]" ) )
{
if (fscanf( fin, "%s\n", txt ) == EOF)
{
missing = true;
break;
}
}
int speed_boost_modifier;
if (missing)
speed_boost_modifier = 255;
else
fscanf( fin, "%d\n", &speed_boost_modifier);
fclose( fin );
fout = fopen( fileCfgName, "wb" );
if (fout == NULL)
{
printf("== FILE : %s == ", fileCfgName );
printf("Error opening output file\n\n");
return -1;
}
unsigned char idx;
idx = gear_nb;
fwrite( &idx, 1, 1, fout );
for (int i = 0; i < gear_nb; i++)
{
for (int j = 0; j < 5; j++)
{
unsigned short s;
s = gear[i][j];
fwrite( &s, 2, 1, fout );
}
}
fwrite( &speed_boost_modifier, 2, 1, fout );
for (int i = 0; i < 3; i++)
{
unsigned short s;
s = size[i];
fwrite( &s, 2, 1, fout );
}
for (int i = 0; i < 2; i++)
{
unsigned char c;
c = breakforce[i];
fwrite( &c, 1, 1, fout );
}
for (int i = 0; i < 4; i++)
{
unsigned short s;
s = sliding[i];
fwrite( &s, 2, 1, fout );
}
for (int i = 0; i < 2; i++)
{
unsigned short s;
s = direction[i];
fwrite( &s, 2, 1, fout );
}
/* for ( i = 0; i < 8; i++)
{
unsigned short s;
s = breaklight[i];
fwrite( &s, 2, 1, fout );
}*/
/* idx = breaklight_nb;
fwrite( &idx, 1, 1, fout );
for (i = 0; i < breaklight_nb; i++)
{
for (int j = 0; j < 8; j++)
{
unsigned short s;
s = breaklight[i][j];
fwrite( &s, 2, 1, fout );
}
}*/
idx = text_nb;
fwrite( &idx, 1, 1, fout );
for (int i = 0; i < text_nb; i++)
{
idx = strlen( text[i] );
fwrite( &idx, 1, 1, fout );
fwrite( text[i], idx, 1, fout );
}
idx = mesh_nb;
fwrite( &idx, 1, 1, fout );
for (int i = 0; i < mesh_nb; i++)
{
idx = strlen( mesh[i] );
fwrite( &idx, 1, 1, fout );
fwrite( mesh[i], idx, 1, fout );
idx = mesh_mirror[i];
fwrite( &idx, 1, 1, fout );
}
for (int i = 0; i < 4; i++)
{
unsigned short s;
s = suspension[i];
fwrite( &s, 2, 1, fout );
}
for (int i = 0; i < 9; i++)
{
signed short s;
s = camera[i];
fwrite( &s, 2, 1, fout );
}
for (int i = 0; i < 2; i++)
{
unsigned short s;
s = jump[i];
fwrite( &s, 2, 1, fout );
}
for (int i = 0; i < 2; i++)
{
unsigned char c;
c = clutch[i];
fwrite( &c, 1, 1, fout );
}
fclose( fout );
}
else if ((options & OPTION_TRAFIC) != 0)
{
// trafic cars
fin = fopen( fileConfigName, "rt" );
if (fin == NULL)
{
printf("== FILE : %s == ", fileConfigName );
printf("Input File Error!\n\n");
return -1;
}
txt[0] = 0;
// find TYPE
while (strcmp( txt, "[TYPE]" ) )
fscanf( fin, "%s\n", txt );
int type;
fscanf( fin, "%d\n", &type );
// find SIZE
while (strcmp( txt, "[SIZE]" ) )
fscanf( fin, "%s\n", txt );
int size[3];
fscanf( fin, "%d %d %d\n", &size[0], &size[1], &size[2] );
// find BREAKLIGHT
/* while (strcmp( txt, "[BREAKLIGHT]" ) )
fscanf( fin, "%s\n", txt );
int breaklight[8];
fscanf( fin, "%d %d %d %d %d %d %d %d\n", &breaklight[0], &breaklight[1], &breaklight[2], &breaklight[3], &breaklight[4], &breaklight[5], &breaklight[6], &breaklight[7] );
*/
// find TEXTURES
while (strcmp( txt, "[TEXTURES]" ) )
fscanf( fin, "%s\n", txt );
int text_nb = 0;
char text[128][128];
while (1)
{
fscanf( fin, "%s\n", text[text_nb] );
if (strcmp( text[text_nb], "[END]" ) == 0)
break;
text_nb++;
}
fclose( fin );
fout = fopen( fileCfgName, "wb" );
if (fout == NULL)
{
printf("== FILE : %s == ", fileCfgName );
printf("Error opening output file\n\n");
return -1;
}
unsigned char idx;
{
unsigned short s;
s = type;
fwrite( &s, 2, 1, fout );
}
for (int i = 0; i < 3; i++)
{
unsigned short s;
s = size[i];
fwrite( &s, 2, 1, fout );
}
/* for ( i = 0; i < 8; i++)
{
unsigned short s;
s = breaklight[i];
fwrite( &s, 2, 1, fout );
}*/
idx = text_nb;
fwrite( &idx, 1, 1, fout );
for (int i = 0; i < text_nb; i++)
{
idx = strlen( text[i] );
fwrite( &idx, 1, 1, fout );
fwrite( text[i], idx, 1, fout );
}
fclose( fout );
}
return 0;
} | [
"jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae"
]
| [
[
[
1,
1333
]
]
]
|
2d1bf77aaadf3a66688d2833607828035c1a1786 | 10c14a95421b63a71c7c99adf73e305608c391bf | /gui/painting/qimagescale.cpp | 59aa997425653241251fac1f8866f4b096b1067e | []
| no_license | eaglezzb/wtlcontrols | 73fccea541c6ef1f6db5600f5f7349f5c5236daa | 61b7fce28df1efe4a1d90c0678ec863b1fd7c81c | refs/heads/master | 2021-01-22T13:47:19.456110 | 2009-05-19T10:58:42 | 2009-05-19T10:58:42 | 33,811,815 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,245 | cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <private/qimagescale_p.h>
#include <private/qdrawhelper_p.h>
#include "qimage.h"
#include "qcolor.h"
QT_BEGIN_NAMESPACE
namespace QImageScale {
struct QImageScaleInfo;
}
typedef void (*qt_qimageScaleFunc)(QImageScale::QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow);
static void qt_qimageScaleAARGB(QImageScale::QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow);
static void qt_qimageScaleAARGBA(QImageScale::QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow);
qt_qimageScaleFunc qt_qimageScaleArgb = qt_qimageScaleAARGBA;
qt_qimageScaleFunc qt_qimageScaleRgb = qt_qimageScaleAARGB;
/*
* Copyright (C) 2004, 2005 Daniel M. Duley
*
* 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 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.
*
*/
/* OTHER CREDITS:
*
* This is the normal smoothscale method, based on Imlib2's smoothscale.
*
* Originally I took the algorithm used in NetPBM and Qt and added MMX/3dnow
* optimizations. It ran in about 1/2 the time as Qt. Then I ported Imlib's
* C algorithm and it ran at about the same speed as my MMX optimized one...
* Finally I ported Imlib's MMX version and it ran in less than half the
* time as my MMX algorithm, (taking only a quarter of the time Qt does).
* After further optimization it seems to run at around 1/6th.
*
* Changes include formatting, namespaces and other C++'ings, removal of old
* #ifdef'ed code, and removal of unneeded border calculation code.
*
* Imlib2 is (C) Carsten Haitzler and various contributors. The MMX code
* is by Willem Monsuwe <[email protected]>. All other modifications are
* (C) Daniel M. Duley.
*/
namespace QImageScale {
struct QImageScaleInfo {
int *xpoints;
unsigned int **ypoints;
int *xapoints, *yapoints;
int xup_yup;
};
unsigned int** qimageCalcYPoints(unsigned int *src, int sw, int sh,
int dh);
int* qimageCalcXPoints(int sw, int dw);
int* qimageCalcApoints(int s, int d, int up);
QImageScaleInfo* qimageFreeScaleInfo(QImageScaleInfo *isi);
QImageScaleInfo *qimageCalcScaleInfo(const QImage &img, int sw, int sh,
int dw, int dh, char aa);
}
using namespace QImageScale;
//
// Code ported from Imlib...
//
// FIXME: replace with qRed, etc... These work on pointers to pixels, not
// pixel values
#define A_VAL(p) (qAlpha(*p))
#define R_VAL(p) (qRed(*p))
#define G_VAL(p) (qGreen(*p))
#define B_VAL(p) (qBlue(*p))
#define INV_XAP (256 - xapoints[x])
#define XAP (xapoints[x])
#define INV_YAP (256 - yapoints[dyy + y])
#define YAP (yapoints[dyy + y])
unsigned int** QImageScale::qimageCalcYPoints(unsigned int *src,
int sw, int sh, int dh)
{
unsigned int **p;
int i, j = 0;
int val, inc, rv = 0;
if(dh < 0){
dh = -dh;
rv = 1;
}
p = new unsigned int* [dh+1];
int up = qAbs(dh) >= sh;
val = up ? 0x8000 * sh / dh - 0x8000 : 0;
inc = (sh << 16) / dh;
for(i = 0; i < dh; i++){
p[j++] = src + qMax(0, val >> 16) * sw;
val += inc;
}
if(rv){
for(i = dh / 2; --i >= 0; ){
unsigned int *tmp = p[i];
p[i] = p[dh - i - 1];
p[dh - i - 1] = tmp;
}
}
return(p);
}
int* QImageScale::qimageCalcXPoints(int sw, int dw)
{
int *p, i, j = 0;
int val, inc, rv = 0;
if(dw < 0){
dw = -dw;
rv = 1;
}
p = new int[dw+1];
int up = qAbs(dw) >= sw;
val = up ? 0x8000 * sw / dw - 0x8000 : 0;
inc = (sw << 16) / dw;
for(i = 0; i < dw; i++){
p[j++] = qMax(0, val >> 16);
val += inc;
}
if(rv){
for(i = dw / 2; --i >= 0; ){
int tmp = p[i];
p[i] = p[dw - i - 1];
p[dw - i - 1] = tmp;
}
}
return(p);
}
int* QImageScale::qimageCalcApoints(int s, int d, int up)
{
int *p, i, j = 0, rv = 0;
if(d < 0){
rv = 1;
d = -d;
}
p = new int[d];
/* scaling up */
if(up){
int val, inc;
val = 0x8000 * s / d - 0x8000;
inc = (s << 16) / d;
for(i = 0; i < d; i++){
int pos = val >> 16;
if (pos < 0)
p[j++] = 0;
else if (pos >= (s - 1))
p[j++] = 0;
else
p[j++] = (val >> 8) - ((val >> 8) & 0xffffff00);
val += inc;
}
}
/* scaling down */
else{
int val, inc, ap, Cp;
val = 0;
inc = (s << 16) / d;
Cp = ((d << 14) / s) + 1;
for(i = 0; i < d; i++){
ap = ((0x100 - ((val >> 8) & 0xff)) * Cp) >> 8;
p[j] = ap | (Cp << 16);
j++;
val += inc;
}
}
if(rv){
int tmp;
for(i = d / 2; --i >= 0; ){
tmp = p[i];
p[i] = p[d - i - 1];
p[d - i - 1] = tmp;
}
}
return(p);
}
QImageScaleInfo* QImageScale::qimageFreeScaleInfo(QImageScaleInfo *isi)
{
if(isi){
delete[] isi->xpoints;
delete[] isi->ypoints;
delete[] isi->xapoints;
delete[] isi->yapoints;
delete isi;
}
return 0;
}
QImageScaleInfo* QImageScale::qimageCalcScaleInfo(const QImage &img,
int sw, int sh,
int dw, int dh, char aa)
{
QImageScaleInfo *isi;
int scw, sch;
scw = dw * qlonglong(img.width()) / sw;
sch = dh * qlonglong(img.height()) / sh;
isi = new QImageScaleInfo;
if(!isi)
return 0;
memset(isi, 0, sizeof(QImageScaleInfo));
isi->xup_yup = (qAbs(dw) >= sw) + ((qAbs(dh) >= sh) << 1);
isi->xpoints = qimageCalcXPoints(img.width(), scw);
if(!isi->xpoints)
return(qimageFreeScaleInfo(isi));
isi->ypoints = qimageCalcYPoints((unsigned int *)img.scanLine(0),
img.bytesPerLine() / 4, img.height(), sch);
if (!isi->ypoints)
return(qimageFreeScaleInfo(isi));
if(aa) {
isi->xapoints = qimageCalcApoints(img.width(), scw, isi->xup_yup & 1);
if(!isi->xapoints)
return(qimageFreeScaleInfo(isi));
isi->yapoints = qimageCalcApoints(img.height(), sch, isi->xup_yup & 2);
if(!isi->yapoints)
return(qimageFreeScaleInfo(isi));
}
return(isi);
}
/* FIXME: NEED to optimise ScaleAARGBA - currently its "ok" but needs work*/
/* scale by area sampling */
static void qt_qimageScaleAARGBA(QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow)
{
unsigned int *sptr, *dptr;
int x, y, end;
unsigned int **ypoints = isi->ypoints;
int *xpoints = isi->xpoints;
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
end = dxx + dw;
/* scaling up both ways */
if(isi->xup_yup == 3){
/* go through every scanline in the output buffer */
for(y = 0; y < dh; y++){
/* calculate the source line we'll scan from */
dptr = dest + dx + ((y + dy) * dow);
sptr = ypoints[dyy + y];
if(YAP > 0){
for(x = dxx; x < end; x++){
int r, g, b, a;
int rr, gg, bb, aa;
unsigned int *pix;
if(XAP > 0){
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * INV_XAP;
g = G_VAL(pix) * INV_XAP;
b = B_VAL(pix) * INV_XAP;
a = A_VAL(pix) * INV_XAP;
pix++;
r += R_VAL(pix) * XAP;
g += G_VAL(pix) * XAP;
b += B_VAL(pix) * XAP;
a += A_VAL(pix) * XAP;
pix += sow;
rr = R_VAL(pix) * XAP;
gg = G_VAL(pix) * XAP;
bb = B_VAL(pix) * XAP;
aa = A_VAL(pix) * XAP;
pix--;
rr += R_VAL(pix) * INV_XAP;
gg += G_VAL(pix) * INV_XAP;
bb += B_VAL(pix) * INV_XAP;
aa += A_VAL(pix) * INV_XAP;
r = ((rr * YAP) + (r * INV_YAP)) >> 16;
g = ((gg * YAP) + (g * INV_YAP)) >> 16;
b = ((bb * YAP) + (b * INV_YAP)) >> 16;
a = ((aa * YAP) + (a * INV_YAP)) >> 16;
*dptr++ = qRgba(r, g, b, a);
}
else{
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * INV_YAP;
g = G_VAL(pix) * INV_YAP;
b = B_VAL(pix) * INV_YAP;
a = A_VAL(pix) * INV_YAP;
pix += sow;
r += R_VAL(pix) * YAP;
g += G_VAL(pix) * YAP;
b += B_VAL(pix) * YAP;
a += A_VAL(pix) * YAP;
r >>= 8;
g >>= 8;
b >>= 8;
a >>= 8;
*dptr++ = qRgba(r, g, b, a);
}
}
}
else{
for(x = dxx; x < end; x++){
int r, g, b, a;
unsigned int *pix;
if(XAP > 0){
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * INV_XAP;
g = G_VAL(pix) * INV_XAP;
b = B_VAL(pix) * INV_XAP;
a = A_VAL(pix) * INV_XAP;
pix++;
r += R_VAL(pix) * XAP;
g += G_VAL(pix) * XAP;
b += B_VAL(pix) * XAP;
a += A_VAL(pix) * XAP;
r >>= 8;
g >>= 8;
b >>= 8;
a >>= 8;
*dptr++ = qRgba(r, g, b, a);
}
else
*dptr++ = sptr[xpoints[x] ];
}
}
}
}
/* if we're scaling down vertically */
else if(isi->xup_yup == 1){
/*\ 'Correct' version, with math units prepared for MMXification \*/
int Cy, j;
unsigned int *pix;
int r, g, b, a, rr, gg, bb, aa;
int yap;
/* go through every scanline in the output buffer */
for(y = 0; y < dh; y++){
Cy = YAP >> 16;
yap = YAP & 0xffff;
dptr = dest + dx + ((y + dy) * dow);
for(x = dxx; x < end; x++){
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * yap;
g = G_VAL(pix) * yap;
b = B_VAL(pix) * yap;
a = A_VAL(pix) * yap;
for(j = (1 << 14) - yap; j > Cy; j -= Cy){
pix += sow;
r += R_VAL(pix) * Cy;
g += G_VAL(pix) * Cy;
b += B_VAL(pix) * Cy;
a += A_VAL(pix) * Cy;
}
if(j > 0){
pix += sow;
r += R_VAL(pix) * j;
g += G_VAL(pix) * j;
b += B_VAL(pix) * j;
a += A_VAL(pix) * j;
}
if(XAP > 0){
pix = ypoints[dyy + y] + xpoints[x] + 1;
rr = R_VAL(pix) * yap;
gg = G_VAL(pix) * yap;
bb = B_VAL(pix) * yap;
aa = A_VAL(pix) * yap;
for(j = (1 << 14) - yap; j > Cy; j -= Cy){
pix += sow;
rr += R_VAL(pix) * Cy;
gg += G_VAL(pix) * Cy;
bb += B_VAL(pix) * Cy;
aa += A_VAL(pix) * Cy;
}
if(j > 0){
pix += sow;
rr += R_VAL(pix) * j;
gg += G_VAL(pix) * j;
bb += B_VAL(pix) * j;
aa += A_VAL(pix) * j;
}
r = r * INV_XAP;
g = g * INV_XAP;
b = b * INV_XAP;
a = a * INV_XAP;
r = (r + ((rr * XAP))) >> 12;
g = (g + ((gg * XAP))) >> 12;
b = (b + ((bb * XAP))) >> 12;
a = (a + ((aa * XAP))) >> 12;
}
else{
r >>= 4;
g >>= 4;
b >>= 4;
a >>= 4;
}
*dptr = qRgba(r >> 10, g >> 10, b >> 10, a >> 10);
dptr++;
}
}
}
/* if we're scaling down horizontally */
else if(isi->xup_yup == 2){
/*\ 'Correct' version, with math units prepared for MMXification \*/
int Cx, j;
unsigned int *pix;
int r, g, b, a, rr, gg, bb, aa;
int xap;
/* go through every scanline in the output buffer */
for(y = 0; y < dh; y++){
dptr = dest + dx + ((y + dy) * dow);
for(x = dxx; x < end; x++){
Cx = XAP >> 16;
xap = XAP & 0xffff;
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * xap;
g = G_VAL(pix) * xap;
b = B_VAL(pix) * xap;
a = A_VAL(pix) * xap;
for(j = (1 << 14) - xap; j > Cx; j -= Cx){
pix++;
r += R_VAL(pix) * Cx;
g += G_VAL(pix) * Cx;
b += B_VAL(pix) * Cx;
a += A_VAL(pix) * Cx;
}
if(j > 0){
pix++;
r += R_VAL(pix) * j;
g += G_VAL(pix) * j;
b += B_VAL(pix) * j;
a += A_VAL(pix) * j;
}
if(YAP > 0){
pix = ypoints[dyy + y] + xpoints[x] + sow;
rr = R_VAL(pix) * xap;
gg = G_VAL(pix) * xap;
bb = B_VAL(pix) * xap;
aa = A_VAL(pix) * xap;
for(j = (1 << 14) - xap; j > Cx; j -= Cx){
pix++;
rr += R_VAL(pix) * Cx;
gg += G_VAL(pix) * Cx;
bb += B_VAL(pix) * Cx;
aa += A_VAL(pix) * Cx;
}
if(j > 0){
pix++;
rr += R_VAL(pix) * j;
gg += G_VAL(pix) * j;
bb += B_VAL(pix) * j;
aa += A_VAL(pix) * j;
}
r = r * INV_YAP;
g = g * INV_YAP;
b = b * INV_YAP;
a = a * INV_YAP;
r = (r + ((rr * YAP))) >> 12;
g = (g + ((gg * YAP))) >> 12;
b = (b + ((bb * YAP))) >> 12;
a = (a + ((aa * YAP))) >> 12;
}
else{
r >>= 4;
g >>= 4;
b >>= 4;
a >>= 4;
}
*dptr = qRgba(r >> 10, g >> 10, b >> 10, a >> 10);
dptr++;
}
}
}
/* if we're scaling down horizontally & vertically */
else{
/*\ 'Correct' version, with math units prepared for MMXification:
|*| The operation 'b = (b * c) >> 16' translates to pmulhw,
|*| so the operation 'b = (b * c) >> d' would translate to
|*| psllw (16 - d), %mmb; pmulh %mmc, %mmb
\*/
int Cx, Cy, i, j;
unsigned int *pix;
int a, r, g, b, ax, rx, gx, bx;
int xap, yap;
for(y = 0; y < dh; y++){
Cy = YAP >> 16;
yap = YAP & 0xffff;
dptr = dest + dx + ((y + dy) * dow);
for(x = dxx; x < end; x++){
Cx = XAP >> 16;
xap = XAP & 0xffff;
sptr = ypoints[dyy + y] + xpoints[x];
pix = sptr;
sptr += sow;
rx = R_VAL(pix) * xap;
gx = G_VAL(pix) * xap;
bx = B_VAL(pix) * xap;
ax = A_VAL(pix) * xap;
pix++;
for(i = (1 << 14) - xap; i > Cx; i -= Cx){
rx += R_VAL(pix) * Cx;
gx += G_VAL(pix) * Cx;
bx += B_VAL(pix) * Cx;
ax += A_VAL(pix) * Cx;
pix++;
}
if(i > 0){
rx += R_VAL(pix) * i;
gx += G_VAL(pix) * i;
bx += B_VAL(pix) * i;
ax += A_VAL(pix) * i;
}
r = (rx >> 5) * yap;
g = (gx >> 5) * yap;
b = (bx >> 5) * yap;
a = (ax >> 5) * yap;
for(j = (1 << 14) - yap; j > Cy; j -= Cy){
pix = sptr;
sptr += sow;
rx = R_VAL(pix) * xap;
gx = G_VAL(pix) * xap;
bx = B_VAL(pix) * xap;
ax = A_VAL(pix) * xap;
pix++;
for(i = (1 << 14) - xap; i > Cx; i -= Cx){
rx += R_VAL(pix) * Cx;
gx += G_VAL(pix) * Cx;
bx += B_VAL(pix) * Cx;
ax += A_VAL(pix) * Cx;
pix++;
}
if(i > 0){
rx += R_VAL(pix) * i;
gx += G_VAL(pix) * i;
bx += B_VAL(pix) * i;
ax += A_VAL(pix) * i;
}
r += (rx >> 5) * Cy;
g += (gx >> 5) * Cy;
b += (bx >> 5) * Cy;
a += (ax >> 5) * Cy;
}
if(j > 0){
pix = sptr;
sptr += sow;
rx = R_VAL(pix) * xap;
gx = G_VAL(pix) * xap;
bx = B_VAL(pix) * xap;
ax = A_VAL(pix) * xap;
pix++;
for(i = (1 << 14) - xap; i > Cx; i -= Cx){
rx += R_VAL(pix) * Cx;
gx += G_VAL(pix) * Cx;
bx += B_VAL(pix) * Cx;
ax += A_VAL(pix) * Cx;
pix++;
}
if(i > 0){
rx += R_VAL(pix) * i;
gx += G_VAL(pix) * i;
bx += B_VAL(pix) * i;
ax += A_VAL(pix) * i;
}
r += (rx >> 5) * j;
g += (gx >> 5) * j;
b += (bx >> 5) * j;
a += (ax >> 5) * j;
}
*dptr = qRgba(r >> 23, g >> 23, b >> 23, a >> 23);
dptr++;
}
}
}
}
/* scale by area sampling - IGNORE the ALPHA byte*/
static void qt_qimageScaleAARGB(QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow)
{
unsigned int *sptr, *dptr;
int x, y, end;
unsigned int **ypoints = isi->ypoints;
int *xpoints = isi->xpoints;
int *xapoints = isi->xapoints;
int *yapoints = isi->yapoints;
end = dxx + dw;
/* scaling up both ways */
if(isi->xup_yup == 3){
/* go through every scanline in the output buffer */
for(y = 0; y < dh; y++){
/* calculate the source line we'll scan from */
dptr = dest + dx + ((y + dy) * dow);
sptr = ypoints[dyy + y];
if(YAP > 0){
for(x = dxx; x < end; x++){
int r = 0, g = 0, b = 0;
int rr = 0, gg = 0, bb = 0;
unsigned int *pix;
if(XAP > 0){
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * INV_XAP;
g = G_VAL(pix) * INV_XAP;
b = B_VAL(pix) * INV_XAP;
pix++;
r += R_VAL(pix) * XAP;
g += G_VAL(pix) * XAP;
b += B_VAL(pix) * XAP;
pix += sow;
rr = R_VAL(pix) * XAP;
gg = G_VAL(pix) * XAP;
bb = B_VAL(pix) * XAP;
pix --;
rr += R_VAL(pix) * INV_XAP;
gg += G_VAL(pix) * INV_XAP;
bb += B_VAL(pix) * INV_XAP;
r = ((rr * YAP) + (r * INV_YAP)) >> 16;
g = ((gg * YAP) + (g * INV_YAP)) >> 16;
b = ((bb * YAP) + (b * INV_YAP)) >> 16;
*dptr++ = qRgba(r, g, b, 0xff);
}
else{
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * INV_YAP;
g = G_VAL(pix) * INV_YAP;
b = B_VAL(pix) * INV_YAP;
pix += sow;
r += R_VAL(pix) * YAP;
g += G_VAL(pix) * YAP;
b += B_VAL(pix) * YAP;
r >>= 8;
g >>= 8;
b >>= 8;
*dptr++ = qRgba(r, g, b, 0xff);
}
}
}
else{
for(x = dxx; x < end; x++){
int r = 0, g = 0, b = 0;
unsigned int *pix;
if(XAP > 0){
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * INV_XAP;
g = G_VAL(pix) * INV_XAP;
b = B_VAL(pix) * INV_XAP;
pix++;
r += R_VAL(pix) * XAP;
g += G_VAL(pix) * XAP;
b += B_VAL(pix) * XAP;
r >>= 8;
g >>= 8;
b >>= 8;
*dptr++ = qRgba(r, g, b, 0xff);
}
else
*dptr++ = sptr[xpoints[x] ];
}
}
}
}
/* if we're scaling down vertically */
else if(isi->xup_yup == 1){
/*\ 'Correct' version, with math units prepared for MMXification \*/
int Cy, j;
unsigned int *pix;
int r, g, b, rr, gg, bb;
int yap;
/* go through every scanline in the output buffer */
for(y = 0; y < dh; y++){
Cy = YAP >> 16;
yap = YAP & 0xffff;
dptr = dest + dx + ((y + dy) * dow);
for(x = dxx; x < end; x++){
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * yap;
g = G_VAL(pix) * yap;
b = B_VAL(pix) * yap;
pix += sow;
for(j = (1 << 14) - yap; j > Cy; j -= Cy){
r += R_VAL(pix) * Cy;
g += G_VAL(pix) * Cy;
b += B_VAL(pix) * Cy;
pix += sow;
}
if(j > 0){
r += R_VAL(pix) * j;
g += G_VAL(pix) * j;
b += B_VAL(pix) * j;
}
if(XAP > 0){
pix = ypoints[dyy + y] + xpoints[x] + 1;
rr = R_VAL(pix) * yap;
gg = G_VAL(pix) * yap;
bb = B_VAL(pix) * yap;
pix += sow;
for(j = (1 << 14) - yap; j > Cy; j -= Cy){
rr += R_VAL(pix) * Cy;
gg += G_VAL(pix) * Cy;
bb += B_VAL(pix) * Cy;
pix += sow;
}
if(j > 0){
rr += R_VAL(pix) * j;
gg += G_VAL(pix) * j;
bb += B_VAL(pix) * j;
}
r = r * INV_XAP;
g = g * INV_XAP;
b = b * INV_XAP;
r = (r + ((rr * XAP))) >> 12;
g = (g + ((gg * XAP))) >> 12;
b = (b + ((bb * XAP))) >> 12;
}
else{
r >>= 4;
g >>= 4;
b >>= 4;
}
*dptr = qRgba(r >> 10, g >> 10, b >> 10, 0xff);
dptr++;
}
}
}
/* if we're scaling down horizontally */
else if(isi->xup_yup == 2){
/*\ 'Correct' version, with math units prepared for MMXification \*/
int Cx, j;
unsigned int *pix;
int r, g, b, rr, gg, bb;
int xap;
/* go through every scanline in the output buffer */
for(y = 0; y < dh; y++){
dptr = dest + dx + ((y + dy) * dow);
for(x = dxx; x < end; x++){
Cx = XAP >> 16;
xap = XAP & 0xffff;
pix = ypoints[dyy + y] + xpoints[x];
r = R_VAL(pix) * xap;
g = G_VAL(pix) * xap;
b = B_VAL(pix) * xap;
pix++;
for(j = (1 << 14) - xap; j > Cx; j -= Cx){
r += R_VAL(pix) * Cx;
g += G_VAL(pix) * Cx;
b += B_VAL(pix) * Cx;
pix++;
}
if(j > 0){
r += R_VAL(pix) * j;
g += G_VAL(pix) * j;
b += B_VAL(pix) * j;
}
if(YAP > 0){
pix = ypoints[dyy + y] + xpoints[x] + sow;
rr = R_VAL(pix) * xap;
gg = G_VAL(pix) * xap;
bb = B_VAL(pix) * xap;
pix++;
for(j = (1 << 14) - xap; j > Cx; j -= Cx){
rr += R_VAL(pix) * Cx;
gg += G_VAL(pix) * Cx;
bb += B_VAL(pix) * Cx;
pix++;
}
if(j > 0){
rr += R_VAL(pix) * j;
gg += G_VAL(pix) * j;
bb += B_VAL(pix) * j;
}
r = r * INV_YAP;
g = g * INV_YAP;
b = b * INV_YAP;
r = (r + ((rr * YAP))) >> 12;
g = (g + ((gg * YAP))) >> 12;
b = (b + ((bb * YAP))) >> 12;
}
else{
r >>= 4;
g >>= 4;
b >>= 4;
}
*dptr = qRgba(r >> 10, g >> 10, b >> 10, 0xff);
dptr++;
}
}
}
/* fully optimized (i think) - onyl change of algorithm can help */
/* if we're scaling down horizontally & vertically */
else{
/*\ 'Correct' version, with math units prepared for MMXification \*/
int Cx, Cy, i, j;
unsigned int *pix;
int r, g, b, rx, gx, bx;
int xap, yap;
for(y = 0; y < dh; y++){
Cy = YAP >> 16;
yap = YAP & 0xffff;
dptr = dest + dx + ((y + dy) * dow);
for(x = dxx; x < end; x++){
Cx = XAP >> 16;
xap = XAP & 0xffff;
sptr = ypoints[dyy + y] + xpoints[x];
pix = sptr;
sptr += sow;
rx = R_VAL(pix) * xap;
gx = G_VAL(pix) * xap;
bx = B_VAL(pix) * xap;
pix++;
for(i = (1 << 14) - xap; i > Cx; i -= Cx){
rx += R_VAL(pix) * Cx;
gx += G_VAL(pix) * Cx;
bx += B_VAL(pix) * Cx;
pix++;
}
if(i > 0){
rx += R_VAL(pix) * i;
gx += G_VAL(pix) * i;
bx += B_VAL(pix) * i;
}
r = (rx >> 5) * yap;
g = (gx >> 5) * yap;
b = (bx >> 5) * yap;
for(j = (1 << 14) - yap; j > Cy; j -= Cy){
pix = sptr;
sptr += sow;
rx = R_VAL(pix) * xap;
gx = G_VAL(pix) * xap;
bx = B_VAL(pix) * xap;
pix++;
for(i = (1 << 14) - xap; i > Cx; i -= Cx){
rx += R_VAL(pix) * Cx;
gx += G_VAL(pix) * Cx;
bx += B_VAL(pix) * Cx;
pix++;
}
if(i > 0){
rx += R_VAL(pix) * i;
gx += G_VAL(pix) * i;
bx += B_VAL(pix) * i;
}
r += (rx >> 5) * Cy;
g += (gx >> 5) * Cy;
b += (bx >> 5) * Cy;
}
if(j > 0){
pix = sptr;
sptr += sow;
rx = R_VAL(pix) * xap;
gx = G_VAL(pix) * xap;
bx = B_VAL(pix) * xap;
pix++;
for(i = (1 << 14) - xap; i > Cx; i -= Cx){
rx += R_VAL(pix) * Cx;
gx += G_VAL(pix) * Cx;
bx += B_VAL(pix) * Cx;
pix++;
}
if(i > 0){
rx += R_VAL(pix) * i;
gx += G_VAL(pix) * i;
bx += B_VAL(pix) * i;
}
r += (rx >> 5) * j;
g += (gx >> 5) * j;
b += (bx >> 5) * j;
}
*dptr = qRgb(r >> 23, g >> 23, b >> 23);
dptr++;
}
}
}
}
#if 0
static void qt_qimageScaleAARGBASetup(QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow)
{
qInitDrawhelperAsm();
qt_qimageScaleAARGBA(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
}
static void qt_qimageScaleAARGBSetup(QImageScaleInfo *isi, unsigned int *dest,
int dxx, int dyy, int dx, int dy, int dw,
int dh, int dow, int sow)
{
qInitDrawhelperAsm();
qt_qimageScaleAARGB(isi, dest, dxx, dyy, dx, dy, dw, dh, dow, sow);
}
#endif
QImage qSmoothScaleImage(const QImage &src, int dw, int dh)
{
QImage buffer;
if (src.isNull() || dw <= 0 || dh <= 0)
return buffer;
int w = src.width();
int h = src.height();
QImageScaleInfo *scaleinfo =
qimageCalcScaleInfo(src, w, h, dw, dh, true);
if (!scaleinfo)
return buffer;
buffer = QImage(dw, dh, src.format());
if (buffer.isNull()) {
qWarning("QImage: out of memory, returning null");
qimageFreeScaleInfo(scaleinfo);
return QImage();
}
if (src.format() == QImage::Format_ARGB32_Premultiplied)
qt_qimageScaleArgb(scaleinfo, (unsigned int *)buffer.scanLine(0),
0, 0, 0, 0, dw, dh, dw, src.bytesPerLine() / 4);
else
qt_qimageScaleRgb(scaleinfo, (unsigned int *)buffer.scanLine(0),
0, 0, 0, 0, dw, dh, dw, src.bytesPerLine() / 4);
qimageFreeScaleInfo(scaleinfo);
return buffer;
}
QT_END_NAMESPACE
| [
"zhangyinquan@0feb242a-2539-11de-a0d7-251e5865a1c7"
]
| [
[
[
1,
1031
]
]
]
|
7cb45f2feff55547bf4d25c33dc69cc75a78e2fa | 5540767a49db0f81dc24079982ec542914d3a72b | /expbinaria.cpp | f45a6007a3ea764d256ed35e5b0429cae54c7400 | []
| no_license | miltonXD/abstract-syntax-tree-in-c-plus-plus | 4296aa14576177a21ebb7cc26c1713ed121c556c | f4d2f48368892b708a2d916640254ca3a475ddef | refs/heads/master | 2021-01-10T06:40:04.184335 | 2011-10-02T13:12:56 | 2011-10-02T13:12:56 | 46,076,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | #include "expbinaria.h"
ExpBinaria::ExpBinaria()
{
}
bool ExpBinaria::CargarTS()
{
bool res=true;
this->Iz->tabla=tabla;
this->Iz->Clase=Clase;
this->Iz->SimboloMetodo=SimboloMetodo;
res=this->Iz->CargarTS();
if(res)
{
this->De->tabla=tabla;
this->De->Clase=Clase;
this->De->SimboloMetodo=SimboloMetodo;
res=this->De->CargarTS();
}
//Verificar la operacion y los tipos de los operandos...
return res;
}
| [
"Eddy@.(none)"
]
| [
[
[
1,
29
]
]
]
|
1a0543bc11efd2ef11c1d2cbc4892fb4cab73f4b | 061348a6be0e0e602d4a5b3e0af28e9eee2d257f | /Examples/Tutorial/Animation/01Animation.cpp | b8fe96f5c82b72168afdb80af3025e2f53e57b79 | []
| no_license | passthefist/OpenSGToolbox | 4a76b8e6b87245685619bdc3a0fa737e61a57291 | d836853d6e0647628a7dd7bb7a729726750c6d28 | refs/heads/master | 2023-06-09T22:44:20.711657 | 2010-07-26T00:43:13 | 2010-07-26T00:43:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,216 | cpp | //
// OpenSGToolbox Tutorial: 01Animation
//
// Demonstrates a simple animation using transformation keyframes.
//
// General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// Methods to create simple geometry: boxes, spheres, tori etc.
#include "OSGSimpleGeometry.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGSimpleMaterial.h"
#include "OSGComponentTransform.h"
#include "OSGTransform.h"
#include "OSGTypeFactory.h"
#include "OSGFieldContainerFactory.h"
#include "OSGNameAttachment.h"
#include "OSGContainerUtils.h"
#include "OSGMTRefCountPtr.h"
// Input
#include "OSGWindowUtils.h"
#include "OSGWindowEventProducer.h"
#include "OSGKeyListener.h"
//Animation
#include "OSGKeyframeSequences.h"
#include "OSGKeyframeAnimator.h"
#include "OSGFieldAnimation.h"
// Activate the OpenSG namespace
// This is not strictly necessary, you can also prefix all OpenSG symbols
// with OSG::, but that would be a bit tedious for this example
OSG_USING_NAMESPACE
// forward declaration so we can have the interesting stuff upfront
void setupAnimation(void);
void display(void);
void reshape(Vec2f Size);
void printAllStats(void);
class TutorialAnimationListener : public AnimationListener
{
public:
virtual void animationStarted(const AnimationEventUnrecPtr e)
{
std::cout << "Animation Started" << std::endl;
}
virtual void animationStopped(const AnimationEventUnrecPtr e)
{
std::cout << "Animation Stopped" << std::endl;
}
virtual void animationPaused(const AnimationEventUnrecPtr e)
{
std::cout << "Animation Paused" << std::endl;
}
virtual void animationUnpaused(const AnimationEventUnrecPtr e)
{
std::cout << "Animation Unpaused" << std::endl;
}
virtual void animationEnded(const AnimationEventUnrecPtr e)
{
std::cout << "Animation Ended" << std::endl;
}
virtual void animationCycled(const AnimationEventUnrecPtr e)
{
std::cout << "Animation Cycled. Cycle Count: " << dynamic_cast<Animation*>(e->getSource())->getCycles() << std::endl;
}
};
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerUnrecPtr TutorialWindow;
Time TimeLastIdle;
FieldAnimationUnrecPtr TheAnimation;
TutorialAnimationListener TheAnimationListener;
MaterialUnrecPtr TheTorusMaterial;
ComponentTransformUnrecPtr Trans;
TransformUnrecPtr TorusNodeTrans;
KeyframeAnimatorUnrecPtr TheAnimator;
KeyframeTransformationSequenceRefPtr TransformationKeyframes;
KeyframeColorSequenceUnrecPtr ColorKeyframes;
KeyframeVectorSequenceUnrecPtr VectorKeyframes;
KeyframeRotationSequenceUnrecPtr RotationKeyframes;
KeyframeNumberSequenceUnrecPtr NumberKeyframes;
// Create a class to allow for the use of the keyboard shortucts
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
switch(e->getKey())
{
case KeyEvent::KEY_SPACE:
TheAnimation->pause(!TheAnimation->isPaused());
break;
case KeyEvent::KEY_ENTER:
TheAnimation->attachUpdateProducer(TutorialWindow->editEventProducer());
TheAnimation->start();
break;
case KeyEvent::KEY_1:
dynamic_pointer_cast<FieldAnimation>(TheAnimation)->setInterpolationType(Animator::STEP_INTERPOLATION);
break;
case KeyEvent::KEY_2:
dynamic_pointer_cast<FieldAnimation>(TheAnimation)->setInterpolationType(Animator::LINEAR_INTERPOLATION);
break;
case KeyEvent::KEY_3:
dynamic_pointer_cast<FieldAnimation>(TheAnimation)->setInterpolationType(Animator::CUBIC_INTERPOLATION);
break;
//case '1':
//TheAnimator->setKeyframeSequence(ColorKeyframes);
//TheAnimation->setAnimatedField(TheTorusMaterial, std::string("diffuse"));
//break;
//case '2':
//TheAnimator->setKeyframeSequence(TransformationKeyframes);
//TheAnimation->setAnimatedField(getFieldContainer("Transform",std::string("TorusNodeTransformationCore")), std::string("matrix"));
//break;
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
class TutorialMouseListener : public MouseListener
{
public:
virtual void mouseClicked(const MouseEventUnrecPtr e)
{
}
virtual void mouseEntered(const MouseEventUnrecPtr e)
{
}
virtual void mouseExited(const MouseEventUnrecPtr e)
{
}
virtual void mousePressed(const MouseEventUnrecPtr e)
{
mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
virtual void mouseReleased(const MouseEventUnrecPtr e)
{
mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
};
class TutorialMouseMotionListener : public MouseMotionListener
{
public:
virtual void mouseMoved(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
virtual void mouseDragged(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
};
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
printAllStats();
{
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
//Add Window Listener
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
TutorialMouseListener TheTutorialMouseListener;
TutorialMouseMotionListener TheTutorialMouseMotionListener;
TutorialWindow->addMouseListener(&TheTutorialMouseListener);
TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
//Initialize Window
TutorialWindow->initWindow();
//Torus Material
TheTorusMaterial = SimpleMaterial::create();
dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setAmbient(Color3f(0.2,0.2,0.2));
dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setDiffuse(Color3f(0.7,0.7,0.7));
dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setSpecular(Color3f(0.7,0.7,0.7));
dynamic_pointer_cast<SimpleMaterial>(TheTorusMaterial)->setShininess(100.0f);
//Torus Geometry
GeometryRefPtr TorusGeometry = makeTorusGeo(.5, 2, 32, 32);
TorusGeometry->setMaterial(TheTorusMaterial);
NodeRefPtr TorusGeometryNode = Node::create();
TorusGeometryNode->setCore(TorusGeometry);
//Make Torus Node
NodeRefPtr TorusNode = Node::create();
TorusNodeTrans = Transform::create();
setName(TorusNodeTrans, std::string("TorusNodeTransformationCore"));
TorusNode->setCore(TorusNodeTrans);
TorusNode->addChild(TorusGeometryNode);
//Make Main Scene Node
NodeRefPtr scene = Node::create();
Trans = ComponentTransform::create();
setName(Trans, std::string("MainTransformationCore"));
scene->setCore(Trans);
scene->addChild(TorusNode);
setupAnimation();
commitChanges();
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
// tell the manager what to manage
mgr->setRoot (scene);
// show the whole scene
mgr->showAll();
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"OpenSG 01Animation Window");
//Enter main Loop
TutorialWindow->mainLoop();
}
osgExit();
return 0;
}
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
void setupAnimation(void)
{
//Number Keyframe Sequence
NumberKeyframes = KeyframeNumberSequenceReal32::create();
NumberKeyframes->addKeyframe(1.0,0.0f);
NumberKeyframes->addKeyframe(60.0,1.0f);
NumberKeyframes->addKeyframe(20.0,2.0f);
NumberKeyframes->addKeyframe(1.0,3.0f);
//Color Keyframe Sequence
ColorKeyframes = KeyframeColorSequenceColor3f::create();
ColorKeyframes->addKeyframe(Color4f(1.0f,0.0f,0.0f,1.0f),0.0f);
ColorKeyframes->addKeyframe(Color4f(0.0f,1.0f,0.0f,1.0f),2.0f);
ColorKeyframes->addKeyframe(Color4f(0.0f,0.0f,1.0f,1.0f),4.0f);
ColorKeyframes->addKeyframe(Color4f(1.0f,0.0f,0.0f,1.0f),6.0f);
//Position Keyframe Sequence
KeyframePositionSequenceUnrecPtr PositionKeyframes = KeyframePositionSequencePnt3f::create();
PositionKeyframes->addKeyframe(Pnt3f(1.0f,1.0f,1.0f),0.0f);
PositionKeyframes->addKeyframe(Pnt3f(0.5f,1.0f,0.5f),1.0f);
PositionKeyframes->addKeyframe(Pnt3f(1.0f,1.0f,0.5f),2.0f);
PositionKeyframes->addKeyframe(Pnt3f(1.0f,0.5f,0.5f),3.0f);
PositionKeyframes->addKeyframe(Pnt3f(1.0f,1.0f,1.0f),4.0f);
//Vector Keyframe Sequence
VectorKeyframes = KeyframeVectorSequenceVec3f::create();
VectorKeyframes->addKeyframe(Vec3f(1.0f,1.0f,1.0f),0.0f);
VectorKeyframes->addKeyframe(Vec3f(0.5f,1.0f,0.5f),1.0f);
VectorKeyframes->addKeyframe(Vec3f(1.0f,1.0f,0.5f),2.0f);
VectorKeyframes->addKeyframe(Vec3f(1.0f,0.5f,0.5f),3.0f);
VectorKeyframes->addKeyframe(Vec3f(1.0f,1.0f,1.0f),4.0f);
//Rotation Keyframe Sequence
RotationKeyframes = KeyframeRotationSequenceQuaternion::create();
RotationKeyframes->addKeyframe(Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*0.0f),0.0f);
RotationKeyframes->addKeyframe(Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*0.5f),1.0f);
RotationKeyframes->addKeyframe(Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*1.0f),2.0f);
RotationKeyframes->addKeyframe(Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*1.5f),3.0f);
RotationKeyframes->addKeyframe(Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*2.0f),4.0f);
//Transformation Keyframe Sequence
TransformationKeyframes = KeyframeTransformationSequenceMatrix4f::create();
Matrix TempMat;
TempMat.setTransform(Vec3f(0.0f,0.0f,0.0f), Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*0.0f));
TransformationKeyframes->addKeyframe(TempMat,0.0f);
TempMat.setTransform(Vec3f(0.0f,1.0f,0.0f), Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*0.5f));
TransformationKeyframes->addKeyframe(TempMat,1.0f);
TempMat.setTransform(Vec3f(1.0f,1.0f,0.0f), Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*1.0f));
TransformationKeyframes->addKeyframe(TempMat,2.0f);
TempMat.setTransform(Vec3f(1.0f,0.0f,0.0f), Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*1.5f));
TransformationKeyframes->addKeyframe(TempMat,3.0f);
TempMat.setTransform(Vec3f(0.0f,0.0f,0.0f), Quaternion(Vec3f(0.0f,1.0f,0.0f), 3.14159f*2.0f));
TransformationKeyframes->addKeyframe(TempMat,4.0f);
//Animator
TheAnimator = KeyframeAnimator::create();
//TheAnimator->setKeyframeSequence(VectorKeyframes);
//TheAnimator->setKeyframeSequence(RotationKeyframes);
//TheAnimator->setKeyframeSequence(ColorKeyframes);
TheAnimator->setKeyframeSequence(TransformationKeyframes);
//TheAnimator->setKeyframeSequence(NumberKeyframes);
//Animation
TheAnimation = FieldAnimation::create();
TheAnimation->setAnimator(TheAnimator);
TheAnimation->setInterpolationType(Animator::LINEAR_INTERPOLATION);
TheAnimation->setCycling(2);
//TheAnimation->setAnimatedField(getFieldContainer("Transform",std::string("TorusNodeTransformationCore")), std::string("matrix"));
//TheAnimation->setAnimatedField(Trans, std::string("scale"));
//TheAnimation->setAnimatedField(Trans, std::string("rotation"));
//TheAnimation->setAnimatedField(TheTorusMaterial, std::string("diffuse"));
//TheAnimation->setAnimatedField(TheTorusMaterial, std::string("shininess"));
TheAnimation->setAnimatedField(TorusNodeTrans, std::string("matrix"));
//Animation Listener
TheAnimation->addAnimationListener(&TheAnimationListener);
TheAnimation->attachUpdateProducer(TutorialWindow->editEventProducer());
TheAnimation->start();
}
#include "OSGStatElemDesc.h"
void printAllStats(void)
{
StatElemDescBase* Desc(NULL);
for(UInt32 i = 0; i < StatElemDescBase::getNumOfDescs(); ++i)
{
Desc = StatElemDescBase::getDesc(i);
std::cout << Desc->getID() << ": "
<< Desc->getName() << ": "
<< Desc->getDescription() << std::endl;
}
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
7
],
[
105,
105
]
],
[
[
8,
8
],
[
10,
11
],
[
13,
14
],
[
16,
16
],
[
18,
18
],
[
22,
22
],
[
25,
25
],
[
28,
29
],
[
33,
34
],
[
38,
54
],
[
56,
59
],
[
61,
64
],
[
66,
69
],
[
71,
74
],
[
76,
79
],
[
81,
81
],
[
83,
88
],
[
90,
91
],
[
93,
93
],
[
97,
97
],
[
104,
104
],
[
106,
109
],
[
111,
113
],
[
115,
122
],
[
124,
125
],
[
128,
128
],
[
131,
131
],
[
134,
148
],
[
150,
152
],
[
154,
160
],
[
162,
163
],
[
165,
166
],
[
168,
169
],
[
171,
173
],
[
175,
182
],
[
184,
187
],
[
189,
200
],
[
203,
203
],
[
205,
205
],
[
208,
210
],
[
212,
213
],
[
216,
216
],
[
220,
221
],
[
226,
227
],
[
230,
230
],
[
233,
234
],
[
236,
238
],
[
241,
242
],
[
244,
245
],
[
249,
251
],
[
260,
266
],
[
270,
273
],
[
277,
296
],
[
304,
304
],
[
318,
319
],
[
326,
327
],
[
334,
335
],
[
348,
350
],
[
354,
358
],
[
366,
371
],
[
373,
388
]
],
[
[
9,
9
],
[
12,
12
],
[
15,
15
],
[
17,
17
],
[
19,
21
],
[
23,
24
],
[
26,
27
],
[
30,
32
],
[
35,
37
],
[
55,
55
],
[
60,
60
],
[
65,
65
],
[
70,
70
],
[
75,
75
],
[
80,
80
],
[
82,
82
],
[
89,
89
],
[
92,
92
],
[
94,
96
],
[
98,
103
],
[
110,
110
],
[
114,
114
],
[
123,
123
],
[
126,
127
],
[
129,
130
],
[
132,
133
],
[
149,
149
],
[
153,
153
],
[
161,
161
],
[
164,
164
],
[
167,
167
],
[
170,
170
],
[
174,
174
],
[
183,
183
],
[
188,
188
],
[
201,
202
],
[
204,
204
],
[
206,
207
],
[
211,
211
],
[
214,
215
],
[
217,
219
],
[
222,
225
],
[
228,
229
],
[
231,
232
],
[
235,
235
],
[
239,
240
],
[
243,
243
],
[
246,
248
],
[
252,
259
],
[
267,
269
],
[
274,
276
],
[
297,
303
],
[
305,
317
],
[
320,
325
],
[
328,
333
],
[
336,
347
],
[
351,
353
],
[
359,
365
],
[
372,
372
]
]
]
|
25df183504327f21e6186d350d9812caca86d817 | fb4cf44e2c146b26ddde6350180cc420611fe17a | /SDK/CvUnitAI.cpp | d5011c3671225d944860b73a27594ff67a5deda6 | []
| 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 | ISO-8859-2 | C++ | false | false | 684,289 | cpp | // unitAI.cpp
#include "CvGameCoreDLL.h"
#include "CvUnitAI.h"
#include "CvMap.h"
#include "CvArea.h"
#include "CvPlot.h"
#include "CvGlobals.h"
#include "CvGameAI.h"
#include "CvTeamAI.h"
#include "CvPlayerAI.h"
#include "CvGameCoreUtils.h"
#include "CvRandom.h"
#include "CyUnit.h"
#include "CyArgsList.h"
#include "CvDLLPythonIFaceBase.h"
#include "CvInfos.h"
#include "FProfiler.h"
#include "FAStarNode.h"
// interface uses
#include "CvDLLInterfaceIFaceBase.h"
#include "CvDLLFAStarIFaceBase.h"
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
#include "BetterBTSAI.h"
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
#define FOUND_RANGE (7)
// Public Functions...
CvUnitAI::CvUnitAI()
{
AI_reset();
}
CvUnitAI::~CvUnitAI()
{
AI_uninit();
}
void CvUnitAI::AI_init(UnitAITypes eUnitAI)
{
AI_reset(eUnitAI);
//--------------------------------
// Init other game data
AI_setBirthmark(GC.getGameINLINE().getSorenRandNum(10000, "AI Unit Birthmark"));
FAssertMsg(AI_getUnitAIType() != NO_UNITAI, "AI_getUnitAIType() is not expected to be equal with NO_UNITAI");
area()->changeNumAIUnits(getOwnerINLINE(), AI_getUnitAIType(), 1);
GET_PLAYER(getOwnerINLINE()).AI_changeNumAIUnits(AI_getUnitAIType(), 1);
}
void CvUnitAI::AI_uninit()
{
}
void CvUnitAI::AI_reset(UnitAITypes eUnitAI)
{
AI_uninit();
m_iBirthmark = 0;
m_eUnitAIType = eUnitAI;
m_iAutomatedAbortTurn = -1;
}
// AI_update returns true when we should abort the loop and wait until next slice
bool CvUnitAI::AI_update()
{
PROFILE_FUNC();
CvUnit* pTransportUnit;
FAssertMsg(canMove(), "canMove is expected to be true");
FAssertMsg(isGroupHead(), "isGroupHead is expected to be true"); // XXX is this a good idea???
// allow python to handle it
CyUnit* pyUnit = new CyUnit(this);
CyArgsList argsList;
argsList.add(gDLL->getPythonIFace()->makePythonObject(pyUnit)); // pass in unit class
long lResult=0;
gDLL->getPythonIFace()->callFunction(PYGameModule, "AI_unitUpdate", argsList.makeFunctionArgs(), &lResult);
delete pyUnit; // python fxn must not hold on to this pointer
if (lResult == 1)
{
return false;
}
if (getDomainType() == DOMAIN_LAND)
{
if (plot()->isWater() && !canMoveAllTerrain())
{
getGroup()->pushMission(MISSION_SKIP);
return false;
}
else
{
pTransportUnit = getTransportUnit();
if (pTransportUnit != NULL)
{
if (pTransportUnit->getGroup()->hasMoved() || (pTransportUnit->getGroup()->headMissionQueueNode() != NULL))
{
getGroup()->pushMission(MISSION_SKIP);
return false;
}
}
}
}
if (AI_afterAttack())
{
return false;
}
if (getGroup()->isAutomated())
{
switch (getGroup()->getAutomateType())
{
case AUTOMATE_BUILD:
if (AI_getUnitAIType() == UNITAI_WORKER)
{
AI_workerMove();
}
else if (AI_getUnitAIType() == UNITAI_WORKER_SEA)
{
AI_workerSeaMove();
}
else
{
FAssert(false);
}
break;
case AUTOMATE_NETWORK:
AI_networkAutomated();
// XXX else wake up???
break;
case AUTOMATE_CITY:
AI_cityAutomated();
// XXX else wake up???
break;
case AUTOMATE_EXPLORE:
switch (getDomainType())
{
case DOMAIN_SEA:
AI_exploreSeaMove();
break;
case DOMAIN_AIR:
// if we are cargo (on a carrier), hold if the carrier is not done moving yet
pTransportUnit = getTransportUnit();
if (pTransportUnit != NULL)
{
if (pTransportUnit->isAutomated() && pTransportUnit->canMove() && pTransportUnit->getGroup()->getActivityType() != ACTIVITY_HOLD)
{
getGroup()->pushMission(MISSION_SKIP);
break;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/12/09 jdog5000 */
/* */
/* Player Interface */
/************************************************************************************************/
// Have air units explore like AI units do
AI_exploreAirMove();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
break;
case DOMAIN_LAND:
AI_exploreMove();
break;
default:
FAssert(false);
break;
}
// if we have air cargo (we are a carrier), and we done moving, explore with the aircraft as well
if (hasCargo() && domainCargo() == DOMAIN_AIR && (!canMove() || getGroup()->getActivityType() == ACTIVITY_HOLD))
{
std::vector<CvUnit*> aCargoUnits;
getCargoUnits(aCargoUnits);
for (uint i = 0; i < aCargoUnits.size() && isAutomated(); ++i)
{
CvUnit* pCargoUnit = aCargoUnits[i];
if (pCargoUnit->getDomainType() == DOMAIN_AIR)
{
if (pCargoUnit->canMove())
{
pCargoUnit->getGroup()->setAutomateType(AUTOMATE_EXPLORE);
pCargoUnit->getGroup()->setActivityType(ACTIVITY_AWAKE);
}
}
}
}
break;
case AUTOMATE_RELIGION:
if (AI_getUnitAIType() == UNITAI_MISSIONARY)
{
AI_missionaryMove();
}
break;
default:
FAssert(false);
break;
}
// if no longer automated, then we want to bail
return !getGroup()->isAutomated();
}
else
{
switch (AI_getUnitAIType())
{
case UNITAI_UNKNOWN:
getGroup()->pushMission(MISSION_SKIP);
break;
case UNITAI_ANIMAL:
AI_animalMove();
break;
case UNITAI_SETTLE:
AI_settleMove();
break;
case UNITAI_WORKER:
AI_workerMove();
break;
case UNITAI_ATTACK:
if (isBarbarian())
{
AI_barbAttackMove();
}
else
{
AI_attackMove();
}
break;
case UNITAI_ATTACK_CITY:
AI_attackCityMove();
break;
case UNITAI_COLLATERAL:
AI_collateralMove();
break;
case UNITAI_PILLAGE:
AI_pillageMove();
break;
case UNITAI_RESERVE:
AI_reserveMove();
break;
case UNITAI_COUNTER:
AI_counterMove();
break;
case UNITAI_PARADROP:
AI_paratrooperMove();
break;
case UNITAI_CITY_DEFENSE:
AI_cityDefenseMove();
break;
case UNITAI_CITY_COUNTER:
case UNITAI_CITY_SPECIAL:
AI_cityDefenseExtraMove();
break;
case UNITAI_EXPLORE:
AI_exploreMove();
break;
case UNITAI_MISSIONARY:
AI_missionaryMove();
break;
case UNITAI_PROPHET:
AI_prophetMove();
break;
case UNITAI_ARTIST:
AI_artistMove();
break;
case UNITAI_SCIENTIST:
AI_scientistMove();
break;
case UNITAI_GENERAL:
AI_generalMove();
break;
case UNITAI_MERCHANT:
AI_merchantMove();
break;
case UNITAI_ENGINEER:
AI_engineerMove();
break;
case UNITAI_SPY:
AI_spyMove();
break;
case UNITAI_ICBM:
AI_ICBMMove();
break;
case UNITAI_WORKER_SEA:
AI_workerSeaMove();
break;
case UNITAI_ATTACK_SEA:
if (isBarbarian())
{
AI_barbAttackSeaMove();
}
else
{
AI_attackSeaMove();
}
break;
case UNITAI_RESERVE_SEA:
AI_reserveSeaMove();
break;
case UNITAI_ESCORT_SEA:
AI_escortSeaMove();
break;
case UNITAI_EXPLORE_SEA:
AI_exploreSeaMove();
break;
case UNITAI_ASSAULT_SEA:
AI_assaultSeaMove();
break;
case UNITAI_SETTLER_SEA:
AI_settlerSeaMove();
break;
case UNITAI_MISSIONARY_SEA:
AI_missionarySeaMove();
break;
case UNITAI_SPY_SEA:
AI_spySeaMove();
break;
case UNITAI_CARRIER_SEA:
AI_carrierSeaMove();
break;
case UNITAI_MISSILE_CARRIER_SEA:
AI_missileCarrierSeaMove();
break;
case UNITAI_PIRATE_SEA:
AI_pirateSeaMove();
break;
case UNITAI_ATTACK_AIR:
AI_attackAirMove();
break;
case UNITAI_DEFENSE_AIR:
AI_defenseAirMove();
break;
case UNITAI_CARRIER_AIR:
AI_carrierAirMove();
break;
case UNITAI_MISSILE_AIR:
AI_missileAirMove();
break;
case UNITAI_ATTACK_CITY_LEMMING:
AI_attackCityLemmingMove();
break;
default:
FAssert(false);
break;
}
}
return false;
}
// Returns true if took an action or should wait to move later...
bool CvUnitAI::AI_follow()
{
if (AI_followBombard())
{
return true;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/31/10 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
// Pushing MISSION_MOVE_TO missions when not all units could move resulted in stack being
// broken up on the next turn. Also, if we can't attack now we don't want to queue up an
// attack for next turn, better to re-evaluate.
bool bCanAllMove = getGroup()->canAllMove();
if( bCanAllMove )
{
if (AI_cityAttack(1, 65, true))
{
return true;
}
}
if (isEnemy(plot()->getTeam()))
{
if (canPillage(plot()))
{
getGroup()->pushMission(MISSION_PILLAGE);
return true;
}
}
if( bCanAllMove )
{
if (AI_anyAttack(1, 70, 2, true, true))
{
return true;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (isFound())
{
if (area()->getBestFoundValue(getOwnerINLINE()) > 0)
{
if (AI_foundRange(FOUND_RANGE, true))
{
return true;
}
}
}
return false;
}
// XXX what if a unit gets stuck b/c of it's UnitAIType???
// XXX is this function costing us a lot? (it's recursive...)
void CvUnitAI::AI_upgrade()
{
PROFILE_FUNC();
FAssertMsg(!isHuman(), "isHuman did not return false as expected");
FAssertMsg(AI_getUnitAIType() != NO_UNITAI, "AI_getUnitAIType() is not expected to be equal with NO_UNITAI");
CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE());
UnitAITypes eUnitAI = AI_getUnitAIType();
CvArea* pArea = area();
int iCurrentValue = kPlayer.AI_unitValue(getUnitType(), eUnitAI, pArea);
for (int iPass = 0; iPass < 2; iPass++)
{
int iBestValue = 0;
UnitTypes eBestUnit = NO_UNIT;
for (int iI = 0; iI < GC.getNumUnitInfos(); iI++)
{
if ((iPass > 0) || GC.getUnitInfo((UnitTypes)iI).getUnitAIType(AI_getUnitAIType()))
{
int iNewValue = kPlayer.AI_unitValue(((UnitTypes)iI), eUnitAI, pArea);
if ((iPass == 0 || iNewValue > 0) && iNewValue > iCurrentValue)
{
if (canUpgrade((UnitTypes)iI))
{
int iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "AI Upgrade"));
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestUnit = ((UnitTypes)iI);
}
}
}
}
}
if (eBestUnit != NO_UNIT)
{
upgrade(eBestUnit);
doDelayedDeath();
return;
}
}
}
void CvUnitAI::AI_promote()
{
PROFILE_FUNC();
PromotionTypes eBestPromotion;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
eBestPromotion = NO_PROMOTION;
for (iI = 0; iI < GC.getNumPromotionInfos(); iI++)
{
if (canPromote((PromotionTypes)iI, -1))
{
iValue = AI_promotionValue((PromotionTypes)iI);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestPromotion = ((PromotionTypes)iI);
}
}
}
if (eBestPromotion != NO_PROMOTION)
{
promote(eBestPromotion, -1);
AI_promote();
}
}
int CvUnitAI::AI_groupFirstVal()
{
switch (AI_getUnitAIType())
{
case UNITAI_UNKNOWN:
case UNITAI_ANIMAL:
FAssert(false);
break;
case UNITAI_SETTLE:
return 21;
break;
case UNITAI_WORKER:
return 20;
break;
case UNITAI_ATTACK:
if (collateralDamage() > 0)
{
return 17;
}
else if (withdrawalProbability() > 0)
{
return 15;
}
else
{
return 13;
}
break;
case UNITAI_ATTACK_CITY:
if (bombardRate() > 0)
{
return 19;
}
else if (collateralDamage() > 0)
{
return 18;
}
else if (withdrawalProbability() > 0)
{
return 16;
}
else
{
return 14;
}
break;
case UNITAI_COLLATERAL:
return 7;
break;
case UNITAI_PILLAGE:
return 12;
break;
case UNITAI_RESERVE:
return 6;
break;
case UNITAI_COUNTER:
return 5;
break;
case UNITAI_CITY_DEFENSE:
return 3;
break;
case UNITAI_CITY_COUNTER:
return 2;
break;
case UNITAI_CITY_SPECIAL:
return 1;
break;
case UNITAI_PARADROP:
return 4;
break;
case UNITAI_EXPLORE:
return 8;
break;
case UNITAI_MISSIONARY:
return 10;
break;
case UNITAI_PROPHET:
case UNITAI_ARTIST:
case UNITAI_SCIENTIST:
case UNITAI_GENERAL:
case UNITAI_MERCHANT:
case UNITAI_ENGINEER:
return 11;
break;
case UNITAI_SPY:
return 9;
break;
case UNITAI_ICBM:
break;
case UNITAI_WORKER_SEA:
return 8;
break;
case UNITAI_ATTACK_SEA:
return 3;
break;
case UNITAI_RESERVE_SEA:
return 2;
break;
case UNITAI_ESCORT_SEA:
return 1;
break;
case UNITAI_EXPLORE_SEA:
return 5;
break;
case UNITAI_ASSAULT_SEA:
return 11;
break;
case UNITAI_SETTLER_SEA:
return 9;
break;
case UNITAI_MISSIONARY_SEA:
return 9;
break;
case UNITAI_SPY_SEA:
return 10;
break;
case UNITAI_CARRIER_SEA:
return 7;
break;
case UNITAI_MISSILE_CARRIER_SEA:
return 6;
break;
case UNITAI_PIRATE_SEA:
return 4;
break;
case UNITAI_ATTACK_AIR:
case UNITAI_DEFENSE_AIR:
case UNITAI_CARRIER_AIR:
case UNITAI_MISSILE_AIR:
break;
case UNITAI_ATTACK_CITY_LEMMING:
return 1;
break;
default:
FAssert(false);
break;
}
return 0;
}
int CvUnitAI::AI_groupSecondVal()
{
return ((getDomainType() == DOMAIN_AIR) ? airBaseCombatStr() : baseCombatStr());
}
// Returns attack odds out of 100 (the higher, the better...)
// Withdrawal odds included in returned value
int CvUnitAI::AI_attackOdds(const CvPlot* pPlot, bool bPotentialEnemy) const
{
PROFILE_FUNC();
CvUnit* pDefender;
int iOurStrength;
int iTheirStrength;
int iOurFirepower;
int iTheirFirepower;
int iBaseOdds;
int iStrengthFactor;
int iDamageToUs;
int iDamageToThem;
int iNeededRoundsUs;
int iNeededRoundsThem;
int iHitLimitThem;
pDefender = pPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, !bPotentialEnemy, bPotentialEnemy);
if (pDefender == NULL)
{
return 100;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/21/10 jdog5000 */
/* */
/* Efficiency, Lead From Behind */
/************************************************************************************************/
// From Lead From Behind by UncutDragon
if (GC.getLFBEnable() && GC.getLFBUseCombatOdds())
{
// Combat odds are out of 1000 - we need odds out of 100
CvUnit* pThis = (CvUnit*)this;
int iOdds = (getCombatOdds(pThis, pDefender) + 5) / 10;
iOdds += GET_PLAYER(getOwnerINLINE()).AI_getAttackOddsChange();
return std::max(1, std::min(iOdds, 99));
}
iOurStrength = ((getDomainType() == DOMAIN_AIR) ? airCurrCombatStr(NULL) : currCombatStr(NULL, NULL));
iOurFirepower = ((getDomainType() == DOMAIN_AIR) ? iOurStrength : currFirepower(NULL, NULL));
if (iOurStrength == 0)
{
return 1;
}
iTheirStrength = pDefender->currCombatStr(pPlot, this);
iTheirFirepower = pDefender->currFirepower(pPlot, this);
FAssert((iOurStrength + iTheirStrength) > 0);
FAssert((iOurFirepower + iTheirFirepower) > 0);
iBaseOdds = (100 * iOurStrength) / (iOurStrength + iTheirStrength);
if (iBaseOdds == 0)
{
return 1;
}
iStrengthFactor = ((iOurFirepower + iTheirFirepower + 1) / 2);
// UncutDragon
/* original code
iDamageToUs = std::max(1,((GC.getDefineINT("COMBAT_DAMAGE") * (iTheirFirepower + iStrengthFactor)) / (iOurFirepower + iStrengthFactor)));
iDamageToThem = std::max(1,((GC.getDefineINT("COMBAT_DAMAGE") * (iOurFirepower + iStrengthFactor)) / (iTheirFirepower + iStrengthFactor)));
*/ // modified
iDamageToUs = std::max(1,((GC.getCOMBAT_DAMAGE() * (iTheirFirepower + iStrengthFactor)) / (iOurFirepower + iStrengthFactor)));
iDamageToThem = std::max(1,((GC.getCOMBAT_DAMAGE() * (iOurFirepower + iStrengthFactor)) / (iTheirFirepower + iStrengthFactor)));
// /UncutDragon
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
iHitLimitThem = pDefender->maxHitPoints() - combatLimit();
iNeededRoundsUs = (std::max(0, pDefender->currHitPoints() - iHitLimitThem) + iDamageToThem - 1 ) / iDamageToThem;
iNeededRoundsThem = (std::max(0, currHitPoints()) + iDamageToUs - 1 ) / iDamageToUs;
if (getDomainType() != DOMAIN_AIR)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/30/09 Mongoose & jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
// From Mongoose SDK
if (!pDefender->immuneToFirstStrikes()) {
iNeededRoundsUs -= ((iBaseOdds * firstStrikes()) + ((iBaseOdds * chanceFirstStrikes()) / 2)) / 100;
}
if (!immuneToFirstStrikes()) {
iNeededRoundsThem -= (((100 - iBaseOdds) * pDefender->firstStrikes()) + (((100 - iBaseOdds) * pDefender->chanceFirstStrikes()) / 2)) / 100;
}
iNeededRoundsUs = std::max(1, iNeededRoundsUs);
iNeededRoundsThem = std::max(1, iNeededRoundsThem);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
int iRoundsDiff = iNeededRoundsUs - iNeededRoundsThem;
if (iRoundsDiff > 0)
{
iTheirStrength *= (1 + iRoundsDiff);
}
else
{
iOurStrength *= (1 - iRoundsDiff);
}
int iOdds = (((iOurStrength * 100) / (iOurStrength + iTheirStrength)));
iOdds += ((100 - iOdds) * withdrawalProbability()) / 100;
iOdds += GET_PLAYER(getOwnerINLINE()).AI_getAttackOddsChange();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/30/09 Mongoose & jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
// From Mongoose SDK
return range(iOdds, 1, 99);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
// Returns true if the unit found a build for this city...
bool CvUnitAI::AI_bestCityBuild(CvCity* pCity, CvPlot** ppBestPlot, BuildTypes* peBestBuild, CvPlot* pIgnorePlot, CvUnit* pUnit)
{
PROFILE_FUNC();
BuildTypes eBuild;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
BuildTypes eBestBuild = NO_BUILD;
CvPlot* pBestPlot = NULL;
for (int iPass = 0; iPass < 2; iPass++)
{
for (iI = 0; iI < NUM_CITY_PLOTS; iI++)
{
CvPlot* pLoopPlot = plotCity(pCity->getX_INLINE(), pCity->getY_INLINE(), iI);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot != pIgnorePlot)
{
if ((pLoopPlot->getImprovementType() == NO_IMPROVEMENT) || !(GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_SAFE_AUTOMATION) && !(pLoopPlot->getImprovementType() == (GC.getDefineINT("RUINS_IMPROVEMENT")))))
{
iValue = pCity->AI_getBestBuildValue(iI);
if (iValue > iBestValue)
{
eBuild = pCity->AI_getBestBuild(iI);
FAssertMsg(eBuild < GC.getNumBuildInfos(), "Invalid Build");
if (eBuild != NO_BUILD)
{
if (0 == iPass)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
eBestBuild = eBuild;
}
else if (canBuild(pLoopPlot, eBuild))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
// XXX take advantage of range (warning... this could lead to some units doing nothing...)
int iMaxWorkers = 1;
if (getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
else if (iPathTurns <= 1)
{
iMaxWorkers = AI_calculatePlotWorkersNeeded(pLoopPlot, eBuild);
}
if (pUnit != NULL)
{
if (pUnit->plot()->isCity() && iPathTurns == 1 && getPathLastNode()->m_iData1 > 0)
{
iMaxWorkers += 10;
}
}
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BUILD, getGroup()) < iMaxWorkers)
{
//XXX this could be improved greatly by
//looking at the real build time and other factors
//when deciding whether to stack.
iValue /= iPathTurns;
iBestValue = iValue;
pBestPlot = pLoopPlot;
eBestBuild = eBuild;
}
}
}
}
}
}
}
}
}
}
}
if (0 == iPass)
{
if (eBestBuild != NO_BUILD)
{
FAssert(pBestPlot != NULL);
int iPathTurns;
if ((generatePath(pBestPlot, 0, true, &iPathTurns)) && canBuild(pBestPlot, eBestBuild)
&& !(pBestPlot->isVisibleEnemyUnit(this)))
{
int iMaxWorkers = 1;
if (pUnit != NULL)
{
if (pUnit->plot()->isCity())
{
iMaxWorkers += 10;
}
}
if (getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
else if (iPathTurns <= 1)
{
iMaxWorkers = AI_calculatePlotWorkersNeeded(pBestPlot, eBestBuild);
}
int iWorkerCount = GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pBestPlot, MISSIONAI_BUILD, getGroup());
if (iWorkerCount < iMaxWorkers)
{
//Good to go.
break;
}
}
eBestBuild = NO_BUILD;
iBestValue = 0;
}
}
}
if (NO_BUILD != eBestBuild)
{
FAssert(NULL != pBestPlot);
if (ppBestPlot != NULL)
{
*ppBestPlot = pBestPlot;
}
if (peBestBuild != NULL)
{
*peBestBuild = eBestBuild;
}
}
return (NO_BUILD != eBestBuild);
}
bool CvUnitAI::AI_isCityAIType() const
{
return ((AI_getUnitAIType() == UNITAI_CITY_DEFENSE) ||
(AI_getUnitAIType() == UNITAI_CITY_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_SPECIAL) ||
(AI_getUnitAIType() == UNITAI_RESERVE));
}
int CvUnitAI::AI_getBirthmark() const
{
return m_iBirthmark;
}
void CvUnitAI::AI_setBirthmark(int iNewValue)
{
m_iBirthmark = iNewValue;
if (AI_getUnitAIType() == UNITAI_EXPLORE_SEA)
{
if (GC.getGame().circumnavigationAvailable())
{
m_iBirthmark -= m_iBirthmark % 4;
int iExplorerCount = GET_PLAYER(getOwnerINLINE()).AI_getNumAIUnits(UNITAI_EXPLORE_SEA);
iExplorerCount += getOwnerINLINE() % 4;
if (GC.getMap().isWrapX())
{
if ((iExplorerCount % 2) == 1)
{
m_iBirthmark += 1;
}
}
if (GC.getMap().isWrapY())
{
if (!GC.getMap().isWrapX())
{
iExplorerCount *= 2;
}
if (((iExplorerCount >> 1) % 2) == 1)
{
m_iBirthmark += 2;
}
}
}
}
}
UnitAITypes CvUnitAI::AI_getUnitAIType() const
{
return m_eUnitAIType;
}
// XXX make sure this gets called...
void CvUnitAI::AI_setUnitAIType(UnitAITypes eNewValue)
{
FAssertMsg(eNewValue != NO_UNITAI, "NewValue is not assigned a valid value");
if (AI_getUnitAIType() != eNewValue)
{
area()->changeNumAIUnits(getOwnerINLINE(), AI_getUnitAIType(), -1);
GET_PLAYER(getOwnerINLINE()).AI_changeNumAIUnits(AI_getUnitAIType(), -1);
m_eUnitAIType = eNewValue;
area()->changeNumAIUnits(getOwnerINLINE(), AI_getUnitAIType(), 1);
GET_PLAYER(getOwnerINLINE()).AI_changeNumAIUnits(AI_getUnitAIType(), 1);
joinGroup(NULL);
}
}
int CvUnitAI::AI_sacrificeValue(const CvPlot* pPlot) const
{
int iValue;
int iCollateralDamageValue = 0;
if (pPlot != NULL)
{
int iPossibleTargets = std::min((pPlot->getNumVisibleEnemyDefenders(this) - 1), collateralDamageMaxUnits());
if (iPossibleTargets > 0)
{
iCollateralDamageValue = collateralDamage();
iCollateralDamageValue += std::max(0, iCollateralDamageValue - 100);
iCollateralDamageValue *= iPossibleTargets;
iCollateralDamageValue /= 5;
}
}
if (getDomainType() == DOMAIN_AIR)
{
iValue = 128 * (100 + currInterceptionProbability());
if (m_pUnitInfo->getNukeRange() != -1)
{
iValue += 25000;
}
iValue /= std::max(1, (1 + m_pUnitInfo->getProductionCost()));
iValue *= (maxHitPoints() - getDamage());
iValue /= 100;
}
else
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/14/10 jdog5000 */
/* */
/* General AI */
/************************************************************************************************/
/*
// original bts code
iValue = 128 * (currEffectiveStr(pPlot, ((pPlot == NULL) ? NULL : this)));
iValue *= (100 + iCollateralDamageValue);
iValue /= (100 + cityDefenseModifier());
iValue *= (100 + withdrawalProbability());
iValue /= std::max(1, (1 + m_pUnitInfo->getProductionCost()));
iValue /= (10 + getExperience());
*/
iValue = 128 * (currEffectiveStr(pPlot, ((pPlot == NULL) ? NULL : this)));
iValue *= (100 + iCollateralDamageValue);
iValue /= (100 + cityDefenseModifier());
iValue *= (100 + withdrawalProbability());
// Experience and medics now better handled in LFB
iValue /= (10 + getExperience());
if( !GC.getLFBEnable() )
{
iValue *= 10;
iValue /= (10 + getSameTileHeal() + getAdjacentTileHeal());
}
// Value units which can't kill units later, also combat limits mean higher survival odds
if (combatLimit() < 100)
{
iValue *= 150;
iValue /= 100;
iValue *= 100;
iValue /= std::max(1, combatLimit());
}
iValue /= std::max(1, (1 + m_pUnitInfo->getProductionCost()));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/14/10 jdog5000 */
/* */
/* From Lead From Behind */
/************************************************************************************************/
// From Lead From Behind by UncutDragon
if (GC.getLFBEnable())
{
// Reduce the value of sacrificing 'valuable' units - based on great general, limited, healer, experience
iValue *= 100;
int iRating = LFBgetRelativeValueRating();
if (iRating > 0)
{
iValue /= (1 + 3*iRating);
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return iValue;
}
// Protected Functions...
void CvUnitAI::AI_animalMove()
{
PROFILE_FUNC();
if (GC.getGameINLINE().getSorenRandNum(100, "Animal Attack") < GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getAnimalAttackProb())
{
if (AI_anyAttack(1, 0))
{
return;
}
}
if (AI_heal())
{
return;
}
if (AI_patrol())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_settleMove()
{
PROFILE_FUNC();
if (GET_PLAYER(getOwnerINLINE()).getNumCities() == 0)
{
/************************************************************************************************/
/* Afforess & Fuyu Start 09/18/10 */
/* */
/* Check for Good City Sites Near Starting Location */
/************************************************************************************************/
int iGameSpeedPercent = ( (2 * GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getTrainPercent())
+ GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getConstructPercent()
+ GC.getGameSpeedInfo(GC.getGameINLINE().getGameSpeedType()).getResearchPercent() ) / 4;
int iMaxFoundTurn = (iGameSpeedPercent + 50) / 150; //quick 0, normal/epic 1, marathon 2
if ( canMove() && !GET_PLAYER(getOwnerINLINE()).AI_isPlotCitySite(plot()) && GC.getGameINLINE().getElapsedGameTurns() <= iMaxFoundTurn )
{
int iBestValue = 0;
int iBestFoundTurn = 0;
CvPlot* pBestPlot = NULL;
for (int iCitySite = 0; iCitySite < GET_PLAYER(getOwnerINLINE()).AI_getNumCitySites(); iCitySite++)
{
CvPlot* pCitySite = GET_PLAYER(getOwnerINLINE()).AI_getCitySite(iCitySite);
if (pCitySite->getArea() == getArea() || canMoveAllTerrain())
{
//int iPlotValue = GET_PLAYER(getOwnerINLINE()).AI_foundValue(pCitySite->getX_INLINE(), pCitySite->getY_INLINE());
int iPlotValue = pCitySite->getFoundValue(getOwnerINLINE());
if (iPlotValue > iBestValue)
{
//Can this unit reach the plot this turn? (getPathLastNode()->m_iData2 == 1)
//Will this unit still have movement points left to found the city the same turn? (getPathLastNode()->m_iData1 > 0))
if (generatePath(pCitySite))
{
int iFoundTurn = GC.getGameINLINE().getElapsedGameTurns() + getPathLastNode()->m_iData2 - ((getPathLastNode()->m_iData1 > 0)? 1 : 0);
if (iFoundTurn <= iMaxFoundTurn)
{
iPlotValue *= 100; //more precision
//the slower the game speed, the less penality the plotvalue gets for long walks towards it. On normal it's -18% per turn
iPlotValue *= 100 - std::min( 100, ( (1800/iGameSpeedPercent) * iFoundTurn ) );
iPlotValue /= 100;
if (iPlotValue > iBestValue)
{
iBestValue = iPlotValue;
iBestFoundTurn = iFoundTurn;
pBestPlot = pCitySite;
}
}
}
}
}
}
if (pBestPlot != NULL)
{
//Don't give up coast or river, don't settle on bonus with food
if ( (plot()->isRiver() && !pBestPlot->isRiver())
|| (plot()->isCoastalLand(GC.getMIN_WATER_SIZE_FOR_OCEAN()) && !pBestPlot->isCoastalLand(GC.getMIN_WATER_SIZE_FOR_OCEAN()))
|| (pBestPlot->getBonusType(NO_TEAM) != NO_BONUS && pBestPlot->calculateNatureYield(YIELD_FOOD, getTeam(), true) > 0) )
{
pBestPlot = NULL;
}
}
if (pBestPlot != NULL)
{
if( gUnitLogLevel >= 2 )
{
logBBAI(" Settler not founding in place but moving %d, %d to nearby city site at %d, %d (%d turns away) with value %d)", (pBestPlot->getX_INLINE() - plot()->getX_INLINE()), (pBestPlot->getY_INLINE() - plot()->getY_INLINE()), pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), iBestFoundTurn, iBestValue);
}
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_FOUND, pBestPlot);
return;
}
}
/************************************************************************************************/
/* Afforess & Fuyu END */
/************************************************************************************************/
// RevDCM TODO: What makes sense for rebels here?
if (canFound(plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
if( gUnitLogLevel >= 2 )
{
logBBAI(" Settler founding in place due to no cities");
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
getGroup()->pushMission(MISSION_FOUND);
return;
}
}
int iDanger = GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 3);
if (iDanger > 0)
{
if ((plot()->getOwnerINLINE() == getOwnerINLINE()) || (iDanger > 2))
{
joinGroup(NULL);
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
}
}
int iAreaBestFoundValue = 0;
int iOtherBestFoundValue = 0;
for (int iI = 0; iI < GET_PLAYER(getOwnerINLINE()).AI_getNumCitySites(); iI++)
{
CvPlot* pCitySitePlot = GET_PLAYER(getOwnerINLINE()).AI_getCitySite(iI);
/************************************************************************************************/
/* UNOFFICIAL_PATCH 01/10/09 jdog5000 */
/* */
/* Bugfix, settler AI */
/************************************************************************************************/
/* original bts code
if (pCitySitePlot->getArea() == getArea())
*/
// Only count city sites we can get to
if ((pCitySitePlot->getArea() == getArea() || canMoveAllTerrain()) && generatePath(pCitySitePlot, MOVE_SAFE_TERRITORY, true))
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
{
if (plot() == pCitySitePlot)
{
if (canFound(plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
if( gUnitLogLevel >= 2 )
{
logBBAI(" Settler founding in place since it's at a city site %d, %d", getX_INLINE(), getY_INLINE());
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
getGroup()->pushMission(MISSION_FOUND);
return;
}
}
iAreaBestFoundValue = std::max(iAreaBestFoundValue, pCitySitePlot->getFoundValue(getOwnerINLINE()));
}
else
{
iOtherBestFoundValue = std::max(iOtherBestFoundValue, pCitySitePlot->getFoundValue(getOwnerINLINE()));
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/16/09 jdog5000 */
/* */
/* Gold AI */
/************************************************************************************************/
// No new settling of colonies when AI is in financial trouble
if( plot()->isCity() && (plot()->getOwnerINLINE() == getOwnerINLINE()) )
{
if( GET_PLAYER(getOwnerINLINE()).AI_isFinancialTrouble() )
{
// Thomas SG
//iOtherBestFoundValue = 0;
iOtherBestFoundValue /= 4;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if ((iAreaBestFoundValue == 0) && (iOtherBestFoundValue == 0))
{
if ((GC.getGame().getGameTurn() - getGameTurnCreated()) > 20)
{
if (NULL != getTransportUnit())
{
getTransportUnit()->unloadAll();
}
if (NULL == getTransportUnit())
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 11/30/08 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
/* original bts code
//may seem wasteful, but settlers confuse the AI.
scrap();
return;
*/
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(getGroup()->getHeadUnit(), MISSIONAI_PICKUP) == 0 )
{
//may seem wasteful, but settlers confuse the AI.
scrap();
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
}
if ((iOtherBestFoundValue * 100) > (iAreaBestFoundValue * 110))
{
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, NO_UNITAI, -1, -1, -1, 0, MOVE_SAFE_TERRITORY))
{
return;
}
}
}
if ((iAreaBestFoundValue > 0) && plot()->isBestAdjacentFound(getOwnerINLINE()))
{
if (canFound(plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
if( gUnitLogLevel >= 2 )
{
logBBAI(" Settler founding in place due to best adjacent found");
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
getGroup()->pushMission(MISSION_FOUND);
return;
}
}
if (!GC.getGameINLINE().isOption(GAMEOPTION_ALWAYS_PEACE) && !GC.getGameINLINE().isOption(GAMEOPTION_AGGRESSIVE_AI) && !getGroup()->canDefend())
{
if (AI_retreatToCity())
{
return;
}
}
if (plot()->isCity() && (plot()->getOwnerINLINE() == getOwnerINLINE()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if ((GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot()) > 0)
if ((GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
&& (GC.getGameINLINE().getMaxCityElimination() > 0))
{
if (getGroup()->getNumUnits() < 3)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
if (iAreaBestFoundValue > 0)
{
if (AI_found())
{
return;
}
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, NO_UNITAI, -1, -1, -1, 0, MOVE_NO_ENEMY_TERRITORY))
{
return;
}
// BBAI TODO: Go to a good city (like one with a transport) ...
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_workerMove()
{
PROFILE_FUNC();
CvCity* pCity;
bool bCanRoute;
bool bNextCity;
bCanRoute = canBuildRoute();
bNextCity = false;
// XXX could be trouble...
if (plot()->getOwnerINLINE() != getOwnerINLINE())
{
if (AI_retreatToCity())
{
return;
}
}
if (!isHuman())
{
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, 2, -1, -1, 0, MOVE_SAFE_TERRITORY))
{
return;
}
}
}
if (!(getGroup()->canDefend()))
{
if (GET_PLAYER(getOwnerINLINE()).AI_isPlotThreatened(plot(), 2))
{
if (AI_retreatToCity()) // XXX maybe not do this??? could be working productively somewhere else...
{
return;
}
}
}
if (bCanRoute)
{
if (plot()->getOwnerINLINE() == getOwnerINLINE()) // XXX team???
{
BonusTypes eNonObsoleteBonus = plot()->getNonObsoleteBonusType(getTeam());
if (NO_BONUS != eNonObsoleteBonus)
{
if (!(plot()->isConnectedToCapital()))
{
ImprovementTypes eImprovement = plot()->getImprovementType();
if (NO_IMPROVEMENT != eImprovement && GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus))
{
if (AI_connectPlot(plot()))
{
return;
}
}
}
}
}
}
CvPlot* pBestBonusPlot = NULL;
BuildTypes eBestBonusBuild = NO_BUILD;
int iBestBonusValue = 0;
if (AI_improveBonus(25, &pBestBonusPlot, &eBestBonusBuild, &iBestBonusValue))
{
return;
}
if (bCanRoute && !isBarbarian())
{
if (AI_connectCity())
{
return;
}
}
pCity = NULL;
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
pCity = plot()->getPlotCity();
if (pCity == NULL)
{
pCity = plot()->getWorkingCity();
}
}
// if (pCity != NULL)
// {
// bool bMoreBuilds = false;
// for (iI = 0; iI < NUM_CITY_PLOTS; iI++)
// {
// CvPlot* pLoopPlot = plotCity(getX_INLINE(), getY_INLINE(), iI);
// if ((iI != CITY_HOME_PLOT) && (pLoopPlot != NULL))
// {
// if (pLoopPlot->getWorkingCity() == pCity)
// {
// if (pLoopPlot->isBeingWorked())
// {
// if (pLoopPlot->getImprovementType() == NO_IMPROVEMENT)
// {
// if (pCity->AI_getBestBuildValue(iI) > 0)
// {
// ImprovementTypes eImprovement;
// eImprovement = (ImprovementTypes)GC.getBuildInfo((BuildTypes)pCity->AI_getBestBuild(iI)).getImprovement();
// if (eImprovement != NO_IMPROVEMENT)
// {
// bMoreBuilds = true;
// break;
// }
// }
// }
// }
// }
// }
// }
//
// if (bMoreBuilds)
// {
// if (AI_improveCity(pCity))
// {
// return;
// }
// }
// }
if (pCity != NULL)
{
if ((pCity->AI_getWorkersNeeded() > 0) && (plot()->isCity() || (pCity->AI_getWorkersNeeded() < ((1 + pCity->AI_getWorkersHave() * 2) / 3))))
{
if (AI_improveCity(pCity))
{
return;
}
}
}
if (AI_improveLocalPlot(2, pCity))
{
return;
}
bool bBuildFort = false;
if (GC.getGame().getSorenRandNum(5, "AI Worker build Fort with Priority"))
{
bool bCanal = ((100 * area()->getNumCities()) / std::max(1, GC.getGame().getNumCities()) < 85);
CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE());
bool bAirbase = false;
bAirbase = (kPlayer.AI_totalUnitAIs(UNITAI_PARADROP) || kPlayer.AI_totalUnitAIs(UNITAI_ATTACK_AIR) || kPlayer.AI_totalUnitAIs(UNITAI_MISSILE_AIR));
if (bCanal || bAirbase)
{
if (AI_fortTerritory(bCanal, bAirbase))
{
return;
}
}
bBuildFort = true;
}
if (bCanRoute && isBarbarian())
{
if (AI_connectCity())
{
return;
}
}
if ((pCity == NULL) || (pCity->AI_getWorkersNeeded() == 0) || ((pCity->AI_getWorkersHave() > (pCity->AI_getWorkersNeeded() + 1))))
{
if ((pBestBonusPlot != NULL) && (iBestBonusValue >= 15))
{
if (AI_improvePlot(pBestBonusPlot, eBestBonusBuild))
{
return;
}
}
// if (pCity == NULL)
// {
// pCity = GC.getMapINLINE().findCity(getX_INLINE(), getY_INLINE(), getOwnerINLINE()); // XXX do team???
// }
if (AI_nextCityToImprove(pCity))
{
return;
}
bNextCity = true;
}
if (pBestBonusPlot != NULL)
{
if (AI_improvePlot(pBestBonusPlot, eBestBonusBuild))
{
return;
}
}
if (pCity != NULL)
{
if (AI_improveCity(pCity))
{
return;
}
}
if (!bNextCity)
{
if (AI_nextCityToImprove(pCity))
{
return;
}
}
if (bCanRoute)
{
if (AI_routeTerritory(true))
{
return;
}
if (AI_connectBonus(false))
{
return;
}
if (AI_routeCity())
{
return;
}
}
if (AI_irrigateTerritory())
{
return;
}
if (!bBuildFort)
{
bool bCanal = ((100 * area()->getNumCities()) / std::max(1, GC.getGame().getNumCities()) < 85);
CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE());
bool bAirbase = false;
bAirbase = (kPlayer.AI_totalUnitAIs(UNITAI_PARADROP) || kPlayer.AI_totalUnitAIs(UNITAI_ATTACK_AIR) || kPlayer.AI_totalUnitAIs(UNITAI_MISSILE_AIR));
if (bCanal || bAirbase)
{
if (AI_fortTerritory(bCanal, bAirbase))
{
return;
}
}
}
if (bCanRoute)
{
if (AI_routeTerritory())
{
return;
}
}
if (!isHuman() || (isAutomated() && GET_TEAM(getTeam()).getAtWarCount(true) == 0))
{
if (!isHuman() || (getGameTurnCreated() < GC.getGame().getGameTurn()))
{
if (AI_nextCityToImproveAirlift())
{
return;
}
}
if (!isHuman())
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/14/09 jdog5000 */
/* */
/* Worker AI */
/************************************************************************************************/
/*
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY))
{
return;
}
*/
// Fill up boats which already have workers
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_WORKER, -1, -1, -1, -1, MOVE_SAFE_TERRITORY))
{
return;
}
// Avoid filling a galley which has just a settler in it, reduce chances for other ships
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, NO_UNITAI, -1, 2, -1, -1, MOVE_SAFE_TERRITORY))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
if (AI_improveLocalPlot(3, NULL))
{
return;
}
if (!(isHuman()) && (AI_getUnitAIType() == UNITAI_WORKER))
{
if (GC.getGameINLINE().getElapsedGameTurns() > 10)
{
if (GET_PLAYER(getOwnerINLINE()).AI_totalUnitAIs(UNITAI_WORKER) > GET_PLAYER(getOwnerINLINE()).getNumCities())
{
if (GET_PLAYER(getOwnerINLINE()).calculateUnitCost() > 0)
{
scrap();
return;
}
}
}
}
if (AI_retreatToCity(false, true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Worker AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_barbAttackMove()
{
PROFILE_FUNC();
if (AI_guardCity(false, true, 1))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/15/10 jdog5000 */
/* */
/* Barbarian AI */
/************************************************************************************************/
if (plot()->isGoody())
{
if (AI_anyAttack(1, 90))
{
return;
}
if (plot()->plotCount(PUF_isUnitAIType, UNITAI_ATTACK, -1, getOwnerINLINE()) == 1 && getGroup()->getNumUnits() == 1)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (GC.getGameINLINE().getSorenRandNum(2, "AI Barb") == 0)
{
if (AI_pillageRange(1))
{
return;
}
}
if (AI_anyAttack(1, 20))
{
return;
}
if (GC.getGameINLINE().isOption(GAMEOPTION_RAGING_BARBARIANS))
{
if (AI_pillageRange(4))
{
return;
}
if (AI_cityAttack(3, 10))
{
return;
}
if (area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/15/10 jdog5000 */
/* */
/* Barbarian AI */
/************************************************************************************************/
if (AI_groupMergeRange(UNITAI_ATTACK, 1, true, true, true))
{
return;
}
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 3, true, true, true))
{
return;
}
if (AI_goToTargetCity(0, 12))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
else if (GC.getGameINLINE().getNumCivCities() > (GC.getGameINLINE().countCivPlayersAlive() * 3))
{
if (AI_cityAttack(1, 15))
{
return;
}
if (AI_pillageRange(3))
{
return;
}
if (AI_cityAttack(2, 10))
{
return;
}
if (area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/15/10 jdog5000 */
/* */
/* Barbarian AI */
/************************************************************************************************/
if (AI_groupMergeRange(UNITAI_ATTACK, 1, true, true, true))
{
return;
}
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 3, true, true, true))
{
return;
}
if (AI_goToTargetCity(0, 12))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
else if (GC.getGameINLINE().getNumCivCities() > (GC.getGameINLINE().countCivPlayersAlive() * 2))
{
if (AI_pillageRange(2))
{
return;
}
if (AI_cityAttack(1, 10))
{
return;
}
}
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 1))
{
return;
}
if (AI_heal())
{
return;
}
if (AI_guardCity(false, true, 2))
{
return;
}
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_attackMove()
{
PROFILE_FUNC();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/14/10 jdog5000 */
/* */
/* Unit AI, Settler AI, Efficiency */
/************************************************************************************************/
bool bDanger = (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 3));
if( getGroup()->getNumUnits() > 2 )
{
UnitAITypes eGroupAI = getGroup()->getHeadUnitAI();
if( eGroupAI == AI_getUnitAIType() )
{
if( plot()->getOwnerINLINE() == getOwnerINLINE() && !bDanger )
{
// Shouldn't have groups of > 2 attack units
if( getGroup()->countNumUnitAIType(UNITAI_ATTACK) > 2 )
{
getGroup()->AI_separate(); // will change group
FAssert( eGroupAI == getGroup()->getHeadUnitAI() );
}
// Should never have attack city group lead by attack unit
if( getGroup()->countNumUnitAIType(UNITAI_ATTACK_CITY) > 0 )
{
getGroup()->AI_separateAI(UNITAI_ATTACK_CITY); // will change group
// Since ATTACK can try to joing ATTACK_CITY again, need these units to
// take a break to let ATTACK_CITY group move and avoid hang
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
}
// Attack choking units
if( plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE() && bDanger )
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( iOurDefense < 3*iEnemyOffense )
{
if (AI_guardCity(true))
{
return;
}
}
if( iOurDefense > 2*iEnemyOffense )
{
if (AI_anyAttack(2, 55))
{
return;
}
}
if (AI_groupMergeRange(UNITAI_ATTACK, 1, true, true, false))
{
return;
}
if( iOurDefense > 2*iEnemyOffense )
{
if (AI_anyAttack(2, 30))
{
return;
}
}
}
{
PROFILE("CvUnitAI::AI_attackMove() 1");
// Guard a city we're in if it needs it
if (AI_guardCity(true))
{
return;
}
if( !(plot()->isOwned()) )
{
// Group with settler after naval drop
//Fuyu: could result in endless loop (at least it does in AND)
if( AI_groupMergeRange(UNITAI_SETTLE, 2, true, false, false) )
{
return;
}
}
if( !(plot()->isOwned()) || (plot()->getOwnerINLINE() == getOwnerINLINE()) )
{
if( area()->getCitiesPerPlayer(getOwnerINLINE()) > GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(area(), UNITAI_CITY_DEFENSE) )
{
// Defend colonies in new world
if (AI_guardCity(true, true, 3))
{
return;
}
}
}
if (AI_heal(30, 1))
{
return;
}
if (!bDanger)
{
if (AI_group(UNITAI_SETTLE, 1, -1, -1, false, false, false, 3, true))
{
return;
}
if (AI_group(UNITAI_SETTLE, 2, -1, -1, false, false, false, 3, true))
{
return;
}
}
if (AI_guardCityAirlift())
{
return;
}
if (AI_guardCity(false, true, 1))
{
return;
}
//join any city attacks in progress
if (plot()->isOwned() && plot()->getOwnerINLINE() != getOwnerINLINE())
{
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 1, true, true))
{
return;
}
}
AreaAITypes eAreaAIType = area()->getAreaAIType(getTeam());
if (plot()->isCity())
{
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if ((eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_ASSIST))
{
if (AI_offensiveAirlift())
{
return;
}
}
}
}
if (bDanger)
{
if (AI_cityAttack(1, 55))
{
return;
}
if (AI_anyAttack(1, 65))
{
return;
}
if (collateralDamage() > 0)
{
if (AI_anyAttack(1, 45, 3))
{
return;
}
}
}
if (!noDefensiveBonus())
{
if (AI_guardCity(false, false))
{
return;
}
}
if (!bDanger)
{
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
bool bAssault = ((eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_MASSING) || (eAreaAIType == AREAAI_ASSAULT_ASSIST));
if ( bAssault )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK_CITY, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, -1, -1, -1, 1, MOVE_SAFE_TERRITORY, 3))
{
return;
}
bool bLandWar = ((eAreaAIType == AREAAI_OFFENSIVE) || (eAreaAIType == AREAAI_DEFENSIVE) || (eAreaAIType == AREAAI_MASSING));
if (!bLandWar)
{
// Fill transports before starting new one, but not just full of our unit ai
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, 1, -1, -1, 1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
// Pick new transport which has space for other unit ai types to join
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, 2, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
if (GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_GROUP) > 0)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
// Allow larger groups if outside territory
if( getGroup()->getNumUnits() < 3 )
{
if( plot()->isOwned() && GET_TEAM(getTeam()).isAtWar(plot()->getTeam()) )
{
if (AI_groupMergeRange(UNITAI_ATTACK, 1, true, true, true))
{
return;
}
}
}
if (AI_goody(3))
{
return;
}
if (AI_anyAttack(1, 70))
{
return;
}
}
{
PROFILE("CvUnitAI::AI_attackMove() 2");
if (bDanger)
{
if (AI_pillageRange(1, 20))
{
return;
}
if (AI_cityAttack(1, 35))
{
return;
}
if (AI_anyAttack(1, 45))
{
return;
}
if (AI_pillageRange(3, 20))
{
return;
}
if( getGroup()->getNumUnits() < 4 )
{
if (AI_choke(1))
{
return;
}
}
if (AI_cityAttack(4, 30))
{
return;
}
if (AI_anyAttack(2, 40))
{
return;
}
}
if (!isEnemy(plot()->getTeam()))
{
if (AI_heal())
{
return;
}
}
if ((GET_PLAYER(getOwnerINLINE()).AI_getNumAIUnits(UNITAI_CITY_DEFENSE) > 0) || (GET_TEAM(getTeam()).getAtWarCount(true) > 0))
{
// BBAI TODO: If we're fast, maybe shadow an attack city stack and pillage off of it
bool bIgnoreFaster = false;
if (GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_LAND_BLITZ))
{
if (area()->getAreaAIType(getTeam()) != AREAAI_ASSAULT)
{
bIgnoreFaster = true;
}
}
if (AI_group(UNITAI_ATTACK_CITY, /*iMaxGroup*/ 1, /*iMaxOwnUnitAI*/ 1, -1, bIgnoreFaster, true, true, /*iMaxPath*/ 5))
{
return;
}
if (AI_group(UNITAI_ATTACK, /*iMaxGroup*/ 1, /*iMaxOwnUnitAI*/ 1, -1, true, true, false, /*iMaxPath*/ 4))
{
return;
}
// BBAI TODO: Need group to be fast, need to ignore slower groups
//if (GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_FASTMOVERS))
//{
// if (AI_group(UNITAI_ATTACK, /*iMaxGroup*/ 4, /*iMaxOwnUnitAI*/ 1, -1, true, false, false, /*iMaxPath*/ 3))
// {
// return;
// }
//}
if (AI_group(UNITAI_ATTACK, /*iMaxGroup*/ 1, /*iMaxOwnUnitAI*/ 1, -1, true, false, false, /*iMaxPath*/ 1))
{
return;
}
}
if (area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE)
{
if (getGroup()->getNumUnits() > 1)
{
//if (AI_targetCity())
if (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2, 12))
{
return;
}
}
}
else if( area()->getAreaAIType(getTeam()) != AREAAI_DEFENSIVE )
{
if (area()->getCitiesPerPlayer(BARBARIAN_PLAYER) > 0)
{
if (getGroup()->getNumUnits() >= GC.getHandicapInfo(GC.getGameINLINE().getHandicapType()).getBarbarianInitialDefenders())
{
if (AI_goToTargetBarbCity(10))
{
return;
}
}
}
}
if (AI_guardCity(false, true, 3))
{
return;
}
if ((GET_PLAYER(getOwnerINLINE()).getNumCities() > 1) && (getGroup()->getNumUnits() == 1))
{
if (area()->getAreaAIType(getTeam()) != AREAAI_DEFENSIVE)
{
if (area()->getNumUnrevealedTiles(getTeam()) > 0)
{
if (GET_PLAYER(getOwnerINLINE()).AI_areaMissionAIs(area(), MISSIONAI_EXPLORE, getGroup()) < (GET_PLAYER(getOwnerINLINE()).AI_neededExplorers(area()) + 1))
{
if (AI_exploreRange(3))
{
return;
}
if (AI_explore())
{
return;
}
}
}
}
}
if (AI_protect(35, 5))
{
return;
}
if (AI_offensiveAirlift())
{
return;
}
if (!bDanger && (area()->getAreaAIType(getTeam()) != AREAAI_DEFENSIVE))
{
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, 1, -1, -1, 1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
if( (GET_TEAM(getTeam()).getAtWarCount(true) > 0) && !(getGroup()->isHasPathToAreaEnemyCity(false)) )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
}
}
if (AI_defend())
{
return;
}
if (AI_travelToUpgradeCity())
{
return;
}
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
if( !bDanger && !isHuman() && plot()->isCoastalLand() && GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_PICKUP) > 0 )
{
// If no other desireable actions, wait for pickup
getGroup()->pushMission(MISSION_SKIP);
return;
}
if( getGroup()->getNumUnits() < 4 )
{
if (AI_patrol())
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
getGroup()->pushMission(MISSION_SKIP);
return;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
void CvUnitAI::AI_paratrooperMove()
{
PROFILE_FUNC();
bool bHostile = (plot()->isOwned() && isPotentialEnemy(plot()->getTeam()));
if (!bHostile)
{
if (AI_guardCity(true))
{
return;
}
if (plot()->getTeam() == getTeam())
{
if (plot()->isCity())
{
if (AI_heal(30, 1))
{
return;
}
}
AreaAITypes eAreaAIType = area()->getAreaAIType(getTeam());
bool bLandWar = ((eAreaAIType == AREAAI_OFFENSIVE) || (eAreaAIType == AREAAI_DEFENSIVE) || (eAreaAIType == AREAAI_MASSING));
if (!bLandWar)
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, 0, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
}
if (AI_guardCity(false, true, 1))
{
return;
}
}
if (AI_cityAttack(1, 45))
{
return;
}
if (AI_anyAttack(1, 55))
{
return;
}
if (!bHostile)
{
if (AI_paradrop(getDropRange()))
{
return;
}
if (AI_offensiveAirlift())
{
return;
}
if (AI_moveToStagingCity())
{
return;
}
if (AI_guardFort(true))
{
return;
}
if (AI_guardCityAirlift())
{
return;
}
}
if (collateralDamage() > 0)
{
if (AI_anyAttack(1, 45, 3))
{
return;
}
}
if (AI_pillageRange(1, 15))
{
return;
}
if (bHostile)
{
if (AI_choke(1))
{
return;
}
}
if (AI_heal())
{
return;
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
//if (AI_protect(35))
if (AI_protect(35, 5))
{
return;
}
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/02/10 jdog5000 */
/* */
/* War tactics AI, Barbarian AI */
/************************************************************************************************/
void CvUnitAI::AI_attackCityMove()
{
PROFILE_FUNC();
AreaAITypes eAreaAIType = area()->getAreaAIType(getTeam());
bool bLandWar = !isBarbarian() && ((eAreaAIType == AREAAI_OFFENSIVE) || (eAreaAIType == AREAAI_DEFENSIVE) || (eAreaAIType == AREAAI_MASSING));
bool bAssault = !isBarbarian() && ((eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_ASSIST) || (eAreaAIType == AREAAI_ASSAULT_MASSING));
bool bTurtle = GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_TURTLE);
bool bAlert1 = GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_ALERT1);
bool bIgnoreFaster = false;
if (GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_LAND_BLITZ))
{
if (!bAssault && area()->getCitiesPerPlayer(getOwnerINLINE()) > 0)
{
bIgnoreFaster = true;
}
}
bool bInCity = plot()->isCity();
if( bInCity && plot()->getOwnerINLINE() == getOwnerINLINE() )
{
// force heal if we in our own city and damaged
// can we remove this or call AI_heal here?
if ((getGroup()->getNumUnits() == 1) && (getDamage() > 0))
{
getGroup()->pushMission(MISSION_HEAL);
return;
}
if( bIgnoreFaster )
{
// BBAI TODO: split out slow units ... will need to test to make sure this doesn't cause loops
}
if ((GC.getGame().getGameTurn() - plot()->getPlotCity()->getGameTurnAcquired()) <= 1)
{
CvSelectionGroup* pOldGroup = getGroup();
pOldGroup->AI_separateNonAI(UNITAI_ATTACK_CITY);
if (pOldGroup != getGroup())
{
return;
}
}
if ((eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_ASSIST))
{
if (AI_offensiveAirlift())
{
return;
}
}
}
bool bAtWar = isEnemy(plot()->getTeam());
bool bHuntBarbs = false;
if (area()->getCitiesPerPlayer(BARBARIAN_PLAYER) > 0 && !isBarbarian())
{
if ((eAreaAIType != AREAAI_OFFENSIVE) && (eAreaAIType != AREAAI_DEFENSIVE) && !bAlert1 && !bTurtle)
{
bHuntBarbs = true;
}
}
bool bReadyToAttack = false;
if( !bTurtle )
{
bReadyToAttack = ((getGroup()->getNumUnits() >= ((bHuntBarbs) ? 3 : AI_stackOfDoomExtra())));
}
if( isBarbarian() )
{
bLandWar = (area()->getNumCities() - area()->getCitiesPerPlayer(BARBARIAN_PLAYER) > 0);
bReadyToAttack = (getGroup()->getNumUnits() >= 3);
}
if( bReadyToAttack )
{
// Check that stack has units which can capture cities
bReadyToAttack = false;
int iCityCaptureCount = 0;
CLLNode<IDInfo>* pUnitNode = getGroup()->headUnitNode();
while (pUnitNode != NULL && !bReadyToAttack)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = getGroup()->nextUnitNode(pUnitNode);
if( !pLoopUnit->isOnlyDefensive() )
{
if( !(pLoopUnit->isNoCapture()) && (pLoopUnit->combatLimit() >= 100) )
{
iCityCaptureCount++;
if( iCityCaptureCount > 5 || 3*iCityCaptureCount > getGroup()->getNumUnits() )
{
bReadyToAttack = true;
}
}
}
}
}
if (AI_guardCity(false, false))
{
if( bReadyToAttack && (eAreaAIType != AREAAI_DEFENSIVE))
{
CvSelectionGroup* pOldGroup = getGroup();
pOldGroup->AI_separateNonAI(UNITAI_ATTACK_CITY);
}
return;
}
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 0, true, true, bIgnoreFaster))
{
return;
}
CvCity* pTargetCity = NULL;
if( isBarbarian() )
{
pTargetCity = AI_pickTargetCity(0, 12);
}
else
{
// BBAI TODO: Find some way of reliably targetting nearby cities with less defense ...
pTargetCity = AI_pickTargetCity(0, MAX_INT, bHuntBarbs);
}
if( pTargetCity != NULL )
{
int iStepDistToTarget = stepDistance(pTargetCity->getX_INLINE(), pTargetCity->getY_INLINE(), getX_INLINE(), getY_INLINE());
int iAttackRatio = std::max(100, GC.getBBAI_ATTACK_CITY_STACK_RATIO());
if( isBarbarian() )
{
iAttackRatio = 80;
}
int iComparePostBombard = 0;
// AI gets a 1-tile sneak peak to compensate for lack of memory
if( iStepDistToTarget <= 2 || pTargetCity->isVisible(getTeam(),false) )
{
iComparePostBombard = getGroup()->AI_compareStacks(pTargetCity->plot(), true, true, true);
int iDefenseModifier = pTargetCity->getDefenseModifier(true);
int iBombardTurns = getGroup()->getBombardTurns(pTargetCity);
iDefenseModifier *= std::max(0, 20 - iBombardTurns);
iDefenseModifier /= 20;
iComparePostBombard *= 100 + std::max(0, iDefenseModifier);
iComparePostBombard /= 100;
}
if( iStepDistToTarget <= 2 )
{
if( iComparePostBombard < iAttackRatio )
{
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 2, true, true, bIgnoreFaster))
{
return;
}
int iOurOffense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),1,false,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(pTargetCity->plot(),2,false,false);
// If in danger, seek defensive ground
if( 4*iOurOffense < 3*iEnemyOffense )
{
if( AI_choke(1, true) )
{
return;
}
}
}
if (iStepDistToTarget == 1)
{
// If next to target city and we would attack after bombarding down defenses,
// or if defenses have crept up past half
if( (iComparePostBombard >= iAttackRatio) || (pTargetCity->getDefenseDamage() < ((GC.getMAX_CITY_DEFENSE_DAMAGE() * 1) / 2)) )
{
if( (iComparePostBombard < std::max(150, GC.getDefineINT("BBAI_SKIP_BOMBARD_MIN_STACK_RATIO"))) )
{
// Move to good tile to attack from unless we're way more powerful
if( AI_goToTargetCity(0,1,pTargetCity) )
{
return;
}
}
// Bombard may skip if stack is powerful enough
if (AI_bombardCity())
{
return;
}
//stack attack
if (getGroup()->getNumUnits() > 1)
{
// BBAI TODO: What is right ratio?
if (AI_stackAttackCity(1, iAttackRatio, true))
{
return;
}
}
// If not strong enough alone, merge if another stack is nearby
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 2, true, true, bIgnoreFaster))
{
return;
}
if( getGroup()->getNumUnits() == 1 )
{
if( AI_cityAttack(1, 50) )
{
return;
}
}
}
}
if( iComparePostBombard < iAttackRatio )
{
// If not strong enough, pillage around target city without exposing ourselves
if( AI_pillageRange(0) )
{
return;
}
if( AI_anyAttack(1, 60, 0, false) )
{
return;
}
if (AI_heal(30, 1))
{
return;
}
// Pillage around enemy city
if( AI_pillageAroundCity(pTargetCity, 11, 3) )
{
return;
}
if( AI_pillageAroundCity(pTargetCity, 0, 5) )
{
return;
}
if( AI_choke(1) )
{
return;
}
}
else
{
if( AI_goToTargetCity(0,4,pTargetCity) )
{
return;
}
}
}
}
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 2, true, true, bIgnoreFaster))
{
return;
}
if (AI_heal(30, 1))
{
return;
}
// BBAI TODO: Stack v stack combat ... definitely want to do in own territory, but what about enemy territory?
if (collateralDamage() > 0 && plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_anyAttack(1, 45, 3, false))
{
return;
}
if( !bReadyToAttack )
{
if (AI_anyAttack(1, 25, 5, false))
{
return;
}
}
}
if (AI_anyAttack(1, 60, 0, false))
{
return;
}
if (bAtWar && (getGroup()->getNumUnits() <= 2))
{
if (AI_pillageRange(3, 11))
{
return;
}
if (AI_pillageRange(1))
{
return;
}
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (!bLandWar)
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
if( bReadyToAttack )
{
// Wait for units about to join our group
MissionAITypes eMissionAIType = MISSIONAI_GROUP;
int iJoiners = GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 2);
if( (iJoiners*5) > getGroup()->getNumUnits() )
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
else
{
if( !isBarbarian() && (eAreaAIType == AREAAI_DEFENSIVE) )
{
// Use smaller attack city stacks on defense
if (AI_guardCity(false, true, 3))
{
return;
}
}
if( bTurtle )
{
if (AI_guardCity(false, true, 7))
{
return;
}
}
int iTargetCount = GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_GROUP);
if ((iTargetCount * 5) > getGroup()->getNumUnits())
{
MissionAITypes eMissionAIType = MISSIONAI_GROUP;
int iJoiners = GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 2);
if( (iJoiners*5) > getGroup()->getNumUnits() )
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_moveToStagingCity())
{
return;
}
}
}
}
if (AI_heal(50, 3))
{
return;
}
if (!bAtWar)
{
if (AI_heal())
{
return;
}
if ((getGroup()->getNumUnits() == 1) && (getTeam() != plot()->getTeam()))
{
if (AI_retreatToCity())
{
return;
}
}
}
if (!bReadyToAttack && !noDefensiveBonus())
{
if (AI_guardCity(false, false))
{
return;
}
}
bool bAnyWarPlan = (GET_TEAM(getTeam()).getAnyWarPlanCount(true) > 0);
if (bReadyToAttack)
{
if( isBarbarian() )
{
if (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2, 12))
{
return;
}
if (AI_pillageRange(3, 11))
{
return;
}
if (AI_pillageRange(1))
{
return;
}
}
else if (bHuntBarbs && AI_goToTargetBarbCity((bAnyWarPlan ? 7 : 12)))
{
return;
}
else if (bLandWar && pTargetCity != NULL)
{
// Before heading out, check whether to wait to allow unit upgrades
if( bInCity && plot()->getOwnerINLINE() == getOwnerINLINE() )
{
if( !(GET_PLAYER(getOwnerINLINE()).AI_isFinancialTrouble()) )
{
// Check if stack has units which can upgrade
int iNeedUpgradeCount = 0;
CLLNode<IDInfo>* pUnitNode = getGroup()->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = getGroup()->nextUnitNode(pUnitNode);
if( pLoopUnit->getUpgradeCity(false) != NULL )
{
iNeedUpgradeCount++;
if( 8*iNeedUpgradeCount > getGroup()->getNumUnits() )
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
}
}
if (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2, 5, pTargetCity))
{
return;
}
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 2, 2))
{
return;
}
if (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2, 8, pTargetCity))
{
return;
}
// Load stack if walking will take a long time
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4, 3))
{
return;
}
if (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2, 12, pTargetCity))
{
return;
}
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4, 7))
{
return;
}
if (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2, MAX_INT, pTargetCity))
{
return;
}
if (bAnyWarPlan)
{
CvCity* pTargetCity = area()->getTargetCity(getOwnerINLINE());
if (pTargetCity != NULL)
{
if (AI_solveBlockageProblem(pTargetCity->plot(), (GET_TEAM(getTeam()).getAtWarCount(true) == 0)))
{
return;
}
}
}
}
}
else
{
int iTargetCount = GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_GROUP);
if( ((iTargetCount * 4) > getGroup()->getNumUnits()) || ((getGroup()->getNumUnits() + iTargetCount) >= (bHuntBarbs ? 3 : AI_stackOfDoomExtra())) )
{
MissionAITypes eMissionAIType = MISSIONAI_GROUP;
int iJoiners = GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 2);
if( (iJoiners*6) > getGroup()->getNumUnits() )
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_safety())
{
return;
}
}
if ((bombardRate() > 0) && noDefensiveBonus())
{
// BBAI Notes: Add this stack lead by bombard unit to stack probably not lead by a bombard unit
// BBAI TODO: Some sense of minimum stack size? Can have big stack moving 10 turns to merge with tiny stacks
if (AI_group(UNITAI_ATTACK_CITY, -1, -1, -1, bIgnoreFaster, true, true, /*iMaxPath*/ 10, /*bAllowRegrouping*/ true))
{
return;
}
}
else
{
if (AI_group(UNITAI_ATTACK_CITY, AI_stackOfDoomExtra() * 2, -1, -1, bIgnoreFaster, true, true, /*iMaxPath*/ 10, /*bAllowRegrouping*/ false))
{
return;
}
}
}
if (plot()->getOwnerINLINE() == getOwnerINLINE() && bLandWar)
{
if( (GET_TEAM(getTeam()).getAtWarCount(true) > 0) )
{
// if no land path to enemy cities, try getting there another way
if (AI_offensiveAirlift())
{
return;
}
if( pTargetCity == NULL )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
}
}
if (AI_moveToStagingCity())
{
return;
}
if (AI_offensiveAirlift())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
if( !isHuman() && plot()->isCoastalLand() && GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_PICKUP) > 0 )
{
// If no other desireable actions, wait for pickup
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_patrol())
{
return;
}
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
void CvUnitAI::AI_attackCityLemmingMove()
{
if (AI_cityAttack(1, 80))
{
return;
}
if (AI_bombardCity())
{
return;
}
if (AI_cityAttack(1, 40))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/29/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (AI_goToTargetCity(MOVE_THROUGH_ENEMY))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
if (AI_anyAttack(1, 70))
{
return;
}
if (AI_anyAttack(1, 0))
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
}
void CvUnitAI::AI_collateralMove()
{
PROFILE_FUNC();
if (AI_leaveAttack(1, 20, 100))
{
return;
}
if (AI_guardCity(false, true, 1))
{
return;
}
if (AI_heal(30, 1))
{
return;
}
if (AI_cityAttack(1, 35))
{
return;
}
if (AI_anyAttack(1, 45, 3))
{
return;
}
if (AI_anyAttack(1, 55, 2))
{
return;
}
if (AI_anyAttack(1, 35, 3))
{
return;
}
if (AI_anyAttack(1, 30, 4))
{
return;
}
if (AI_anyAttack(1, 20, 5))
{
return;
}
if (AI_heal())
{
return;
}
if (!noDefensiveBonus())
{
if (AI_guardCity(false, false))
{
return;
}
}
if (AI_anyAttack(2, 55, 3))
{
return;
}
if (AI_cityAttack(2, 50))
{
return;
}
if (AI_anyAttack(2, 60))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
//if (AI_protect(50))
if (AI_protect(50, 8))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
if (AI_guardCity(false, true, 3))
{
return;
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_pillageMove()
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/05/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
PROFILE_FUNC();
if (AI_guardCity(false, true, 1))
{
return;
}
if (AI_heal(30, 1))
{
return;
}
// BBAI TODO: Shadow ATTACK_CITY stacks and pillage
//join any city attacks in progress
if (plot()->isOwned() && plot()->getOwnerINLINE() != getOwnerINLINE())
{
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 1, true, true))
{
return;
}
}
if (AI_cityAttack(1, 55))
{
return;
}
if (AI_anyAttack(1, 65))
{
return;
}
if (!noDefensiveBonus())
{
if (AI_guardCity(false, false))
{
return;
}
}
if (AI_pillageRange(3, 11))
{
return;
}
if (AI_choke(1))
{
return;
}
if (AI_pillageRange(1))
{
return;
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
if (AI_heal(50, 3))
{
return;
}
if (!isEnemy(plot()->getTeam()))
{
if (AI_heal())
{
return;
}
}
if (AI_group(UNITAI_PILLAGE, /*iMaxGroup*/ 1, /*iMaxOwnUnitAI*/ 1, -1, /*bIgnoreFaster*/ true, false, false, /*iMaxPath*/ 3))
{
return;
}
if ((area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE) || isEnemy(plot()->getTeam()))
{
if (AI_pillage(20))
{
return;
}
}
if (AI_heal())
{
return;
}
if (AI_guardCity(false, true, 3))
{
return;
}
if (AI_offensiveAirlift())
{
return;
}
if (AI_travelToUpgradeCity())
{
return;
}
if( !isHuman() && plot()->isCoastalLand() && GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_PICKUP) > 0 )
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
void CvUnitAI::AI_reserveMove()
{
PROFILE_FUNC();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//bool bDanger = (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 3) > 0);
bool bDanger = (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 3));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (bDanger && AI_leaveAttack(2, 55, 130))
{
return;
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, -1, -1, 1, -1, MOVE_SAFE_TERRITORY))
{
return;
}
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_WORKER, -1, -1, 1, -1, MOVE_SAFE_TERRITORY))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
if( !(plot()->isOwned()) )
{
if (AI_group(UNITAI_SETTLE, 1, -1, -1, false, false, false, 1, true))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (!bDanger)
{
if (AI_group(UNITAI_SETTLE, 2, -1, -1, false, false, false, 3, true))
{
return;
}
}
if (AI_guardCity(true))
{
return;
}
if (!noDefensiveBonus())
{
if (AI_guardFort(false))
{
return;
}
}
if (AI_guardCityAirlift())
{
return;
}
if (AI_guardCity(false, true, 1))
{
return;
}
if (AI_guardCitySite())
{
return;
}
if (!noDefensiveBonus())
{
if (AI_guardFort(true))
{
return;
}
if (AI_guardBonus(15))
{
return;
}
}
if (AI_heal(30, 1))
{
return;
}
if (bDanger)
{
if (AI_cityAttack(1, 55))
{
return;
}
if (AI_anyAttack(1, 60))
{
return;
}
}
if (!noDefensiveBonus())
{
if (AI_guardCity(false, false))
{
return;
}
}
if (bDanger)
{
if (AI_cityAttack(3, 45))
{
return;
}
if (AI_anyAttack(3, 50))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
//if (AI_protect(45))
if (AI_protect(45, 8))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
if (AI_guardCity(false, true, 3))
{
return;
}
if (AI_defend())
{
return;
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_counterMove()
{
PROFILE_FUNC();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/03/10 jdog5000 */
/* */
/* Unit AI, Settler AI */
/************************************************************************************************/
// Should never have group lead by counter unit
if( getGroup()->getNumUnits() > 1 )
{
UnitAITypes eGroupAI = getGroup()->getHeadUnitAI();
if( eGroupAI == AI_getUnitAIType() )
{
if( plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE() )
{
//FAssert(false); // just interested in when this happens, not a problem
getGroup()->AI_separate(); // will change group
return;
}
}
}
if( !(plot()->isOwned()) )
{
//Fuyu: could result in endless loop (at least it does in AND)
if( AI_groupMergeRange(UNITAI_SETTLE, 2, true, false, false) )
{
return;
}
}
if (AI_guardCity(false, true, 1))
{
return;
}
if (getSameTileHeal() > 0)
{
if (!canAttack())
{
// Don't restrict to groups carrying cargo ... does this apply to any units in standard bts anyway?
if (AI_shadow(UNITAI_ATTACK_CITY, -1, 21, false, false, 4))
{
return;
}
}
}
bool bDanger = (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 3));
AreaAITypes eAreaAIType = area()->getAreaAIType(getTeam());
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if( !bDanger )
{
if (plot()->isCity())
{
if ((eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_ASSIST))
{
if (AI_offensiveAirlift())
{
return;
}
}
}
if( (eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_ASSIST) || (eAreaAIType == AREAAI_ASSAULT_MASSING) )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK_CITY, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
}
if (!noDefensiveBonus())
{
if (AI_guardCity(false, false))
{
return;
}
}
}
//join any city attacks in progress
if (plot()->getOwnerINLINE() != getOwnerINLINE())
{
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 1, true, true))
{
return;
}
}
if (bDanger)
{
if (AI_cityAttack(1, 35))
{
return;
}
if (AI_anyAttack(1, 40))
{
return;
}
}
bool bIgnoreFasterStacks = false;
if (GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_LAND_BLITZ))
{
if (area()->getAreaAIType(getTeam()) != AREAAI_ASSAULT)
{
bIgnoreFasterStacks = true;
}
}
if (AI_group(UNITAI_ATTACK_CITY, /*iMaxGroup*/ -1, 2, -1, bIgnoreFasterStacks, /*bIgnoreOwnUnitType*/ true, /*bStackOfDoom*/ true, /*iMaxPath*/ 6))
{
return;
}
bool bFastMovers = (GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_FASTMOVERS));
if (AI_group(UNITAI_ATTACK, /*iMaxGroup*/ 2, -1, -1, bFastMovers, /*bIgnoreOwnUnitType*/ true, /*bStackOfDoom*/ true, /*iMaxPath*/ 5))
{
return;
}
// BBAI TODO: merge with nearby pillage
if (AI_guardCity(false, true, 3))
{
return;
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if( !bDanger )
{
if( (eAreaAIType != AREAAI_DEFENSIVE) )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK_CITY, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK, -1, -1, -1, -1, MOVE_SAFE_TERRITORY, 4))
{
return;
}
}
}
}
if (AI_heal())
{
return;
}
if (AI_offensiveAirlift())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
void CvUnitAI::AI_cityDefenseMove()
{
PROFILE_FUNC();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//bool bDanger = (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 3) > 0);
bool bDanger = (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 3));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
if( !(plot()->isOwned()) )
{
if (AI_group(UNITAI_SETTLE, 1, -1, -1, false, false, false, 2, true))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (bDanger)
{
if (AI_leaveAttack(1, 70, 175))
{
return;
}
if (AI_chokeDefend())
{
return;
}
}
if (AI_guardCityBestDefender())
{
return;
}
if (!bDanger)
{
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, -1, -1, 1, -1, MOVE_SAFE_TERRITORY, 1))
{
return;
}
}
}
if (AI_guardCityMinDefender(true))
{
return;
}
if (AI_guardCity(true))
{
return;
}
if (!bDanger)
{
if (AI_group(UNITAI_SETTLE, /*iMaxGroup*/ 1, -1, -1, false, false, false, /*iMaxPath*/ 2, /*bAllowRegrouping*/ true))
{
return;
}
if (AI_group(UNITAI_SETTLE, /*iMaxGroup*/ 2, -1, -1, false, false, false, /*iMaxPath*/ 2, /*bAllowRegrouping*/ true))
{
return;
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, -1, -1, 1, -1, MOVE_SAFE_TERRITORY))
{
return;
}
}
}
AreaAITypes eAreaAI = area()->getAreaAIType(getTeam());
if ((eAreaAI == AREAAI_ASSAULT) || (eAreaAI == AREAAI_ASSAULT_MASSING) || (eAreaAI == AREAAI_ASSAULT_ASSIST))
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK_CITY, -1, -1, -1, 0, MOVE_SAFE_TERRITORY))
{
return;
}
}
if ((AI_getBirthmark() % 4) == 0)
{
if (AI_guardFort())
{
return;
}
}
if (AI_guardCityAirlift())
{
return;
}
if (AI_guardCity(false, true, 1))
{
return;
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, 3, -1, -1, -1, MOVE_SAFE_TERRITORY))
{
// will enter here if in danger
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/02/10 jdog5000 */
/* */
/* City AI */
/************************************************************************************************/
//join any city attacks in progress
if (plot()->getOwnerINLINE() != getOwnerINLINE())
{
if (AI_groupMergeRange(UNITAI_ATTACK_CITY, 1, true, true))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_guardCity(false, true))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/04/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (!isBarbarian() && ((area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE) || (area()->getAreaAIType(getTeam()) == AREAAI_MASSING)))
{
bool bIgnoreFaster = false;
if (GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_LAND_BLITZ))
{
if (area()->getAreaAIType(getTeam()) != AREAAI_ASSAULT)
{
bIgnoreFaster = true;
}
}
if (AI_group(UNITAI_ATTACK_CITY, -1, 2, 4, bIgnoreFaster))
{
return;
}
}
if (area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT)
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, UNITAI_ATTACK_CITY, 2, -1, -1, 1, MOVE_SAFE_TERRITORY))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_cityDefenseExtraMove()
{
PROFILE_FUNC();
CvCity* pCity;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
if( !(plot()->isOwned()) )
{
if (AI_group(UNITAI_SETTLE, 1, -1, -1, false, false, false, 1, true))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_leaveAttack(2, 55, 150))
{
return;
}
if (AI_chokeDefend())
{
return;
}
if (AI_guardCityBestDefender())
{
return;
}
if (AI_guardCity(true))
{
return;
}
if (AI_group(UNITAI_SETTLE, /*iMaxGroup*/ 1, -1, -1, false, false, false, /*iMaxPath*/ 2, /*bAllowRegrouping*/ true))
{
return;
}
if (AI_group(UNITAI_SETTLE, /*iMaxGroup*/ 2, -1, -1, false, false, false, /*iMaxPath*/ 2, /*bAllowRegrouping*/ true))
{
return;
}
pCity = plot()->getPlotCity();
if ((pCity != NULL) && (pCity->getOwnerINLINE() == getOwnerINLINE())) // XXX check for other team?
{
if (plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isUnitAIType, AI_getUnitAIType()) == 1)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if (AI_guardCityAirlift())
{
return;
}
if (AI_guardCity(false, true, 1))
{
return;
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_load(UNITAI_SETTLER_SEA, MISSIONAI_LOAD_SETTLER, UNITAI_SETTLE, 3, -1, -1, -1, MOVE_SAFE_TERRITORY, 3))
{
return;
}
}
if (AI_guardCity(false, true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_exploreMove()
{
PROFILE_FUNC();
if (!isHuman() && canAttack())
{
if (AI_cityAttack(1, 60))
{
return;
}
if (AI_anyAttack(1, 70))
{
return;
}
}
if (getDamage() > 0)
{
// Mongoose FeatureDamageFix BEGIN
if ((plot()->getFeatureType() == NO_FEATURE) || (GC.getFeatureInfo(plot()->getFeatureType()).getTurnDamage() <= 0))
// Mongoose FeatureDamageFix END
{
getGroup()->pushMission(MISSION_HEAL);
return;
}
}
if (!isHuman())
{
if (AI_pillageRange(1))
{
return;
}
if (AI_cityAttack(3, 80))
{
return;
}
}
if (AI_goody(4))
{
return;
}
if (AI_exploreRange(3))
{
return;
}
if (!isHuman())
{
if (AI_pillageRange(3))
{
return;
}
}
if (AI_explore())
{
return;
}
if (!isHuman())
{
if (AI_pillage())
{
return;
}
}
if (!isHuman())
{
if (AI_travelToUpgradeCity())
{
return;
}
}
if (!isHuman() && (AI_getUnitAIType() == UNITAI_EXPLORE))
{
if (GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(area(), UNITAI_EXPLORE) > GET_PLAYER(getOwnerINLINE()).AI_neededExplorers(area()))
{
if (GET_PLAYER(getOwnerINLINE()).calculateUnitCost() > 0)
{
scrap();
return;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 12/03/08 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( !isHuman() && plot()->isCoastalLand() && GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_PICKUP) > 0 )
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_missionaryMove()
{
PROFILE_FUNC();
if (AI_spreadReligion())
{
return;
}
if (AI_spreadCorporation())
{
return;
}
if (!isHuman() || (isAutomated() && GET_TEAM(getTeam()).getAtWarCount(true) == 0))
{
if (!isHuman() || (getGameTurnCreated() < GC.getGame().getGameTurn()))
{
if (AI_spreadReligionAirlift())
{
return;
}
if (AI_spreadCorporationAirlift())
{
return;
}
}
if (!isHuman())
{
if (AI_load(UNITAI_MISSIONARY_SEA, MISSIONAI_LOAD_SPECIAL, NO_UNITAI, -1, -1, -1, 0, MOVE_SAFE_TERRITORY))
{
return;
}
if (AI_load(UNITAI_MISSIONARY_SEA, MISSIONAI_LOAD_SPECIAL, NO_UNITAI, -1, -1, -1, 0, MOVE_NO_ENEMY_TERRITORY))
{
return;
}
}
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_prophetMove()
{
PROFILE_FUNC();
if (AI_construct(1))
{
return;
}
if (AI_discover(true, true))
{
return;
}
if (AI_construct(3))
{
return;
}
int iGoldenAgeValue = (GET_PLAYER(getOwnerINLINE()).AI_calculateGoldenAgeValue() / (GET_PLAYER(getOwnerINLINE()).unitsRequiredForGoldenAge()));
int iDiscoverValue = std::max(1, getDiscoverResearch(NO_TECH));
if (((iGoldenAgeValue * 100) / iDiscoverValue) > 60)
{
if (AI_goldenAge())
{
return;
}
if (iDiscoverValue > iGoldenAgeValue)
{
if (AI_discover())
{
return;
}
if (GET_PLAYER(getOwnerINLINE()).getUnitClassCount(getUnitClassType()) > 1)
{
if (AI_join())
{
return;
}
}
}
}
else
{
if (AI_discover())
{
return;
}
if (AI_join())
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if ((GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0) ||
if ((GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 2)) ||
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
(getGameTurnCreated() < (GC.getGameINLINE().getGameTurn() - 25)))
{
if (AI_discover())
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_artistMove()
{
PROFILE_FUNC();
if (AI_artistCultureVictoryMove())
{
return;
}
if (AI_construct())
{
return;
}
if (AI_discover(true, true))
{
return;
}
if (AI_greatWork())
{
return;
}
int iGoldenAgeValue = (GET_PLAYER(getOwnerINLINE()).AI_calculateGoldenAgeValue() / (GET_PLAYER(getOwnerINLINE()).unitsRequiredForGoldenAge()));
int iDiscoverValue = std::max(1, getDiscoverResearch(NO_TECH));
if (((iGoldenAgeValue * 100) / iDiscoverValue) > 60)
{
if (AI_goldenAge())
{
return;
}
if (iDiscoverValue > iGoldenAgeValue)
{
if (AI_discover())
{
return;
}
if (GET_PLAYER(getOwnerINLINE()).getUnitClassCount(getUnitClassType()) > 1)
{
if (AI_join())
{
return;
}
}
}
}
else
{
if (AI_discover())
{
return;
}
if (AI_join())
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if ((GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0) ||
if ((GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 2)) ||
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
(getGameTurnCreated() < (GC.getGameINLINE().getGameTurn() - 25)))
{
if (AI_discover())
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_scientistMove()
{
PROFILE_FUNC();
if (AI_discover(true, true))
{
return;
}
if (AI_construct(MAX_INT, 1))
{
return;
}
if (GET_PLAYER(getOwnerINLINE()).getCurrentEra() < 3)
{
if (AI_join(2))
{
return;
}
}
if (GET_PLAYER(getOwnerINLINE()).getCurrentEra() <= (GC.getNumEraInfos() / 2))
{
if (AI_construct())
{
return;
}
}
int iGoldenAgeValue = (GET_PLAYER(getOwnerINLINE()).AI_calculateGoldenAgeValue() / (GET_PLAYER(getOwnerINLINE()).unitsRequiredForGoldenAge()));
int iDiscoverValue = std::max(1, getDiscoverResearch(NO_TECH));
if (((iGoldenAgeValue * 100) / iDiscoverValue) > 60)
{
if (AI_goldenAge())
{
return;
}
if (iDiscoverValue > iGoldenAgeValue)
{
if (AI_discover())
{
return;
}
if (GET_PLAYER(getOwnerINLINE()).getUnitClassCount(getUnitClassType()) > 1)
{
if (AI_join())
{
return;
}
}
}
}
else
{
if (AI_discover())
{
return;
}
if (AI_join())
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if ((GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0) ||
if ((GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 2)) ||
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
(getGameTurnCreated() < (GC.getGameINLINE().getGameTurn() - 25)))
{
if (AI_discover())
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_generalMove()
{
PROFILE_FUNC();
std::vector<UnitAITypes> aeUnitAITypes;
int iDanger = GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2);
bool bOffenseWar = (area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE);
if (iDanger > 0)
{
aeUnitAITypes.clear();
aeUnitAITypes.push_back(UNITAI_ATTACK);
aeUnitAITypes.push_back(UNITAI_COUNTER);
if (AI_lead(aeUnitAITypes))
{
return;
}
}
if (AI_construct(1))
{
return;
}
if (AI_join(1))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/14/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (bOffenseWar && (AI_getBirthmark() % 2 == 0))
{
aeUnitAITypes.clear();
aeUnitAITypes.push_back(UNITAI_ATTACK_CITY);
if (AI_lead(aeUnitAITypes))
{
return;
}
aeUnitAITypes.clear();
aeUnitAITypes.push_back(UNITAI_ATTACK);
if (AI_lead(aeUnitAITypes))
{
return;
}
}
if (AI_join(2))
{
return;
}
if (AI_construct(2))
{
return;
}
if (AI_join(4))
{
return;
}
if (GC.getGameINLINE().getSorenRandNum(3, "AI General Construct") == 0)
{
if (AI_construct())
{
return;
}
}
if (AI_join())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_merchantMove()
{
PROFILE_FUNC();
if (AI_construct())
{
return;
}
if (AI_discover(true, true))
{
return;
}
int iGoldenAgeValue = (GET_PLAYER(getOwnerINLINE()).AI_calculateGoldenAgeValue() / (GET_PLAYER(getOwnerINLINE()).unitsRequiredForGoldenAge()));
int iDiscoverValue = std::max(1, getDiscoverResearch(NO_TECH));
if (AI_trade(iGoldenAgeValue * 2))
{
return;
}
if (((iGoldenAgeValue * 100) / iDiscoverValue) > 60)
{
if (AI_goldenAge())
{
return;
}
if (AI_trade(iGoldenAgeValue))
{
return;
}
if (iDiscoverValue > iGoldenAgeValue)
{
if (AI_discover())
{
return;
}
if (GET_PLAYER(getOwnerINLINE()).getUnitClassCount(getUnitClassType()) > 1)
{
if (AI_join())
{
return;
}
}
}
}
else
{
if (AI_discover())
{
return;
}
if (AI_join())
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if ((GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0) ||
if ((GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 2)) ||
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
(getGameTurnCreated() < (GC.getGameINLINE().getGameTurn() - 25)))
{
if (AI_discover())
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_engineerMove()
{
PROFILE_FUNC();
if (AI_construct())
{
return;
}
if (AI_switchHurry())
{
return;
}
if (AI_hurry())
{
return;
}
if (AI_discover(true, true))
{
return;
}
int iGoldenAgeValue = (GET_PLAYER(getOwnerINLINE()).AI_calculateGoldenAgeValue() / (GET_PLAYER(getOwnerINLINE()).unitsRequiredForGoldenAge()));
int iDiscoverValue = std::max(1, getDiscoverResearch(NO_TECH));
if (((iGoldenAgeValue * 100) / iDiscoverValue) > 60)
{
if (AI_goldenAge())
{
return;
}
if (iDiscoverValue > iGoldenAgeValue)
{
if (AI_discover())
{
return;
}
if (GET_PLAYER(getOwnerINLINE()).getUnitClassCount(getUnitClassType()) > 1)
{
if (AI_join())
{
return;
}
}
}
}
else
{
if (AI_discover())
{
return;
}
if (AI_join())
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if ((GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0) ||
if ((GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 2)) ||
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
(getGameTurnCreated() < (GC.getGameINLINE().getGameTurn() - 25)))
{
if (AI_discover())
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( getGroup()->isStranded() )
{
if (AI_load(UNITAI_ASSAULT_SEA, MISSIONAI_LOAD_ASSAULT, NO_UNITAI, -1, -1, -1, -1, MOVE_NO_ENEMY_TERRITORY, 1))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/25/10 jdog5000 */
/* */
/* Espionage AI */
/************************************************************************************************/
void CvUnitAI::AI_spyMove()
{
PROFILE_FUNC();
CvTeamAI& kTeam = GET_TEAM(getTeam());
int iEspionageChance = 0;
if (plot()->isOwned() && (plot()->getTeam() != getTeam()))
{
switch (GET_PLAYER(getOwnerINLINE()).AI_getAttitude(plot()->getOwnerINLINE()))
{
case ATTITUDE_FURIOUS:
iEspionageChance = 100;
break;
case ATTITUDE_ANNOYED:
iEspionageChance = 50;
break;
case ATTITUDE_CAUTIOUS:
iEspionageChance = (GC.getGameINLINE().isOption(GAMEOPTION_AGGRESSIVE_AI) ? 30 : 10);
break;
case ATTITUDE_PLEASED:
iEspionageChance = (GC.getGameINLINE().isOption(GAMEOPTION_AGGRESSIVE_AI) ? 20 : 0);
break;
case ATTITUDE_FRIENDLY:
iEspionageChance = 0;
break;
default:
FAssert(false);
break;
}
WarPlanTypes eWarPlan = kTeam.AI_getWarPlan(plot()->getTeam());
if (eWarPlan != NO_WARPLAN)
{
if (eWarPlan == WARPLAN_LIMITED)
{
iEspionageChance += 50;
}
else
{
iEspionageChance += 20;
}
}
if (plot()->isCity() && plot()->getTeam() != getTeam())
{
bool bTargetCity = false;
// would we have more power if enemy defenses were down?
int iOurPower = GET_PLAYER(getOwnerINLINE()).AI_getOurPlotStrength(plot(),1,false,true);
int iEnemyPower = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),0,false,false);
if( 5*iOurPower > 6*iEnemyPower && eWarPlan != NO_WARPLAN )
{
bTargetCity = true;
if( AI_revoltCitySpy() )
{
return;
}
if (GC.getGame().getSorenRandNum(5, "AI Spy Skip Turn") > 0)
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
return;
}
if ( AI_cityOffenseSpy(5, plot()->getPlotCity()) )
{
return;
}
}
if( GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(plot(), MISSIONAI_ASSAULT, getGroup()) > 0 )
{
bTargetCity = true;
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
return;
}
if( !bTargetCity )
{
// normal city handling
if (getFortifyTurns() >= GC.getDefineINT("MAX_FORTIFY_TURNS"))
{
if (AI_espionageSpy())
{
return;
}
}
else if (GC.getGame().getSorenRandNum(100, "AI Spy Skip Turn") > 5)
{
// don't get stuck forever
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
return;
}
}
}
else if (GC.getGameINLINE().getSorenRandNum(100, "AI Spy Espionage") < iEspionageChance)
{
// This applies only when not in an enemy city, so for destroying improvements
if (AI_espionageSpy())
{
return;
}
}
}
if (plot()->getTeam() == getTeam())
{
if (kTeam.getAnyWarPlanCount(true) == 0 || GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_SPACE4) || GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_CULTURE3))
{
if( GC.getGame().getSorenRandNum(10, "AI Spy defense") > 0)
{
if (AI_guardSpy(0))
{
return;
}
}
}
if (GC.getGame().getSorenRandNum(100, "AI Spy pillage improvement") < 25)
{
if (AI_bonusOffenseSpy(5))
{
return;
}
}
else
{
if (AI_cityOffenseSpy(10))
{
return;
}
}
}
if (iEspionageChance > 0 && (plot()->isCity() || (plot()->getNonObsoleteBonusType(getTeam()) != NO_BONUS)))
{
if (GC.getGame().getSorenRandNum(7, "AI Spy Skip Turn") > 0)
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
return;
}
}
if( area()->getNumCities() > area()->getCitiesPerPlayer(getOwnerINLINE()) )
{
if (GC.getGame().getSorenRandNum(4, "AI Spy Choose Movement") > 0)
{
if (AI_reconSpy(3))
{
return;
}
}
else
{
if (AI_cityOffenseSpy(10))
{
return;
}
}
}
if (AI_load(UNITAI_SPY_SEA, MISSIONAI_LOAD_SPECIAL, NO_UNITAI, -1, -1, -1, 0, MOVE_NO_ENEMY_TERRITORY))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
void CvUnitAI::AI_ICBMMove()
{
PROFILE_FUNC();
// CvCity* pCity = plot()->getPlotCity();
// if (pCity != NULL)
// {
// if (pCity->AI_isDanger())
// {
// if (!(pCity->AI_isDefended()))
// {
// if (AI_airCarrier())
// {
// return;
// }
// }
// }
// }
if (airRange() > 0)
{
if (AI_nukeRange(airRange()))
{
return;
}
}
else if (AI_nuke())
{
return;
}
if (isCargo())
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (airRange() > 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/25/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if (4*iEnemyOffense > iOurDefense || iOurDefense == 0)
{
// Too risky, pull back
if (AI_airOffensiveCity())
{
return;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_missileLoad(UNITAI_MISSILE_CARRIER_SEA, 2, true))
{
return;
}
if (AI_missileLoad(UNITAI_MISSILE_CARRIER_SEA, 1, false))
{
return;
}
if (AI_getBirthmark() % 3 == 0)
{
if (AI_missileLoad(UNITAI_ATTACK_SEA, 0, false))
{
return;
}
}
if (AI_airOffensiveCity())
{
return;
}
}
getGroup()->pushMission(MISSION_SKIP);
}
void CvUnitAI::AI_workerSeaMove()
{
PROFILE_FUNC();
CvCity* pCity;
int iI;
if (!(getGroup()->canDefend()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot()) > 0)
if (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (AI_retreatToCity())
{
return;
}
}
}
if (AI_improveBonus(20))
{
return;
}
if (AI_improveBonus(10))
{
return;
}
if (AI_improveBonus())
{
return;
}
if (isHuman())
{
FAssert(isAutomated());
if (plot()->getBonusType() != NO_BONUS)
{
if ((plot()->getOwnerINLINE() == getOwnerINLINE()) || (!plot()->isOwned()))
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
CvPlot* pLoopPlot = plotDirection(getX_INLINE(), getY_INLINE(), (DirectionTypes)iI);
if (pLoopPlot != NULL)
{
if (pLoopPlot->getBonusType() != NO_BONUS)
{
if (pLoopPlot->isValidDomainForLocation(*this))
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
}
}
if (!(isHuman()) && (AI_getUnitAIType() == UNITAI_WORKER_SEA))
{
pCity = plot()->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (pCity->AI_neededSeaWorkers() == 0)
{
if (GC.getGameINLINE().getElapsedGameTurns() > 10)
{
if (GET_PLAYER(getOwnerINLINE()).calculateUnitCost() > 0)
{
scrap();
return;
}
}
}
else
{
//Probably icelocked since it can't perform actions.
scrap();
return;
}
}
}
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_barbAttackSeaMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 9/25/08 jdog5000 */
/* */
/* Barbarian AI */
/********************************************************************************/
/* original BTS code
if (GC.getGameINLINE().getSorenRandNum(2, "AI Barb") == 0)
{
if (AI_pillageRange(1))
{
return;
}
}
if (AI_anyAttack(2, 25))
{
return;
}
if (AI_pillageRange(4))
{
return;
}
if (AI_heal())
{
return;
}
*/
// Less suicide, always chase good targets
if( AI_anyAttack(2,51) )
{
return;
}
if (AI_pillageRange(1))
{
return;
}
if( AI_anyAttack(1,34) )
{
return;
}
// We're easy to take out if wounded
if (AI_heal())
{
return;
}
if (AI_pillageRange(3))
{
return;
}
// Barb ships will often hang out for a little while blockading before moving on
if( (GC.getGame().getGameTurn() + getID())%12 > 5 )
{
if( AI_pirateBlockade())
{
return;
}
}
if( GC.getGameINLINE().getSorenRandNum(3, "AI Check trapped") == 0 )
{
// If trapped in small hole in ice or around tiny island, disband to allow other units to be generated
bool bScrap = true;
int iMaxRange = baseMoves() + 2;
for (int iDX = -(iMaxRange); iDX <= iMaxRange; iDX++)
{
for (int iDY = -(iMaxRange); iDY <= iMaxRange; iDY++)
{
if( bScrap )
{
CvPlot* pLoopPlot = plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL && AI_plotValid(pLoopPlot))
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if( iPathTurns > 1 )
{
bScrap = false;
}
}
}
}
}
}
if( bScrap )
{
scrap();
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/23/10 jdog5000 */
/* */
/* Pirate AI */
/************************************************************************************************/
void CvUnitAI::AI_pirateSeaMove()
{
PROFILE_FUNC();
CvArea* pWaterArea;
// heal in defended, unthreatened forts and cities
if (plot()->isCity(true) && (GET_PLAYER(getOwnerINLINE()).AI_getOurPlotStrength(plot(),0,true,false) > 0) && !(GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot(), 2, false)) )
{
if (AI_heal())
{
return;
}
}
if (plot()->isOwned() && (plot()->getTeam() == getTeam()))
{
if (AI_anyAttack(2, 40))
{
return;
}
//if (AI_protect(30))
if (AI_protect(40, 3))
{
return;
}
if (((AI_getBirthmark() / 8) % 2) == 0)
{
// Previously code actually blocked grouping
if (AI_group(UNITAI_PIRATE_SEA, -1, 1, -1, true, false, false, 8))
{
return;
}
}
}
else
{
if (AI_anyAttack(2, 51))
{
return;
}
}
if (GC.getGame().getSorenRandNum(10, "AI Pirate Explore") == 0)
{
pWaterArea = plot()->waterArea();
if (pWaterArea != NULL)
{
if (pWaterArea->getNumUnrevealedTiles(getTeam()) > 0)
{
if (GET_PLAYER(getOwnerINLINE()).AI_areaMissionAIs(pWaterArea, MISSIONAI_EXPLORE, getGroup()) < (GET_PLAYER(getOwnerINLINE()).AI_neededExplorers(pWaterArea)))
{
if (AI_exploreRange(2))
{
return;
}
}
}
}
}
if (GC.getGame().getSorenRandNum(11, "AI Pirate Pillage") == 0)
{
if (AI_pillageRange(1))
{
return;
}
}
//Includes heal and retreat to sea routines.
if (AI_pirateBlockade())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
void CvUnitAI::AI_attackSeaMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 06/14/09 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0) //prioritize getting outta there
{
if (AI_anyAttack(2, 50))
{
return;
}
if (AI_shadow(UNITAI_ASSAULT_SEA, 4, 34, false, true, 2))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
//if (AI_protect(35))
if (AI_protect(35, 3))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_heal(30, 1))
{
return;
}
if (AI_anyAttack(1, 35))
{
return;
}
if (AI_anyAttack(2, 40))
{
return;
}
if (AI_seaBombardRange(6))
{
return;
}
if (AI_heal(50, 3))
{
return;
}
if (AI_heal())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/10/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
// BBAI TODO: Turn this into a function, have docked escort ships do it to
//Fuyu: search for more attackers, and when enough are found, always try to break through
CvCity* pCity = plot()->getPlotCity();
if( pCity != NULL )
{
if( pCity->isBlockaded() )
{
int iBlockadeRange = GC.getDefineINT("SHIP_BLOCKADE_RANGE");
// City under blockade
// Attacker has low odds since anyAttack checks above passed, try to break if sufficient numbers
int iAttackers = plot()->plotCount(PUF_isUnitAIType, UNITAI_ATTACK_SEA, -1, NO_PLAYER, getTeam(), PUF_isGroupHead, -1, -1);
int iBlockaders = GET_PLAYER(getOwnerINLINE()).AI_getWaterDanger(plot(), (iBlockadeRange + 1));
//bool bBreakBlockade = (iAttackers > (iBlockaders + 2) || iAttackers >= 2*iBlockaders);
if (true)
{
int iMaxRange = iBlockadeRange - 1;
if( gUnitLogLevel > 2 ) logBBAI(" Not enough attack fleet found in %S, searching for more in a %d-tile radius", pCity->getName().GetCString(), iMaxRange);
for (int iDX = -(iMaxRange); iDX <= iMaxRange; iDX++)
{
for (int iDY = -(iMaxRange); iDY <= iMaxRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(plot()->getX_INLINE(), plot()->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL && pLoopPlot->isWater())
{
if (pLoopPlot->getBlockadedCount(getTeam()) > 0)
{
iAttackers += pLoopPlot->plotCount(PUF_isUnitAIType, UNITAI_ATTACK_SEA, -1, NO_PLAYER, getTeam(), PUF_isGroupHead, -1, -1);
}
}
}
}
}
//bBreakBlockade = (iAttackers > (iBlockaders + 2) || iAttackers >= 2*iBlockaders);
//if (bBreakBlockade)
if (iAttackers > (iBlockaders + 2) || iAttackers >= 2*iBlockaders)
{
if( gUnitLogLevel > 2 ) logBBAI(" Found %d attackers and %d blockaders, proceeding to break blockade", iAttackers, iBlockaders);
if(true) /* (iAttackers > GC.getGameINLINE().getSorenRandNum(2*iBlockaders + 1, "AI - Break blockade")) */
{
// BBAI TODO: Make odds scale by # of blockaders vs number of attackers
if (baseMoves() >= iBlockadeRange)
{
if (AI_anyAttack(1, 15))
{
return;
}
}
else
{
//Fuyu: Even slow ships should attack
//Assuming that every ship can reach a blockade with 2 moves
if (AI_anyAttack(2, 15))
{
return;
}
}
//If no mission was pushed yet and we have a lot of ships, try again with even lower odds
if(iAttackers > 2*iBlockaders)
{
if (AI_anyAttack(1, 10))
{
return;
}
}
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_group(UNITAI_CARRIER_SEA, /*iMaxGroup*/ 4, 1, -1, true, false, false, /*iMaxPath*/ 5))
{
return;
}
if (AI_group(UNITAI_ATTACK_SEA, /*iMaxGroup*/ 1, -1, -1, true, false, false, /*iMaxPath*/ 3))
{
return;
}
if (!plot()->isOwned() || !isEnemy(plot()->getTeam()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/11/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
if (AI_shadow(UNITAI_ASSAULT_SEA, 4, 34))
{
return;
}
if (AI_shadow(UNITAI_CARRIER_SEA, 4, 51))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, 4, -1, false, false, false))
{
return;
}
}
if (AI_group(UNITAI_CARRIER_SEA, -1, 1, -1, false, false, false))
{
return;
}
*/
if (AI_shadow(UNITAI_ASSAULT_SEA, 4, 34, true, false, 4))
{
return;
}
if (AI_shadow(UNITAI_CARRIER_SEA, 4, 51, true, false, 5))
{
return;
}
// Group with large flotillas first
if (AI_group(UNITAI_ASSAULT_SEA, -1, 4, 3, false, false, false, 3, false, true, false))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, 2, -1, false, false, false, 5, false, true, false))
{
return;
}
}
if (AI_group(UNITAI_CARRIER_SEA, -1, 1, -1, false, false, false, 10))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (plot()->isOwned() && (isEnemy(plot()->getTeam())))
{
if (AI_blockade())
{
return;
}
}
if (AI_pillageRange(4))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
//if (AI_protect(35))
if (AI_protect(35, 3))
{
return;
}
if (AI_protect(35, 8))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
if (AI_travelToUpgradeCity())
{
return;
}
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_reserveSeaMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 06/14/09 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0) //prioritize getting outta there
{
if (AI_anyAttack(2, 60))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
//if (AI_protect(40))
if (AI_protect(40, 3))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
if (AI_shadow(UNITAI_SETTLER_SEA, 2, -1, false, true, 4))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_guardBonus(30))
{
return;
}
if (AI_heal(30, 1))
{
return;
}
if (AI_anyAttack(1, 55))
{
return;
}
if (AI_seaBombardRange(6))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
//if (AI_protect(40))
if (AI_protect(40, 5))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/03/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
if (AI_shadow(UNITAI_SETTLER_SEA, 1, -1, true))
{
return;
}
if (AI_group(UNITAI_RESERVE_SEA, 1))
{
return;
}
if (bombardRate() > 0)
{
if (AI_shadow(UNITAI_ASSAULT_SEA, 2, 30, true))
{
return;
}
}
*/
// Shadow any nearby settler sea transport out at sea
if (AI_shadow(UNITAI_SETTLER_SEA, 2, -1, false, true, 5))
{
return;
}
if (AI_group(UNITAI_RESERVE_SEA, 1, -1, -1, false, false, false, 8))
{
return;
}
if (bombardRate() > 0)
{
if (AI_shadow(UNITAI_ASSAULT_SEA, 2, 30, true, false, 8))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_heal(50, 3))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if (AI_protect(40))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_anyAttack(3, 45))
{
return;
}
if (AI_heal())
{
return;
}
if (!isNeverInvisible())
{
if (AI_anyAttack(5, 35))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/03/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
// Shadow settler transport with cargo
if (AI_shadow(UNITAI_SETTLER_SEA, 1, -1, true, false, 10))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_travelToUpgradeCity())
{
return;
}
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_escortSeaMove()
{
PROFILE_FUNC();
// // if we have cargo, possibly convert to UNITAI_ASSAULT_SEA (this will most often happen with galleons)
// // note, this should not happen when we are not the group head, so escort galleons are fine joining a group, just not as head
// if (hasCargo() && (getUnitAICargo(UNITAI_ATTACK_CITY) > 0 || getUnitAICargo(UNITAI_ATTACK) > 0))
// {
// // non-zero AI_unitValue means that UNITAI_ASSAULT_SEA is valid for this unit (that is the check used everywhere)
// if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_ASSAULT_SEA, NULL) > 0)
// {
// // save old group, so we can merge it back in
// CvSelectionGroup* pOldGroup = getGroup();
//
// // this will remove this unit from the current group
// AI_setUnitAIType(UNITAI_ASSAULT_SEA);
//
// // merge back the rest of the group into the new group
// CvSelectionGroup* pNewGroup = getGroup();
// if (pOldGroup != pNewGroup)
// {
// pOldGroup->mergeIntoGroup(pNewGroup);
// }
//
// // perform assault sea action
// AI_assaultSeaMove();
// return;
// }
// }
/********************************************************************************/
/* BETTER_BTS_AI_MOD 06/14/09 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true)) //prioritize getting outta there
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0)
{
if (AI_anyAttack(1, 60))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ 1, -1, /*bIgnoreFaster*/ true, false, false, /*iMaxPath*/ 1))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_heal(30, 1))
{
return;
}
if (AI_anyAttack(1, 55))
{
return;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 9/14/08 jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
// Galleons can get stuck with this AI type since they don't upgrade to any escort unit
// Galleon escorts are much less useful once Frigates or later are available
if (!isHuman() && !isBarbarian())
{
if( getCargo() > 0 && (GC.getUnitInfo(getUnitType()).getSpecialCargo() == NO_SPECIALUNIT) )
{
//Obsolete?
int iValue = GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), AI_getUnitAIType(), area());
int iBestValue = GET_PLAYER(getOwnerINLINE()).AI_bestAreaUnitAIValue(AI_getUnitAIType(), area());
if (iValue < iBestValue)
{
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_ASSAULT_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_ASSAULT_SEA);
return;
}
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_SETTLER_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_SETTLER_SEA);
return;
}
scrap();
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_group(UNITAI_CARRIER_SEA, -1, /*iMaxOwnUnitAI*/ 0, -1, /*bIgnoreFaster*/ true))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ 0, -1, /*bIgnoreFaster*/ true, false, false, /*iMaxPath*/ 3))
{
return;
}
if (AI_heal(50, 3))
{
return;
}
if (AI_pillageRange(2))
{
return;
}
if (AI_group(UNITAI_MISSILE_CARRIER_SEA, 1, 1, true))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, 1, /*iMaxOwnUnitAI*/ 0, /*iMinUnitAI*/ -1, /*bIgnoreFaster*/ true))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ 2, /*iMinUnitAI*/ -1, /*bIgnoreFaster*/ true))
{
return;
}
if (AI_group(UNITAI_CARRIER_SEA, -1, /*iMaxOwnUnitAI*/ 2, /*iMinUnitAI*/ -1, /*bIgnoreFaster*/ true))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/01/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
if (AI_group(UNITAI_ASSAULT_SEA, -1, 4, -1, true))
{
return;
}
*/
// Group only with large flotillas first
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ 4, /*iMinUnitAI*/ 3, /*bIgnoreFaster*/ true))
{
return;
}
if (AI_shadow(UNITAI_SETTLER_SEA, 2, -1, false, true, 4))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_heal())
{
return;
}
if (AI_travelToUpgradeCity())
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/18/10 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
// If nothing else useful to do, escort nearby large flotillas even if they're faster
// Gives Caravel escorts something to do during the Galleon/pre-Frigate era
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ 4, /*iMinUnitAI*/ 3, /*bIgnoreFaster*/ false, false, false, 4, false, true))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ 2, /*iMinUnitAI*/ -1, /*bIgnoreFaster*/ false, false, false, 1, false, true))
{
return;
}
// Pull back to primary area if it's not too far so primary area cities know you exist
// and don't build more, unnecessary escorts
if (AI_retreatToCity(true,false,6))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_exploreSeaMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true)) //prioritize getting outta there
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 )
{
if (!isHuman())
{
if (AI_anyAttack(1, 60))
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
CvArea* pWaterArea = plot()->waterArea();
if (!isHuman())
{
if (AI_anyAttack(1, 60))
{
return;
}
}
if (!isHuman() && !isBarbarian()) //XXX move some of this into a function? maybe useful elsewhere
{
//Obsolete?
int iValue = GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), AI_getUnitAIType(), area());
int iBestValue = GET_PLAYER(getOwnerINLINE()).AI_bestAreaUnitAIValue(AI_getUnitAIType(), area());
if (iValue < iBestValue)
{
//Transform
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_WORKER_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_WORKER_SEA);
return;
}
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_PIRATE_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_PIRATE_SEA);
return;
}
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_MISSIONARY_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_MISSIONARY_SEA);
return;
}
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_RESERVE_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_RESERVE_SEA);
return;
}
scrap();
}
}
if (getDamage() > 0)
{
// Mongoose FeatureDamageFix BEGIN
if ((plot()->getFeatureType() == NO_FEATURE) || (GC.getFeatureInfo(plot()->getFeatureType()).getTurnDamage() <= 0))
// Mongoose FeatureDamageFix ÉND
{
getGroup()->pushMission(MISSION_HEAL);
return;
}
}
if (!isHuman())
{
if (AI_pillageRange(1))
{
return;
}
}
if (AI_exploreRange(4))
{
return;
}
if (!isHuman())
{
if (AI_pillageRange(4))
{
return;
}
}
if (AI_explore())
{
return;
}
if (!isHuman())
{
if (AI_pillage())
{
return;
}
}
if (!isHuman())
{
if (AI_travelToUpgradeCity())
{
return;
}
}
if (!(isHuman()) && (AI_getUnitAIType() == UNITAI_EXPLORE_SEA))
{
pWaterArea = plot()->waterArea();
if (pWaterArea != NULL)
{
if (GET_PLAYER(getOwnerINLINE()).AI_totalWaterAreaUnitAIs(pWaterArea, UNITAI_EXPLORE_SEA) > GET_PLAYER(getOwnerINLINE()).AI_neededExplorers(pWaterArea))
{
if (GET_PLAYER(getOwnerINLINE()).calculateUnitCost() > 0)
{
scrap();
return;
}
}
}
}
if (AI_patrol())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/18/10 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
void CvUnitAI::AI_assaultSeaMove()
{
PROFILE_FUNC();
FAssert(AI_getUnitAIType() == UNITAI_ASSAULT_SEA);
bool bEmpty = !getGroup()->hasCargo();
bool bFull = (getGroup()->AI_isFull() && (getGroup()->getCargo() > 0));
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/8 || iOurDefense == 0 )
{
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 ) //prioritize getting outta there
{
if( !bEmpty )
{
getGroup()->unloadAll();
}
if (AI_anyAttack(1, 65))
{
return;
}
// Retreat to primary area first
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
if( !bFull && !bEmpty )
{
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
if (bEmpty)
{
if (AI_anyAttack(1, 65))
{
return;
}
if (AI_anyAttack(1, 45))
{
return;
}
}
bool bReinforce = false;
bool bAttack = false;
bool bNoWarPlans = (GET_TEAM(getTeam()).getAnyWarPlanCount(true) == 0);
bool bAttackBarbarian = false;
bool bLandWar = false;
bool bIsBarbarian = isBarbarian();
// Count forts as cities
bool bIsCity = plot()->isCity(true);
// Cargo if already at war
int iTargetReinforcementSize = (bIsBarbarian ? AI_stackOfDoomExtra() : 2);
// Cargo to launch a new invasion
int iTargetInvasionSize = 2*iTargetReinforcementSize;
int iCargo = getGroup()->getCargo();
int iEscorts = getGroup()->countNumUnitAIType(UNITAI_ESCORT_SEA) + getGroup()->countNumUnitAIType(UNITAI_ATTACK_SEA);
AreaAITypes eAreaAIType = area()->getAreaAIType(getTeam());
bLandWar = !bIsBarbarian && ((eAreaAIType == AREAAI_OFFENSIVE) || (eAreaAIType == AREAAI_DEFENSIVE) || (eAreaAIType == AREAAI_MASSING));
// Plot danger case handled above
if( hasCargo() && (getUnitAICargo(UNITAI_SETTLE) > 0 || getUnitAICargo(UNITAI_WORKER) > 0) )
{
// Dump inappropriate load at first oppurtunity after pick up
if( bIsCity && (plot()->getOwnerINLINE() == getOwnerINLINE()) )
{
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return;
}
else
{
if( !isFull() )
{
if(AI_pickupStranded(NO_UNITAI, 1))
{
return;
}
}
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
}
}
if (bIsCity)
{
CvCity* pCity = plot()->getPlotCity();
if( pCity != NULL && (plot()->getOwnerINLINE() == getOwnerINLINE()) )
{
// split out galleys from stack of ocean capable ships
if( GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(getUnitType()) == 0 && getGroup()->getNumUnits() > 1 )
{
getGroup()->AI_separateImpassable();
}
// galleys with upgrade available should get that ASAP
if( GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(getUnitType()) > 0 )
{
CvCity* pUpgradeCity = getUpgradeCity(false);
if( pUpgradeCity != NULL && pUpgradeCity == pCity )
{
// Wait for upgrade, this unit is top upgrade priority
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
if( (iCargo > 0) )
{
if( pCity != NULL )
{
if( (GC.getGameINLINE().getGameTurn() - pCity->getGameTurnAcquired()) <= 1 )
{
if( pCity->getPreviousOwner() != NO_PLAYER )
{
// Just captured city, probably from naval invasion. If area targets, drop cargo and leave so as to not to be lost in quick counter attack
if( GET_TEAM(getTeam()).countEnemyPowerByArea(plot()->area()) > 0 )
{
getGroup()->unloadAll();
if( iEscorts > 2 )
{
if( getGroup()->countNumUnitAIType(UNITAI_ESCORT_SEA) > 1 && getGroup()->countNumUnitAIType(UNITAI_ATTACK_SEA) > 0 )
{
getGroup()->AI_separateAI(UNITAI_ATTACK_SEA);
getGroup()->AI_separateAI(UNITAI_RESERVE_SEA);
iEscorts = getGroup()->countNumUnitAIType(UNITAI_ESCORT_SEA);
}
}
iCargo = getGroup()->getCargo();
}
}
}
}
}
if( (iCargo > 0) && (iEscorts == 0) )
{
if (AI_group(UNITAI_ASSAULT_SEA,-1,-1,-1,/*bIgnoreFaster*/true,false,false,/*iMaxPath*/1,false,/*bCargoOnly*/true,false,MISSIONAI_ASSAULT))
{
return;
}
if( plot()->plotCount(PUF_isUnitAIType, UNITAI_ESCORT_SEA, -1, getOwnerINLINE(), NO_TEAM, PUF_isGroupHead, -1, -1) > 0 )
{
// Loaded but with no escort, wait for escorts in plot to join us
getGroup()->pushMission(MISSION_SKIP);
return;
}
MissionAITypes eMissionAIType = MISSIONAI_GROUP;
if( (GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 3) > 0) || (GET_PLAYER(getOwnerINLINE()).AI_getWaterDanger(plot(), 4, false) > 0) )
{
// Loaded but with no escort, wait for others joining us soon or avoid dangerous waters
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if (bLandWar)
{
if ( iCargo > 0 )
{
if( (eAreaAIType == AREAAI_DEFENSIVE) || (pCity != NULL && pCity->AI_isDanger()))
{
// Unload cargo when on defense or if small load of troops and can reach enemy city over land (generally less risky)
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if ((iCargo >= iTargetReinforcementSize))
{
getGroup()->AI_separateEmptyTransports();
if( !(getGroup()->hasCargo()) )
{
// this unit was empty group leader
getGroup()->pushMission(MISSION_SKIP);
return;
}
// Send ready transports
if (AI_assaultSeaReinforce(false))
{
return;
}
if( iCargo >= iTargetInvasionSize )
{
if (AI_assaultSeaTransport(false))
{
return;
}
}
}
}
else
{
if ( (eAreaAIType == AREAAI_ASSAULT) )
{
if( iCargo >= iTargetInvasionSize )
{
bAttack = true;
}
}
if( (eAreaAIType == AREAAI_ASSAULT) || (eAreaAIType == AREAAI_ASSAULT_ASSIST) )
{
if( (bFull && iCargo > cargoSpace()) || (iCargo >= iTargetReinforcementSize) )
{
bReinforce = true;
}
}
}
if( !bAttack && !bReinforce && (plot()->getTeam() == getTeam()) )
{
if( iEscorts > 3 && iEscorts > (2*getGroup()->countNumUnitAIType(UNITAI_ASSAULT_SEA)) )
{
// If we have too many escorts, try freeing some for others
getGroup()->AI_separateAI(UNITAI_ATTACK_SEA);
getGroup()->AI_separateAI(UNITAI_RESERVE_SEA);
iEscorts = getGroup()->countNumUnitAIType(UNITAI_ESCORT_SEA);
if( iEscorts > 3 && iEscorts > (2*getGroup()->countNumUnitAIType(UNITAI_ASSAULT_SEA)) )
{
getGroup()->AI_separateAI(UNITAI_ESCORT_SEA);
}
}
}
MissionAITypes eMissionAIType = MISSIONAI_GROUP;
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 1) > 0 )
{
// Wait for units which are joining our group this turn
getGroup()->pushMission(MISSION_SKIP);
return;
}
if( !bFull )
{
if( bAttack )
{
eMissionAIType = MISSIONAI_LOAD_ASSAULT;
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 1) > 0 )
{
// Wait for cargo which will load this turn
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
else if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_LOAD_ASSAULT) > 0 )
{
// Wait for cargo which is on the way
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if( !bAttack && !bReinforce )
{
if ( iCargo > 0 )
{
if (AI_group(UNITAI_ASSAULT_SEA,-1,-1,-1,/*bIgnoreFaster*/true,false,false,/*iMaxPath*/5,false,/*bCargoOnly*/true,false,MISSIONAI_ASSAULT))
{
return;
}
}
else if (plot()->getTeam() == getTeam() && getGroup()->getNumUnits() > 1)
{
CvCity* pCity = plot()->getPlotCity();
if( pCity != NULL && (GC.getGameINLINE().getGameTurn() - pCity->getGameTurnAcquired()) > 10 )
{
if( pCity->plot()->plotCount(PUF_isAvailableUnitAITypeGroupie, UNITAI_ATTACK_CITY, -1, getOwnerINLINE()) < iTargetReinforcementSize )
{
// Not attacking, no cargo so release any escorts, attack ships, etc and split transports
getGroup()->AI_makeForceSeparate();
}
}
}
}
}
if (!bIsCity)
{
if( iCargo >= iTargetInvasionSize )
{
bAttack = true;
}
if ((iCargo >= iTargetReinforcementSize) || (bFull && iCargo > cargoSpace()))
{
bReinforce = true;
}
CvPlot* pAdjacentPlot = NULL;
for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(getX_INLINE(), getY_INLINE(), ((DirectionTypes)iI));
if( pAdjacentPlot != NULL )
{
if( iCargo > 0 )
{
CvCity* pAdjacentCity = pAdjacentPlot->getPlotCity();
if( pAdjacentCity != NULL && pAdjacentCity->getOwner() == getOwnerINLINE() && pAdjacentCity->getPreviousOwner() != NO_PLAYER )
{
if( (GC.getGameINLINE().getGameTurn() - pAdjacentCity->getGameTurnAcquired()) < 5 )
{
// If just captured city and we have some cargo, dump units in city
getGroup()->pushMission(MISSION_MOVE_TO, pAdjacentPlot->getX_INLINE(), pAdjacentPlot->getY_INLINE(), 0, false, false, MISSIONAI_ASSAULT, pAdjacentPlot);
return;
}
}
}
else
{
if (pAdjacentPlot->isOwned() && isEnemy(pAdjacentPlot->getTeam()))
{
if( pAdjacentPlot->getNumDefenders(getOwnerINLINE()) > 2 )
{
// if we just made a dropoff in enemy territory, release sea bombard units to support invaders
if ((getGroup()->countNumUnitAIType(UNITAI_ATTACK_SEA) + getGroup()->countNumUnitAIType(UNITAI_RESERVE_SEA)) > 0)
{
bool bMissionPushed = false;
if (AI_seaBombardRange(1))
{
bMissionPushed = true;
}
CvSelectionGroup* pOldGroup = getGroup();
//Release any Warships to finish the job.
getGroup()->AI_separateAI(UNITAI_ATTACK_SEA);
getGroup()->AI_separateAI(UNITAI_RESERVE_SEA);
/************************************************************************************************/
/* UNOFFICIAL_PATCH 05/11/09 jdog5000 */
/* */
/* Bugfix */
/************************************************************************************************/
/* original bts code
if (pOldGroup == getGroup() && getUnitType() == UNITAI_ASSAULT_SEA)
{
if (AI_retreatToCity(true))
{
bMissionPushed = true;
}
}
*/
// Fixed bug in next line with checking unit type instead of unit AI
if (pOldGroup == getGroup() && AI_getUnitAIType() == UNITAI_ASSAULT_SEA)
{
// Need to be sure all units can move
if( getGroup()->canAllMove() )
{
if (AI_retreatToCity(true))
{
bMissionPushed = true;
}
}
}
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
if (bMissionPushed)
{
return;
}
}
}
}
}
}
}
if(iCargo > 0)
{
MissionAITypes eMissionAIType = MISSIONAI_GROUP;
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, &eMissionAIType, 1, getGroup(), 1) > 0 )
{
if( iEscorts < GET_PLAYER(getOwnerINLINE()).AI_getWaterDanger(plot(), 2, false) )
{
// Wait for units which are joining our group this turn (hopefully escorts)
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
}
if (bIsBarbarian)
{
if (getGroup()->isFull() || iCargo > iTargetInvasionSize)
{
if (AI_assaultSeaTransport(false))
{
return;
}
}
else
{
if (AI_pickup(UNITAI_ATTACK_CITY, true, 5))
{
return;
}
if (AI_pickup(UNITAI_ATTACK, true, 5))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if( !(getGroup()->getCargo()) )
{
AI_barbAttackSeaMove();
return;
}
if( AI_safety() )
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
else
{
if (bAttack || bReinforce)
{
if( bIsCity )
{
getGroup()->AI_separateEmptyTransports();
}
if( !(getGroup()->hasCargo()) )
{
// this unit was empty group leader
getGroup()->pushMission(MISSION_SKIP);
return;
}
FAssert(getGroup()->hasCargo());
//BBAI TODO: Check that group has escorts, otherwise usually wait
if( bAttack )
{
if( bReinforce && (AI_getBirthmark()%2 == 0) )
{
if (AI_assaultSeaReinforce())
{
return;
}
bReinforce = false;
}
if (AI_assaultSeaTransport())
{
return;
}
}
// If not enough troops for own invasion,
if( bReinforce )
{
if (AI_assaultSeaReinforce())
{
return;
}
}
}
if( bNoWarPlans && (iCargo >= iTargetReinforcementSize) )
{
bAttackBarbarian = true;
getGroup()->AI_separateEmptyTransports();
if( !(getGroup()->hasCargo()) )
{
// this unit was empty group leader
getGroup()->pushMission(MISSION_SKIP);
return;
}
FAssert(getGroup()->hasCargo());
if (AI_assaultSeaReinforce(bAttackBarbarian))
{
return;
}
FAssert(getGroup()->hasCargo());
if (AI_assaultSeaTransport(bAttackBarbarian))
{
return;
}
}
}
if ((bFull || bReinforce) && !bAttack)
{
// Group with nearby transports with units on board
if (AI_group(UNITAI_ASSAULT_SEA, -1, /*iMaxOwnUnitAI*/ -1, -1, true, false, false, 2, false, true, false, MISSIONAI_ASSAULT))
{
return;
}
if (AI_group(UNITAI_ASSAULT_SEA, -1, -1, -1, true, false, false, 10, false, true, false, MISSIONAI_ASSAULT))
{
return;
}
}
else if( !bFull )
{
bool bHasOneLoad = (getGroup()->getCargo() >= cargoSpace());
bool bHasCargo = getGroup()->hasCargo();
if (AI_pickup(UNITAI_ATTACK_CITY, !bHasCargo, (bHasOneLoad ? 3 : 7)))
{
return;
}
if (AI_pickup(UNITAI_ATTACK, !bHasCargo, (bHasOneLoad ? 3 : 7)))
{
return;
}
if (AI_pickup(UNITAI_COUNTER, !bHasCargo, (bHasOneLoad ? 3 : 7)))
{
return;
}
if (AI_pickup(UNITAI_ATTACK_CITY, !bHasCargo))
{
return;
}
if( !bHasCargo )
{
if(AI_pickupStranded(UNITAI_ATTACK_CITY))
{
return;
}
if(AI_pickupStranded(UNITAI_ATTACK))
{
return;
}
if(AI_pickupStranded(UNITAI_COUNTER))
{
return;
}
if( (getGroup()->countNumUnitAIType(AI_getUnitAIType()) == 1) )
{
// Try picking up any thing
if(AI_pickupStranded())
{
return;
}
}
}
}
if (bIsCity && bLandWar && getGroup()->hasCargo())
{
// Enemy units in this player's territory
if( GET_PLAYER(getOwnerINLINE()).AI_countNumAreaHostileUnits(area(),true,false,false,false) > (getGroup()->getCargo()/2))
{
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
void CvUnitAI::AI_settlerSeaMove()
{
PROFILE_FUNC();
bool bEmpty = !getGroup()->hasCargo();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 ) //prioritize getting outta there
{
if( bEmpty )
{
if (AI_anyAttack(1, 65))
{
return;
}
}
// Retreat to primary area first
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (bEmpty)
{
if (AI_anyAttack(1, 65))
{
return;
}
if (AI_anyAttack(1, 40))
{
return;
}
}
int iSettlerCount = getUnitAICargo(UNITAI_SETTLE);
int iWorkerCount = getUnitAICargo(UNITAI_WORKER);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 12/07/08 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if( hasCargo() && (iSettlerCount == 0) && (iWorkerCount == 0))
{
// Dump troop load at first oppurtunity after pick up
if( plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE() )
{
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return;
}
else
{
if( !(isFull()) )
{
if(AI_pickupStranded(NO_UNITAI, 1))
{
return;
}
}
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 06/02/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
// Don't send transport with settler and no defense
if( (iSettlerCount > 0) && (iSettlerCount + iWorkerCount == cargoSpace()) )
{
// No defenders for settler
if( plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE() )
{
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if ((iSettlerCount > 0) && (isFull() ||
((getUnitAICargo(UNITAI_CITY_DEFENSE) > 0) &&
(GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_LOAD_SETTLER) == 0))))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (AI_settlerSeaTransport())
{
return;
}
}
else if ((getTeam() != plot()->getTeam()) && bEmpty)
{
if (AI_pillageRange(3))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if (plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE() && !hasCargo())
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
AreaAITypes eAreaAI = area()->getAreaAIType(getTeam());
if ((eAreaAI == AREAAI_ASSAULT) || (eAreaAI == AREAAI_ASSAULT_MASSING))
{
CvArea* pWaterArea = plot()->waterArea();
FAssert(pWaterArea != NULL);
if (pWaterArea != NULL)
{
if (GET_PLAYER(getOwnerINLINE()).AI_totalWaterAreaUnitAIs(pWaterArea, UNITAI_SETTLER_SEA) > 1)
{
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_ASSAULT_SEA, pWaterArea) > 0)
{
AI_setUnitAIType(UNITAI_ASSAULT_SEA);
AI_assaultSeaMove();
return;
}
}
}
}
}
if ((iWorkerCount > 0)
&& GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_LOAD_SETTLER) == 0)
{
if (isFull() || (iSettlerCount == 0))
{
if (AI_settlerSeaFerry())
{
return;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
/* original bts code
if (AI_pickup(UNITAI_SETTLE))
{
return;
}
*/
if( !(getGroup()->hasCargo()) )
{
if(AI_pickupStranded(UNITAI_SETTLE))
{
return;
}
}
if( !(getGroup()->isFull()) )
{
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_LOAD_SETTLER) > 0 )
{
// Wait for units on the way
getGroup()->pushMission(MISSION_SKIP);
return;
}
if( iSettlerCount > 0 )
{
if (AI_pickup(UNITAI_CITY_DEFENSE))
{
return;
}
}
else if( cargoSpace() - 2 >= getCargo() + iWorkerCount )
{
if (AI_pickup(UNITAI_SETTLE, true))
{
return;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if ((GC.getGame().getGameTurn() - getGameTurnCreated()) < 8)
{
if ((plot()->getPlotCity() == NULL) || GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(plot()->area(), UNITAI_SETTLE) == 0)
{
if (AI_explore())
{
return;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/18/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
if (AI_pickup(UNITAI_WORKER))
{
return;
}
*/
if( !getGroup()->hasCargo() )
{
// Rescue stranded non-settlers
if(AI_pickupStranded())
{
return;
}
}
if( cargoSpace() - 2 < getCargo() + iWorkerCount )
{
// If full of workers and not going anywhere, dump them if a settler is available
if( (iSettlerCount == 0) && (plot()->plotCount(PUF_isAvailableUnitAITypeGroupie, UNITAI_SETTLE, -1, getOwnerINLINE(), NO_TEAM, PUF_isFiniteRange) > 0) )
{
getGroup()->unloadAll();
if (AI_pickup(UNITAI_SETTLE, true))
{
return;
}
return;
}
}
if( !(getGroup()->isFull()) )
{
if (AI_pickup(UNITAI_WORKER))
{
return;
}
}
// Carracks cause problems for transport upgrades, galleys can't upgrade to them and they can't
// upgrade to galleons. Scrap galleys, switch unit AI for stuck Carracks.
if( plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE() )
{
//
{
UnitTypes eBestSettlerTransport = NO_UNIT;
GET_PLAYER(getOwnerINLINE()).AI_bestCityUnitAIValue(AI_getUnitAIType(), NULL, &eBestSettlerTransport);
if( eBestSettlerTransport != NO_UNIT )
{
if( eBestSettlerTransport != getUnitType() && GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(eBestSettlerTransport) == 0 )
{
UnitClassTypes ePotentialUpgradeClass = (UnitClassTypes)GC.getUnitInfo(eBestSettlerTransport).getUnitClassType();
if( !upgradeAvailable(getUnitType(), ePotentialUpgradeClass) )
{
getGroup()->unloadAll();
if( GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(getUnitType()) > 0 )
{
scrap();
return;
}
else
{
CvArea* pWaterArea = plot()->waterArea();
FAssert(pWaterArea != NULL);
if (pWaterArea != NULL)
{
if( GET_PLAYER(getOwnerINLINE()).AI_totalUnitAIs(UNITAI_EXPLORE_SEA) == 0 )
{
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_EXPLORE_SEA, pWaterArea) > 0)
{
AI_setUnitAIType(UNITAI_EXPLORE_SEA);
AI_exploreSeaMove();
return;
}
}
if( GET_PLAYER(getOwnerINLINE()).AI_totalUnitAIs(UNITAI_SPY_SEA) == 0 )
{
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_SPY_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_SPY_SEA);
AI_spySeaMove();
return;
}
}
if( GET_PLAYER(getOwnerINLINE()).AI_totalUnitAIs(UNITAI_MISSIONARY_SEA) == 0 )
{
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_MISSIONARY_SEA, area()) > 0)
{
AI_setUnitAIType(UNITAI_MISSIONARY_SEA);
AI_missionarySeaMove();
return;
}
}
if (GET_PLAYER(getOwnerINLINE()).AI_unitValue(getUnitType(), UNITAI_ATTACK_SEA, pWaterArea) > 0)
{
AI_setUnitAIType(UNITAI_ATTACK_SEA);
AI_attackSeaMove();
return;
}
}
}
}
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_missionarySeaMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 ) //prioritize getting outta there
{
// Retreat to primary area first
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (getUnitAICargo(UNITAI_MISSIONARY) > 0)
{
if (AI_specialSeaTransportMissionary())
{
return;
}
}
else if (!(getGroup()->hasCargo()))
{
if (AI_pillageRange(4))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/14/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if( !(getGroup()->isFull()) )
{
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_LOAD_SPECIAL) > 0 )
{
// Wait for units on the way
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if (AI_pickup(UNITAI_MISSIONARY, true))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_explore())
{
return;
}
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_spySeaMove()
{
PROFILE_FUNC();
CvCity* pCity;
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 ) //prioritize getting outta there
{
// Retreat to primary area first
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (getUnitAICargo(UNITAI_SPY) > 0)
{
if (AI_specialSeaTransportSpy())
{
return;
}
pCity = plot()->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY, pCity->plot());
return;
}
}
}
else if (!(getGroup()->hasCargo()))
{
if (AI_pillageRange(5))
{
return;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/14/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if( !(getGroup()->isFull()) )
{
if( GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_LOAD_SPECIAL) > 0 )
{
// Wait for units on the way
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
if (AI_pickup(UNITAI_SPY, true))
{
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_carrierSeaMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 ) //prioritize getting outta there
{
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_heal(50))
{
return;
}
if (!isEnemy(plot()->getTeam()))
{
if (GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(this, MISSIONAI_GROUP) > 0)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
else
{
if (AI_seaBombardRange(1))
{
return;
}
}
if (AI_group(UNITAI_CARRIER_SEA, -1, /*iMaxOwnUnitAI*/ 1))
{
return;
}
if (getGroup()->countNumUnitAIType(UNITAI_ATTACK_SEA) + getGroup()->countNumUnitAIType(UNITAI_ESCORT_SEA) == 0)
{
if (plot()->isCity() && plot()->getOwnerINLINE() == getOwnerINLINE())
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_retreatToCity())
{
return;
}
}
if (getCargo() > 0)
{
if (AI_carrierSeaTransport())
{
return;
}
if (AI_blockade())
{
return;
}
if (AI_shadow(UNITAI_ASSAULT_SEA))
{
return;
}
}
if (AI_travelToUpgradeCity())
{
return;
}
if (AI_retreatToCity(true))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_missileCarrierSeaMove()
{
PROFILE_FUNC();
bool bIsStealth = (getInvisibleType() != NO_INVISIBLE);
/********************************************************************************/
/* BETTER_BTS_AI_MOD 06/14/09 Solver & jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if( getDamage() > 0 ) // extra risk to leaving when wounded
{
iOurDefense *= 2;
}
if( iEnemyOffense > iOurDefense/4 || iOurDefense == 0 ) //prioritize getting outta there
{
if (AI_shadow(UNITAI_ASSAULT_SEA, 1, 50, false, true, 1))
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (plot()->isCity() && plot()->getTeam() == getTeam())
{
if (AI_heal())
{
return;
}
}
if (((plot()->getTeam() != getTeam()) && getGroup()->hasCargo()) || getGroup()->AI_isFull())
{
if (bIsStealth)
{
if (AI_carrierSeaTransport())
{
return;
}
}
else
{
/********************************************************************************/
/* BETTER_BTS_AI_MOD 06/14/09 jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
if (AI_shadow(UNITAI_ASSAULT_SEA, 1, 50, true, false, 12))
{
return;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (AI_carrierSeaTransport())
{
return;
}
}
}
// if (AI_pickup(UNITAI_ICBM))
// {
// return;
// }
//
// if (AI_pickup(UNITAI_MISSILE_AIR))
// {
// return;
// }
if (AI_retreatToCity())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
}
void CvUnitAI::AI_attackAirMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
CvCity* pCity = plot()->getPlotCity();
bool bSkiesClear = true;
int iDX, iDY;
// Check for sufficient defenders to stay
int iDefenders = plot()->plotCount(PUF_canDefend, -1, -1, plot()->getOwner());
int iAttackAirCount = plot()->plotCount(PUF_canAirAttack, -1, -1, NO_PLAYER, getTeam());
iAttackAirCount += 2 * plot()->plotCount(PUF_isUnitAIType, UNITAI_ICBM, -1, NO_PLAYER, getTeam());
if( plot()->isCoastalLand(GC.getMIN_WATER_SIZE_FOR_OCEAN()) )
{
iDefenders -= 1;
}
if( pCity != NULL )
{
if( pCity->getDefenseModifier(true) < 40 )
{
iDefenders -= 1;
}
if( pCity->getOccupationTimer() > 1 )
{
iDefenders -= 1;
}
}
if( iAttackAirCount > iDefenders )
{
if (AI_airOffensiveCity())
{
return;
}
}
// Check for direct threat to current base
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if (iEnemyOffense > iOurDefense || iOurDefense == 0)
{
// Too risky, pull back
if (AI_airOffensiveCity())
{
return;
}
if( canAirDefend() )
{
if (AI_airDefensiveCity())
{
return;
}
}
}
else if( iEnemyOffense > iOurDefense/3 )
{
if( getDamage() == 0 )
{
if( collateralDamage() == 0 && canAirDefend() )
{
if (pCity != NULL)
{
// Check for whether city needs this unit to air defend
if( !(pCity->AI_isAirDefended(true,-1)) )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
}
}
// Attack the invaders!
if (AI_defendBaseAirStrike())
{
return;
}
if (AI_defensiveAirStrike())
{
return;
}
if (AI_airStrike())
{
return;
}
// If no targets, no sense staying in risky place
if (AI_airOffensiveCity())
{
return;
}
if( canAirDefend() )
{
if (AI_airDefensiveCity())
{
return;
}
}
}
if( healTurns(plot()) > 1 )
{
// If very damaged, no sense staying in risky place
if (AI_airOffensiveCity())
{
return;
}
if( canAirDefend() )
{
if (AI_airDefensiveCity())
{
return;
}
}
}
}
}
if( getDamage() > 0 )
{
if (((100*currHitPoints()) / maxHitPoints()) < 40)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
else
{
CvPlot *pLoopPlot;
int iSearchRange = airRange();
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
if (!bSkiesClear) break;
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (bestInterceptor(pLoopPlot) != NULL)
{
bSkiesClear = false;
break;
}
}
}
}
if (!bSkiesClear)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE());
CvArea* pArea = area();
int iAttackValue = kPlayer.AI_unitValue(getUnitType(), UNITAI_ATTACK_AIR, pArea);
int iCarrierValue = kPlayer.AI_unitValue(getUnitType(), UNITAI_CARRIER_AIR, pArea);
if (iCarrierValue > 0)
{
int iCarriers = kPlayer.AI_totalUnitAIs(UNITAI_CARRIER_SEA);
if (iCarriers > 0)
{
UnitTypes eBestCarrierUnit = NO_UNIT;
kPlayer.AI_bestAreaUnitAIValue(UNITAI_CARRIER_SEA, NULL, &eBestCarrierUnit);
if (eBestCarrierUnit != NO_UNIT)
{
int iCarrierAirNeeded = iCarriers * GC.getUnitInfo(eBestCarrierUnit).getCargoSpace();
if (kPlayer.AI_totalUnitAIs(UNITAI_CARRIER_AIR) < iCarrierAirNeeded)
{
AI_setUnitAIType(UNITAI_CARRIER_AIR);
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
}
}
int iDefenseValue = kPlayer.AI_unitValue(getUnitType(), UNITAI_DEFENSE_AIR, pArea);
if (iDefenseValue > iAttackValue)
{
if (kPlayer.AI_bestAreaUnitAIValue(UNITAI_ATTACK_AIR, pArea) > iAttackValue)
{
AI_setUnitAIType(UNITAI_DEFENSE_AIR);
getGroup()->pushMission(MISSION_SKIP);
return;
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/6/08 jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
/* original BTS code
if (AI_airBombDefenses())
{
return;
}
if (GC.getGameINLINE().getSorenRandNum(4, "AI Air Attack Move") == 0)
{
if (AI_airBombPlots())
{
return;
}
}
if (AI_airStrike())
{
return;
}
if (canAirAttack())
{
if (AI_airOffensiveCity())
{
return;
}
}
if (canRecon(plot()))
{
if (AI_exploreAir())
{
return;
}
}
if (canAirDefend())
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
*/
bool bDefensive = false;
if( pArea != NULL )
{
bDefensive = pArea->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE;
}
if (GC.getGameINLINE().getSorenRandNum(bDefensive ? 3 : 6, "AI Air Attack Move") == 0)
{
if( AI_defensiveAirStrike() )
{
return;
}
}
if (GC.getGameINLINE().getSorenRandNum(4, "AI Air Attack Move") == 0)
{
// only moves unit in a fort
if (AI_travelToUpgradeCity())
{
return;
}
}
// Support ground attacks
if (AI_airBombDefenses())
{
return;
}
if (GC.getGameINLINE().getSorenRandNum(bDefensive ? 6 : 4, "AI Air Attack Move") == 0)
{
if (AI_airBombPlots())
{
return;
}
}
if (AI_airStrike())
{
return;
}
if (canAirAttack())
{
if (AI_airOffensiveCity())
{
return;
}
}
else
{
if( canAirDefend() )
{
if (AI_airDefensiveCity())
{
return;
}
}
}
// BBAI TODO: Support friendly attacks on common enemies, if low risk?
if (canAirDefend())
{
if( bDefensive || GC.getGameINLINE().getSorenRandNum(2, "AI Air Attack Move") == 0 )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
}
if (canRecon(plot()))
{
if (AI_exploreAir())
{
return;
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_defenseAirMove()
{
PROFILE_FUNC();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
CvCity* pCity = plot()->getPlotCity();
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
// includes forts
if (plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
if (3*iEnemyOffense > 4*iOurDefense || iOurDefense == 0)
{
// Too risky, pull out
// AI_airDefensiveCity will leave some air defense, pull extras out
if (AI_airDefensiveCity())
{
return;
}
}
else if ( iEnemyOffense > iOurDefense/3 )
{
if (getDamage() > 0)
{
if( healTurns(plot()) > 1 + GC.getGameINLINE().getSorenRandNum(2, "AI Air Defense Move") )
{
// Can't help current situation, only risk losing unit
if (AI_airDefensiveCity())
{
return;
}
}
// Stay to defend in the future
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (canAirDefend() && pCity != NULL)
{
// Check for whether city needs this unit to air defend
if( !(pCity->AI_isAirDefended(true,-1)) )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
// Consider adding extra defenders
if( collateralDamage() == 0 && (!pCity->AI_isAirDefended(false,-2)) )
{
if( GC.getGameINLINE().getSorenRandNum(3, "AI Air Defense Move") == 0 )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
}
}
// Attack the invaders!
if (AI_defendBaseAirStrike())
{
return;
}
if (AI_defensiveAirStrike())
{
return;
}
if (AI_airStrike())
{
return;
}
if (AI_airDefensiveCity())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (getDamage() > 0)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/17/08 Solver & jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
/* original BTS code
if ((GC.getGameINLINE().getSorenRandNum(2, "AI Air Defense Move") == 0))
{
if ((pCity != NULL) && pCity->AI_isDanger())
{
if (AI_airStrike())
{
return;
}
}
else
{
if (AI_airBombDefenses())
{
return;
}
if (AI_airStrike())
{
return;
}
if (AI_getBirthmark() % 2 == 0)
{
if (AI_airBombPlots())
{
return;
}
}
}
if (AI_travelToUpgradeCity())
{
return;
}
}
bool bNoWar = (GET_TEAM(getTeam()).getAtWarCount(false) == 0);
if (canRecon(plot()))
{
if (GC.getGame().getSorenRandNum(bNoWar ? 2 : 4, "AI defensive air recon") == 0)
{
if (AI_exploreAir())
{
return;
}
}
}
if (AI_airDefensiveCity())
{
return;
}
*/
if((GC.getGameINLINE().getSorenRandNum(4, "AI Air Defense Move") == 0))
{
// only moves unit in a fort
if (AI_travelToUpgradeCity())
{
return;
}
}
if( canAirDefend() )
{
// Check for whether city needs this unit for base air defenses
int iBaseAirDefenders = 0;
if( iEnemyOffense > 0 )
{
iBaseAirDefenders++;
}
if( pCity != NULL )
{
iBaseAirDefenders += pCity->AI_neededAirDefenders()/2;
}
if( plot()->countAirInterceptorsActive(getTeam()) < iBaseAirDefenders )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
}
CvArea* pArea = area();
bool bDefensive = false;
bool bOffensive = false;
if( pArea != NULL )
{
bDefensive = (pArea->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE);
bOffensive = (pArea->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE);
}
if( (iEnemyOffense > 0) || bDefensive )
{
if( canAirDefend() )
{
if( pCity != NULL )
{
// Consider adding extra defenders
if( !(pCity->AI_isAirDefended(false,-1)) )
{
if ((GC.getGameINLINE().getSorenRandNum((bOffensive ? 3 : 2), "AI Air Defense Move") == 0))
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
}
}
else
{
if ((GC.getGameINLINE().getSorenRandNum((bOffensive ? 3 : 2), "AI Air Defense Move") == 0))
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
}
}
if((GC.getGameINLINE().getSorenRandNum(3, "AI Air Defense Move") > 0))
{
if (AI_defensiveAirStrike())
{
return;
}
if (AI_airStrike())
{
return;
}
}
}
else
{
if ((GC.getGameINLINE().getSorenRandNum(3, "AI Air Defense Move") > 0))
{
// Clear out any enemy fighters, support offensive units
if (AI_airBombDefenses())
{
return;
}
if (GC.getGameINLINE().getSorenRandNum(3, "AI Air Defense Move") == 0)
{
// Hit enemy land stacks near our cities
if (AI_defensiveAirStrike())
{
return;
}
}
if (AI_airStrike())
{
return;
}
if (AI_getBirthmark() % 2 == 0 || bOffensive)
{
if (AI_airBombPlots())
{
return;
}
}
}
}
if (AI_airDefensiveCity())
{
return;
}
// BBAI TODO: how valuable is recon information to AI in war time?
if (canRecon(plot()))
{
if (GC.getGame().getSorenRandNum(bDefensive ? 6 : 3, "AI defensive air recon") == 0)
{
if (AI_exploreAir())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (canAirDefend())
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_carrierAirMove()
{
PROFILE_FUNC();
// XXX maybe protect land troops?
if (getDamage() > 0)
{
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (isCargo())
{
int iRand = GC.getGameINLINE().getSorenRandNum(3, "AI Air Carrier Move");
if (iRand == 2 && canAirDefend())
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
else if (AI_airBombDefenses())
{
return;
}
else if (iRand == 1)
{
if (AI_airBombPlots())
{
return;
}
if (AI_airStrike())
{
return;
}
}
else
{
if (AI_airStrike())
{
return;
}
if (AI_airBombPlots())
{
return;
}
}
if (AI_travelToUpgradeCity())
{
return;
}
if (canAirDefend())
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_airCarrier())
{
return;
}
if (AI_airDefensiveCity())
{
return;
}
if (canAirDefend())
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_missileAirMove()
{
PROFILE_FUNC();
CvCity* pCity = plot()->getPlotCity();
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/21/08 Solver & jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
// includes forts
if (!isCargo() && plot()->isCity(true))
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if (iEnemyOffense > (iOurDefense/2) || iOurDefense == 0)
{
if (AI_airOffensiveCity())
{
return;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (isCargo())
{
int iRand = GC.getGameINLINE().getSorenRandNum(3, "AI Air Missile plot bombing");
if (iRand != 0)
{
if (AI_airBombPlots())
{
return;
}
}
iRand = GC.getGameINLINE().getSorenRandNum(3, "AI Air Missile Carrier Move");
if (iRand == 0)
{
if (AI_airBombDefenses())
{
return;
}
if (AI_airStrike())
{
return;
}
}
else
{
if (AI_airStrike())
{
return;
}
if (AI_airBombDefenses())
{
return;
}
}
if (AI_airBombPlots())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
if (AI_airStrike())
{
return;
}
if (AI_missileLoad(UNITAI_MISSILE_CARRIER_SEA))
{
return;
}
if (AI_missileLoad(UNITAI_RESERVE_SEA, 1))
{
return;
}
if (AI_missileLoad(UNITAI_ATTACK_SEA, 1))
{
return;
}
if (AI_airBombDefenses())
{
return;
}
if (!isCargo())
{
if (AI_airOffensiveCity())
{
return;
}
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_networkAutomated()
{
FAssertMsg(canBuildRoute(), "canBuildRoute is expected to be true");
if (!(getGroup()->canDefend()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot()) > 0)
if (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (AI_retreatToCity()) // XXX maybe not do this??? could be working productively somewhere else...
{
return;
}
}
}
if (AI_improveBonus(20))
{
return;
}
if (AI_improveBonus(10))
{
return;
}
if (AI_connectBonus())
{
return;
}
if (AI_connectCity())
{
return;
}
if (AI_improveBonus())
{
return;
}
if (AI_routeTerritory(true))
{
return;
}
if (AI_connectBonus(false))
{
return;
}
if (AI_routeCity())
{
return;
}
if (AI_routeTerritory())
{
return;
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
void CvUnitAI::AI_cityAutomated()
{
CvCity* pCity;
if (!(getGroup()->canDefend()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot()) > 0)
if (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (AI_retreatToCity()) // XXX maybe not do this??? could be working productively somewhere else...
{
return;
}
}
}
pCity = NULL;
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
pCity = plot()->getWorkingCity();
}
if (pCity == NULL)
{
pCity = GC.getMapINLINE().findCity(getX_INLINE(), getY_INLINE(), getOwnerINLINE()); // XXX do team???
}
if (pCity != NULL)
{
if (AI_improveCity(pCity))
{
return;
}
}
if (AI_retreatToCity())
{
return;
}
if (AI_safety())
{
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
// XXX make sure we include any new UnitAITypes...
int CvUnitAI::AI_promotionValue(PromotionTypes ePromotion)
{
int iValue;
int iTemp;
int iExtra;
int iI;
iValue = 0;
if (GC.getPromotionInfo(ePromotion).isLeader())
{
// Don't consume the leader as a regular promotion
return 0;
}
if (GC.getPromotionInfo(ePromotion).isBlitz())
{
if ((AI_getUnitAIType() == UNITAI_RESERVE && baseMoves() > 1) ||
AI_getUnitAIType() == UNITAI_PARADROP)
{
iValue += 10;
}
else
{
iValue += 2;
}
}
if (GC.getPromotionInfo(ePromotion).isAmphib())
{
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_ATTACK_CITY))
{
iValue += 5;
}
else
{
iValue++;
}
}
if (GC.getPromotionInfo(ePromotion).isRiver())
{
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_ATTACK_CITY))
{
iValue += 5;
}
else
{
iValue++;
}
}
if (GC.getPromotionInfo(ePromotion).isEnemyRoute())
{
if (AI_getUnitAIType() == UNITAI_PILLAGE)
{
iValue += 40;
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_ATTACK_CITY))
{
iValue += 20;
}
else if (AI_getUnitAIType() == UNITAI_PARADROP)
{
iValue += 10;
}
else
{
iValue += 4;
}
}
if (GC.getPromotionInfo(ePromotion).isAlwaysHeal())
{
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_ATTACK_CITY) ||
(AI_getUnitAIType() == UNITAI_PILLAGE) ||
(AI_getUnitAIType() == UNITAI_COUNTER) ||
(AI_getUnitAIType() == UNITAI_ATTACK_SEA) ||
(AI_getUnitAIType() == UNITAI_PIRATE_SEA) ||
(AI_getUnitAIType() == UNITAI_ESCORT_SEA) ||
(AI_getUnitAIType() == UNITAI_PARADROP))
{
iValue += 10;
}
else
{
iValue += 8;
}
}
if (GC.getPromotionInfo(ePromotion).isHillsDoubleMove())
{
if (AI_getUnitAIType() == UNITAI_EXPLORE)
{
iValue += 20;
}
else
{
iValue += 10;
}
}
if (GC.getPromotionInfo(ePromotion).isImmuneToFirstStrikes()
&& !immuneToFirstStrikes())
{
if ((AI_getUnitAIType() == UNITAI_ATTACK_CITY))
{
iValue += 12;
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK))
{
iValue += 8;
}
else
{
iValue += 4;
}
}
iTemp = GC.getPromotionInfo(ePromotion).getVisibilityChange();
if ((AI_getUnitAIType() == UNITAI_EXPLORE_SEA) ||
(AI_getUnitAIType() == UNITAI_EXPLORE))
{
iValue += (iTemp * 40);
}
else if (AI_getUnitAIType() == UNITAI_PIRATE_SEA)
{
iValue += (iTemp * 20);
}
iTemp = GC.getPromotionInfo(ePromotion).getMovesChange();
if ((AI_getUnitAIType() == UNITAI_ATTACK_SEA) ||
(AI_getUnitAIType() == UNITAI_PIRATE_SEA) ||
(AI_getUnitAIType() == UNITAI_RESERVE_SEA) ||
(AI_getUnitAIType() == UNITAI_ESCORT_SEA) ||
(AI_getUnitAIType() == UNITAI_EXPLORE_SEA) ||
(AI_getUnitAIType() == UNITAI_ASSAULT_SEA) ||
(AI_getUnitAIType() == UNITAI_SETTLER_SEA) ||
(AI_getUnitAIType() == UNITAI_PILLAGE) ||
(AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_PARADROP))
{
iValue += (iTemp * 20);
}
else
{
iValue += (iTemp * 4);
}
iTemp = GC.getPromotionInfo(ePromotion).getMoveDiscountChange();
if (AI_getUnitAIType() == UNITAI_PILLAGE)
{
iValue += (iTemp * 10);
}
else
{
iValue += (iTemp * 2);
}
iTemp = GC.getPromotionInfo(ePromotion).getAirRangeChange();
if (AI_getUnitAIType() == UNITAI_ATTACK_AIR ||
AI_getUnitAIType() == UNITAI_CARRIER_AIR)
{
iValue += (iTemp * 20);
}
else if (AI_getUnitAIType() == UNITAI_DEFENSE_AIR)
{
iValue += (iTemp * 10);
}
iTemp = GC.getPromotionInfo(ePromotion).getInterceptChange();
if (AI_getUnitAIType() == UNITAI_DEFENSE_AIR)
{
iValue += (iTemp * 3);
}
else if (AI_getUnitAIType() == UNITAI_CITY_SPECIAL || AI_getUnitAIType() == UNITAI_CARRIER_AIR)
{
iValue += (iTemp * 2);
}
else
{
iValue += (iTemp / 10);
}
iTemp = GC.getPromotionInfo(ePromotion).getEvasionChange();
if (AI_getUnitAIType() == UNITAI_ATTACK_AIR || AI_getUnitAIType() == UNITAI_CARRIER_AIR)
{
iValue += (iTemp * 3);
}
else
{
iValue += (iTemp / 10);
}
iTemp = GC.getPromotionInfo(ePromotion).getFirstStrikesChange() * 2;
iTemp += GC.getPromotionInfo(ePromotion).getChanceFirstStrikesChange();
if ((AI_getUnitAIType() == UNITAI_RESERVE) ||
(AI_getUnitAIType() == UNITAI_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_DEFENSE) ||
(AI_getUnitAIType() == UNITAI_CITY_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_SPECIAL) ||
(AI_getUnitAIType() == UNITAI_ATTACK))
{
iTemp *= 8;
iExtra = getExtraChanceFirstStrikes() + getExtraFirstStrikes() * 2;
iTemp *= 100 + iExtra * 15;
iTemp /= 100;
iValue += iTemp;
}
else
{
iValue += (iTemp * 5);
}
iTemp = GC.getPromotionInfo(ePromotion).getWithdrawalChange();
if (iTemp != 0)
{
iExtra = (m_pUnitInfo->getWithdrawalProbability() + (getExtraWithdrawal() * 4));
iTemp *= (100 + iExtra);
iTemp /= 100;
if ((AI_getUnitAIType() == UNITAI_ATTACK_CITY))
{
iValue += (iTemp * 4) / 3;
}
else if ((AI_getUnitAIType() == UNITAI_COLLATERAL) ||
(AI_getUnitAIType() == UNITAI_RESERVE) ||
(AI_getUnitAIType() == UNITAI_RESERVE_SEA) ||
getLeaderUnitType() != NO_UNIT)
{
iValue += iTemp * 1;
}
else
{
iValue += (iTemp / 4);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getCollateralDamageChange();
if (iTemp != 0)
{
iExtra = (getExtraCollateralDamage());//collateral has no strong synergy (not like retreat)
iTemp *= (100 + iExtra);
iTemp /= 100;
if (AI_getUnitAIType() == UNITAI_COLLATERAL)
{
iValue += (iTemp * 1);
}
else if (AI_getUnitAIType() == UNITAI_ATTACK_CITY)
{
iValue += ((iTemp * 2) / 3);
}
else
{
iValue += (iTemp / 8);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getBombardRateChange();
if (AI_getUnitAIType() == UNITAI_ATTACK_CITY)
{
iValue += (iTemp * 2);
}
else
{
iValue += (iTemp / 8);
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/26/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
iTemp = GC.getPromotionInfo(ePromotion).getEnemyHealChange();
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_PILLAGE) ||
(AI_getUnitAIType() == UNITAI_ATTACK_SEA) ||
(AI_getUnitAIType() == UNITAI_PARADROP) ||
(AI_getUnitAIType() == UNITAI_PIRATE_SEA))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 8);
}
iTemp = GC.getPromotionInfo(ePromotion).getNeutralHealChange();
iValue += (iTemp / 8);
iTemp = GC.getPromotionInfo(ePromotion).getFriendlyHealChange();
if ((AI_getUnitAIType() == UNITAI_CITY_DEFENSE) ||
(AI_getUnitAIType() == UNITAI_CITY_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_SPECIAL))
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 8);
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/26/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if ( getDamage() > 0 || ((AI_getBirthmark() % 8 == 0) && (AI_getUnitAIType() == UNITAI_COUNTER ||
AI_getUnitAIType() == UNITAI_PILLAGE ||
AI_getUnitAIType() == UNITAI_ATTACK_CITY ||
AI_getUnitAIType() == UNITAI_RESERVE )) )
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
iTemp = GC.getPromotionInfo(ePromotion).getSameTileHealChange() + getSameTileHeal();
iExtra = getSameTileHeal();
iTemp *= (100 + iExtra * 5);
iTemp /= 100;
if (iTemp > 0)
{
if (healRate(plot()) < iTemp)
{
iValue += iTemp * ((getGroup()->getNumUnits() > 4) ? 4 : 2);
}
else
{
iValue += (iTemp / 8);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getAdjacentTileHealChange();
iExtra = getAdjacentTileHeal();
iTemp *= (100 + iExtra * 5);
iTemp /= 100;
if (getSameTileHeal() >= iTemp)
{
iValue += (iTemp * ((getGroup()->getNumUnits() > 9) ? 4 : 2));
}
else
{
iValue += (iTemp / 4);
}
}
// try to use Warlords to create super-medic units
if (GC.getPromotionInfo(ePromotion).getAdjacentTileHealChange() > 0 || GC.getPromotionInfo(ePromotion).getSameTileHealChange() > 0)
{
PromotionTypes eLeader = NO_PROMOTION;
for (iI = 0; iI < GC.getNumPromotionInfos(); iI++)
{
if (GC.getPromotionInfo((PromotionTypes)iI).isLeader())
{
eLeader = (PromotionTypes)iI;
}
}
if (isHasPromotion(eLeader) && eLeader != NO_PROMOTION)
{
iValue += GC.getPromotionInfo(ePromotion).getAdjacentTileHealChange() + GC.getPromotionInfo(ePromotion).getSameTileHealChange();
}
}
iTemp = GC.getPromotionInfo(ePromotion).getCombatPercent();
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_COUNTER) ||
(AI_getUnitAIType() == UNITAI_ATTACK_SEA) ||
(AI_getUnitAIType() == UNITAI_RESERVE_SEA) ||
(AI_getUnitAIType() == UNITAI_ATTACK_SEA) ||
(AI_getUnitAIType() == UNITAI_PARADROP) ||
(AI_getUnitAIType() == UNITAI_PIRATE_SEA) ||
(AI_getUnitAIType() == UNITAI_RESERVE_SEA) ||
(AI_getUnitAIType() == UNITAI_ESCORT_SEA) ||
(AI_getUnitAIType() == UNITAI_CARRIER_SEA) ||
(AI_getUnitAIType() == UNITAI_ATTACK_AIR) ||
(AI_getUnitAIType() == UNITAI_CARRIER_AIR))
{
iValue += (iTemp * 2);
}
else
{
iValue += (iTemp * 1);
}
iTemp = GC.getPromotionInfo(ePromotion).getCityAttackPercent();
if (iTemp != 0)
{
if (m_pUnitInfo->getUnitAIType(UNITAI_ATTACK) || m_pUnitInfo->getUnitAIType(UNITAI_ATTACK_CITY) || m_pUnitInfo->getUnitAIType(UNITAI_ATTACK_CITY_LEMMING))
{
iExtra = (m_pUnitInfo->getCityAttackModifier() + (getExtraCityAttackPercent() * 2));
iTemp *= (100 + iExtra);
iTemp /= 100;
if (AI_getUnitAIType() == UNITAI_ATTACK_CITY)
{
iValue += (iTemp * 1);
}
else
{
iValue -= iTemp / 4;
}
}
}
iTemp = GC.getPromotionInfo(ePromotion).getCityDefensePercent();
if (iTemp != 0)
{
if ((AI_getUnitAIType() == UNITAI_CITY_DEFENSE) ||
(AI_getUnitAIType() == UNITAI_CITY_SPECIAL))
{
iExtra = m_pUnitInfo->getCityDefenseModifier() + (getExtraCityDefensePercent() * 2);
iValue += ((iTemp * (100 + iExtra)) / 100);
}
else
{
iValue += (iTemp / 4);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getHillsAttackPercent();
if (iTemp != 0)
{
iExtra = getExtraHillsAttackPercent();
iTemp *= (100 + iExtra * 2);
iTemp /= 100;
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_COUNTER))
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 16);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getHillsDefensePercent();
if (iTemp != 0)
{
iExtra = (m_pUnitInfo->getHillsDefenseModifier() + (getExtraHillsDefensePercent() * 2));
iTemp *= (100 + iExtra);
iTemp /= 100;
if (AI_getUnitAIType() == UNITAI_CITY_DEFENSE)
{
if (plot()->isCity() && plot()->isHills())
{
iValue += (iTemp * 4) / 3;
}
}
else if (AI_getUnitAIType() == UNITAI_COUNTER)
{
if (plot()->isHills())
{
iValue += (iTemp / 4);
}
else
{
iValue++;
}
}
else
{
iValue += (iTemp / 16);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getRevoltProtection();
if ((AI_getUnitAIType() == UNITAI_CITY_DEFENSE) ||
(AI_getUnitAIType() == UNITAI_CITY_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_SPECIAL))
{
if (iTemp > 0)
{
PlayerTypes eOwner = plot()->calculateCulturalOwner();
if (eOwner != NO_PLAYER && GET_PLAYER(eOwner).getTeam() != GET_PLAYER(getOwnerINLINE()).getTeam())
{
iValue += (iTemp / 2);
}
}
}
iTemp = GC.getPromotionInfo(ePromotion).getCollateralDamageProtection();
if ((AI_getUnitAIType() == UNITAI_CITY_DEFENSE) ||
(AI_getUnitAIType() == UNITAI_CITY_COUNTER) ||
(AI_getUnitAIType() == UNITAI_CITY_SPECIAL))
{
iValue += (iTemp / 3);
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_COUNTER))
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 8);
}
iTemp = GC.getPromotionInfo(ePromotion).getPillageChange();
if (AI_getUnitAIType() == UNITAI_PILLAGE ||
AI_getUnitAIType() == UNITAI_ATTACK_SEA ||
AI_getUnitAIType() == UNITAI_PIRATE_SEA)
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 16);
}
iTemp = GC.getPromotionInfo(ePromotion).getUpgradeDiscount();
iValue += (iTemp / 16);
iTemp = GC.getPromotionInfo(ePromotion).getExperiencePercent();
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_ATTACK_SEA) ||
(AI_getUnitAIType() == UNITAI_PIRATE_SEA) ||
(AI_getUnitAIType() == UNITAI_RESERVE_SEA) ||
(AI_getUnitAIType() == UNITAI_ESCORT_SEA) ||
(AI_getUnitAIType() == UNITAI_CARRIER_SEA) ||
(AI_getUnitAIType() == UNITAI_MISSILE_CARRIER_SEA))
{
iValue += (iTemp * 1);
}
else
{
iValue += (iTemp / 2);
}
iTemp = GC.getPromotionInfo(ePromotion).getKamikazePercent();
if (AI_getUnitAIType() == UNITAI_ATTACK_CITY)
{
iValue += (iTemp / 16);
}
else
{
iValue += (iTemp / 64);
}
for (iI = 0; iI < GC.getNumTerrainInfos(); iI++)
{
iTemp = GC.getPromotionInfo(ePromotion).getTerrainAttackPercent(iI);
if (iTemp != 0)
{
iExtra = getExtraTerrainAttackPercent((TerrainTypes)iI);
iTemp *= (100 + iExtra * 2);
iTemp /= 100;
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_COUNTER))
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 16);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getTerrainDefensePercent(iI);
if (iTemp != 0)
{
iExtra = getExtraTerrainDefensePercent((TerrainTypes)iI);
iTemp *= (100 + iExtra);
iTemp /= 100;
if (AI_getUnitAIType() == UNITAI_COUNTER)
{
if (plot()->getTerrainType() == (TerrainTypes)iI)
{
iValue += (iTemp / 4);
}
else
{
iValue++;
}
}
else
{
iValue += (iTemp / 16);
}
}
if (GC.getPromotionInfo(ePromotion).getTerrainDoubleMove(iI))
{
if (AI_getUnitAIType() == UNITAI_EXPLORE)
{
iValue += 20;
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK) || (AI_getUnitAIType() == UNITAI_PILLAGE))
{
iValue += 10;
}
else
{
iValue += 1;
}
}
}
for (iI = 0; iI < GC.getNumFeatureInfos(); iI++)
{
iTemp = GC.getPromotionInfo(ePromotion).getFeatureAttackPercent(iI);
if (iTemp != 0)
{
iExtra = getExtraFeatureAttackPercent((FeatureTypes)iI);
iTemp *= (100 + iExtra * 2);
iTemp /= 100;
if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_COUNTER))
{
iValue += (iTemp / 4);
}
else
{
iValue += (iTemp / 16);
}
}
iTemp = GC.getPromotionInfo(ePromotion).getFeatureDefensePercent(iI);
if (iTemp != 0)
{
iExtra = getExtraFeatureDefensePercent((FeatureTypes)iI);
iTemp *= (100 + iExtra * 2);
iTemp /= 100;
if (!noDefensiveBonus())
{
if (AI_getUnitAIType() == UNITAI_COUNTER)
{
if (plot()->getFeatureType() == (FeatureTypes)iI)
{
iValue += (iTemp / 4);
}
else
{
iValue++;
}
}
else
{
iValue += (iTemp / 16);
}
}
}
if (GC.getPromotionInfo(ePromotion).getFeatureDoubleMove(iI))
{
if (AI_getUnitAIType() == UNITAI_EXPLORE)
{
iValue += 20;
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK) || (AI_getUnitAIType() == UNITAI_PILLAGE))
{
iValue += 10;
}
else
{
iValue += 1;
}
}
}
int iOtherCombat = 0;
int iSameCombat = 0;
for (iI = 0; iI < GC.getNumUnitCombatInfos(); iI++)
{
if ((UnitCombatTypes)iI == getUnitCombatType())
{
iSameCombat += unitCombatModifier((UnitCombatTypes)iI);
}
else
{
iOtherCombat += unitCombatModifier((UnitCombatTypes)iI);
}
}
for (iI = 0; iI < GC.getNumUnitCombatInfos(); iI++)
{
iTemp = GC.getPromotionInfo(ePromotion).getUnitCombatModifierPercent(iI);
int iCombatWeight = 0;
//Fighting their own kind
if ((UnitCombatTypes)iI == getUnitCombatType())
{
if (iSameCombat >= iOtherCombat)
{
iCombatWeight = 70;//"axeman takes formation"
}
else
{
iCombatWeight = 30;
}
}
else
{
//fighting other kinds
if (unitCombatModifier((UnitCombatTypes)iI) > 10)
{
iCombatWeight = 70;//"spearman takes formation"
}
else
{
iCombatWeight = 30;
}
}
iCombatWeight *= GET_PLAYER(getOwnerINLINE()).AI_getUnitCombatWeight((UnitCombatTypes)iI);
iCombatWeight /= 100;
if ((AI_getUnitAIType() == UNITAI_COUNTER) || (AI_getUnitAIType() == UNITAI_CITY_COUNTER))
{
iValue += (iTemp * iCombatWeight) / 50;
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_RESERVE))
{
iValue += (iTemp * iCombatWeight) / 100;
}
else
{
iValue += (iTemp * iCombatWeight) / 200;
}
}
for (iI = 0; iI < NUM_DOMAIN_TYPES; iI++)
{
//WTF? why float and cast to int?
//iTemp = ((int)((GC.getPromotionInfo(ePromotion).getDomainModifierPercent(iI) + getExtraDomainModifier((DomainTypes)iI)) * 100.0f));
iTemp = GC.getPromotionInfo(ePromotion).getDomainModifierPercent(iI);
if (AI_getUnitAIType() == UNITAI_COUNTER)
{
iValue += (iTemp * 1);
}
else if ((AI_getUnitAIType() == UNITAI_ATTACK) ||
(AI_getUnitAIType() == UNITAI_RESERVE))
{
iValue += (iTemp / 2);
}
else
{
iValue += (iTemp / 8);
}
}
if (iValue > 0)
{
iValue += GC.getGameINLINE().getSorenRandNum(15, "AI Promote");
}
return iValue;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_shadow(UnitAITypes eUnitAI, int iMax, int iMaxRatio, bool bWithCargoOnly, bool bOutsideCityOnly, int iMaxPath)
{
PROFILE_FUNC();
CvUnit* pLoopUnit;
CvUnit* pBestUnit;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
iBestValue = 0;
pBestUnit = NULL;
for(pLoopUnit = GET_PLAYER(getOwnerINLINE()).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER(getOwnerINLINE()).nextUnit(&iLoop))
{
if (pLoopUnit != this)
{
if (AI_plotValid(pLoopUnit->plot()))
{
if (pLoopUnit->isGroupHead())
{
if (!(pLoopUnit->isCargo()))
{
if (pLoopUnit->AI_getUnitAIType() == eUnitAI)
{
if (pLoopUnit->getGroup()->baseMoves() <= getGroup()->baseMoves())
{
if (!bWithCargoOnly || pLoopUnit->getGroup()->hasCargo())
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 12/08/08 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if( bOutsideCityOnly && pLoopUnit->plot()->isCity() )
{
continue;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
int iShadowerCount = GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(pLoopUnit, MISSIONAI_SHADOW, getGroup());
if (((-1 == iMax) || (iShadowerCount < iMax)) &&
((-1 == iMaxRatio) || (iShadowerCount == 0) || (((100 * iShadowerCount) / std::max(1, pLoopUnit->getGroup()->countNumUnitAIType(eUnitAI))) <= iMaxRatio)))
{
if (!(pLoopUnit->plot()->isVisibleEnemyUnit(this)))
{
if (generatePath(pLoopUnit->plot(), 0, true, &iPathTurns))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 12/08/08 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
//if (iPathTurns <= iMaxPath) XXX
*/
if (iPathTurns <= iMaxPath)
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
iValue = 1 + pLoopUnit->getGroup()->getCargo();
iValue *= 1000;
iValue /= 1 + iPathTurns;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestUnit = pLoopUnit;
}
}
}
}
}
}
}
}
}
}
}
}
}
if (pBestUnit != NULL)
{
if (atPlot(pBestUnit->plot()))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_SHADOW, NULL, pBestUnit);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO_UNIT, pBestUnit->getOwnerINLINE(), pBestUnit->getID(), 0, false, false, MISSIONAI_SHADOW, NULL, pBestUnit);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
// Added new options to aid transport grouping
// Returns true if a group was joined or a mission was pushed...
bool CvUnitAI::AI_group(UnitAITypes eUnitAI, int iMaxGroup, int iMaxOwnUnitAI, int iMinUnitAI, bool bIgnoreFaster, bool bIgnoreOwnUnitType, bool bStackOfDoom, int iMaxPath, bool bAllowRegrouping, bool bWithCargoOnly, bool bInCityOnly, MissionAITypes eIgnoreMissionAIType)
{
PROFILE_FUNC();
CvUnit* pLoopUnit;
CvUnit* pBestUnit;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
// if we are on a transport, then do not regroup
if (isCargo())
{
return false;
}
if (!bAllowRegrouping)
{
if (getGroup()->getNumUnits() > 1)
{
return false;
}
}
if ((getDomainType() == DOMAIN_LAND) && !canMoveAllTerrain())
{
if (area()->getNumAIUnits(getOwnerINLINE(), eUnitAI) == 0)
{
return false;
}
}
if (!AI_canGroupWithAIType(eUnitAI))
{
return false;
}
int iOurImpassableCount = 0;
CLLNode<IDInfo>* pUnitNode = getGroup()->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pImpassUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = getGroup()->nextUnitNode(pUnitNode);
iOurImpassableCount = std::max(iOurImpassableCount, GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(pImpassUnit->getUnitType()));
}
iBestValue = MAX_INT;
pBestUnit = NULL;
// Loop over groups, ai_allowgroup blocks non-head units anyway
CvSelectionGroup* pLoopGroup = NULL;
for(pLoopGroup = GET_PLAYER(getOwnerINLINE()).firstSelectionGroup(&iLoop); pLoopGroup != NULL; pLoopGroup = GET_PLAYER(getOwnerINLINE()).nextSelectionGroup(&iLoop))
{
pLoopUnit = pLoopGroup->getHeadUnit();
if( pLoopUnit == NULL )
{
continue;
}
CvPlot* pPlot = pLoopUnit->plot();
if (AI_plotValid(pPlot))
{
if (iMaxPath > 0 || pPlot == plot())
{
if (!isEnemy(pPlot->getTeam()))
{
if (AI_allowGroup(pLoopUnit, eUnitAI))
{
if ((iMaxGroup == -1) || ((pLoopGroup->getNumUnits() + GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(pLoopUnit, MISSIONAI_GROUP, getGroup())) <= (iMaxGroup + ((bStackOfDoom) ? AI_stackOfDoomExtra() : 0))))
{
if ((iMaxOwnUnitAI == -1) || (pLoopGroup->countNumUnitAIType(AI_getUnitAIType()) <= (iMaxOwnUnitAI + ((bStackOfDoom) ? AI_stackOfDoomExtra() : 0))))
{
if ((iMinUnitAI == -1) || (pLoopGroup->countNumUnitAIType(eUnitAI) >= iMinUnitAI))
{
if (!bIgnoreFaster || (pLoopGroup->baseMoves() <= baseMoves()))
{
if (!bIgnoreOwnUnitType || (pLoopUnit->getUnitType() != getUnitType()))
{
if (!bWithCargoOnly || pLoopUnit->getGroup()->hasCargo())
{
if( !bInCityOnly || pLoopUnit->plot()->isCity() )
{
if( (eIgnoreMissionAIType == NO_MISSIONAI) || (eIgnoreMissionAIType != pLoopUnit->getGroup()->AI_getMissionAIType()) )
{
if (!(pPlot->isVisibleEnemyUnit(this)))
{
if( iOurImpassableCount > 0 || AI_getUnitAIType() == UNITAI_ASSAULT_SEA )
{
int iTheirImpassableCount = 0;
pUnitNode = pLoopGroup->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pImpassUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopGroup->nextUnitNode(pUnitNode);
iTheirImpassableCount = std::max(iTheirImpassableCount, GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(pImpassUnit->getUnitType()));
}
if( iOurImpassableCount != iTheirImpassableCount )
{
continue;
}
}
if (generatePath(pPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= iMaxPath)
{
iValue = 1000 * (iPathTurns + 1);
iValue *= 4 + pLoopGroup->getCargo();
iValue /= pLoopGroup->getNumUnits();
if (iValue < iBestValue)
{
iBestValue = iValue;
pBestUnit = pLoopUnit;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (pBestUnit != NULL)
{
if (atPlot(pBestUnit->plot()))
{
joinGroup(pBestUnit->getGroup());
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO_UNIT, pBestUnit->getOwnerINLINE(), pBestUnit->getID(), 0, false, false, MISSIONAI_GROUP, NULL, pBestUnit);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
bool CvUnitAI::AI_groupMergeRange(UnitAITypes eUnitAI, int iMaxRange, bool bBiggerOnly, bool bAllowRegrouping, bool bIgnoreFaster)
{
PROFILE_FUNC();
// if we are on a transport, then do not regroup
if (isCargo())
{
return false;
}
if (!bAllowRegrouping)
{
if (getGroup()->getNumUnits() > 1)
{
return false;
}
}
if ((getDomainType() == DOMAIN_LAND) && !canMoveAllTerrain())
{
if (area()->getNumAIUnits(getOwnerINLINE(), eUnitAI) == 0)
{
return false;
}
}
if (!AI_canGroupWithAIType(eUnitAI))
{
return false;
}
// cached values
CvPlot* pPlot = plot();
CvSelectionGroup* pGroup = getGroup();
// best match
CvUnit* pBestUnit = NULL;
int iBestValue = MAX_INT;
// iterate over plots at each range
for (int iDX = -(iMaxRange); iDX <= iMaxRange; iDX++)
{
for (int iDY = -(iMaxRange); iDY <= iMaxRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL && pLoopPlot->getArea() == pPlot->getArea())
{
CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopPlot->nextUnitNode(pUnitNode);
CvSelectionGroup* pLoopGroup = pLoopUnit->getGroup();
if (AI_allowGroup(pLoopUnit, eUnitAI))
{
if (!bIgnoreFaster || (pLoopUnit->getGroup()->baseMoves() <= baseMoves()))
{
if (!bBiggerOnly || (pLoopGroup->getNumUnits() > pGroup->getNumUnits()))
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= (iMaxRange + 2))
{
int iValue = 1000 * (iPathTurns + 1);
iValue /= pLoopGroup->getNumUnits();
if (iValue < iBestValue)
{
iBestValue = iValue;
pBestUnit = pLoopUnit;
}
}
}
}
}
}
}
}
}
}
if (pBestUnit != NULL)
{
if (atPlot(pBestUnit->plot()))
{
pGroup->mergeIntoGroup(pBestUnit->getGroup());
return true;
}
else
{
pGroup->pushMission(MISSION_MOVE_TO_UNIT, pBestUnit->getOwnerINLINE(), pBestUnit->getID(), 0, false, false, MISSIONAI_GROUP, NULL, pBestUnit);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/18/10 jdog5000 */
/* */
/* War tactics AI, Unit AI */
/************************************************************************************************/
// Returns true if we loaded onto a transport or a mission was pushed...
bool CvUnitAI::AI_load(UnitAITypes eUnitAI, MissionAITypes eMissionAI, UnitAITypes eTransportedUnitAI, int iMinCargo, int iMinCargoSpace, int iMaxCargoSpace, int iMaxCargoOurUnitAI, int iFlags, int iMaxPath, int iMaxTransportPath)
{
PROFILE_FUNC();
CvUnit* pLoopUnit;
CvUnit* pBestUnit;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
if (getCargo() > 0)
{
return false;
}
if (isCargo())
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
if ((getDomainType() == DOMAIN_LAND) && !canMoveAllTerrain())
{
if (area()->getNumAIUnits(getOwnerINLINE(), eUnitAI) == 0)
{
return false;
}
}
iBestValue = MAX_INT;
pBestUnit = NULL;
const int iLoadMissionAICount = 4;
MissionAITypes aeLoadMissionAI[iLoadMissionAICount] = {MISSIONAI_LOAD_ASSAULT, MISSIONAI_LOAD_SETTLER, MISSIONAI_LOAD_SPECIAL, MISSIONAI_ATTACK_SPY};
int iCurrentGroupSize = getGroup()->getNumUnits();
for(pLoopUnit = GET_PLAYER(getOwnerINLINE()).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER(getOwnerINLINE()).nextUnit(&iLoop))
{
if (pLoopUnit != this)
{
if (AI_plotValid(pLoopUnit->plot()))
{
if (canLoadUnit(pLoopUnit, pLoopUnit->plot()))
{
// special case ASSAULT_SEA UnitAI, so that, if a unit is marked escort, but can load units, it will load them
// transport units might have been built as escort, this most commonly happens with galleons
UnitAITypes eLoopUnitAI = pLoopUnit->AI_getUnitAIType();
if (eLoopUnitAI == eUnitAI)// || (eUnitAI == UNITAI_ASSAULT_SEA && eLoopUnitAI == UNITAI_ESCORT_SEA))
{
int iCargoSpaceAvailable = pLoopUnit->cargoSpaceAvailable(getSpecialUnitType(), getDomainType());
iCargoSpaceAvailable -= GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(pLoopUnit, aeLoadMissionAI, iLoadMissionAICount, getGroup());
if (iCargoSpaceAvailable > 0)
{
if ((eTransportedUnitAI == NO_UNITAI) || (pLoopUnit->getUnitAICargo(eTransportedUnitAI) > 0))
{
if ((iMinCargo == -1) || (pLoopUnit->getCargo() >= iMinCargo))
{
// Use existing count of cargo space available
if ((iMinCargoSpace == -1) || (iCargoSpaceAvailable >= iMinCargoSpace))
{
if ((iMaxCargoSpace == -1) || (iCargoSpaceAvailable <= iMaxCargoSpace))
{
if ((iMaxCargoOurUnitAI == -1) || (pLoopUnit->getUnitAICargo(AI_getUnitAIType()) <= iMaxCargoOurUnitAI))
{
// Don't block city defense from getting on board
if (true)
{
if (!(pLoopUnit->plot()->isVisibleEnemyUnit(this)))
{
CvPlot* pUnitTargetPlot = pLoopUnit->getGroup()->AI_getMissionAIPlot();
if ((pUnitTargetPlot == NULL) || (pUnitTargetPlot->getTeam() == getTeam()) || (!pUnitTargetPlot->isOwned() || !isPotentialEnemy(pUnitTargetPlot->getTeam(), pUnitTargetPlot)))
{
if (generatePath(pLoopUnit->plot(), iFlags, true, &iPathTurns))
{
if (iPathTurns <= iMaxPath || (iMaxPath == 0 && plot() == pLoopUnit->plot()))
{
// prefer a transport that can hold as much of our group as possible
iValue = (std::max(0, iCurrentGroupSize - iCargoSpaceAvailable) * 5) + iPathTurns;
if (iValue < iBestValue)
{
iBestValue = iValue;
pBestUnit = pLoopUnit;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if( pBestUnit != NULL && iMaxTransportPath < MAX_INT )
{
// Can transport reach enemy in requested time
bool bFoundEnemyPlotInRange = false;
int iPathTurns;
int iRange = iMaxTransportPath * pBestUnit->baseMoves();
CvPlot* pAdjacentPlot = NULL;
for( int iDX = -iRange; (iDX <= iRange && !bFoundEnemyPlotInRange); iDX++ )
{
for( int iDY = -iRange; (iDY <= iRange && !bFoundEnemyPlotInRange); iDY++ )
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if( pLoopPlot != NULL )
{
if( pLoopPlot->isCoastalLand() )
{
if( pLoopPlot->isOwned() )
{
if( isPotentialEnemy(pLoopPlot->getTeam(), pLoopPlot) && !isBarbarian() )
{
if( pLoopPlot->area()->getCitiesPerPlayer(pLoopPlot->getOwnerINLINE()) > 0 )
{
// Transport cannot enter land plot without cargo, so generate path only works properly if
// land units are already loaded
for( int iI = 0; (iI < NUM_DIRECTION_TYPES && !bFoundEnemyPlotInRange); iI++ )
{
pAdjacentPlot = plotDirection(getX_INLINE(), getY_INLINE(), (DirectionTypes)iI);
if (pAdjacentPlot != NULL)
{
if( pAdjacentPlot->isWater() )
{
if( pBestUnit->generatePath(pAdjacentPlot, 0, true, &iPathTurns) )
{
if (pBestUnit->getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
if( iPathTurns <= iMaxTransportPath )
{
bFoundEnemyPlotInRange = true;
}
}
}
}
}
}
}
}
}
}
}
}
if( !bFoundEnemyPlotInRange )
{
pBestUnit = NULL;
}
}
if (pBestUnit != NULL)
{
if (atPlot(pBestUnit->plot()))
{
CvSelectionGroup* pOtherGroup = NULL;
getGroup()->setTransportUnit(pBestUnit, &pOtherGroup); // XXX is this dangerous (not pushing a mission...) XXX air units?
// If part of large group loaded, then try to keep loading the rest
if( eUnitAI == UNITAI_ASSAULT_SEA && eMissionAI == MISSIONAI_LOAD_ASSAULT )
{
if( pOtherGroup != NULL && pOtherGroup->getNumUnits() > 0 )
{
if( pOtherGroup->getHeadUnitAI() == AI_getUnitAIType() )
{
pOtherGroup->getHeadUnit()->AI_load( eUnitAI, eMissionAI, eTransportedUnitAI, iMinCargo, iMinCargoSpace, iMaxCargoSpace, iMaxCargoOurUnitAI, iFlags, 0, iMaxTransportPath );
}
else if( eTransportedUnitAI == NO_UNITAI && iMinCargo < 0 && iMinCargoSpace < 0 && iMaxCargoSpace < 0 && iMaxCargoOurUnitAI < 0 )
{
pOtherGroup->getHeadUnit()->AI_load( eUnitAI, eMissionAI, NO_UNITAI, -1, -1, -1, -1, iFlags, 0, iMaxTransportPath );
}
}
}
return true;
}
else
{
// BBAI TODO: To split or not to split?
int iCargoSpaceAvailable = pBestUnit->cargoSpaceAvailable(getSpecialUnitType(), getDomainType());
FAssertMsg(iCargoSpaceAvailable > 0, "best unit has no space");
// split our group to fit on the transport
CvSelectionGroup* pOtherGroup = NULL;
CvSelectionGroup* pSplitGroup = getGroup()->splitGroup(iCargoSpaceAvailable, this, &pOtherGroup);
FAssertMsg(pSplitGroup != NULL, "splitGroup failed");
FAssertMsg(m_iGroupID == pSplitGroup->getID(), "splitGroup failed to put unit in the new group");
if (pSplitGroup != NULL)
{
CvPlot* pOldPlot = pSplitGroup->plot();
pSplitGroup->pushMission(MISSION_MOVE_TO_UNIT, pBestUnit->getOwnerINLINE(), pBestUnit->getID(), iFlags, false, false, eMissionAI, NULL, pBestUnit);
bool bMoved = (pSplitGroup->plot() != pOldPlot);
if (!bMoved && pOtherGroup != NULL)
{
joinGroup(pOtherGroup);
}
return bMoved;
}
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_guardCityBestDefender()
{
CvCity* pCity;
CvPlot* pPlot;
pPlot = plot();
pCity = pPlot->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (pPlot->getBestDefender(getOwnerINLINE()) == this)
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_CITY, NULL);
return true;
}
}
}
return false;
}
bool CvUnitAI::AI_guardCityMinDefender(bool bSearch)
{
PROFILE_FUNC();
CvCity* pPlotCity = plot()->getPlotCity();
if ((pPlotCity != NULL) && (pPlotCity->getOwnerINLINE() == getOwnerINLINE()))
{
int iCityDefenderCount = pPlotCity->plot()->plotCount(PUF_isUnitAIType, UNITAI_CITY_DEFENSE, -1, getOwnerINLINE());
if ((iCityDefenderCount - 1) < pPlotCity->AI_minDefenders())
{
if ((iCityDefenderCount <= 2) || (GC.getGame().getSorenRandNum(5, "AI shuffle defender") != 0))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_CITY, NULL);
return true;
}
}
}
if (bSearch)
{
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestGuardPlot = NULL;
CvCity* pLoopCity;
int iLoop;
int iCurrentTurn = GC.getGame().getGameTurn();
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
int iDefendersHave = pLoopCity->plot()->plotCount(PUF_isUnitAIType, UNITAI_CITY_DEFENSE, -1, getOwnerINLINE());
int iDefendersNeed = pLoopCity->AI_minDefenders();
if (iDefendersHave < iDefendersNeed)
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
iDefendersHave += GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_GUARD_CITY, getGroup());
if (iDefendersHave < iDefendersNeed + 1)
{
int iPathTurns;
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
if (iPathTurns <= 10)
{
int iValue = (iDefendersNeed - iDefendersHave) * 20;
iValue += 2 * std::min(15, iCurrentTurn - pLoopCity->getGameTurnAcquired());
if (pLoopCity->isOccupation())
{
iValue += 5;
}
iValue -= iPathTurns;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGuardPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestGuardPlot))
{
FAssert(pBestGuardPlot == pBestPlot);
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_CITY, NULL);
return true;
}
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_CITY, pBestGuardPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_guardCity(bool bLeave, bool bSearch, int iMaxPath)
{
PROFILE_FUNC();
CLLNode<IDInfo>* pUnitNode;
CvCity* pCity;
CvCity* pLoopCity;
CvUnit* pLoopUnit;
CvPlot* pPlot;
CvPlot* pBestPlot;
CvPlot* pBestGuardPlot;
bool bDefend;
int iExtra;
int iCount;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
FAssert(getDomainType() == DOMAIN_LAND);
FAssert(canDefend());
pPlot = plot();
pCity = pPlot->getPlotCity();
if ((pCity != NULL) && (pCity->getOwnerINLINE() == getOwnerINLINE())) // XXX check for other team?
{
if (bLeave && !(pCity->AI_isDanger()))
{
iExtra = 1;
}
else
{
iExtra = (bSearch ? 0 : -GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pPlot, 2));
}
bDefend = false;
if (pPlot->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE()) == 1) // XXX check for other team's units?
{
bDefend = true;
}
else if (!(pCity->AI_isDefended(((AI_isCityAIType()) ? -1 : 0) + iExtra))) // XXX check for other team's units?
{
if (AI_isCityAIType())
{
bDefend = true;
}
else
{
iCount = 0;
pUnitNode = pPlot->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pPlot->nextUnitNode(pUnitNode);
if (pLoopUnit->getOwnerINLINE() == getOwnerINLINE())
{
if (pLoopUnit->isGroupHead())
{
if (!(pLoopUnit->isCargo()))
{
if (pLoopUnit->canDefend())
{
if (!(pLoopUnit->AI_isCityAIType()))
{
if (!(pLoopUnit->isHurt()))
{
if (pLoopUnit->isWaiting())
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/24/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
//FAssert(pLoopUnit != this);
if( pLoopUnit != this )
{
iCount++;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
}
else
{
if (pLoopUnit->getGroup()->getMissionType(0) != MISSION_SKIP)
{
iCount++;
}
}
}
}
}
}
}
if (!(pCity->AI_isDefended(iCount + iExtra))) // XXX check for other team's units?
{
bDefend = true;
}
}
}
if (bDefend)
{
CvSelectionGroup* pOldGroup = getGroup();
CvUnit* pEjectedUnit = getGroup()->AI_ejectBestDefender(pPlot);
if (pEjectedUnit != NULL)
{
if (pPlot->plotCount(PUF_isCityAIType, -1, -1, getOwnerINLINE()) == 0)
{
if (pEjectedUnit->cityDefenseModifier() > 0)
{
pEjectedUnit->AI_setUnitAIType(UNITAI_CITY_DEFENSE);
}
}
pEjectedUnit->getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_CITY, NULL);
if (pEjectedUnit->getGroup() == pOldGroup || pEjectedUnit == this)
{
return true;
}
else
{
return false;
}
}
else
{
//This unit is not suited for defense, skip the mission
//to protect this city but encourage others to defend instead.
getGroup()->pushMission(MISSION_SKIP);
if (!isHurt())
{
finishMoves();
}
}
return true;
}
}
if (bSearch)
{
iBestValue = MAX_INT;
pBestPlot = NULL;
pBestGuardPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (!(pLoopCity->AI_isDefended((!AI_isCityAIType()) ? pLoopCity->plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isNotCityAIType) : 0))) // XXX check for other team's units?
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if ((GC.getGame().getGameTurn() - pLoopCity->getGameTurnAcquired() < 10) || GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_GUARD_CITY, getGroup()) < 2)
{
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
if (iPathTurns <= iMaxPath)
{
iValue = iPathTurns;
if (iValue < iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGuardPlot = pLoopCity->plot();
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
if (pBestPlot != NULL)
{
break;
}
}
}
if ((pBestPlot != NULL) && (pBestGuardPlot != NULL))
{
FAssert(!atPlot(pBestPlot));
// split up group if we are going to defend, so rest of group has opportunity to do something else
// if (getGroup()->getNumUnits() > 1)
// {
// getGroup()->AI_separate(); // will change group
// }
//
// getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_CITY, pBestGuardPlot);
// return true;
CvSelectionGroup* pOldGroup = getGroup();
CvUnit* pEjectedUnit = getGroup()->AI_ejectBestDefender(pPlot);
if (pEjectedUnit != NULL)
{
pEjectedUnit->getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_CITY, NULL);
if (pEjectedUnit->getGroup() == pOldGroup || pEjectedUnit == this)
{
return true;
}
else
{
return false;
}
}
else
{
//This unit is not suited for defense, skip the mission
//to protect this city but encourage others to defend instead.
if (atPlot(pBestGuardPlot))
{
getGroup()->pushMission(MISSION_SKIP);
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_CITY, NULL);
}
return true;
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_guardCityAirlift()
{
PROFILE_FUNC();
CvCity* pCity;
CvCity* pLoopCity;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iLoop;
if (getGroup()->getNumUnits() > 1)
{
return false;
}
pCity = plot()->getPlotCity();
if (pCity == NULL)
{
return false;
}
if (pCity->getMaxAirlift() == 0)
{
return false;
}
iBestValue = 0;
pBestPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (pLoopCity != pCity)
{
if (canAirliftAt(pCity->plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
if (!(pLoopCity->AI_isDefended((!AI_isCityAIType()) ? pLoopCity->plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isNotCityAIType) : 0))) // XXX check for other team's units?
{
iValue = pLoopCity->getPopulation();
if (pLoopCity->AI_isDanger())
{
iValue *= 2;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
FAssert(pLoopCity != pCity);
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRLIFT, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_guardBonus(int iMinValue)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestGuardPlot;
ImprovementTypes eImprovement;
BonusTypes eNonObsoleteBonus;
int iPathTurns;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
pBestPlot = NULL;
pBestGuardPlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE())
{
eNonObsoleteBonus = pLoopPlot->getNonObsoleteBonusType(getTeam());
if (eNonObsoleteBonus != NO_BONUS)
{
eImprovement = pLoopPlot->getImprovementType();
if ((eImprovement != NO_IMPROVEMENT) && GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus))
{
iValue = GET_PLAYER(getOwnerINLINE()).AI_bonusVal(eNonObsoleteBonus);
iValue += std::max(0, 200 * GC.getBonusInfo(eNonObsoleteBonus).getAIObjective());
if (pLoopPlot->getPlotGroupConnectedBonus(getOwnerINLINE(), eNonObsoleteBonus) == 1)
{
iValue *= 2;
}
if (iValue > iMinValue)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
// BBAI TODO: Multiple defenders for higher value resources?
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_GUARD_BONUS, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGuardPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestGuardPlot != NULL))
{
if (atPlot(pBestGuardPlot))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_BONUS, pBestGuardPlot);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_BONUS, pBestGuardPlot);
return true;
}
}
return false;
}
int CvUnitAI::AI_getPlotDefendersNeeded(CvPlot* pPlot, int iExtra)
{
int iNeeded = iExtra;
BonusTypes eNonObsoleteBonus = pPlot->getNonObsoleteBonusType(getTeam());
if (eNonObsoleteBonus != NO_BONUS)
{
iNeeded += (GET_PLAYER(getOwnerINLINE()).AI_bonusVal(eNonObsoleteBonus) + 10) / 19;
}
int iDefense = pPlot->defenseModifier(getTeam(), true);
iNeeded += (iDefense + 25) / 50;
if (iNeeded == 0)
{
return 0;
}
iNeeded += GET_PLAYER(getOwnerINLINE()).AI_getPlotAirbaseValue(pPlot) / 50;
int iNumHostiles = 0;
int iNumPlots = 0;
int iRange = 2;
for (int iX = -iRange; iX <= iRange; iX++)
{
for (int iY = -iRange; iY <= iRange; iY++)
{
CvPlot* pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iX, iY);
if (pLoopPlot != NULL)
{
iNumHostiles += pLoopPlot->getNumVisibleEnemyDefenders(this);
if ((pLoopPlot->getTeam() != getTeam()) || pLoopPlot->isCoastalLand())
{
iNumPlots++;
if (isEnemy(pLoopPlot->getTeam()))
{
iNumPlots += 4;
}
}
}
}
}
if ((iNumHostiles == 0) && (iNumPlots < 4))
{
if (iNeeded > 1)
{
iNeeded = 1;
}
else
{
iNeeded = 0;
}
}
return iNeeded;
}
bool CvUnitAI::AI_guardFort(bool bSearch)
{
PROFILE_FUNC();
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
ImprovementTypes eImprovement = plot()->getImprovementType();
if (eImprovement != NO_IMPROVEMENT)
{
if (GC.getImprovementInfo(eImprovement).isActsAsCity())
{
if (plot()->plotCount(PUF_isCityAIType, -1, -1, getOwnerINLINE()) <= AI_getPlotDefendersNeeded(plot(), 0))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_BONUS, plot());
return true;
}
}
}
}
if (!bSearch)
{
return false;
}
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestGuardPlot = NULL;
for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot) && !atPlot(pLoopPlot))
{
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE())
{
ImprovementTypes eImprovement = pLoopPlot->getImprovementType();
if (eImprovement != NO_IMPROVEMENT)
{
if (GC.getImprovementInfo(eImprovement).isActsAsCity())
{
int iValue = AI_getPlotDefendersNeeded(pLoopPlot, 0);
if (iValue > 0)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_GUARD_BONUS, getGroup()) < iValue)
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue *= 1000;
iValue /= (iPathTurns + 2);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGuardPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestGuardPlot != NULL))
{
if (atPlot(pBestGuardPlot))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_BONUS, pBestGuardPlot);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_BONUS, pBestGuardPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_guardCitySite()
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestGuardPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
pBestPlot = NULL;
pBestGuardPlot = NULL;
for (iI = 0; iI < GET_PLAYER(getOwnerINLINE()).AI_getNumCitySites(); iI++)
{
pLoopPlot = GET_PLAYER(getOwnerINLINE()).AI_getCitySite(iI);
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_GUARD_CITY, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue = pLoopPlot->getFoundValue(getOwnerINLINE());
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGuardPlot = pLoopPlot;
}
}
}
}
if ((pBestPlot != NULL) && (pBestGuardPlot != NULL))
{
if (atPlot(pBestGuardPlot))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_CITY, pBestGuardPlot);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_CITY, pBestGuardPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_guardSpy(int iRandomPercent)
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestGuardPlot;
int iValue;
int iBestValue;
int iLoop;
iBestValue = 0;
pBestPlot = NULL;
pBestGuardPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
iValue = 0;
if( GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_SPACE4) )
{
if( pLoopCity->isCapital() )
{
iValue += 30;
}
else if( pLoopCity->isProductionProject() )
{
iValue += 5;
}
}
if( GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_CULTURE3) )
{
if( pLoopCity->getCultureLevel() >= (GC.getNumCultureLevelInfos() - 2))
{
iValue += 10;
}
}
if (pLoopCity->isProductionUnit())
{
if (isLimitedUnitClass((UnitClassTypes)(GC.getUnitInfo(pLoopCity->getProductionUnit()).getUnitClassType())))
{
iValue += 4;
}
}
else if (pLoopCity->isProductionBuilding())
{
if (isLimitedWonderClass((BuildingClassTypes)(GC.getBuildingInfo(pLoopCity->getProductionBuilding()).getBuildingClassType())))
{
iValue += 5;
}
}
else if (pLoopCity->isProductionProject())
{
if (isLimitedProject(pLoopCity->getProductionProject()))
{
iValue += 6;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (iValue > 0)
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_GUARD_SPY, getGroup()) == 0)
{
int iPathTurns;
if (generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
iValue *= 100 + GC.getGameINLINE().getSorenRandNum(iRandomPercent, "AI Guard Spy");
//iValue /= 100;
iValue /= iPathTurns + 1;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGuardPlot = pLoopCity->plot();
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestGuardPlot != NULL))
{
if (atPlot(pBestGuardPlot))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_GUARD_SPY, pBestGuardPlot);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_GUARD_SPY, pBestGuardPlot);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/25/09 jdog5000 */
/* */
/* Espionage AI */
/************************************************************************************************/
/*
// Never used BTS functions ...
// Returns true if a mission was pushed...
bool CvUnitAI::AI_destroySpy()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvCity* pBestCity;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iLoop;
int iI;
iBestValue = 0;
pBestPlot = NULL;
pBestCity = NULL;
for (iI = 0; iI < MAX_CIV_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive())
{
if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam())
{
if (GET_PLAYER(getOwnerINLINE()).AI_getAttitude((PlayerTypes)iI) <= ATTITUDE_ANNOYED)
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_ATTACK_SPY, getGroup()) == 0)
{
if (generatePath(pLoopCity->plot(), 0, true))
{
iValue = (pLoopCity->getPopulation() * 2);
iValue += pLoopCity->getYieldRate(YIELD_PRODUCTION);
if (atPlot(pLoopCity->plot()))
{
iValue *= 4;
iValue /= 3;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestCity = pLoopCity;
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestCity != NULL))
{
if (atPlot(pBestCity->plot()))
{
if (canDestroy(pBestCity->plot()))
{
if (pBestCity->getProduction() > ((pBestCity->getProductionNeeded() * 2) / 3))
{
if (pBestCity->isProductionUnit())
{
if (isLimitedUnitClass((UnitClassTypes)(GC.getUnitInfo(pBestCity->getProductionUnit()).getUnitClassType())))
{
getGroup()->pushMission(MISSION_DESTROY);
return true;
}
}
else if (pBestCity->isProductionBuilding())
{
if (isLimitedWonderClass((BuildingClassTypes)(GC.getBuildingInfo(pBestCity->getProductionBuilding()).getBuildingClassType())))
{
getGroup()->pushMission(MISSION_DESTROY);
return true;
}
}
else if (pBestCity->isProductionProject())
{
if (isLimitedProject(pBestCity->getProductionProject()))
{
getGroup()->pushMission(MISSION_DESTROY);
return true;
}
}
}
}
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY, pBestCity->plot());
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY, pBestCity->plot());
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_sabotageSpy()
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestSabotagePlot;
bool abPlayerAngry[MAX_PLAYERS];
ImprovementTypes eImprovement;
BonusTypes eNonObsoleteBonus;
int iValue;
int iBestValue;
int iI;
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
abPlayerAngry[iI] = false;
if (GET_PLAYER((PlayerTypes)iI).isAlive())
{
if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam())
{
if (GET_PLAYER(getOwnerINLINE()).AI_getAttitude((PlayerTypes)iI) <= ATTITUDE_ANNOYED)
{
abPlayerAngry[iI] = true;
}
}
}
}
iBestValue = 0;
pBestPlot = NULL;
pBestSabotagePlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isOwned())
{
if (pLoopPlot->getTeam() != getTeam())
{
if (abPlayerAngry[pLoopPlot->getOwnerINLINE()])
{
eNonObsoleteBonus = pLoopPlot->getNonObsoleteBonusType(pLoopPlot->getTeam());
if (eNonObsoleteBonus != NO_BONUS)
{
eImprovement = pLoopPlot->getImprovementType();
if ((eImprovement != NO_IMPROVEMENT) && GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus))
{
if (canSabotage(pLoopPlot))
{
iValue = GET_PLAYER(pLoopPlot->getOwnerINLINE()).AI_bonusVal(eNonObsoleteBonus);
if (pLoopPlot->isConnectedToCapital() && (pLoopPlot->getPlotGroupConnectedBonus(pLoopPlot->getOwnerINLINE(), eNonObsoleteBonus) == 1))
{
iValue *= 3;
}
if (iValue > 25)
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_ATTACK_SPY, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true))
{
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestSabotagePlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestSabotagePlot != NULL))
{
if (atPlot(pBestSabotagePlot))
{
getGroup()->pushMission(MISSION_SABOTAGE);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY, pBestSabotagePlot);
return true;
}
}
return false;
}
bool CvUnitAI::AI_pickupTargetSpy()
{
PROFILE_FUNC();
CvCity* pCity;
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestPickupPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
pCity = plot()->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (pCity->isCoastal(GC.getMIN_WATER_SIZE_FOR_OCEAN()))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY, pCity->plot());
return true;
}
}
}
iBestValue = MAX_INT;
pBestPlot = NULL;
pBestPickupPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
if (pLoopCity->isCoastal(GC.getMIN_WATER_SIZE_FOR_OCEAN()))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
iValue = iPathTurns;
if (iValue < iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestPickupPlot = pLoopCity->plot();
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestPickupPlot != NULL))
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY, pBestPickupPlot);
return true;
}
return false;
}
*/
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_chokeDefend()
{
CvCity* pCity;
int iPlotDanger;
FAssert(AI_isCityAIType());
// XXX what about amphib invasions?
pCity = plot()->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (pCity->AI_neededDefenders() > 1)
{
if (pCity->AI_isDefended(pCity->plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isNotCityAIType)))
{
iPlotDanger = GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 3);
if (iPlotDanger <= 4)
{
if (AI_anyAttack(1, 65, std::max(0, (iPlotDanger - 1))))
{
return true;
}
}
}
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_heal(int iDamagePercent, int iMaxPath)
{
PROFILE_FUNC();
CLLNode<IDInfo>* pEntityNode;
std::vector<CvUnit*> aeDamagedUnits;
CvSelectionGroup* pGroup;
CvUnit* pLoopUnit;
int iTotalDamage;
int iTotalHitpoints;
int iHurtUnitCount;
bool bRetreat;
if (plot()->getFeatureType() != NO_FEATURE)
{
// Mongoose FeatureDamageFix BEGIN
if (GC.getFeatureInfo(plot()->getFeatureType()).getTurnDamage() > 0)
// Mongoose FeatureDamageFix END
{
//Pass through
//(actively seeking a safe spot may result in unit getting stuck)
return false;
}
}
pGroup = getGroup();
if (iDamagePercent == 0)
{
iDamagePercent = 10;
}
bRetreat = false;
if (getGroup()->getNumUnits() == 1)
{
if (getDamage() > 0)
{
if (plot()->isCity() || (healTurns(plot()) == 1))
{
if (!(isAlwaysHeal()))
{
getGroup()->pushMission(MISSION_HEAL);
return true;
}
}
}
return false;
}
iMaxPath = std::min(iMaxPath, 2);
pEntityNode = getGroup()->headUnitNode();
iTotalDamage = 0;
iTotalHitpoints = 0;
iHurtUnitCount = 0;
while (pEntityNode != NULL)
{
pLoopUnit = ::getUnit(pEntityNode->m_data);
FAssert(pLoopUnit != NULL);
pEntityNode = pGroup->nextUnitNode(pEntityNode);
int iDamageThreshold = (pLoopUnit->maxHitPoints() * iDamagePercent) / 100;
if (NO_UNIT != getLeaderUnitType())
{
iDamageThreshold /= 2;
}
if (pLoopUnit->getDamage() > 0)
{
iHurtUnitCount++;
}
iTotalDamage += pLoopUnit->getDamage();
iTotalHitpoints += pLoopUnit->maxHitPoints();
if (pLoopUnit->getDamage() > iDamageThreshold)
{
bRetreat = true;
if (!(pLoopUnit->hasMoved()))
{
if (!(pLoopUnit->isAlwaysHeal()))
{
if (pLoopUnit->healTurns(pLoopUnit->plot()) <= iMaxPath)
{
aeDamagedUnits.push_back(pLoopUnit);
}
}
}
}
}
if (iHurtUnitCount == 0)
{
return false;
}
bool bPushedMission = false;
if (plot()->isCity() && (plot()->getOwnerINLINE() == getOwnerINLINE()))
{
FAssertMsg(((int) aeDamagedUnits.size()) <= iHurtUnitCount, "damaged units array is larger than our hurt unit count");
for (unsigned int iI = 0; iI < aeDamagedUnits.size(); iI++)
{
CvUnit* pUnitToHeal = aeDamagedUnits[iI];
pUnitToHeal->joinGroup(NULL);
pUnitToHeal->getGroup()->pushMission(MISSION_HEAL);
// note, removing the head unit from a group will force the group to be completely split if non-human
if (pUnitToHeal == this)
{
bPushedMission = true;
}
iHurtUnitCount--;
}
}
if ((iHurtUnitCount * 2) > pGroup->getNumUnits())
{
FAssertMsg(pGroup->getNumUnits() > 0, "group now has zero units");
if (AI_moveIntoCity(2))
{
return true;
}
else if (healRate(plot()) > 10)
{
pGroup->pushMission(MISSION_HEAL);
return true;
}
}
return bPushedMission;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_afterAttack()
{
if (!isMadeAttack())
{
return false;
}
if (!canFight())
{
return false;
}
if (isBlitz())
{
return false;
}
if (getDomainType() == DOMAIN_LAND)
{
if (AI_guardCity(false, true, 1))
{
return true;
}
}
if (AI_pillageRange(1))
{
return true;
}
if (AI_retreatToCity(false, false, 1))
{
return true;
}
if (AI_hide())
{
return true;
}
if (AI_goody(1))
{
return true;
}
if (AI_pillageRange(2))
{
return true;
}
if (AI_defend())
{
return true;
}
if (AI_safety())
{
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_goldenAge()
{
if (canGoldenAge(plot()))
{
getGroup()->pushMission(MISSION_GOLDEN_AGE);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_spreadReligion()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestSpreadPlot;
ReligionTypes eReligion;
int iPathTurns;
int iValue;
int iBestValue;
int iPlayerMultiplierPercent;
int iLoop;
int iI;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/08/10 jdog5000 */
/* */
/* Victory Strategy AI */
/************************************************************************************************/
bool bCultureVictory = GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_CULTURE2);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
eReligion = NO_RELIGION;
// BBAI TODO: Unnecessary with changes below ...
if (eReligion == NO_RELIGION)
{
if (GET_PLAYER(getOwnerINLINE()).getStateReligion() != NO_RELIGION)
{
if (m_pUnitInfo->getReligionSpreads(GET_PLAYER(getOwnerINLINE()).getStateReligion()) > 0)
{
eReligion = GET_PLAYER(getOwnerINLINE()).getStateReligion();
}
}
}
if (eReligion == NO_RELIGION)
{
for (iI = 0; iI < GC.getNumReligionInfos(); iI++)
{
//if (bCultureVictory || GET_TEAM(getTeam()).hasHolyCity((ReligionTypes)iI))
{
if (m_pUnitInfo->getReligionSpreads((ReligionTypes)iI) > 0)
{
eReligion = ((ReligionTypes)iI);
break;
}
}
}
}
if (eReligion == NO_RELIGION)
{
return false;
}
bool bHasHolyCity = GET_TEAM(getTeam()).hasHolyCity(eReligion);
bool bHasAnyHolyCity = bHasHolyCity;
if (!bHasAnyHolyCity)
{
for (iI = 0; !bHasAnyHolyCity && iI < GC.getNumReligionInfos(); iI++)
{
bHasAnyHolyCity = GET_TEAM(getTeam()).hasHolyCity((ReligionTypes)iI);
}
}
iBestValue = 0;
pBestPlot = NULL;
pBestSpreadPlot = NULL;
// BBAI TODO: Could also use CvPlayerAI::AI_missionaryValue to determine which player to target ...
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive())
{
iPlayerMultiplierPercent = 0;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 11/28/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam())
if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam() && canEnterTerritory(GET_PLAYER((PlayerTypes)iI).getTeam()))
{
if (bHasHolyCity)
{
iPlayerMultiplierPercent = 100;
// BBAI TODO: If going for cultural victory, don't spread to other teams? Sure, this might decrease the chance of
// someone else winning by culture, but at the cost of $$ in holy city and diplomatic conversions (ie future wars!).
// Doesn't seem to up our odds of winning by culture really. Also, no foreign spread after Free Religion? Still get
// gold for city count.
if (!bCultureVictory || (eReligion == GET_PLAYER(getOwnerINLINE()).getStateReligion()))
{
if (GET_PLAYER((PlayerTypes)iI).getStateReligion() == NO_RELIGION)
{
if (0 == (GET_PLAYER((PlayerTypes)iI).getNonStateReligionHappiness()))
{
iPlayerMultiplierPercent += 600;
}
}
else if (GET_PLAYER((PlayerTypes)iI).getStateReligion() == eReligion)
{
iPlayerMultiplierPercent += 300;
}
else
{
if (GET_PLAYER((PlayerTypes)iI).hasHolyCity(GET_PLAYER((PlayerTypes)iI).getStateReligion()))
{
iPlayerMultiplierPercent += 50;
}
else
{
iPlayerMultiplierPercent += 300;
}
}
int iReligionCount = GET_PLAYER((PlayerTypes)iI).countTotalHasReligion();
int iCityCount = GET_PLAYER(getOwnerINLINE()).getNumCities();
//magic formula to produce normalized adjustment factor based on religious infusion
int iAdjustment = (100 * (iCityCount + 1));
iAdjustment /= ((iCityCount + 1) + iReligionCount);
iAdjustment = (((iAdjustment - 25) * 4) / 3);
iAdjustment = std::max(10, iAdjustment);
iPlayerMultiplierPercent *= iAdjustment;
iPlayerMultiplierPercent /= 100;
}
}
}
else if (iI == getOwnerINLINE())
{
iPlayerMultiplierPercent = 100;
}
else if (bHasHolyCity && GET_PLAYER((PlayerTypes)iI).getTeam() == getTeam())
{
iPlayerMultiplierPercent = 80;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (iPlayerMultiplierPercent > 0)
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()) && pLoopCity->area() == area())
{
if (canSpread(pLoopCity->plot(), eReligion))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_SPREAD, getGroup()) == 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/03/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (generatePath(pLoopCity->plot(), MOVE_NO_ENEMY_TERRITORY, true, &iPathTurns))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
iValue = (7 + (pLoopCity->getPopulation() * 4));
bool bOurCity = false;
// BBAI TODO: Why not just use iPlayerMultiplier??
if (pLoopCity->getOwnerINLINE() == getOwnerINLINE())
{
iValue *= (bCultureVictory ? 16 : 4);
bOurCity = true;
}
else if (pLoopCity->getTeam() == getTeam())
{
iValue *= 3;
bOurCity = true;
}
else
{
iValue *= iPlayerMultiplierPercent;
iValue /= 100;
}
int iCityReligionCount = pLoopCity->getReligionCount();
int iReligionCountFactor = iCityReligionCount;
if (bOurCity)
{
// count cities with no religion the same as cities with 2 religions
// prefer a city with exactly 1 religion already
if (iCityReligionCount == 0)
{
iReligionCountFactor = 2;
}
else if (iCityReligionCount == 1)
{
iValue *= 2;
}
}
else
{
// absolutely prefer cities with zero religions
if (iCityReligionCount == 0)
{
iValue *= 2;
}
// not our city, so prefer the lowest number of religions (increment so no divide by zero)
iReligionCountFactor++;
}
iValue /= iReligionCountFactor;
FAssert(iPathTurns > 0);
bool bForceMove = false;
if (isHuman())
{
//If human, prefer to spread to the player where automated from.
if (plot()->getOwnerINLINE() == pLoopCity->getOwnerINLINE())
{
iValue *= 10;
if (pLoopCity->isRevealed(getTeam(), false))
{
bForceMove = true;
}
}
}
iValue *= 1000;
iValue /= (iPathTurns + 2);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = bForceMove ? pLoopCity->plot() : getPathEndTurnPlot();
pBestSpreadPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestSpreadPlot != NULL))
{
if (atPlot(pBestSpreadPlot))
{
getGroup()->pushMission(MISSION_SPREAD, eReligion);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/09/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_SPREAD, pBestSpreadPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_spreadCorporation()
{
PROFILE_FUNC();
CorporationTypes eCorporation = NO_CORPORATION;
for (int iI = 0; iI < GC.getNumCorporationInfos(); ++iI)
{
if (m_pUnitInfo->getCorporationSpreads((CorporationTypes)iI) > 0)
{
eCorporation = ((CorporationTypes)iI);
break;
}
}
if (NO_CORPORATION == eCorporation)
{
return false;
}
/*************************************************************************************************/
/** Xienwolf Tweak 03/20/09 **/
/** **/
/** Firaxis Typo Fix **/
/*************************************************************************************************/
/** ---- Start Original Code ---- **
bool bHasHQ = (GET_TEAM(getTeam()).hasHeadquarters((CorporationTypes)iI));
/** ---- End Original Code ---- **/
bool bHasHQ = (GET_TEAM(getTeam()).hasHeadquarters(eCorporation));
/*************************************************************************************************/
/** Tweak END **/
/*************************************************************************************************/
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestSpreadPlot = NULL;
CvTeam& kTeam = GET_TEAM(getTeam());
for (int iI = 0; iI < MAX_PLAYERS; iI++)
{
CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iI);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/21/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (kLoopPlayer.isAlive() && (bHasHQ || (getTeam() == kLoopPlayer.getTeam())))
if (kLoopPlayer.isAlive() && ((bHasHQ && canEnterTerritory(GET_PLAYER((PlayerTypes)iI).getTeam())) || (getTeam() == kLoopPlayer.getTeam())))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
int iLoopPlayerCorpCount = kLoopPlayer.countCorporations(eCorporation);
CvTeam& kLoopTeam = GET_TEAM(kLoopPlayer.getTeam());
int iLoop;
for (CvCity* pLoopCity = kLoopPlayer.firstCity(&iLoop); NULL != pLoopCity; pLoopCity = kLoopPlayer.nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if ( pLoopCity->area() == area() && canSpreadCorporation(pLoopCity->plot(), eCorporation))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_SPREAD_CORPORATION, getGroup()) == 0)
{
int iPathTurns;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/03/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (generatePath(pLoopCity->plot(), MOVE_NO_ENEMY_TERRITORY, true, &iPathTurns))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
// BBAI TODO: Serious need for more intelligent self spread, keep certain corps from
// enemies based on their victory pursuits (culture ...)
int iValue = (10 + pLoopCity->getPopulation() * 2);
if (pLoopCity->getOwnerINLINE() == getOwnerINLINE())
{
iValue *= 4;
}
else if (kLoopTeam.isVassal(getTeam()))
{
iValue *= 3;
}
else if (kTeam.isVassal(kLoopTeam.getID()))
{
if (iLoopPlayerCorpCount == 0)
{
iValue *= 10;
}
else
{
iValue *= 3;
iValue /= 2;
}
}
else if (pLoopCity->getTeam() == getTeam())
{
iValue *= 2;
}
if (iLoopPlayerCorpCount == 0)
{
//Generally prefer to heavily target one player
iValue /= 2;
}
bool bForceMove = false;
if (isHuman())
{
//If human, prefer to spread to the player where automated from.
if (plot()->getOwnerINLINE() == pLoopCity->getOwnerINLINE())
{
iValue *= 10;
if (pLoopCity->isRevealed(getTeam(), false))
{
bForceMove = true;
}
}
}
FAssert(iPathTurns > 0);
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = bForceMove ? pLoopCity->plot() : getPathEndTurnPlot();
pBestSpreadPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestSpreadPlot != NULL))
{
if (atPlot(pBestSpreadPlot))
{
if (canSpreadCorporation(pBestSpreadPlot, eCorporation))
{
getGroup()->pushMission(MISSION_SPREAD_CORPORATION, eCorporation);
}
else
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_SPREAD_CORPORATION, pBestSpreadPlot);
}
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/09/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_SPREAD_CORPORATION, pBestSpreadPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
bool CvUnitAI::AI_spreadReligionAirlift()
{
PROFILE_FUNC();
CvPlot* pBestPlot;
ReligionTypes eReligion;
int iValue;
int iBestValue;
int iI;
if (getGroup()->getNumUnits() > 1)
{
return false;
}
CvCity* pCity = plot()->getPlotCity();
if (pCity == NULL)
{
return false;
}
if (pCity->getMaxAirlift() == 0)
{
return false;
}
//bool bCultureVictory = GET_PLAYER(getOwnerINLINE()).AI_isDoStrategy(AI_STRATEGY_CULTURE2);
eReligion = NO_RELIGION;
if (eReligion == NO_RELIGION)
{
if (GET_PLAYER(getOwnerINLINE()).getStateReligion() != NO_RELIGION)
{
if (m_pUnitInfo->getReligionSpreads(GET_PLAYER(getOwnerINLINE()).getStateReligion()) > 0)
{
eReligion = GET_PLAYER(getOwnerINLINE()).getStateReligion();
}
}
}
if (eReligion == NO_RELIGION)
{
for (iI = 0; iI < GC.getNumReligionInfos(); iI++)
{
//if (bCultureVictory || GET_TEAM(getTeam()).hasHolyCity((ReligionTypes)iI))
{
if (m_pUnitInfo->getReligionSpreads((ReligionTypes)iI) > 0)
{
eReligion = ((ReligionTypes)iI);
break;
}
}
}
}
if (eReligion == NO_RELIGION)
{
return false;
}
iBestValue = 0;
pBestPlot = NULL;
for (int iI = 0; iI < MAX_PLAYERS; iI++)
{
CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iI);
if (kLoopPlayer.isAlive() && (getTeam() == kLoopPlayer.getTeam()))
{
int iLoop;
for (CvCity* pLoopCity = kLoopPlayer.firstCity(&iLoop); NULL != pLoopCity; pLoopCity = kLoopPlayer.nextCity(&iLoop))
{
if (canAirliftAt(pCity->plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
if (canSpread(pLoopCity->plot(), eReligion))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_SPREAD, getGroup()) == 0)
{
/************************************************************************************************/
/* UNOFFICIAL_PATCH 08/04/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
// Don't airlift where there's already one of our unit types (probably just airlifted)
if( pLoopCity->plot()->plotCount(PUF_isUnitType, getUnitType(), -1, getOwnerINLINE()) > 0 )
{
continue;
}
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
iValue = (7 + (pLoopCity->getPopulation() * 4));
int iCityReligionCount = pLoopCity->getReligionCount();
int iReligionCountFactor = iCityReligionCount;
// count cities with no religion the same as cities with 2 religions
// prefer a city with exactly 1 religion already
if (iCityReligionCount == 0)
{
iReligionCountFactor = 2;
}
else if (iCityReligionCount == 1)
{
iValue *= 2;
}
iValue /= iReligionCountFactor;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRLIFT, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_SPREAD, pBestPlot);
return true;
}
return false;
}
bool CvUnitAI::AI_spreadCorporationAirlift()
{
PROFILE_FUNC();
if (getGroup()->getNumUnits() > 1)
{
return false;
}
CvCity* pCity = plot()->getPlotCity();
if (pCity == NULL)
{
return false;
}
if (pCity->getMaxAirlift() == 0)
{
return false;
}
CorporationTypes eCorporation = NO_CORPORATION;
for (int iI = 0; iI < GC.getNumCorporationInfos(); ++iI)
{
if (m_pUnitInfo->getCorporationSpreads((CorporationTypes)iI) > 0)
{
eCorporation = ((CorporationTypes)iI);
break;
}
}
if (NO_CORPORATION == eCorporation)
{
return false;
}
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
for (int iI = 0; iI < MAX_PLAYERS; iI++)
{
CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iI);
if (kLoopPlayer.isAlive() && (getTeam() == kLoopPlayer.getTeam()))
{
int iLoop;
for (CvCity* pLoopCity = kLoopPlayer.firstCity(&iLoop); NULL != pLoopCity; pLoopCity = kLoopPlayer.nextCity(&iLoop))
{
if (canAirliftAt(pCity->plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
if (canSpreadCorporation(pLoopCity->plot(), eCorporation))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_SPREAD_CORPORATION, getGroup()) == 0)
{
/************************************************************************************************/
/* UNOFFICIAL_PATCH 08/04/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
// Don't airlift where there's already one of our unit types (probably just airlifted)
if( pLoopCity->plot()->plotCount(PUF_isUnitType, getUnitType(), -1, getOwnerINLINE()) > 0 )
{
continue;
}
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
int iValue = (pLoopCity->getPopulation() * 4);
if (pLoopCity->getOwnerINLINE() == getOwnerINLINE())
{
iValue *= 4;
}
else
{
iValue *= 3;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRLIFT, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_SPREAD, pBestPlot);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_discover(bool bThisTurnOnly, bool bFirstResearchOnly)
{
TechTypes eDiscoverTech;
bool bIsFirstTech;
int iPercentWasted = 0;
if (canDiscover(plot()))
{
eDiscoverTech = getDiscoveryTech();
bIsFirstTech = (GET_PLAYER(getOwnerINLINE()).AI_isFirstTech(eDiscoverTech));
if (bFirstResearchOnly && !bIsFirstTech)
{
return false;
}
iPercentWasted = (100 - ((getDiscoverResearch(eDiscoverTech) * 100) / getDiscoverResearch(NO_TECH)));
FAssert(((iPercentWasted >= 0) && (iPercentWasted <= 100)));
if (getDiscoverResearch(eDiscoverTech) >= GET_TEAM(getTeam()).getResearchLeft(eDiscoverTech))
{
if ((iPercentWasted < 51) && bFirstResearchOnly && bIsFirstTech)
{
getGroup()->pushMission(MISSION_DISCOVER);
return true;
}
if (iPercentWasted < (bIsFirstTech ? 31 : 11))
{
//I need a good way to assess if the tech is actually valuable...
//but don't have one.
getGroup()->pushMission(MISSION_DISCOVER);
return true;
}
}
else if (bThisTurnOnly)
{
return false;
}
if (iPercentWasted <= 11)
{
if (GET_PLAYER(getOwnerINLINE()).getCurrentResearch() == eDiscoverTech)
{
getGroup()->pushMission(MISSION_DISCOVER);
return true;
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_lead(std::vector<UnitAITypes>& aeUnitAITypes)
{
PROFILE_FUNC();
FAssertMsg(!isHuman(), "isHuman did not return false as expected");
FAssertMsg(AI_getUnitAIType() != NO_UNITAI, "AI_getUnitAIType() is not expected to be equal with NO_UNITAI");
FAssert(NO_PLAYER != getOwnerINLINE());
CvPlayer& kOwner = GET_PLAYER(getOwnerINLINE());
bool bNeedLeader = false;
for (int iI = 0; iI < MAX_CIV_TEAMS; iI++)
{
CvTeamAI& kLoopTeam = GET_TEAM((TeamTypes)iI);
if (isEnemy((TeamTypes)iI))
{
if (kLoopTeam.countNumUnitsByArea(area()) > 0)
{
bNeedLeader = true;
break;
}
}
}
CvUnit* pBestUnit = NULL;
CvPlot* pBestPlot = NULL;
// AI may use Warlords to create super-medic units
CvUnit* pBestStrUnit = NULL;
CvPlot* pBestStrPlot = NULL;
CvUnit* pBestHealUnit = NULL;
CvPlot* pBestHealPlot = NULL;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 05/14/10 jdog5000 */
/* */
/* Great People AI, Unit AI */
/************************************************************************************************/
if (bNeedLeader)
{
int iBestStrength = 0;
int iBestHealing = 0;
int iLoop;
for (CvUnit* pLoopUnit = kOwner.firstUnit(&iLoop); pLoopUnit; pLoopUnit = kOwner.nextUnit(&iLoop))
{
bool bValid = isWorldUnitClass(pLoopUnit->getUnitClassType());
if( !bValid )
{
for (uint iI = 0; iI < aeUnitAITypes.size(); iI++)
{
if (pLoopUnit->AI_getUnitAIType() == aeUnitAITypes[iI] || NO_UNITAI == aeUnitAITypes[iI])
{
bValid = true;
break;
}
}
}
if( bValid )
{
if (canLead(pLoopUnit->plot(), pLoopUnit->getID()) > 0)
{
if (AI_plotValid(pLoopUnit->plot()))
{
if (!(pLoopUnit->plot()->isVisibleEnemyUnit(this)))
{
if( pLoopUnit->combatLimit() == 100 )
{
if (generatePath(pLoopUnit->plot(), MOVE_AVOID_ENEMY_WEIGHT_3, true))
{
// pick the unit with the highest current strength
int iCombatStrength = pLoopUnit->currCombatStr(NULL, NULL);
iCombatStrength *= 30 + pLoopUnit->getExperience();
iCombatStrength /= 30;
if( GC.getUnitClassInfo(pLoopUnit->getUnitClassType()).getMaxGlobalInstances() > -1 )
{
iCombatStrength *= 1 + GC.getUnitClassInfo(pLoopUnit->getUnitClassType()).getMaxGlobalInstances();
iCombatStrength /= std::max(1, GC.getUnitClassInfo(pLoopUnit->getUnitClassType()).getMaxGlobalInstances());
}
if (iCombatStrength > iBestStrength)
{
iBestStrength = iCombatStrength;
pBestStrUnit = pLoopUnit;
pBestStrPlot = getPathEndTurnPlot();
}
// or the unit with the best healing ability
int iHealing = pLoopUnit->getSameTileHeal() + pLoopUnit->getAdjacentTileHeal();
if (iHealing > iBestHealing)
{
iBestHealing = iHealing;
pBestHealUnit = pLoopUnit;
pBestHealPlot = getPathEndTurnPlot();
}
}
}
}
}
}
}
}
}
if( AI_getBirthmark() % 3 == 0 && pBestHealUnit != NULL )
{
pBestPlot = pBestHealPlot;
pBestUnit = pBestHealUnit;
}
else
{
pBestPlot = pBestStrPlot;
pBestUnit = pBestStrUnit;
}
if (pBestPlot)
{
if (atPlot(pBestPlot) && pBestUnit)
{
if( gUnitLogLevel > 2 )
{
CvWString szString;
getUnitAIString(szString, pBestUnit->AI_getUnitAIType());
logBBAI(" Great general %d for %S chooses to lead %S with UNITAI %S", getID(), GET_PLAYER(getOwner()).getCivilizationDescription(0), pBestUnit->getName(0).GetCString(), szString);
}
getGroup()->pushMission(MISSION_LEAD, pBestUnit->getID());
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3);
return true;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return false;
}
// Returns true if a mission was pushed...
// iMaxCounts = 1 would mean join a city if there's no existing joined GP of that type.
bool CvUnitAI::AI_join(int iMaxCount)
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
SpecialistTypes eBestSpecialist;
int iValue;
int iBestValue;
int iLoop;
int iI;
int iCount;
iBestValue = 0;
pBestPlot = NULL;
eBestSpecialist = NO_SPECIALIST;
iCount = 0;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if ((pLoopCity->area() == area()) && AI_plotValid(pLoopCity->plot()))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (generatePath(pLoopCity->plot(), MOVE_SAFE_TERRITORY, true))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
for (iI = 0; iI < GC.getNumSpecialistInfos(); iI++)
{
bool bDoesJoin = false;
SpecialistTypes eSpecialist = (SpecialistTypes)iI;
if (m_pUnitInfo->getGreatPeoples(eSpecialist))
{
bDoesJoin = true;
}
if (bDoesJoin)
{
iCount += pLoopCity->getSpecialistCount(eSpecialist);
if (iCount >= iMaxCount)
{
return false;
}
}
if (canJoin(pLoopCity->plot(), ((SpecialistTypes)iI)))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pLoopCity->plot(), 2) == 0)
if ( !(GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(pLoopCity->plot(), 2)) )
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
iValue = pLoopCity->AI_specialistValue(((SpecialistTypes)iI), pLoopCity->AI_avoidGrowth(), false);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
eBestSpecialist = ((SpecialistTypes)iI);
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (eBestSpecialist != NO_SPECIALIST))
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_JOIN, eBestSpecialist);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/09/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_SAFE_TERRITORY);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
// iMaxCount = 1 would mean construct only if there are no existing buildings
// constructed by this GP type.
bool CvUnitAI::AI_construct(int iMaxCount, int iMaxSingleBuildingCount, int iThreshold)
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestConstructPlot;
BuildingTypes eBestBuilding;
int iValue;
int iBestValue;
int iLoop;
int iI;
int iCount;
iBestValue = 0;
pBestPlot = NULL;
pBestConstructPlot = NULL;
eBestBuilding = NO_BUILDING;
iCount = 0;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()) && pLoopCity->area() == area())
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_CONSTRUCT, getGroup()) == 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/03/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (generatePath(pLoopCity->plot(), MOVE_NO_ENEMY_TERRITORY, true))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++)
{
BuildingTypes eBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iI);
if (NO_BUILDING != eBuilding)
{
bool bDoesBuild = false;
if ((m_pUnitInfo->getForceBuildings(eBuilding))
|| (m_pUnitInfo->getBuildings(eBuilding)))
{
bDoesBuild = true;
}
if (bDoesBuild && (pLoopCity->getNumBuilding(eBuilding) > 0))
{
iCount++;
if (iCount >= iMaxCount)
{
return false;
}
}
if (bDoesBuild && GET_PLAYER(getOwnerINLINE()).getBuildingClassCount((BuildingClassTypes)GC.getBuildingInfo(eBuilding).getBuildingClassType()) < iMaxSingleBuildingCount)
{
if (canConstruct(pLoopCity->plot(), eBuilding))
{
iValue = pLoopCity->AI_buildingValue(eBuilding);
if ((iValue > iThreshold) && (iValue > iBestValue))
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestConstructPlot = pLoopCity->plot();
eBestBuilding = eBuilding;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestConstructPlot != NULL) && (eBestBuilding != NO_BUILDING))
{
if (atPlot(pBestConstructPlot))
{
getGroup()->pushMission(MISSION_CONSTRUCT, eBestBuilding);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/09/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_CONSTRUCT, pBestConstructPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_switchHurry()
{
CvCity* pCity;
BuildingTypes eBestBuilding;
int iValue;
int iBestValue;
int iI;
pCity = plot()->getPlotCity();
if ((pCity == NULL) || (pCity->getOwnerINLINE() != getOwnerINLINE()))
{
return false;
}
iBestValue = 0;
eBestBuilding = NO_BUILDING;
for (iI = 0; iI < GC.getNumBuildingClassInfos(); iI++)
{
if (isWorldWonderClass((BuildingClassTypes)iI))
{
BuildingTypes eBuilding = (BuildingTypes)GC.getCivilizationInfo(getCivilizationType()).getCivilizationBuildings(iI);
if (NO_BUILDING != eBuilding)
{
if (pCity->canConstruct(eBuilding))
{
if (pCity->getBuildingProduction(eBuilding) == 0)
{
if (getMaxHurryProduction(pCity) >= pCity->getProductionNeeded(eBuilding))
{
iValue = pCity->AI_buildingValue(eBuilding);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuilding = eBuilding;
}
}
}
}
}
}
}
if (eBestBuilding != NO_BUILDING)
{
pCity->pushOrder(ORDER_CONSTRUCT, eBestBuilding, -1, false, false, false);
if (pCity->getProductionBuilding() == eBestBuilding)
{
if (canHurry(plot()))
{
getGroup()->pushMission(MISSION_HURRY);
return true;
}
}
FAssert(false);
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_hurry()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestHurryPlot;
bool bHurry;
int iTurnsLeft;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
iBestValue = 0;
pBestPlot = NULL;
pBestHurryPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if ((pLoopCity->area() == area()) && AI_plotValid(pLoopCity->plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if ( canHurry(pLoopCity->plot()))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_HURRY, getGroup()) == 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/03/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (generatePath(pLoopCity->plot(), MOVE_NO_ENEMY_TERRITORY, true, &iPathTurns))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
bHurry = false;
if (pLoopCity->isProductionBuilding())
{
if (isWorldWonderClass((BuildingClassTypes)(GC.getBuildingInfo(pLoopCity->getProductionBuilding()).getBuildingClassType())))
{
bHurry = true;
}
}
if (bHurry)
{
iTurnsLeft = pLoopCity->getProductionTurnsLeft();
iTurnsLeft -= iPathTurns;
if (iTurnsLeft > 8)
{
iValue = iTurnsLeft;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestHurryPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestHurryPlot != NULL))
{
if (atPlot(pBestHurryPlot))
{
getGroup()->pushMission(MISSION_HURRY);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/09/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_HURRY, pBestHurryPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_greatWork()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestGreatWorkPlot;
int iValue;
int iBestValue;
int iLoop;
iBestValue = 0;
pBestPlot = NULL;
pBestGreatWorkPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if ((pLoopCity->area() == area()) && AI_plotValid(pLoopCity->plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (canGreatWork(pLoopCity->plot()))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_GREAT_WORK, getGroup()) == 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/03/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if (generatePath(pLoopCity->plot(), MOVE_NO_ENEMY_TERRITORY, true))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
iValue = pLoopCity->AI_calculateCulturePressure(true);
iValue -= ((100 * pLoopCity->getCulture(pLoopCity->getOwnerINLINE())) / std::max(1, getGreatWorkCulture(pLoopCity->plot())));
if (iValue > 0)
{
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestGreatWorkPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestGreatWorkPlot != NULL))
{
if (atPlot(pBestGreatWorkPlot))
{
getGroup()->pushMission(MISSION_GREAT_WORK);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/09/09 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_GREAT_WORK, pBestGreatWorkPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_offensiveAirlift()
{
PROFILE_FUNC();
CvCity* pCity;
CvCity* pTargetCity;
CvCity* pLoopCity;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iLoop;
if (getGroup()->getNumUnits() > 1)
{
return false;
}
if (area()->getTargetCity(getOwnerINLINE()) != NULL)
{
return false;
}
pCity = plot()->getPlotCity();
if (pCity == NULL)
{
return false;
}
if (pCity->getMaxAirlift() == 0)
{
return false;
}
iBestValue = 0;
pBestPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (pLoopCity->area() != pCity->area())
{
if (canAirliftAt(pCity->plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
pTargetCity = pLoopCity->area()->getTargetCity(getOwnerINLINE());
if (pTargetCity != NULL)
{
AreaAITypes eAreaAIType = pTargetCity->area()->getAreaAIType(getTeam());
if (((eAreaAIType == AREAAI_OFFENSIVE) || (eAreaAIType == AREAAI_DEFENSIVE) || (eAreaAIType == AREAAI_MASSING))
|| pTargetCity->AI_isDanger())
{
iValue = 10000;
iValue *= (GET_PLAYER(getOwnerINLINE()).AI_militaryWeight(pLoopCity->area()) + 10);
iValue /= (GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(pLoopCity->area(), AI_getUnitAIType()) + 10);
iValue += std::max(1, ((GC.getMapINLINE().maxStepDistance() * 2) - GC.getMapINLINE().calculatePathDistance(pLoopCity->plot(), pTargetCity->plot())));
if (AI_getUnitAIType() == UNITAI_PARADROP)
{
CvCity* pNearestEnemyCity = GC.getMapINLINE().findCity(pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE(), NO_PLAYER, NO_TEAM, false, false, getTeam());
if (pNearestEnemyCity != NULL)
{
int iDistance = plotDistance(pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE(), pNearestEnemyCity->getX_INLINE(), pNearestEnemyCity->getY_INLINE());
if (iDistance <= getDropRange())
{
iValue *= 5;
}
}
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
FAssert(pLoopCity != pCity);
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRLIFT, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_paradrop(int iRange)
{
PROFILE_FUNC();
if (getGroup()->getNumUnits() > 1)
{
return false;
}
int iParatrooperCount = plot()->plotCount(PUF_isUnitAIType, UNITAI_PARADROP, -1, getOwnerINLINE());
FAssert(iParatrooperCount > 0);
CvPlot* pPlot = plot();
if (!canParadrop(pPlot))
{
return false;
}
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
int iSearchRange = AI_searchRange(iRange);
for (int iDX = -iSearchRange; iDX <= iSearchRange; ++iDX)
{
for (int iDY = -iSearchRange; iDY <= iSearchRange; ++iDY)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (isPotentialEnemy(pLoopPlot->getTeam(), pLoopPlot))
{
if (canParadropAt(pPlot, pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
int iValue = 0;
PlayerTypes eTargetPlayer = pLoopPlot->getOwnerINLINE();
FAssert(NO_PLAYER != eTargetPlayer);
/************************************************************************************************/
/* UNOFFICIAL_PATCH 08/01/08 jdog5000 */
/* */
/* Bugfix */
/************************************************************************************************/
/* original BTS code
if (NO_BONUS != pLoopPlot->getBonusType())
{
iValue += GET_PLAYER(eTargetPlayer).AI_bonusVal(pLoopPlot->getBonusType()) - 10;
}
*/
// Bonus values for bonuses the AI has are less than 10 for non-strategic resources... since this is
// in the AI territory they probably have it
if (NO_BONUS != pLoopPlot->getNonObsoleteBonusType(getTeam()))
{
iValue += std::max(1,GET_PLAYER(eTargetPlayer).AI_bonusVal(pLoopPlot->getBonusType()) - 10);
}
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
for (int i = -1; i <= 1; ++i)
{
for (int j = -1; j <= 1; ++j)
{
CvPlot* pAdjacentPlot = plotXY(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), i, j);
if (NULL != pAdjacentPlot)
{
CvCity* pAdjacentCity = pAdjacentPlot->getPlotCity();
if (NULL != pAdjacentCity)
{
if (pAdjacentCity->getOwnerINLINE() == eTargetPlayer)
{
int iAttackerCount = GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pAdjacentPlot, true);
int iDefenderCount = pAdjacentPlot->getNumVisibleEnemyDefenders(this);
iValue += 20 * (AI_attackOdds(pAdjacentPlot, true) - ((50 * iDefenderCount) / (iParatrooperCount + iAttackerCount)));
}
}
}
}
}
if (iValue > 0)
{
iValue += pLoopPlot->defenseModifier(getTeam(), ignoreBuildingDefense());
CvUnit* pInterceptor = bestInterceptor(pLoopPlot);
if (NULL != pInterceptor)
{
int iInterceptProb = isSuicide() ? 100 : pInterceptor->currInterceptionProbability();
iInterceptProb *= std::max(0, (100 - evasionProbability()));
iInterceptProb /= 100;
iValue *= std::max(0, 100 - iInterceptProb / 2);
iValue /= 100;
}
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
FAssert(pBestPlot != pPlot);
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_PARADROP, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 09/01/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_protect(int iOddsThreshold, int iMaxPathTurns)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
pBestPlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE())
{
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isVisibleEnemyUnit(this))
{
if (!atPlot(pLoopPlot))
{
// BBAI efficiency: Check area for land units
if( (getDomainType() != DOMAIN_LAND) || (pLoopPlot->area() == area()) || getGroup()->canMoveAllTerrain() )
{
// BBAI efficiency: Most of the time, path will exist and odds will be checked anyway. When path doesn't exist, checking path
// takes longer. Therefore, check odds first.
iValue = getGroup()->AI_attackOdds(pLoopPlot, true);
if ((iValue >= AI_finalOddsThreshold(pLoopPlot, iOddsThreshold)) && (iValue*50 > iBestValue))
{
int iPathTurns;
if( generatePath(pLoopPlot, 0, true, &iPathTurns) )
{
// BBAI TODO: Other units targeting this already (if path turns > 1 or 0)?
if( iPathTurns <= iMaxPathTurns )
{
iValue *= 100;
iValue /= (2 + iPathTurns);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_patrol()
{
PROFILE_FUNC();
CvPlot* pAdjacentPlot;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
pBestPlot = NULL;
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(getX_INLINE(), getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL)
{
if (AI_plotValid(pAdjacentPlot))
{
if (!(pAdjacentPlot->isVisibleEnemyUnit(this)))
{
if (generatePath(pAdjacentPlot, 0, true))
{
/*************************************************************************************************/
/** Xienwolf Tweak 12/13/08 **/
/** **/
/** Reduction in massive Random Spam in Logger files by using Map **/
/*************************************************************************************************/
/** ---- Start Original Code ---- **
iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "AI Patrol"));
/** ---- End Original Code ---- **/
iValue = (1 + GC.getGameINLINE().getMapRandNum(10000, "AI Patrol"));
/*************************************************************************************************/
/** Tweak END **/
/*************************************************************************************************/
if (isBarbarian())
{
if (!(pAdjacentPlot->isOwned()))
{
iValue += 20000;
}
if (!(pAdjacentPlot->isAdjacentOwned()))
{
iValue += 10000;
}
}
else
{
if (pAdjacentPlot->isRevealedGoody(getTeam()))
{
iValue += 100000;
}
if (pAdjacentPlot->getOwnerINLINE() == getOwnerINLINE())
{
iValue += 10000;
}
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_defend()
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
if (AI_defendPlot(plot()))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
iSearchRange = AI_searchRange(1);
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (AI_defendPlot(pLoopPlot))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (!atPlot(pLoopPlot) && generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= 1)
{
iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "AI Defend"));
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 12/06/08 jdog5000 */
/* */
/* Unit AI */
/************************************************************************************************/
if( !(pBestPlot->isCity()) && (getGroup()->getNumUnits() > 1) )
{
getGroup()->AI_makeForceSeparate();
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_safety()
{
PROFILE_FUNC();
CLLNode<IDInfo>* pUnitNode;
CvUnit* pLoopUnit;
CvUnit* pHeadUnit;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iCount;
int iPass;
int iDX, iDY;
iSearchRange = AI_searchRange(1);
iBestValue = 0;
pBestPlot = NULL;
for (iPass = 0; iPass < 2; iPass++)
{
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (generatePath(pLoopPlot, ((iPass > 0) ? MOVE_IGNORE_DANGER : 0), true, &iPathTurns))
{
if (iPathTurns <= 1)
{
iCount = 0;
pUnitNode = pLoopPlot->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopPlot->nextUnitNode(pUnitNode);
if (pLoopUnit->getOwnerINLINE() == getOwnerINLINE())
{
if (pLoopUnit->canDefend())
{
pHeadUnit = pLoopUnit->getGroup()->getHeadUnit();
FAssert(pHeadUnit != NULL);
FAssert(getGroup()->getHeadUnit() == this);
if (pHeadUnit != this)
{
if (pHeadUnit->isWaiting() || !(pHeadUnit->canMove()))
{
FAssert(pLoopUnit != this);
FAssert(pHeadUnit != getGroup()->getHeadUnit());
iCount++;
}
}
}
}
}
iValue = (iCount * 100);
iValue += pLoopPlot->defenseModifier(getTeam(), false);
if (atPlot(pLoopPlot))
{
iValue += 50;
}
else
{
iValue += GC.getGameINLINE().getSorenRandNum(50, "AI Safety");
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), ((iPass > 0) ? MOVE_IGNORE_DANGER : 0));
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_hide()
{
PROFILE_FUNC();
CLLNode<IDInfo>* pUnitNode;
CvUnit* pLoopUnit;
CvUnit* pHeadUnit;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
bool bValid;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iCount;
int iDX, iDY;
int iI;
if (getInvisibleType() == NO_INVISIBLE)
{
return false;
}
iSearchRange = AI_searchRange(1);
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
bValid = true;
for (iI = 0; iI < MAX_TEAMS; iI++)
{
if (GET_TEAM((TeamTypes)iI).isAlive())
{
if (pLoopPlot->isInvisibleVisible(((TeamTypes)iI), getInvisibleType()))
{
bValid = false;
break;
}
}
}
if (bValid)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= 1)
{
iCount = 1;
pUnitNode = pLoopPlot->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopPlot->nextUnitNode(pUnitNode);
if (pLoopUnit->getOwnerINLINE() == getOwnerINLINE())
{
if (pLoopUnit->canDefend())
{
pHeadUnit = pLoopUnit->getGroup()->getHeadUnit();
FAssert(pHeadUnit != NULL);
FAssert(getGroup()->getHeadUnit() == this);
if (pHeadUnit != this)
{
if (pHeadUnit->isWaiting() || !(pHeadUnit->canMove()))
{
FAssert(pLoopUnit != this);
FAssert(pHeadUnit != getGroup()->getHeadUnit());
iCount++;
}
}
}
}
}
iValue = (iCount * 100);
iValue += pLoopPlot->defenseModifier(getTeam(), false);
if (atPlot(pLoopPlot))
{
iValue += 50;
}
else
{
iValue += GC.getGameINLINE().getSorenRandNum(50, "AI Hide");
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_goody(int iRange)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
// CvPlot* pAdjacentPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
// int iI;
if (isBarbarian())
{
return false;
}
iSearchRange = AI_searchRange(iRange);
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isRevealedGoody(getTeam()))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (!atPlot(pLoopPlot) && generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= iRange)
{
iValue = (1 + GC.getGameINLINE().getSorenRandNum(10000, "AI Goody"));
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_explore()
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pAdjacentPlot;
CvPlot* pBestPlot;
CvPlot* pBestExplorePlot;
int iPathTurns;
int iValue;
int iBestValue;
int iI, iJ;
iBestValue = 0;
pBestPlot = NULL;
pBestExplorePlot = NULL;
bool bNoContact = (GC.getGameINLINE().countCivTeamsAlive() > GET_TEAM(getTeam()).getHasMetCivCount(true));
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
PROFILE("AI_explore 1");
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
iValue = 0;
if (pLoopPlot->isRevealedGoody(getTeam()))
{
iValue += 100000;
}
/*************************************************************************************************/
/** Xienwolf Tweak 12/13/08 **/
/** **/
/** Reduction in massive Random Spam in Logger files by using Map **/
/*************************************************************************************************/
/** ---- Start Original Code ---- **
if (iValue > 0 || GC.getGameINLINE().getSorenRandNum(4, "AI make explore faster ;)") == 0)
/** ---- End Original Code ---- **/
if (iValue > 0 || GC.getGameINLINE().getMapRandNum(4, "AI make explore faster ;)") == 0)
/*************************************************************************************************/
/** Tweak END **/
/*************************************************************************************************/
{
if (!(pLoopPlot->isRevealed(getTeam(), false)))
{
iValue += 10000;
}
// XXX is this too slow?
for (iJ = 0; iJ < NUM_DIRECTION_TYPES; iJ++)
{
PROFILE("AI_explore 2");
pAdjacentPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((DirectionTypes)iJ));
if (pAdjacentPlot != NULL)
{
if (!(pAdjacentPlot->isRevealed(getTeam(), false)))
{
iValue += 1000;
}
else if (bNoContact)
{
if (pAdjacentPlot->getRevealedTeam(getTeam(), false) != pAdjacentPlot->getTeam())
{
iValue += 100;
}
}
}
}
if (iValue > 0)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_EXPLORE, getGroup(), 3) == 0)
{
if (!atPlot(pLoopPlot) && generatePath(pLoopPlot, MOVE_NO_ENEMY_TERRITORY, true, &iPathTurns))
{
/*************************************************************************************************/
/** Xienwolf Tweak 12/13/08 **/
/** **/
/** Reduction in massive Random Spam in Logger files by using Map **/
/*************************************************************************************************/
/** ---- Start Original Code ---- **
iValue += GC.getGameINLINE().getSorenRandNum(250 * abs(xDistance(getX_INLINE(), pLoopPlot->getX_INLINE())) + abs(yDistance(getY_INLINE(), pLoopPlot->getY_INLINE())), "AI explore");
/** ---- End Original Code ---- **/
iValue += GC.getGameINLINE().getMapRandNum(250 * abs(xDistance(getX_INLINE(), pLoopPlot->getX_INLINE())) + abs(yDistance(getY_INLINE(), pLoopPlot->getY_INLINE())), "AI explore");
/*************************************************************************************************/
/** Tweak END **/
/*************************************************************************************************/
if (pLoopPlot->isAdjacentToLand())
{
iValue += 10000;
}
if (pLoopPlot->isOwned())
{
iValue += 5000;
}
iValue /= 3 + std::max(1, iPathTurns);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot->isRevealedGoody(getTeam()) ? getPathEndTurnPlot() : pLoopPlot;
pBestExplorePlot = pLoopPlot;
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestExplorePlot != NULL))
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_EXPLORE, pBestExplorePlot);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_exploreRange(int iRange)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pAdjacentPlot;
CvPlot* pBestPlot;
CvPlot* pBestExplorePlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
int iI;
iSearchRange = AI_searchRange(iRange);
iBestValue = 0;
pBestPlot = NULL;
pBestExplorePlot = NULL;
int iImpassableCount = GET_PLAYER(getOwnerINLINE()).AI_unitImpassableCount(getUnitType());
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
PROFILE("AI_exploreRange 1");
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
iValue = 0;
if (pLoopPlot->isRevealedGoody(getTeam()))
{
iValue += 100000;
}
if (!(pLoopPlot->isRevealed(getTeam(), false)))
{
iValue += 10000;
}
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
PROFILE("AI_exploreRange 2");
pAdjacentPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL)
{
if (!(pAdjacentPlot->isRevealed(getTeam(), false)))
{
iValue += 1000;
}
}
}
if (iValue > 0)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
PROFILE("AI_exploreRange 3");
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_EXPLORE, getGroup(), 3) == 0)
{
PROFILE("AI_exploreRange 4");
if (!atPlot(pLoopPlot) && generatePath(pLoopPlot, MOVE_NO_ENEMY_TERRITORY, true, &iPathTurns))
{
if (iPathTurns <= iRange)
{
/*************************************************************************************************/
/** Xienwolf Tweak 12/13/08 **/
/** **/
/** Reduction in massive Random Spam in Logger files by using Map **/
/*************************************************************************************************/
/** ---- Start Original Code ---- **
iValue += GC.getGameINLINE().getSorenRandNum(10000, "AI Explore");
/** ---- End Original Code ---- **/
iValue += GC.getGameINLINE().getMapRandNum(10000, "AI Explore");
/*************************************************************************************************/
/** Tweak END **/
/*************************************************************************************************/
if (pLoopPlot->isAdjacentToLand())
{
iValue += 10000;
}
if (pLoopPlot->isOwned())
{
iValue += 5000;
}
if (!isHuman())
{
int iDirectionModifier = 100;
if (AI_getUnitAIType() == UNITAI_EXPLORE_SEA && iImpassableCount == 0)
{
iDirectionModifier += (50 * (abs(iDX) + abs(iDY))) / iSearchRange;
if (GC.getGame().circumnavigationAvailable())
{
if (GC.getMap().isWrapX())
{
if ((iDX * ((AI_getBirthmark() % 2 == 0) ? 1 : -1)) > 0)
{
iDirectionModifier *= 150 + ((iDX * 100) / iSearchRange);
}
else
{
iDirectionModifier /= 2;
}
}
if (GC.getMap().isWrapY())
{
if ((iDY * (((AI_getBirthmark() >> 1) % 2 == 0) ? 1 : -1)) > 0)
{
iDirectionModifier *= 150 + ((iDY * 100) / iSearchRange);
}
else
{
iDirectionModifier /= 2;
}
}
}
iValue *= iDirectionModifier;
iValue /= 100;
}
}
if (iValue > iBestValue)
{
iBestValue = iValue;
if (getDomainType() == DOMAIN_LAND)
{
pBestPlot = getPathEndTurnPlot();
}
else
{
pBestPlot = pLoopPlot;
}
pBestExplorePlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestExplorePlot != NULL))
{
PROFILE("AI_exploreRange 5");
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_EXPLORE, pBestExplorePlot);
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/29/10 jdog5000 */
/* */
/* War tactics AI, Efficiency */
/************************************************************************************************/
// Returns target city
CvCity* CvUnitAI::AI_pickTargetCity(int iFlags, int iMaxPathTurns, bool bHuntBarbs )
{
PROFILE_FUNC();
CvCity* pTargetCity;
CvCity* pLoopCity;
CvCity* pBestCity;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
int iI;
iBestValue = 0;
pBestCity = NULL;
pTargetCity = area()->getTargetCity(getOwnerINLINE());
// Don't always go after area target ... don't know how far away it is
/*
if (pTargetCity != NULL)
{
if (AI_potentialEnemy(pTargetCity->getTeam(), pTargetCity->plot()))
{
if (!atPlot(pTargetCity->plot()) && generatePath(pTargetCity->plot(), iFlags, true))
{
pBestCity = pTargetCity;
}
}
}
*/
if (pBestCity == NULL)
{
for (iI = 0; iI < (bHuntBarbs ? MAX_PLAYERS : MAX_CIV_PLAYERS); iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive() && ::isPotentialEnemy(getTeam(), GET_PLAYER((PlayerTypes)iI).getTeam()))
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
// BBAI efficiency: check area for land units before generating path
if (AI_plotValid(pLoopCity->plot()) && (pLoopCity->area() == area()))
{
if(AI_potentialEnemy(GET_PLAYER((PlayerTypes)iI).getTeam(), pLoopCity->plot()))
{
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), iFlags, true, &iPathTurns))
{
if( iPathTurns <= iMaxPathTurns )
{
// If city is visible and our force already in position is dominantly powerful or we have a huge force
// already on the way, pick a different target
if( iPathTurns > 2 && pLoopCity->isVisible(getTeam(), false) )
{
/*
int iOurOffense = GET_TEAM(getTeam()).AI_getOurPlotStrength(pLoopCity->plot(),2,false,false,true);
int iEnemyDefense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(pLoopCity->plot(),1,true,false);
if( 100*iOurOffense >= GC.getBBAI_SKIP_BOMBARD_BASE_STACK_RATIO()*iEnemyDefense )
{
continue;
}
*/
if( GET_PLAYER(getOwnerINLINE()).AI_cityTargetUnitsByPath(pLoopCity, getGroup(), iPathTurns) > std::max( 6, 3 * pLoopCity->plot()->getNumVisibleEnemyDefenders(this) ) )
{
continue;
}
}
iValue = 0;
if (AI_getUnitAIType() == UNITAI_ATTACK_CITY) //lemming?
{
iValue = GET_PLAYER(getOwnerINLINE()).AI_targetCityValue(pLoopCity, false, false);
}
else
{
iValue = GET_PLAYER(getOwnerINLINE()).AI_targetCityValue(pLoopCity, true, true);
}
if( pLoopCity == pTargetCity )
{
iValue *= 2;
}
if ((area()->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE))
{
iValue *= 50 + pLoopCity->calculateCulturePercent(getOwnerINLINE());
iValue /= 50;
}
iValue *= 1000;
// If city is minor civ, less interesting
if( GET_PLAYER(pLoopCity->getOwnerINLINE()).isMinorCiv() || GET_PLAYER(pLoopCity->getOwnerINLINE()).isBarbarian() )
{
iValue /= 2;
}
// If stack has poor bombard, direct towards lower defense cities
iPathTurns += std::min(12, getGroup()->getBombardTurns(pLoopCity)/4);
iValue /= (4 + iPathTurns*iPathTurns);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestCity = pLoopCity;
}
}
}
}
}
}
}
}
}
return pBestCity;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_goToTargetCity(int iFlags, int iMaxPathTurns, CvCity* pTargetCity )
{
PROFILE_FUNC();
CvPlot* pAdjacentPlot;
CvPlot* pBestPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iI;
if( pTargetCity == NULL )
{
pTargetCity = AI_pickTargetCity(iFlags, iMaxPathTurns);
}
if (pTargetCity != NULL)
{
PROFILE("CvUnitAI::AI_targetCity plot attack");
iBestValue = 0;
pBestPlot = NULL;
if (0 == (iFlags & MOVE_THROUGH_ENEMY))
{
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(pTargetCity->getX_INLINE(), pTargetCity->getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL)
{
if (AI_plotValid(pAdjacentPlot))
{
if (!(pAdjacentPlot->isVisibleEnemyUnit(this)))
{
if (generatePath(pAdjacentPlot, iFlags, true, &iPathTurns))
{
if( iPathTurns <= iMaxPathTurns )
{
iValue = std::max(0, (pAdjacentPlot->defenseModifier(getTeam(), false) + 100));
if (!(pAdjacentPlot->isRiverCrossing(directionXY(pAdjacentPlot, pTargetCity->plot()))))
{
iValue += (12 * -(GC.getRIVER_ATTACK_MODIFIER()));
}
if (!isEnemy(pAdjacentPlot->getTeam(), pAdjacentPlot))
{
iValue += 100;
}
if( atPlot(pAdjacentPlot) )
{
iValue += 50;
}
iValue = std::max(1, iValue);
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
}
}
}
}
}
}
}
}
else
{
pBestPlot = pTargetCity->plot();
}
if (pBestPlot != NULL)
{
FAssert(!(pTargetCity->at(pBestPlot)) || 0 != (iFlags & MOVE_THROUGH_ENEMY)); // no suicide missions...
if (!atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), iFlags);
return true;
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_goToTargetBarbCity(int iMaxPathTurns)
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvCity* pBestCity;
CvPlot* pAdjacentPlot;
CvPlot* pBestPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
int iI;
if (isBarbarian())
{
return false;
}
iBestValue = 0;
pBestCity = NULL;
for (pLoopCity = GET_PLAYER(BARBARIAN_PLAYER).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(BARBARIAN_PLAYER).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
// BBAI efficiency: check area for land units before generating path
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
if (pLoopCity->isRevealed(getTeam(), false))
{
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
if (iPathTurns < iMaxPathTurns)
{
iValue = GET_PLAYER(getOwnerINLINE()).AI_targetCityValue(pLoopCity, false);
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestCity = pLoopCity;
}
}
}
}
}
}
if (pBestCity != NULL)
{
iBestValue = 0;
pBestPlot = NULL;
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(pBestCity->getX_INLINE(), pBestCity->getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL)
{
if (AI_plotValid(pAdjacentPlot))
{
if (!(pAdjacentPlot->isVisibleEnemyUnit(this)))
{
if (generatePath(pAdjacentPlot, 0, true, &iPathTurns))
{
if( iPathTurns <= iMaxPathTurns )
{
iValue = std::max(0, (pAdjacentPlot->defenseModifier(getTeam(), false) + 100));
if (!(pAdjacentPlot->isRiverCrossing(directionXY(pAdjacentPlot, pBestCity->plot()))))
{
iValue += (10 * -(GC.getRIVER_ATTACK_MODIFIER()));
}
iValue = std::max(1, iValue);
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!(pBestCity->at(pBestPlot))); // no suicide missions...
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
}
}
return false;
}
bool CvUnitAI::AI_pillageAroundCity(CvCity* pTargetCity, int iBonusValueThreshold, int iMaxPathTurns )
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestPillagePlot;
int iPathTurns;
int iValue;
int iBestValue;
iBestValue = 0;
pBestPlot = NULL;
pBestPillagePlot = NULL;
for( int iI = 0; iI < NUM_CITY_PLOTS; iI++ )
{
pLoopPlot = pTargetCity->getCityIndexPlot(iI);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot) && !(pLoopPlot->isBarbarian()))
{
if (potentialWarAction(pLoopPlot) && (pLoopPlot->getTeam() == pTargetCity->getTeam()))
{
if (canPillage(pLoopPlot))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_PILLAGE, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
if ( iPathTurns <= iMaxPathTurns )
{
iValue = AI_pillageValue(pLoopPlot, iBonusValueThreshold);
iValue *= 1000 + 30*(pLoopPlot->defenseModifier(getTeam(),false));
iValue /= (iPathTurns + 1);
// if not at war with this plot owner, then devalue plot if we already inside this owner's borders
// (because declaring war will pop us some unknown distance away)
if (!isEnemy(pLoopPlot->getTeam()) && plot()->getTeam() == pLoopPlot->getTeam())
{
iValue /= 10;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestPillagePlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestPillagePlot != NULL))
{
if (atPlot(pBestPillagePlot) && !isEnemy(pBestPillagePlot->getTeam()))
{
//getGroup()->groupDeclareWar(pBestPillagePlot, true);
// rather than declare war, just find something else to do, since we may already be deep in enemy territory
return false;
}
if (atPlot(pBestPillagePlot))
{
if (isEnemy(pBestPillagePlot->getTeam()))
{
getGroup()->pushMission(MISSION_PILLAGE, -1, -1, 0, false, false, MISSIONAI_PILLAGE, pBestPillagePlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_PILLAGE, pBestPillagePlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_bombardCity()
{
PROFILE_FUNC();
CvCity* pBombardCity;
if (canBombard(plot()))
{
pBombardCity = bombardTarget(plot());
FAssertMsg(pBombardCity != NULL, "BombardCity is not assigned a valid value");
// do not bombard cities with no defenders
int iDefenderStrength = pBombardCity->plot()->AI_sumStrength(NO_PLAYER, getOwnerINLINE(), DOMAIN_LAND, /*bDefensiveBonuses*/ true, /*bTestAtWar*/ true, false);
if (iDefenderStrength == 0)
{
return false;
}
// do not bombard cities if we have overwelming odds
int iAttackOdds = getGroup()->AI_attackOdds(pBombardCity->plot(), /*bPotentialEnemy*/ true);
if ( (iAttackOdds > 95) )
{
return false;
}
// If we have reasonable odds, check for attacking without waiting for bombards
if( (iAttackOdds >= GC.getDefineINT("BBAI_SKIP_BOMBARD_BEST_ATTACK_ODDS")) )
{
int iBase = std::max(150, GC.getDefineINT("BBAI_SKIP_BOMBARD_BASE_STACK_RATIO"));
int iComparison = getGroup()->AI_compareStacks(pBombardCity->plot(), /*bPotentialEnemy*/ true, /*bCheckCanAttack*/ true, /*bCheckCanMove*/ true);
// Big troop advantage plus pretty good starting odds, don't wait to allow reinforcements
if( iComparison > (iBase - 4*iAttackOdds) )
{
if( gUnitLogLevel > 2 ) logBBAI(" Stack skipping bombard of %S with compare %d and starting odds %d", pBombardCity->getName().GetCString(), iComparison, iAttackOdds);
return false;
}
int iMin = std::max(100, GC.getDefineINT("BBAI_SKIP_BOMBARD_MIN_STACK_RATIO"));
bool bHasWaited = false;
CLLNode<IDInfo>* pUnitNode = getGroup()->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
if( pLoopUnit->getFortifyTurns() > 0 )
{
bHasWaited = true;
break;
}
pUnitNode = getGroup()->nextUnitNode(pUnitNode);
}
// Bombard at least one turn to allow bombers/ships to get some shots in too
if( bHasWaited && (pBombardCity->getDefenseDamage() > 0) )
{
int iBombardTurns = getGroup()->getBombardTurns(pBombardCity);
if( iComparison > std::max(iMin, iBase - 3*iAttackOdds - 3*iBombardTurns) )
{
if( gUnitLogLevel > 2 ) logBBAI(" Stack skipping bombard of %S with compare %d, starting odds %d, and bombard turns %d", pBombardCity->getName().GetCString(), iComparison, iAttackOdds, iBombardTurns);
return false;
}
}
}
//getGroup()->pushMission(MISSION_PILLAGE);
getGroup()->pushMission(MISSION_BOMBARD);
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_cityAttack(int iRange, int iOddsThreshold, bool bFollow)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
FAssert(canMove());
if (bFollow)
{
iSearchRange = 1;
}
else
{
iSearchRange = AI_searchRange(iRange);
}
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isCity() || (pLoopPlot->isCity(true, getTeam()) && pLoopPlot->isVisibleEnemyUnit(this)))
{
if (AI_potentialEnemy(pLoopPlot->getTeam(), pLoopPlot))
{
if (!atPlot(pLoopPlot) && ((bFollow) ? canMoveInto(pLoopPlot, true) : (generatePath(pLoopPlot, 0, true, &iPathTurns) && (iPathTurns <= iRange))))
{
iValue = getGroup()->AI_attackOdds(pLoopPlot, true);
if (iValue >= AI_finalOddsThreshold(pLoopPlot, iOddsThreshold))
{
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = ((bFollow) ? pLoopPlot : getPathEndTurnPlot());
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), ((bFollow) ? MOVE_DIRECT_ATTACK : 0));
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 04/01/10 jdog5000 */
/* */
/* War tactics AI, Efficiency */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_anyAttack(int iRange, int iOddsThreshold, int iMinStack, bool bAllowCities, bool bFollow)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
FAssert(canMove());
if (AI_rangeAttack(iRange))
{
return true;
}
if (bFollow)
{
iSearchRange = 1;
}
else
{
iSearchRange = AI_searchRange(iRange);
}
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if( (bAllowCities) || !(pLoopPlot->isCity(false)) )
{
if (pLoopPlot->isVisibleEnemyUnit(this) || (pLoopPlot->isCity() && AI_potentialEnemy(pLoopPlot->getTeam())))
{
if (pLoopPlot->getNumVisibleEnemyDefenders(this) >= iMinStack)
{
if (!atPlot(pLoopPlot) && ((bFollow) ? canMoveInto(pLoopPlot, true) : (generatePath(pLoopPlot, 0, true, &iPathTurns) && (iPathTurns <= iRange))))
{
iValue = getGroup()->AI_attackOdds(pLoopPlot, true);
if (iValue >= AI_finalOddsThreshold(pLoopPlot, iOddsThreshold))
{
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = ((bFollow) ? pLoopPlot : getPathEndTurnPlot());
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), ((bFollow) ? MOVE_DIRECT_ATTACK : 0));
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_rangeAttack(int iRange)
{
PROFILE_FUNC();
FAssert(canMove());
if (!canRangeStrike())
{
return false;
}
int iSearchRange = AI_searchRange(iRange);
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
for (int iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (int iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (pLoopPlot->isVisibleEnemyUnit(this) || (pLoopPlot->isCity() && AI_potentialEnemy(pLoopPlot->getTeam())))
{
if (!atPlot(pLoopPlot) && canRangeStrikeAt(plot(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
int iValue = getGroup()->AI_attackOdds(pLoopPlot, true);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_RANGE_ATTACK, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0);
return true;
}
return false;
}
bool CvUnitAI::AI_leaveAttack(int iRange, int iOddsThreshold, int iStrengthThreshold)
{
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvCity* pCity;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
FAssert(canMove());
iSearchRange = iRange;
iBestValue = 0;
pBestPlot = NULL;
pCity = plot()->getPlotCity();
if ((pCity != NULL) && (pCity->getOwnerINLINE() == getOwnerINLINE()))
{
int iOurStrength = GET_PLAYER(getOwnerINLINE()).AI_getOurPlotStrength(plot(), 0, false, false);
int iEnemyStrength = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(), 2, false, false);
if (iEnemyStrength > 0)
{
if (((iOurStrength * 100) / iEnemyStrength) < iStrengthThreshold)
{
return false;
}
if (plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE()) <= getGroup()->getNumUnits())
{
return false;
}
}
}
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isVisibleEnemyUnit(this) || (pLoopPlot->isCity() && AI_potentialEnemy(pLoopPlot->getTeam(), pLoopPlot)))
{
if (pLoopPlot->getNumVisibleEnemyDefenders(this) > 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 06/27/10 jdog5000 */
/* */
/* Bugfix */
/************************************************************************************************/
if (!atPlot(pLoopPlot) && (generatePath(pLoopPlot, 0, true, &iPathTurns) && (iPathTurns <= iRange)))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
iValue = getGroup()->AI_attackOdds(pLoopPlot, true);
if (iValue >= AI_finalOddsThreshold(pLoopPlot, iOddsThreshold))
{
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_blockade()
{
PROFILE_FUNC();
CvCity* pCity;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestBlockadePlot;
int iPathTurns;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
pBestPlot = NULL;
pBestBlockadePlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (potentialWarAction(pLoopPlot))
{
pCity = pLoopPlot->getWorkingCity();
if (pCity != NULL)
{
if (pCity->isCoastal(GC.getMIN_WATER_SIZE_FOR_OCEAN()))
{
if (!(pCity->isBarbarian()))
{
FAssert(isEnemy(pCity->getTeam()) || GET_TEAM(getTeam()).AI_getWarPlan(pCity->getTeam()) != NO_WARPLAN);
if (!(pLoopPlot->isVisibleEnemyUnit(this)) && canPlunder(pLoopPlot))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BLOCKADE, getGroup(), 2) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue = 1;
iValue += std::min(pCity->getPopulation(), pCity->countNumWaterPlots());
iValue += GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pCity->plot());
iValue += (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCity->plot(), MISSIONAI_ASSAULT, getGroup(), 2) * 3);
if (canBombard(pLoopPlot))
{
iValue *= 2;
}
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iPathTurns == 1)
{
//Prefer to have movement remaining to Bombard + Plunder
iValue *= 1 + std::min(2, getPathLastNode()->m_iData1);
}
// if not at war with this plot owner, then devalue plot if we already inside this owner's borders
// (because declaring war will pop us some unknown distance away)
if (!isEnemy(pLoopPlot->getTeam()) && plot()->getTeam() == pLoopPlot->getTeam())
{
iValue /= 10;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestBlockadePlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestBlockadePlot != NULL))
{
FAssert(canPlunder(pBestBlockadePlot));
if (atPlot(pBestBlockadePlot) && !isEnemy(pBestBlockadePlot->getTeam(), pBestBlockadePlot))
{
getGroup()->groupDeclareWar(pBestBlockadePlot, true);
}
if (atPlot(pBestBlockadePlot))
{
if (canBombard(plot()))
{
getGroup()->pushMission(MISSION_BOMBARD, -1, -1, 0, false, false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
}
getGroup()->pushMission(MISSION_PLUNDER, -1, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_pirateBlockade()
{
PROFILE_FUNC();
int iPathTurns;
int iValue;
int iI;
std::vector<int> aiDeathZone(GC.getMapINLINE().numPlotsINLINE(), 0);
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot) || (pLoopPlot->isCity() && pLoopPlot->isAdjacentToArea(area())))
{
if (pLoopPlot->isOwned() && (pLoopPlot->getTeam() != getTeam()))
{
int iBestHostileMoves = 0;
CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopPlot->nextUnitNode(pUnitNode);
if (isEnemy(pLoopUnit->getTeam(), pLoopUnit->plot()))
{
if (pLoopUnit->getDomainType() == DOMAIN_SEA && !pLoopUnit->isInvisible(getTeam(), false))
{
if (pLoopUnit->canAttack())
{
if (pLoopUnit->currEffectiveStr(NULL, NULL, NULL) > currEffectiveStr(pLoopPlot, pLoopUnit, NULL))
{
//Fuyu: No (rail)roads on water, always movement cost 1. Rounding up of course
iBestHostileMoves = std::max(iBestHostileMoves, (pLoopUnit->getMoves() + GC.getMOVE_DENOMINATOR() - 1) / GC.getMOVE_DENOMINATOR());
}
}
}
}
}
if (iBestHostileMoves > 0)
{
for (int iX = -iBestHostileMoves; iX <= iBestHostileMoves; iX++)
{
for (int iY = -iBestHostileMoves; iY <= iBestHostileMoves; iY++)
{
CvPlot * pRangePlot = plotXY(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), iX, iY);
if (pRangePlot != NULL)
{
aiDeathZone[GC.getMap().plotNumINLINE(pRangePlot->getX_INLINE(), pRangePlot->getY_INLINE())]++;
}
}
}
}
}
}
}
bool bIsInDanger = aiDeathZone[GC.getMap().plotNumINLINE(getX_INLINE(), getY_INLINE())] > 0;
if (!bIsInDanger)
{
if (getDamage() > 0)
{
if (!plot()->isOwned() && !plot()->isAdjacentOwned())
{
if (AI_retreatToCity(false, false, 1 + getDamage() / 20))
{
return true;
}
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
}
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestBlockadePlot = NULL;
bool bBestIsForceMove = false;
bool bBestIsMove = false;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)) && canPlunder(pLoopPlot))
{
if (GC.getGame().getSorenRandNum(4, "AI Pirate Blockade") == 0)
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BLOCKADE, getGroup(), 3) == 0)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/17/09 jdog5000 */
/* */
/* Pirate AI */
/************************************************************************************************/
/* original bts code
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
*/
if (generatePath(pLoopPlot, MOVE_AVOID_ENEMY_WEIGHT_3, true, &iPathTurns))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
int iBlockadedCount = 0;
int iPopulationValue = 0;
int iRange = GC.getDefineINT("SHIP_BLOCKADE_RANGE") - 1;
for (int iX = -iRange; iX <= iRange; iX++)
{
for (int iY = -iRange; iY <= iRange; iY++)
{
CvPlot* pRangePlot = plotXY(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), iX, iY);
if (pRangePlot != NULL)
{
bool bPlotBlockaded = false;
if (pRangePlot->isWater() && pRangePlot->isOwned() && isEnemy(pRangePlot->getTeam(), pLoopPlot))
{
bPlotBlockaded = true;
iBlockadedCount += pRangePlot->getBlockadedCount(pRangePlot->getTeam());
}
if (!bPlotBlockaded)
{
CvCity* pPlotCity = pRangePlot->getPlotCity();
if (pPlotCity != NULL)
{
if (isEnemy(pPlotCity->getTeam(), pLoopPlot))
{
int iCityValue = 3 + pPlotCity->getPopulation();
iCityValue *= (atWar(getTeam(), pPlotCity->getTeam()) ? 1 : 3);
if (GET_PLAYER(pPlotCity->getOwnerINLINE()).isNoForeignTrade())
{
iCityValue /= 2;
}
iPopulationValue += iCityValue;
}
}
}
}
}
}
iValue = iPopulationValue;
iValue *= 1000;
iValue /= 16 + iBlockadedCount;
bool bMove = ((getPathLastNode()->m_iData2 == 1) && getPathLastNode()->m_iData1 > 0);
if (atPlot(pLoopPlot))
{
iValue *= 3;
}
else if (bMove)
{
iValue *= 2;
}
int iDeath = aiDeathZone[GC.getMap().plotNumINLINE(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE())];
bool bForceMove = false;
if (iDeath)
{
iValue /= 10;
}
else if (bIsInDanger && (iPathTurns <= 2) && (0 == iPopulationValue))
{
if (getPathLastNode()->m_iData1 == 0)
{
if (!pLoopPlot->isAdjacentOwned())
{
int iRand = GC.getGame().getSorenRandNum(2500, "AI Pirate Retreat");
iValue += iRand;
if (iRand > 1000)
{
iValue += GC.getGame().getSorenRandNum(2500, "AI Pirate Retreat");
bForceMove = true;
}
}
}
}
if (!bForceMove)
{
iValue /= iPathTurns + 1;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = bForceMove ? pLoopPlot : getPathEndTurnPlot();
pBestBlockadePlot = pLoopPlot;
bBestIsForceMove = bForceMove;
bBestIsMove = bMove;
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestBlockadePlot != NULL))
{
FAssert(canPlunder(pBestBlockadePlot));
if (atPlot(pBestBlockadePlot))
{
getGroup()->pushMission(MISSION_PLUNDER, -1, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
if (bBestIsForceMove)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/01/09 jdog5000 */
/* */
/* Pirate AI */
/************************************************************************************************/
/* original bts code
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
*/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
else
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/01/09 jdog5000 */
/* */
/* Pirate AI */
/************************************************************************************************/
/* original bts code
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
*/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (bBestIsMove)
{
getGroup()->pushMission(MISSION_PLUNDER, -1, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BLOCKADE, pBestBlockadePlot);
}
return true;
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_seaBombardRange(int iMaxRange)
{
PROFILE_FUNC();
// cached values
CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE());
CvPlot* pPlot = plot();
CvSelectionGroup* pGroup = getGroup();
// can any unit in this group bombard?
bool bHasBombardUnit = false;
bool bBombardUnitCanBombardNow = false;
CLLNode<IDInfo>* pUnitNode = pGroup->headUnitNode();
while (pUnitNode != NULL && !bBombardUnitCanBombardNow)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pGroup->nextUnitNode(pUnitNode);
if (pLoopUnit->bombardRate() > 0)
{
bHasBombardUnit = true;
if (pLoopUnit->canMove() && !pLoopUnit->isMadeAttack())
{
bBombardUnitCanBombardNow = true;
}
}
}
if (!bHasBombardUnit)
{
return false;
}
// best match
CvPlot* pBestPlot = NULL;
CvPlot* pBestBombardPlot = NULL;
int iBestValue = 0;
// iterate over plots at each range
for (int iDX = -(iMaxRange); iDX <= iMaxRange; iDX++)
{
for (int iDY = -(iMaxRange); iDY <= iMaxRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL && AI_plotValid(pLoopPlot))
{
CvCity* pBombardCity = bombardTarget(pLoopPlot);
if (pBombardCity != NULL && isEnemy(pBombardCity->getTeam(), pLoopPlot) && pBombardCity->getDefenseDamage() < GC.getMAX_CITY_DEFENSE_DAMAGE())
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
/********************************************************************************/
/* BETTER_BTS_AI_MOD 6/24/08 jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
// Loop construction doesn't guarantee we can get there anytime soon, could be on other side of narrow continent
if( iPathTurns <= (1 + iMaxRange/std::max(1, baseMoves())) )
{
// Check only for supporting our own ground troops first, if none will look for another target
int iValue = (kPlayer.AI_plotTargetMissionAIs(pBombardCity->plot(), MISSIONAI_ASSAULT, NULL, 2) * 3);
iValue += (kPlayer.AI_adjacentPotentialAttackers(pBombardCity->plot(), true));
if (iValue > 0)
{
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iPathTurns == 1)
{
//Prefer to have movement remaining to Bombard + Plunder
iValue *= 1 + std::min(2, getPathLastNode()->m_iData1);
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestBombardPlot = pLoopPlot;
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
}
}
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 6/24/08 jdog5000 */
/* */
/* Naval AI */
/********************************************************************************/
// If no troops of ours to support, check for other bombard targets
if( (pBestPlot == NULL) && (pBestBombardPlot == NULL) )
{
if( (AI_getUnitAIType() != UNITAI_ASSAULT_SEA) )
{
for (int iDX = -(iMaxRange); iDX <= iMaxRange; iDX++)
{
for (int iDY = -(iMaxRange); iDY <= iMaxRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL && AI_plotValid(pLoopPlot))
{
CvCity* pBombardCity = bombardTarget(pLoopPlot);
// Consider city even if fully bombarded, causes ship to camp outside blockading instead of twitching between
// cities after bombarding to 0
if (pBombardCity != NULL && isEnemy(pBombardCity->getTeam(), pLoopPlot) && pBombardCity->getTotalDefense(false) > 0)
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
// Loop construction doesn't guarantee we can get there anytime soon, could be on other side of narrow continent
if( iPathTurns <= 1 + iMaxRange/std::max(1, baseMoves()) )
{
int iValue = std::min(20,pBombardCity->getDefenseModifier(false)/2);
// Inclination to support attacks by others
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if( GET_PLAYER(pBombardCity->getOwnerINLINE()).AI_getPlotDanger(pBombardCity->plot(), 2, false) > 0 )
if( GET_PLAYER(pBombardCity->getOwnerINLINE()).AI_getAnyPlotDanger(pBombardCity->plot(), 2, false) )
{
iValue += 60;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Inclination to bombard a different nearby city to extend the reach of blockade
if( GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pBombardCity->plot(), MISSIONAI_BLOCKADE, getGroup(), 3) == 0 )
{
iValue += 35 + pBombardCity->getPopulation();
}
// Small inclination to bombard area target, not too large so as not to tip our hand
if( pBombardCity == pBombardCity->area()->getTargetCity(getOwnerINLINE()) )
{
iValue += 10;
}
if (iValue > 0)
{
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iPathTurns == 1)
{
//Prefer to have movement remaining to Bombard + Plunder
iValue *= 1 + std::min(2, getPathLastNode()->m_iData1);
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestBombardPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if ((pBestPlot != NULL) && (pBestBombardPlot != NULL))
{
if (atPlot(pBestBombardPlot))
{
// if we are at the plot from which to bombard, and we have a unit that can bombard this turn, do it
if (bBombardUnitCanBombardNow && pGroup->canBombard(pBestBombardPlot))
{
getGroup()->pushMission(MISSION_BOMBARD, -1, -1, 0, false, false, MISSIONAI_BLOCKADE, pBestBombardPlot);
// if city bombarded enough, wake up any units that were waiting to bombard this city
CvCity* pBombardCity = bombardTarget(pBestBombardPlot); // is NULL if city cannot be bombarded any more
if (pBombardCity == NULL || pBombardCity->getDefenseDamage() < ((GC.getMAX_CITY_DEFENSE_DAMAGE()*5)/6))
{
kPlayer.AI_wakePlotTargetMissionAIs(pBestBombardPlot, MISSIONAI_BLOCKADE, getGroup());
}
}
// otherwise, skip until next turn, when we will surely bombard
else if (canPlunder(pBestBombardPlot))
{
getGroup()->pushMission(MISSION_PLUNDER, -1, -1, 0, false, false, MISSIONAI_BLOCKADE, pBestBombardPlot);
}
else
{
getGroup()->pushMission(MISSION_SKIP);
}
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BLOCKADE, pBestBombardPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_pillage(int iBonusValueThreshold)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestPillagePlot;
int iPathTurns;
int iValue;
int iBestValue;
int iI;
iBestValue = 0;
pBestPlot = NULL;
pBestPillagePlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot) && !(pLoopPlot->isBarbarian()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (potentialWarAction(pLoopPlot))
if( pLoopPlot->isOwned() && isEnemy(pLoopPlot->getTeam(),pLoopPlot) )
{
CvCity * pWorkingCity = pLoopPlot->getWorkingCity();
if (pWorkingCity != NULL)
{
if (!(pWorkingCity == area()->getTargetCity(getOwnerINLINE())) && canPillage(pLoopPlot))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_PILLAGE, getGroup(), 1) == 0)
{
iValue = AI_pillageValue(pLoopPlot, iBonusValueThreshold);
iValue *= 1000;
// if not at war with this plot owner, then devalue plot if we already inside this owner's borders
// (because declaring war will pop us some unknown distance away)
if (!isEnemy(pLoopPlot->getTeam()) && plot()->getTeam() == pLoopPlot->getTeam())
{
iValue /= 10;
}
if( iValue > iBestValue )
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestPillagePlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
if ((pBestPlot != NULL) && (pBestPillagePlot != NULL))
{
if (atPlot(pBestPillagePlot) && !isEnemy(pBestPillagePlot->getTeam()))
{
//getGroup()->groupDeclareWar(pBestPillagePlot, true);
// rather than declare war, just find something else to do, since we may already be deep in enemy territory
return false;
}
if (atPlot(pBestPillagePlot))
{
if (isEnemy(pBestPillagePlot->getTeam()))
{
getGroup()->pushMission(MISSION_PILLAGE, -1, -1, 0, false, false, MISSIONAI_PILLAGE, pBestPillagePlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_PILLAGE, pBestPillagePlot);
return true;
}
}
return false;
}
bool CvUnitAI::AI_canPillage(CvPlot& kPlot) const
{
if (isEnemy(kPlot.getTeam(), &kPlot))
{
return true;
}
if (!kPlot.isOwned())
{
bool bPillageUnowned = true;
for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS && bPillageUnowned; ++iPlayer)
{
int iIndx;
CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer);
if (!isEnemy(kLoopPlayer.getTeam(), &kPlot))
{
for (CvCity* pCity = kLoopPlayer.firstCity(&iIndx); NULL != pCity; pCity = kLoopPlayer.nextCity(&iIndx))
{
if (kPlot.getPlotGroup((PlayerTypes)iPlayer) == pCity->plot()->getPlotGroup((PlayerTypes)iPlayer))
{
bPillageUnowned = false;
break;
}
}
}
}
if (bPillageUnowned)
{
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_pillageRange(int iRange, int iBonusValueThreshold)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestPillagePlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
iSearchRange = AI_searchRange(iRange);
iBestValue = 0;
pBestPlot = NULL;
pBestPillagePlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot) && !(pLoopPlot->isBarbarian()))
{
if (potentialWarAction(pLoopPlot))
{
CvCity * pWorkingCity = pLoopPlot->getWorkingCity();
if (pWorkingCity != NULL)
{
if (!(pWorkingCity == area()->getTargetCity(getOwnerINLINE())) && canPillage(pLoopPlot))
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_PILLAGE, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
if (iPathTurns <= iRange)
{
iValue = AI_pillageValue(pLoopPlot, iBonusValueThreshold);
iValue *= 1000;
iValue /= (iPathTurns + 1);
// if not at war with this plot owner, then devalue plot if we already inside this owner's borders
// (because declaring war will pop us some unknown distance away)
if (!isEnemy(pLoopPlot->getTeam()) && plot()->getTeam() == pLoopPlot->getTeam())
{
iValue /= 10;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestPillagePlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestPillagePlot != NULL))
{
if (atPlot(pBestPillagePlot) && !isEnemy(pBestPillagePlot->getTeam()))
{
//getGroup()->groupDeclareWar(pBestPillagePlot, true);
// rather than declare war, just find something else to do, since we may already be deep in enemy territory
return false;
}
if (atPlot(pBestPillagePlot))
{
if (isEnemy(pBestPillagePlot->getTeam()))
{
getGroup()->pushMission(MISSION_PILLAGE, -1, -1, 0, false, false, MISSIONAI_PILLAGE, pBestPillagePlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_PILLAGE, pBestPillagePlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_found()
{
PROFILE_FUNC();
//
// CvPlot* pLoopPlot;
// CvPlot* pBestPlot;
// CvPlot* pBestFoundPlot;
// int iPathTurns;
// int iValue;
// int iBestValue;
// int iI;
//
// iBestValue = 0;
// pBestPlot = NULL;
// pBestFoundPlot = NULL;
//
// for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
// {
// pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
//
// if (AI_plotValid(pLoopPlot) && (pLoopPlot != plot() || GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pLoopPlot, 1) <= pLoopPlot->plotCount(PUF_canDefend, -1, -1, getOwnerINLINE())))
// {
// if (canFound(pLoopPlot))
// {
// iValue = pLoopPlot->getFoundValue(getOwnerINLINE());
//
// if (iValue > 0)
// {
// if (!(pLoopPlot->isVisibleEnemyUnit(this)))
// {
// if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_FOUND, getGroup(), 3) == 0)
// {
// if (generatePath(pLoopPlot, MOVE_SAFE_TERRITORY, true, &iPathTurns))
// {
// iValue *= 1000;
//
// iValue /= (iPathTurns + 1);
//
// if (iValue > iBestValue)
// {
// iBestValue = iValue;
// pBestPlot = getPathEndTurnPlot();
// pBestFoundPlot = pLoopPlot;
// }
// }
// }
// }
// }
// }
// }
// }
int iPathTurns;
int iValue;
int iBestFoundValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestFoundPlot = NULL;
for (int iI = 0; iI < GET_PLAYER(getOwnerINLINE()).AI_getNumCitySites(); iI++)
{
CvPlot* pCitySitePlot = GET_PLAYER(getOwnerINLINE()).AI_getCitySite(iI);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/23/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
/* orginal BTS code
if (pCitySitePlot->getArea() == getArea())
*/
if (pCitySitePlot->getArea() == getArea() || canMoveAllTerrain())
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (canFound(pCitySitePlot))
{
if (!(pCitySitePlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCitySitePlot, MISSIONAI_FOUND, getGroup()) == 0)
{
if (getGroup()->canDefend() || GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCitySitePlot, MISSIONAI_GUARD_CITY) > 0)
{
if (generatePath(pCitySitePlot, MOVE_SAFE_TERRITORY, true, &iPathTurns))
{
iValue = pCitySitePlot->getFoundValue(getOwnerINLINE());
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestFoundValue)
{
iBestFoundValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestFoundPlot = pCitySitePlot;
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestFoundPlot != NULL))
{
if (atPlot(pBestFoundPlot))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
if( gUnitLogLevel >= 2 )
{
logBBAI(" Settler founding at best found plot %d, %d", pBestFoundPlot->getX_INLINE(), pBestFoundPlot->getY_INLINE());
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
getGroup()->pushMission(MISSION_FOUND, -1, -1, 0, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
else
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/02/09 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
if( gUnitLogLevel >= 2 )
{
logBBAI(" Settler heading for best found plot %d, %d", pBestFoundPlot->getX_INLINE(), pBestFoundPlot->getY_INLINE());
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_foundRange(int iRange, bool bFollow)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestFoundPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
iSearchRange = AI_searchRange(iRange);
iBestValue = 0;
pBestPlot = NULL;
pBestFoundPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot) && (pLoopPlot != plot() || GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pLoopPlot, 1) <= pLoopPlot->plotCount(PUF_canDefend, -1, -1, getOwnerINLINE())))
{
if (canFound(pLoopPlot))
{
iValue = pLoopPlot->getFoundValue(getOwnerINLINE());
if (iValue > iBestValue)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_FOUND, getGroup(), 3) == 0)
{
if (generatePath(pLoopPlot, MOVE_SAFE_TERRITORY, true, &iPathTurns))
{
if (iPathTurns <= iRange)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestFoundPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestFoundPlot != NULL))
{
if (atPlot(pBestFoundPlot))
{
getGroup()->pushMission(MISSION_FOUND, -1, -1, 0, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
else if (!bFollow)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_assaultSeaTransport(bool bBarbarian)
{
PROFILE_FUNC();
bool bIsAttackCity = (getUnitAICargo(UNITAI_ATTACK_CITY) > 0);
FAssert(getGroup()->hasCargo());
//FAssert(bIsAttackCity || getGroup()->getUnitAICargo(UNITAI_ATTACK) > 0);
if (!canCargoAllMove())
{
return false;
}
std::vector<CvUnit*> aGroupCargo;
CLLNode<IDInfo>* pUnitNode = plot()->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = plot()->nextUnitNode(pUnitNode);
CvUnit* pTransport = pLoopUnit->getTransportUnit();
if (pTransport != NULL && pTransport->getGroup() == getGroup())
{
aGroupCargo.push_back(pLoopUnit);
}
}
int iCargo = getGroup()->getCargo();
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestAssaultPlot = NULL;
for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (pLoopPlot->isCoastalLand())
{
if (pLoopPlot->isOwned())
{
if (((bBarbarian || !pLoopPlot->isBarbarian())) || GET_PLAYER(getOwnerINLINE()).isMinorCiv())
{
if (isPotentialEnemy(pLoopPlot->getTeam(), pLoopPlot))
{
int iTargetCities = pLoopPlot->area()->getCitiesPerPlayer(pLoopPlot->getOwnerINLINE());
if (iTargetCities > 0)
{
bool bCanCargoAllUnload = true;
int iVisibleEnemyDefenders = pLoopPlot->getNumVisibleEnemyDefenders(this);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 11/30/08 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if (iVisibleEnemyDefenders > 0 || pLoopPlot->isCity())
{
for (uint i = 0; i < aGroupCargo.size(); ++i)
{
CvUnit* pAttacker = aGroupCargo[i];
if( iVisibleEnemyDefenders > 0 )
{
CvUnit* pDefender = pLoopPlot->getBestDefender(NO_PLAYER, pAttacker->getOwnerINLINE(), pAttacker, true);
if (pDefender == NULL || !pAttacker->canAttack(*pDefender))
{
bCanCargoAllUnload = false;
break;
}
}
else if( pLoopPlot->isCity() && !(pLoopPlot->isVisible(getTeam(),false)) )
{
// Assume city is defended, artillery can't naval invade
if( pAttacker->combatLimit() < 100 )
{
bCanCargoAllUnload = false;
break;
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (bCanCargoAllUnload)
{
int iPathTurns;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/17/09 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
/* original bts code
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
*/
if (generatePath(pLoopPlot, MOVE_AVOID_ENEMY_WEIGHT_3, true, &iPathTurns))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
int iValue = 1;
if (!bIsAttackCity)
{
iValue += (AI_pillageValue(pLoopPlot, 15) * 10);
}
int iAssaultsHere = GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_ASSAULT, getGroup());
iValue += (iAssaultsHere * 100);
CvCity* pCity = pLoopPlot->getPlotCity();
if (pCity == NULL)
{
for (int iJ = 0; iJ < NUM_DIRECTION_TYPES; iJ++)
{
CvPlot* pAdjacentPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((DirectionTypes)iJ));
if (pAdjacentPlot != NULL)
{
pCity = pAdjacentPlot->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == pLoopPlot->getOwnerINLINE())
{
break;
}
else
{
pCity = NULL;
}
}
}
}
}
if (pCity != NULL)
{
FAssert(isPotentialEnemy(pCity->getTeam(), pLoopPlot));
if (!(pLoopPlot->isRiverCrossing(directionXY(pLoopPlot, pCity->plot()))))
{
iValue += (50 * -(GC.getRIVER_ATTACK_MODIFIER()));
}
iValue += 15 * (pLoopPlot->defenseModifier(getTeam(), false));
iValue += 1000;
iValue += (GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pCity->plot()) * 200);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/26/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
// Continue attacking in area we have already captured cities
if( pCity->area()->getCitiesPerPlayer(getOwnerINLINE()) > 0 )
{
if( pCity->AI_playerCloseness(getOwnerINLINE()) > 5 )
{
iValue *= 3;
iValue /= 2;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (iPathTurns == 1)
{
iValue += GC.getGameINLINE().getSorenRandNum(50, "AI Assault");
}
}
FAssert(iPathTurns > 0);
if (iPathTurns == 1)
{
if (pCity != NULL)
{
if (pCity->area()->getNumCities() > 1)
{
iValue *= 2;
}
}
}
iValue *= 1000;
if (iTargetCities <= iAssaultsHere)
{
iValue /= 2;
}
if (iTargetCities == 1)
{
if (iCargo > 7)
{
iValue *= 3;
iValue /= iCargo - 4;
}
}
if (pLoopPlot->isCity())
{
if (iVisibleEnemyDefenders * 3 > iCargo)
{
iValue /= 10;
}
else
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 11/30/08 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/*
// original bts code
iValue *= iCargo;
iValue /= std::max(1, (iVisibleEnemyDefenders * 3));
*/
// Assume non-visible city is properly defended
iValue *= iCargo;
iValue /= std::max(pLoopPlot->getPlotCity()->AI_neededDefenders(), (iVisibleEnemyDefenders * 3));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
else
{
if (0 == iVisibleEnemyDefenders)
{
iValue *= 4;
iValue /= 3;
}
else
{
iValue /= iVisibleEnemyDefenders;
}
}
// if more than 3 turns to get there, then put some randomness into our preference of distance
// +/- 33%
if (iPathTurns > 3)
{
int iPathAdjustment = GC.getGameINLINE().getSorenRandNum(67, "AI Assault Target");
iPathTurns *= 66 + iPathAdjustment;
iPathTurns /= 100;
}
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestAssaultPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestAssaultPlot != NULL))
{
FAssert(!(pBestPlot->isImpassable()));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/11/10 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
// Cancel missions of all those coming to join departing transport
CvSelectionGroup* pLoopGroup = NULL;
int iLoop = 0;
CvPlayer& kPlayer = GET_PLAYER(getOwnerINLINE());
for(pLoopGroup = kPlayer.firstSelectionGroup(&iLoop); pLoopGroup != NULL; pLoopGroup = kPlayer.nextSelectionGroup(&iLoop))
{
if( pLoopGroup != getGroup() )
{
if( pLoopGroup->AI_getMissionAIType() == MISSIONAI_GROUP && pLoopGroup->getHeadUnitAI() == AI_getUnitAIType() )
{
CvUnit* pMissionUnit = pLoopGroup->AI_getMissionAIUnit();
if( pMissionUnit != NULL && pMissionUnit->getGroup() == getGroup() )
{
pLoopGroup->clearMissionQueue();
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if ((pBestPlot == pBestAssaultPlot) || (stepDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pBestAssaultPlot->getX_INLINE(), pBestAssaultPlot->getY_INLINE()) == 1))
{
if (atPlot(pBestAssaultPlot))
{
getGroup()->unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/01/09 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
/* original bts code
getGroup()->pushMission(MISSION_MOVE_TO, pBestAssaultPlot->getX_INLINE(), pBestAssaultPlot->getY_INLINE(), 0, false, false, MISSIONAI_ASSAULT, pBestAssaultPlot);
*/
getGroup()->pushMission(MISSION_MOVE_TO, pBestAssaultPlot->getX_INLINE(), pBestAssaultPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_ASSAULT, pBestAssaultPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/01/09 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
/* original bts code
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ASSAULT, pBestAssaultPlot);
*/
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_ASSAULT, pBestAssaultPlot);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/07/10 jdog5000 */
/* */
/* Naval AI, Efficiency */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_assaultSeaReinforce(bool bBarbarian)
{
PROFILE_FUNC();
bool bIsAttackCity = (getUnitAICargo(UNITAI_ATTACK_CITY) > 0);
FAssert(getGroup()->hasCargo());
if (!canCargoAllMove())
{
return false;
}
if( !(getGroup()->canAllMove()) )
{
return false;
}
std::vector<CvUnit*> aGroupCargo;
CLLNode<IDInfo>* pUnitNode = plot()->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = plot()->nextUnitNode(pUnitNode);
CvUnit* pTransport = pLoopUnit->getTransportUnit();
if (pTransport != NULL && pTransport->getGroup() == getGroup())
{
aGroupCargo.push_back(pLoopUnit);
}
}
int iCargo = getGroup()->getCargo();
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvPlot* pBestAssaultPlot = NULL;
CvArea* pWaterArea = plot()->waterArea();
bool bCity = plot()->isCity(true,getTeam());
bool bCanMoveAllTerrain = getGroup()->canMoveAllTerrain();
int iTargetCities;
int iOurFightersHere;
int iPathTurns;
int iValue;
// Loop over nearby plots for groups in enemy territory to reinforce
int iRange = 2*baseMoves();
int iDX, iDY;
for (iDX = -(iRange); iDX <= iRange; iDX++)
{
for (iDY = -(iRange); iDY <= iRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if( pLoopPlot != NULL )
{
if (pLoopPlot->isOwned())
{
if (isEnemy(pLoopPlot->getTeam(), pLoopPlot))
{
if ( bCanMoveAllTerrain || (pWaterArea != NULL && pLoopPlot->isAdjacentToArea(pWaterArea)) )
{
iTargetCities = pLoopPlot->area()->getCitiesPerPlayer(pLoopPlot->getOwnerINLINE());
if (iTargetCities > 0)
{
iOurFightersHere = pLoopPlot->getNumDefenders(getOwnerINLINE());
if( iOurFightersHere > 2 )
{
iPathTurns;
if (generatePath(pLoopPlot, MOVE_AVOID_ENEMY_WEIGHT_3, true, &iPathTurns))
{
if( iPathTurns <= 2 )
{
CvPlot* pEndTurnPlot = getPathEndTurnPlot();
iValue = 10*iTargetCities;
iValue += 8*iOurFightersHere;
iValue += 3*GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pLoopPlot);
iValue *= 100;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pEndTurnPlot;
pBestAssaultPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
}
// Loop over other transport groups, looking for synchronized landing
if ((pBestPlot == NULL) && (pBestAssaultPlot == NULL))
{
int iLoop;
for(CvSelectionGroup* pLoopSelectionGroup = GET_PLAYER(getOwnerINLINE()).firstSelectionGroup(&iLoop); pLoopSelectionGroup; pLoopSelectionGroup = GET_PLAYER(getOwnerINLINE()).nextSelectionGroup(&iLoop))
{
if (pLoopSelectionGroup != getGroup())
{
if (pLoopSelectionGroup->AI_getMissionAIType() == MISSIONAI_ASSAULT)
{
CvPlot* pLoopPlot = pLoopSelectionGroup->AI_getMissionAIPlot();
if( pLoopPlot != NULL )
{
if (pLoopPlot->isOwned())
{
if (isPotentialEnemy(pLoopPlot->getTeam(), pLoopPlot))
{
if ( bCanMoveAllTerrain || (pWaterArea != NULL && pLoopPlot->isAdjacentToArea(pWaterArea)) )
{
iTargetCities = pLoopPlot->area()->getCitiesPerPlayer(pLoopPlot->getOwnerINLINE());
if (iTargetCities > 0)
{
int iAssaultsHere = pLoopSelectionGroup->getCargo();
if( iAssaultsHere > 2 )
{
iPathTurns;
if (generatePath(pLoopPlot, MOVE_AVOID_ENEMY_WEIGHT_3, true, &iPathTurns))
{
CvPlot* pEndTurnPlot = getPathEndTurnPlot();
int iOtherPathTurns = MAX_INT;
if (pLoopSelectionGroup->generatePath(pLoopSelectionGroup->plot(), pLoopPlot, MOVE_AVOID_ENEMY_WEIGHT_3, true, &iOtherPathTurns))
{
// We need to get there the turn after they do, +1 required whether
// they move first or we do
iOtherPathTurns += 1;
}
else
{
// Should never happen ...
continue;
}
if( (iPathTurns >= iOtherPathTurns) && (iPathTurns < iOtherPathTurns + 5) )
{
bool bCanCargoAllUnload = true;
int iVisibleEnemyDefenders = pLoopPlot->getNumVisibleEnemyDefenders(this);
if (iVisibleEnemyDefenders > 0 || pLoopPlot->isCity())
{
for (uint i = 0; i < aGroupCargo.size(); ++i)
{
CvUnit* pAttacker = aGroupCargo[i];
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/21/10 jdog5000 */
/* */
/* Efficiency */
/************************************************************************************************/
// From Lead From Behind by UncutDragon
// original
//CvUnit* pDefender = pLoopPlot->getBestDefender(NO_PLAYER, pAttacker->getOwnerINLINE(), pAttacker, true);
//if (pDefender == NULL || !pAttacker->canAttack(*pDefender))
// modified
if (!pLoopPlot->hasDefender(true, NO_PLAYER, pAttacker->getOwnerINLINE(), pAttacker, true))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
bCanCargoAllUnload = false;
break;
}
else if( pLoopPlot->isCity() && !(pLoopPlot->isVisible(getTeam(),false)) )
{
// Artillery can't naval invade, so don't try
if( pAttacker->combatLimit() < 100 )
{
bCanCargoAllUnload = false;
break;
}
}
}
}
iValue = (iAssaultsHere * 5);
iValue += iTargetCities*10;
iValue *= 100;
// if more than 3 turns to get there, then put some randomness into our preference of distance
// +/- 33%
if (iPathTurns > 3)
{
int iPathAdjustment = GC.getGameINLINE().getSorenRandNum(67, "AI Assault Target");
iPathTurns *= 66 + iPathAdjustment;
iPathTurns /= 100;
}
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pEndTurnPlot;
pBestAssaultPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
}
}
}
// Reinforce our cities in need
if ((pBestPlot == NULL) && (pBestAssaultPlot == NULL))
{
int iLoop;
CvCity* pLoopCity;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if( bCanMoveAllTerrain || (pWaterArea != NULL && (pLoopCity->waterArea(true) == pWaterArea || pLoopCity->secondWaterArea() == pWaterArea)) )
{
iValue = 0;
if(pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE)
{
iValue = 3;
}
else if(pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE)
{
iValue = 2;
}
else if(pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_MASSING)
{
iValue = 1;
}
else if( bBarbarian && (pLoopCity->area()->getCitiesPerPlayer(BARBARIAN_PLAYER) > 0) )
{
iValue = 1;
}
if( iValue > 0 )
{
bool bCityDanger = pLoopCity->AI_isDanger();
if( (bCity && pLoopCity->area() != area()) || bCityDanger || ((GC.getGameINLINE().getGameTurn() - pLoopCity->getGameTurnAcquired()) < 10 && pLoopCity->getPreviousOwner() != NO_PLAYER) )
{
int iOurPower = std::max(1, pLoopCity->area()->getPower(getOwnerINLINE()));
// Enemy power includes barb power
int iEnemyPower = GET_TEAM(getTeam()).countEnemyPowerByArea(pLoopCity->area());
// Don't send troops to areas we are dominating already
// Don't require presence of enemy cities, just a dangerous force
if( iOurPower < (3*iEnemyPower) )
{
iPathTurns;
if (generatePath(pLoopCity->plot(), MOVE_AVOID_ENEMY_WEIGHT_3, true, &iPathTurns))
{
iValue *= 10*pLoopCity->AI_cityThreat();
iValue += 20 * GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_ASSAULT, getGroup());
iValue *= std::min(iEnemyPower, 3*iOurPower);
iValue /= iOurPower;
iValue *= 100;
// if more than 3 turns to get there, then put some randomness into our preference of distance
// +/- 33%
if (iPathTurns > 3)
{
int iPathAdjustment = GC.getGameINLINE().getSorenRandNum(67, "AI Assault Target");
iPathTurns *= 66 + iPathAdjustment;
iPathTurns /= 100;
}
iValue /= (iPathTurns + 6);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = (bCityDanger ? getPathEndTurnPlot() : pLoopCity->plot());
pBestAssaultPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
if ((pBestPlot == NULL) && (pBestAssaultPlot == NULL))
{
if( bCity )
{
if( GET_TEAM(getTeam()).isAVassal() )
{
TeamTypes eMasterTeam = NO_TEAM;
for( int iI = 0; iI < MAX_CIV_TEAMS; iI++ )
{
if( GET_TEAM(getTeam()).isVassal((TeamTypes)iI) )
{
eMasterTeam = (TeamTypes)iI;
}
}
if( (eMasterTeam != NO_TEAM) && GET_TEAM(getTeam()).isOpenBorders(eMasterTeam) )
{
for( int iI = 0; iI < MAX_CIV_PLAYERS; iI++ )
{
if( GET_PLAYER((PlayerTypes)iI).getTeam() == eMasterTeam )
{
int iLoop;
CvCity* pLoopCity;
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if( pLoopCity->area() != area() )
{
iValue = 0;
if(pLoopCity->area()->getAreaAIType(eMasterTeam) == AREAAI_OFFENSIVE)
{
iValue = 2;
}
else if(pLoopCity->area()->getAreaAIType(eMasterTeam) == AREAAI_MASSING)
{
iValue = 1;
}
if( iValue > 0 )
{
if( bCanMoveAllTerrain || (pWaterArea != NULL && (pLoopCity->waterArea(true) == pWaterArea || pLoopCity->secondWaterArea() == pWaterArea)) )
{
int iOurPower = std::max(1, pLoopCity->area()->getPower(getOwnerINLINE()));
iOurPower += GET_TEAM(eMasterTeam).countPowerByArea(pLoopCity->area());
// Enemy power includes barb power
int iEnemyPower = GET_TEAM(eMasterTeam).countEnemyPowerByArea(pLoopCity->area());
// Don't send troops to areas we are dominating already
// Don't require presence of enemy cities, just a dangerous force
if( iOurPower < (2*iEnemyPower) )
{
int iPathTurns;
if (generatePath(pLoopCity->plot(), MOVE_AVOID_ENEMY_WEIGHT_3, true, &iPathTurns))
{
iValue *= pLoopCity->AI_cityThreat();
iValue += 10 * GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_ASSAULT, getGroup());
iValue *= std::min(iEnemyPower, 3*iOurPower);
iValue /= iOurPower;
iValue *= 100;
// if more than 3 turns to get there, then put some randomness into our preference of distance
// +/- 33%
if (iPathTurns > 3)
{
int iPathAdjustment = GC.getGameINLINE().getSorenRandNum(67, "AI Assault Target");
iPathTurns *= 66 + iPathAdjustment;
iPathTurns /= 100;
}
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestAssaultPlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestAssaultPlot != NULL))
{
FAssert(!(pBestPlot->isImpassable()));
// Cancel missions of all those coming to join departing transport
CvSelectionGroup* pLoopGroup = NULL;
int iLoop = 0;
CvPlayer& kPlayer = GET_PLAYER(getOwnerINLINE());
for(pLoopGroup = kPlayer.firstSelectionGroup(&iLoop); pLoopGroup != NULL; pLoopGroup = kPlayer.nextSelectionGroup(&iLoop))
{
if( pLoopGroup != getGroup() )
{
if( pLoopGroup->AI_getMissionAIType() == MISSIONAI_GROUP && pLoopGroup->getHeadUnitAI() == AI_getUnitAIType() )
{
CvUnit* pMissionUnit = pLoopGroup->AI_getMissionAIUnit();
if( pMissionUnit != NULL && pMissionUnit->getGroup() == getGroup() )
{
pLoopGroup->clearMissionQueue();
}
}
}
}
if ((pBestPlot == pBestAssaultPlot) || (stepDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pBestAssaultPlot->getX_INLINE(), pBestAssaultPlot->getY_INLINE()) == 1))
{
if (atPlot(pBestAssaultPlot))
{
getGroup()->unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestAssaultPlot->getX_INLINE(), pBestAssaultPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_ASSAULT, pBestAssaultPlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_ASSAULT, pBestAssaultPlot);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_settlerSeaTransport()
{
PROFILE_FUNC();
CLLNode<IDInfo>* pUnitNode;
CvUnit* pLoopUnit;
CvPlot* pLoopPlot;
CvPlot* pPlot;
CvPlot* pBestPlot;
CvPlot* pBestFoundPlot;
CvArea* pWaterArea;
bool bValid;
int iValue;
int iBestValue;
int iI;
FAssert(getCargo() > 0);
FAssert(getUnitAICargo(UNITAI_SETTLE) > 0);
if (!canCargoAllMove())
{
return false;
}
//New logic should allow some new tricks like
//unloading settlers when a better site opens up locally
//and delivering settlers
//to inland sites
pWaterArea = plot()->waterArea();
FAssertMsg(pWaterArea != NULL, "Ship out of water?");
CvUnit* pSettlerUnit = NULL;
pPlot = plot();
pUnitNode = pPlot->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pPlot->nextUnitNode(pUnitNode);
if (pLoopUnit->getTransportUnit() == this)
{
if (pLoopUnit->AI_getUnitAIType() == UNITAI_SETTLE)
{
pSettlerUnit = pLoopUnit;
break;
}
}
}
FAssert(pSettlerUnit != NULL);
int iAreaBestFoundValue = 0;
CvPlot* pAreaBestPlot = NULL;
int iOtherAreaBestFoundValue = 0;
CvPlot* pOtherAreaBestPlot = NULL;
for (iI = 0; iI < GET_PLAYER(getOwnerINLINE()).AI_getNumCitySites(); iI++)
{
CvPlot* pCitySitePlot = GET_PLAYER(getOwnerINLINE()).AI_getCitySite(iI);
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCitySitePlot, MISSIONAI_FOUND, getGroup()) == 0)
{
iValue = pCitySitePlot->getFoundValue(getOwnerINLINE());
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/13/09 jdog5000 */
/* */
/* Settler AI */
/************************************************************************************************/
/* original bts code
if (pCitySitePlot->getArea() == getArea())
{
if (iValue > iAreaBestFoundValue)
{
*/
// Only count city sites we can get to
if (pCitySitePlot->getArea() == getArea() && pSettlerUnit->generatePath(pCitySitePlot, MOVE_SAFE_TERRITORY, true))
{
if (iValue > iAreaBestFoundValue)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
iAreaBestFoundValue = iValue;
pAreaBestPlot = pCitySitePlot;
}
}
else
{
if (iValue > iOtherAreaBestFoundValue)
{
iOtherAreaBestFoundValue = iValue;
pOtherAreaBestPlot = pCitySitePlot;
}
}
}
}
if ((0 == iAreaBestFoundValue) && (0 == iOtherAreaBestFoundValue))
{
return false;
}
if (iAreaBestFoundValue > iOtherAreaBestFoundValue)
{
//let the settler walk.
getGroup()->unloadAll();
getGroup()->pushMission(MISSION_SKIP);
return true;
}
iBestValue = 0;
pBestPlot = NULL;
pBestFoundPlot = NULL;
for (iI = 0; iI < GET_PLAYER(getOwnerINLINE()).AI_getNumCitySites(); iI++)
{
CvPlot* pCitySitePlot = GET_PLAYER(getOwnerINLINE()).AI_getCitySite(iI);
if (!(pCitySitePlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCitySitePlot, MISSIONAI_FOUND, getGroup(), 4) == 0)
{
int iPathTurns;
// BBAI TODO: Nearby plots too if much shorter (settler walk from there)
// also, if plots are in area player already has cities, then may not be coastal ... (see Earth 1000 AD map for Inca)
if (generatePath(pCitySitePlot, 0, true, &iPathTurns))
{
iValue = pCitySitePlot->getFoundValue(getOwnerINLINE());
iValue *= 1000;
iValue /= (2 + iPathTurns);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestFoundPlot = pCitySitePlot;
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestFoundPlot != NULL))
{
FAssert(!(pBestPlot->isImpassable()));
if ((pBestPlot == pBestFoundPlot) || (stepDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pBestFoundPlot->getX_INLINE(), pBestFoundPlot->getY_INLINE()) == 1))
{
if (atPlot(pBestFoundPlot))
{
unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestFoundPlot->getX_INLINE(), pBestFoundPlot->getY_INLINE(), 0, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
}
//Try original logic
//(sometimes new logic breaks)
pPlot = plot();
iBestValue = 0;
pBestPlot = NULL;
pBestFoundPlot = NULL;
int iMinFoundValue = GET_PLAYER(getOwnerINLINE()).AI_getMinFoundValue();
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (pLoopPlot->isCoastalLand())
{
iValue = pLoopPlot->getFoundValue(getOwnerINLINE());
if ((iValue > iBestValue) && (iValue >= iMinFoundValue))
{
bValid = false;
pUnitNode = pPlot->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pPlot->nextUnitNode(pUnitNode);
if (pLoopUnit->getTransportUnit() == this)
{
if (pLoopUnit->canFound(pLoopPlot))
{
bValid = true;
break;
}
}
}
if (bValid)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_FOUND, getGroup(), 4) == 0)
{
if (generatePath(pLoopPlot, 0, true))
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestFoundPlot = pLoopPlot;
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestFoundPlot != NULL))
{
FAssert(!(pBestPlot->isImpassable()));
if ((pBestPlot == pBestFoundPlot) || (stepDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pBestFoundPlot->getX_INLINE(), pBestFoundPlot->getY_INLINE()) == 1))
{
if (atPlot(pBestFoundPlot))
{
unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestFoundPlot->getX_INLINE(), pBestFoundPlot->getY_INLINE(), 0, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_FOUND, pBestFoundPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_settlerSeaFerry()
{
PROFILE_FUNC();
FAssert(getCargo() > 0);
FAssert(getUnitAICargo(UNITAI_WORKER) > 0);
if (!canCargoAllMove())
{
return false;
}
CvArea* pWaterArea = plot()->waterArea();
FAssertMsg(pWaterArea != NULL, "Ship out of water?");
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
CvCity* pLoopCity;
int iLoop;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
int iValue = pLoopCity->AI_getWorkersNeeded();
if (iValue > 0)
{
iValue -= GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_FOUND, getGroup());
if (iValue > 0)
{
int iPathTurns;
if (generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
iValue += std::max(0, (GET_PLAYER(getOwnerINLINE()).AI_neededWorkers(pLoopCity->area()) - GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(pLoopCity->area(), UNITAI_WORKER)));
iValue *= 1000;
iValue /= 4 + iPathTurns;
if (atPlot(pLoopCity->plot()))
{
iValue += 100;
}
else
{
iValue += GC.getGame().getSorenRandNum(100, "AI settler sea ferry");
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_FOUND, pBestPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_specialSeaTransportMissionary()
{
//PROFILE_FUNC();
CLLNode<IDInfo>* pUnitNode;
CvCity* pCity;
CvUnit* pMissionaryUnit;
CvUnit* pLoopUnit;
CvPlot* pLoopPlot;
CvPlot* pPlot;
CvPlot* pBestPlot;
CvPlot* pBestSpreadPlot;
int iPathTurns;
int iValue;
int iCorpValue;
int iBestValue;
int iI, iJ;
bool bExecutive = false;
FAssert(getCargo() > 0);
FAssert(getUnitAICargo(UNITAI_MISSIONARY) > 0);
if (!canCargoAllMove())
{
return false;
}
pPlot = plot();
pMissionaryUnit = NULL;
pUnitNode = pPlot->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pPlot->nextUnitNode(pUnitNode);
if (pLoopUnit->getTransportUnit() == this)
{
if (pLoopUnit->AI_getUnitAIType() == UNITAI_MISSIONARY)
{
pMissionaryUnit = pLoopUnit;
break;
}
}
}
if (pMissionaryUnit == NULL)
{
return false;
}
iBestValue = 0;
pBestPlot = NULL;
pBestSpreadPlot = NULL;
// XXX what about non-coastal cities?
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (pLoopPlot->isCoastalLand())
{
pCity = pLoopPlot->getPlotCity();
if (pCity != NULL)
{
iValue = 0;
iCorpValue = 0;
for (iJ = 0; iJ < GC.getNumReligionInfos(); iJ++)
{
if (pMissionaryUnit->canSpread(pLoopPlot, ((ReligionTypes)iJ)))
{
if (GET_PLAYER(getOwnerINLINE()).getStateReligion() == ((ReligionTypes)iJ))
{
iValue += 3;
}
if (GET_PLAYER(getOwnerINLINE()).hasHolyCity((ReligionTypes)iJ))
{
iValue++;
}
}
}
for (iJ = 0; iJ < GC.getNumCorporationInfos(); iJ++)
{
if (pMissionaryUnit->canSpreadCorporation(pLoopPlot, ((CorporationTypes)iJ)))
{
if (GET_PLAYER(getOwnerINLINE()).hasHeadquarters((CorporationTypes)iJ))
{
iCorpValue += 3;
}
}
}
if (iValue > 0)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_SPREAD, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue *= pCity->getPopulation();
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
iValue *= 4;
}
else if (pCity->getTeam() == getTeam())
{
iValue *= 3;
}
if (pCity->getReligionCount() == 0)
{
iValue *= 2;
}
iValue /= (pCity->getReligionCount() + 1);
FAssert(iPathTurns > 0);
if (iPathTurns == 1)
{
iValue *= 2;
}
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestSpreadPlot = pLoopPlot;
bExecutive = false;
}
}
}
}
}
if (iCorpValue > 0)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_SPREAD_CORPORATION, getGroup()) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iCorpValue *= pCity->getPopulation();
FAssert(iPathTurns > 0);
if (iPathTurns == 1)
{
/************************************************************************************************/
/* UNOFFICIAL_PATCH 02/22/10 jdog5000 */
/* */
/* Bugfix */
/************************************************************************************************/
/* original bts code
iValue *= 2;
*/
iCorpValue *= 2;
/************************************************************************************************/
/* UNOFFICIAL_PATCH END */
/************************************************************************************************/
}
iCorpValue *= 1000;
iCorpValue /= (iPathTurns + 1);
if (iCorpValue > iBestValue)
{
iBestValue = iCorpValue;
pBestPlot = getPathEndTurnPlot();
pBestSpreadPlot = pLoopPlot;
bExecutive = true;
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestSpreadPlot != NULL))
{
FAssert(!(pBestPlot->isImpassable()) || canMoveImpassable());
if ((pBestPlot == pBestSpreadPlot) || (stepDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pBestSpreadPlot->getX_INLINE(), pBestSpreadPlot->getY_INLINE()) == 1))
{
if (atPlot(pBestSpreadPlot))
{
unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestSpreadPlot->getX_INLINE(), pBestSpreadPlot->getY_INLINE(), 0, false, false, bExecutive ? MISSIONAI_SPREAD_CORPORATION : MISSIONAI_SPREAD, pBestSpreadPlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, bExecutive ? MISSIONAI_SPREAD_CORPORATION : MISSIONAI_SPREAD, pBestSpreadPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_specialSeaTransportSpy()
{
//PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
CvPlot* pBestSpyPlot;
PlayerTypes eBestPlayer;
int iPathTurns;
int iValue;
int iBestValue;
int iI;
FAssert(getCargo() > 0);
FAssert(getUnitAICargo(UNITAI_SPY) > 0);
if (!canCargoAllMove())
{
return false;
}
iBestValue = 0;
eBestPlayer = NO_PLAYER;
for (iI = 0; iI < MAX_CIV_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive())
{
if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam())
{
if (GET_PLAYER(getOwnerINLINE()).AI_getAttitude((PlayerTypes)iI) <= ATTITUDE_ANNOYED)
{
iValue = GET_PLAYER((PlayerTypes)iI).getTotalPopulation();
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestPlayer = ((PlayerTypes)iI);
}
}
}
}
}
if (eBestPlayer == NO_PLAYER)
{
return false;
}
pBestPlot = NULL;
pBestSpyPlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (pLoopPlot->isCoastalLand())
{
if (pLoopPlot->getOwnerINLINE() == eBestPlayer)
{
iValue = pLoopPlot->area()->getCitiesPerPlayer(eBestPlayer);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/23/10 jdog5000 */
/* */
/* Efficiency */
/************************************************************************************************/
iValue *= 1000;
if (iValue > iBestValue)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_ATTACK_SPY, getGroup(), 4) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestSpyPlot = pLoopPlot;
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestSpyPlot != NULL))
{
FAssert(!(pBestPlot->isImpassable()));
if ((pBestPlot == pBestSpyPlot) || (stepDistance(pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), pBestSpyPlot->getX_INLINE(), pBestSpyPlot->getY_INLINE()) == 1))
{
if (atPlot(pBestSpyPlot))
{
unloadAll(); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestSpyPlot->getX_INLINE(), pBestSpyPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY, pBestSpyPlot);
return true;
}
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY, pBestSpyPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_carrierSeaTransport()
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pLoopPlotAir;
CvPlot* pBestPlot;
CvPlot* pBestCarrierPlot;
int iMaxAirRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
int iI;
iMaxAirRange = 0;
std::vector<CvUnit*> aCargoUnits;
getCargoUnits(aCargoUnits);
for (uint i = 0; i < aCargoUnits.size(); ++i)
{
iMaxAirRange = std::max(iMaxAirRange, aCargoUnits[i]->airRange());
}
if (iMaxAirRange == 0)
{
return false;
}
iBestValue = 0;
pBestPlot = NULL;
pBestCarrierPlot = NULL;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Naval AI, War tactics, Efficiency */
/************************************************************************************************/
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isAdjacentToLand())
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
iValue = 0;
for (iDX = -(iMaxAirRange); iDX <= iMaxAirRange; iDX++)
{
for (iDY = -(iMaxAirRange); iDY <= iMaxAirRange; iDY++)
{
pLoopPlotAir = plotXY(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), iDX, iDY);
if (pLoopPlotAir != NULL)
{
if (plotDistance(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), pLoopPlotAir->getX_INLINE(), pLoopPlotAir->getY_INLINE()) <= iMaxAirRange)
{
if (!(pLoopPlotAir->isBarbarian()))
{
if (potentialWarAction(pLoopPlotAir))
{
if (pLoopPlotAir->isCity())
{
iValue += 3;
// BBAI: Support invasions
iValue += (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlotAir, MISSIONAI_ASSAULT, getGroup(), 2) * 6);
}
if (pLoopPlotAir->getImprovementType() != NO_IMPROVEMENT)
{
iValue += 2;
}
if (plotDistance(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), pLoopPlotAir->getX_INLINE(), pLoopPlotAir->getY_INLINE()) <= iMaxAirRange/2)
{
// BBAI: Support/air defense for land troops
iValue += pLoopPlotAir->plotCount(PUF_canDefend, -1, -1, getOwnerINLINE());
}
}
}
}
}
}
}
if( iValue > 0 )
{
iValue *= 1000;
for (int iDirection = 0; iDirection < NUM_DIRECTION_TYPES; iDirection++)
{
CvPlot* pDirectionPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), (DirectionTypes)iDirection);
if (pDirectionPlot != NULL)
{
if (pDirectionPlot->isCity() && isEnemy(pDirectionPlot->getTeam(), pLoopPlot))
{
iValue /= 2;
break;
}
}
}
if (iValue > iBestValue)
{
bool bStealth = (getInvisibleType() != NO_INVISIBLE);
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_CARRIER, getGroup(), bStealth ? 5 : 3) <= (bStealth ? 0 : 3))
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestCarrierPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if ((pBestPlot != NULL) && (pBestCarrierPlot != NULL))
{
if (atPlot(pBestCarrierPlot))
{
if (getGroup()->hasCargo())
{
CvPlot* pPlot = plot();
int iNumUnits = pPlot->getNumUnits();
for (int i = 0; i < iNumUnits; ++i)
{
bool bDone = true;
CLLNode<IDInfo>* pUnitNode = pPlot->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pCargoUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pPlot->nextUnitNode(pUnitNode);
if (pCargoUnit->isCargo())
{
FAssert(pCargoUnit->getTransportUnit() != NULL);
if (pCargoUnit->getOwnerINLINE() == getOwnerINLINE() && (pCargoUnit->getTransportUnit()->getGroup() == getGroup()) && (pCargoUnit->getDomainType() == DOMAIN_AIR))
{
if (pCargoUnit->canMove() && pCargoUnit->isGroupHead())
{
// careful, this might kill the cargo group
if (pCargoUnit->getGroup()->AI_update())
{
bDone = false;
break;
}
}
}
}
}
if (bDone)
{
break;
}
}
}
if (canPlunder(pBestCarrierPlot))
{
getGroup()->pushMission(MISSION_PLUNDER, -1, -1, 0, false, false, MISSIONAI_CARRIER, pBestCarrierPlot);
}
else
{
getGroup()->pushMission(MISSION_SKIP);
}
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_CARRIER, pBestCarrierPlot);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_connectPlot(CvPlot* pPlot, int iRange)
{
PROFILE_FUNC();
CvCity* pLoopCity;
int iLoop;
FAssert(canBuildRoute());
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units before generating paths
if( (getDomainType() == DOMAIN_LAND) && (pPlot->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (!(pPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pPlot, MISSIONAI_BUILD, getGroup(), iRange) == 0)
{
if (generatePath(pPlot, MOVE_SAFE_TERRITORY, true))
{
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (!(pPlot->isConnectedTo(pLoopCity)))
{
FAssertMsg(pPlot->getPlotCity() != pLoopCity, "pPlot->getPlotCity() is not expected to be equal with pLoopCity");
if (plot()->getPlotGroup(getOwnerINLINE()) == pLoopCity->plot()->getPlotGroup(getOwnerINLINE()))
{
getGroup()->pushMission(MISSION_ROUTE_TO, pPlot->getX_INLINE(), pPlot->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_BUILD, pPlot);
return true;
}
}
}
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if( (pLoopCity->area() != pPlot->area()) )
{
continue;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (!(pPlot->isConnectedTo(pLoopCity)))
{
FAssertMsg(pPlot->getPlotCity() != pLoopCity, "pPlot->getPlotCity() is not expected to be equal with pLoopCity");
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (generatePath(pLoopCity->plot(), MOVE_SAFE_TERRITORY, true))
{
if (atPlot(pPlot)) // need to test before moving...
{
getGroup()->pushMission(MISSION_ROUTE_TO, pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_BUILD, pPlot);
}
else
{
getGroup()->pushMission(MISSION_ROUTE_TO, pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_BUILD, pPlot);
getGroup()->pushMission(MISSION_ROUTE_TO, pPlot->getX_INLINE(), pPlot->getY_INLINE(), MOVE_SAFE_TERRITORY, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pPlot);
}
return true;
}
}
}
}
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_improveCity(CvCity* pCity)
{
PROFILE_FUNC();
CvPlot* pBestPlot;
BuildTypes eBestBuild;
MissionTypes eMission;
if (AI_bestCityBuild(pCity, &pBestPlot, &eBestBuild, NULL, this))
{
FAssertMsg(pBestPlot != NULL, "BestPlot is not assigned a valid value");
FAssertMsg(eBestBuild != NO_BUILD, "BestBuild is not assigned a valid value");
FAssertMsg(eBestBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
if ((plot()->getWorkingCity() != pCity) || (GC.getBuildInfo(eBestBuild).getRoute() != NO_ROUTE))
{
eMission = MISSION_ROUTE_TO;
}
else
{
eMission = MISSION_MOVE_TO;
if (NULL != pBestPlot && generatePath(pBestPlot) && (getPathLastNode()->m_iData2 == 1) && (getPathLastNode()->m_iData1 == 0))
{
if (pBestPlot->getRouteType() != NO_ROUTE)
{
eMission = MISSION_ROUTE_TO;
}
}
else if (plot()->getRouteType() == NO_ROUTE)
{
int iPlotMoveCost = 0;
iPlotMoveCost = ((plot()->getFeatureType() == NO_FEATURE) ? GC.getTerrainInfo(plot()->getTerrainType()).getMovementCost() : GC.getFeatureInfo(plot()->getFeatureType()).getMovementCost());
if (plot()->isHills())
{
iPlotMoveCost += GC.getHILLS_EXTRA_MOVEMENT();
}
if (iPlotMoveCost > 1)
{
eMission = MISSION_ROUTE_TO;
}
}
}
eBestBuild = AI_betterPlotBuild(pBestPlot, eBestBuild);
getGroup()->pushMission(eMission, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pBestPlot);
getGroup()->pushMission(MISSION_BUILD, eBestBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pBestPlot);
return true;
}
return false;
}
bool CvUnitAI::AI_improveLocalPlot(int iRange, CvCity* pIgnoreCity)
{
int iX, iY;
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
BuildTypes eBestBuild = NO_BUILD;
for (iX = -iRange; iX <= iRange; iX++)
{
for (iY = -iRange; iY <= iRange; iY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iX, iY);
if ((pLoopPlot != NULL) && (pLoopPlot->isCityRadius()))
{
CvCity* pCity = pLoopPlot->getWorkingCity();
if ((NULL != pCity) && (pCity->getOwnerINLINE() == getOwnerINLINE()))
{
if ((NULL == pIgnoreCity) || (pCity != pIgnoreCity))
{
if (AI_plotValid(pLoopPlot))
{
int iIndex = pCity->getCityPlotIndex(pLoopPlot);
if (iIndex != CITY_HOME_PLOT)
{
if (((NULL == pIgnoreCity) || ((pCity->AI_getWorkersNeeded() > 0) && (pCity->AI_getWorkersHave() < (1 + pCity->AI_getWorkersNeeded() * 2 / 3)))) && (pCity->AI_getBestBuild(iIndex) != NO_BUILD))
{
if (canBuild(pLoopPlot, pCity->AI_getBestBuild(iIndex)))
{
bool bAllowed = true;
if (GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_SAFE_AUTOMATION))
{
if (pLoopPlot->getImprovementType() != NO_IMPROVEMENT && pLoopPlot->getImprovementType() != GC.getDefineINT("RUINS_IMPROVEMENT"))
{
bAllowed = false;
}
}
if (bAllowed)
{
if (pLoopPlot->getImprovementType() != NO_IMPROVEMENT && GC.getBuildInfo(pCity->AI_getBestBuild(iIndex)).getImprovement() != NO_IMPROVEMENT)
{
bAllowed = false;
}
}
if (bAllowed)
{
int iValue = pCity->AI_getBestBuildValue(iIndex);
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
int iMaxWorkers = 1;
if (plot() == pLoopPlot)
{
iValue *= 3;
iValue /= 2;
}
else if (getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
else if (iPathTurns <= 1)
{
iMaxWorkers = AI_calculatePlotWorkersNeeded(pLoopPlot, pCity->AI_getBestBuild(iIndex));
}
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BUILD, getGroup()) < iMaxWorkers)
{
iValue *= 1000;
iValue /= 1 + iPathTurns;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
eBestBuild = pCity->AI_getBestBuild(iIndex);
}
}
}
}
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssertMsg(eBestBuild != NO_BUILD, "BestBuild is not assigned a valid value");
FAssertMsg(eBestBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
FAssert(pBestPlot->getWorkingCity() != NULL);
if (NULL != pBestPlot->getWorkingCity())
{
pBestPlot->getWorkingCity()->AI_changeWorkersHave(+1);
if (plot()->getWorkingCity() != NULL)
{
plot()->getWorkingCity()->AI_changeWorkersHave(-1);
}
}
MissionTypes eMission = MISSION_MOVE_TO;
int iPathTurns;
if (generatePath(pBestPlot, 0, true, &iPathTurns) && (getPathLastNode()->m_iData2 == 1) && (getPathLastNode()->m_iData1 == 0))
{
if (pBestPlot->getRouteType() != NO_ROUTE)
{
eMission = MISSION_ROUTE_TO;
}
}
else if (plot()->getRouteType() == NO_ROUTE)
{
int iPlotMoveCost = 0;
iPlotMoveCost = ((plot()->getFeatureType() == NO_FEATURE) ? GC.getTerrainInfo(plot()->getTerrainType()).getMovementCost() : GC.getFeatureInfo(plot()->getFeatureType()).getMovementCost());
if (plot()->isHills())
{
iPlotMoveCost += GC.getHILLS_EXTRA_MOVEMENT();
}
if (iPlotMoveCost > 1)
{
eMission = MISSION_ROUTE_TO;
}
}
eBestBuild = AI_betterPlotBuild(pBestPlot, eBestBuild);
getGroup()->pushMission(eMission, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pBestPlot);
getGroup()->pushMission(MISSION_BUILD, eBestBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pBestPlot);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_nextCityToImprove(CvCity* pCity)
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pPlot;
CvPlot* pBestPlot;
BuildTypes eBuild;
BuildTypes eBestBuild;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
iBestValue = 0;
eBestBuild = NO_BUILD;
pBestPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (pLoopCity != pCity)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Worker AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units before path generation
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
//iValue = pLoopCity->AI_totalBestBuildValue(area());
int iWorkersNeeded = pLoopCity->AI_getWorkersNeeded();
int iWorkersHave = pLoopCity->AI_getWorkersHave();
iValue = std::max(0, iWorkersNeeded - iWorkersHave) * 100;
iValue += iWorkersNeeded * 10;
iValue *= (iWorkersNeeded + 1);
iValue /= (iWorkersHave + 1);
if (iValue > 0)
{
if (AI_bestCityBuild(pLoopCity, &pPlot, &eBuild, NULL, this))
{
FAssert(pPlot != NULL);
FAssert(eBuild != NO_BUILD);
if( AI_plotValid(pPlot) )
{
iValue *= 1000;
if (pLoopCity->isCapital())
{
iValue *= 2;
}
if( iValue > iBestValue )
{
if( generatePath(pPlot, 0, true, &iPathTurns) )
{
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuild = eBuild;
pBestPlot = pPlot;
FAssert(!atPlot(pBestPlot) || NULL == pCity || pCity->AI_getWorkersNeeded() == 0 || pCity->AI_getWorkersHave() > pCity->AI_getWorkersNeeded() + 1);
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
}
}
if (pBestPlot != NULL)
{
FAssertMsg(eBestBuild != NO_BUILD, "BestBuild is not assigned a valid value");
FAssertMsg(eBestBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
if (plot()->getWorkingCity() != NULL)
{
plot()->getWorkingCity()->AI_changeWorkersHave(-1);
}
FAssert(pBestPlot->getWorkingCity() != NULL || GC.getBuildInfo(eBestBuild).getImprovement() == NO_IMPROVEMENT);
if (NULL != pBestPlot->getWorkingCity())
{
pBestPlot->getWorkingCity()->AI_changeWorkersHave(+1);
}
eBestBuild = AI_betterPlotBuild(pBestPlot, eBestBuild);
getGroup()->pushMission(MISSION_ROUTE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pBestPlot);
getGroup()->pushMission(MISSION_BUILD, eBestBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pBestPlot);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_nextCityToImproveAirlift()
{
PROFILE_FUNC();
CvCity* pCity;
CvCity* pLoopCity;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iLoop;
if (getGroup()->getNumUnits() > 1)
{
return false;
}
pCity = plot()->getPlotCity();
if (pCity == NULL)
{
return false;
}
if (pCity->getMaxAirlift() == 0)
{
return false;
}
iBestValue = 0;
pBestPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (pLoopCity != pCity)
{
if (canAirliftAt(pCity->plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
iValue = pLoopCity->AI_totalBestBuildValue(pLoopCity->area());
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
FAssert(pLoopCity != pCity);
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRLIFT, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_irrigateTerritory()
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
ImprovementTypes eImprovement;
BuildTypes eBuild;
BuildTypes eBestBuild;
BuildTypes eBestTempBuild;
BonusTypes eNonObsoleteBonus;
bool bValid;
int iPathTurns;
int iValue;
int iBestValue;
int iBestTempBuildValue;
int iI, iJ;
iBestValue = 0;
eBestBuild = NO_BUILD;
pBestPlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE()) // XXX team???
{
if (pLoopPlot->getWorkingCity() == NULL)
{
eImprovement = pLoopPlot->getImprovementType();
if ((eImprovement == NO_IMPROVEMENT) || !(GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_SAFE_AUTOMATION) && !(eImprovement == (GC.getDefineINT("RUINS_IMPROVEMENT")))))
{
if ((eImprovement == NO_IMPROVEMENT) || !(GC.getImprovementInfo(eImprovement).isCarriesIrrigation()))
{
eNonObsoleteBonus = pLoopPlot->getNonObsoleteBonusType(getTeam());
if ((eImprovement == NO_IMPROVEMENT) || (eNonObsoleteBonus == NO_BONUS) || !(GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus)))
{
if (pLoopPlot->isIrrigationAvailable(true))
{
iBestTempBuildValue = MAX_INT;
eBestTempBuild = NO_BUILD;
for (iJ = 0; iJ < GC.getNumBuildInfos(); iJ++)
{
eBuild = ((BuildTypes)iJ);
FAssertMsg(eBuild < GC.getNumBuildInfos(), "Invalid Build");
if (GC.getBuildInfo(eBuild).getImprovement() != NO_IMPROVEMENT)
{
if (GC.getImprovementInfo((ImprovementTypes)(GC.getBuildInfo(eBuild).getImprovement())).isCarriesIrrigation())
{
if (canBuild(pLoopPlot, eBuild))
{
iValue = 10000;
iValue /= (GC.getBuildInfo(eBuild).getTime() + 1);
// XXX feature production???
if (iValue < iBestTempBuildValue)
{
iBestTempBuildValue = iValue;
eBestTempBuild = eBuild;
}
}
}
}
}
if (eBestTempBuild != NO_BUILD)
{
bValid = true;
if (GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_LEAVE_FORESTS))
{
if (pLoopPlot->getFeatureType() != NO_FEATURE)
{
if (GC.getBuildInfo(eBestTempBuild).isFeatureRemove(pLoopPlot->getFeatureType()))
{
if (GC.getFeatureInfo(pLoopPlot->getFeatureType()).getYieldChange(YIELD_PRODUCTION) > 0)
{
bValid = false;
}
}
}
}
if (bValid)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BUILD, getGroup(), 1) == 0)
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns)) // XXX should this actually be at the top of the loop? (with saved paths and all...)
{
iValue = 10000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuild = eBestTempBuild;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssertMsg(eBestBuild != NO_BUILD, "BestBuild is not assigned a valid value");
FAssertMsg(eBestBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
getGroup()->pushMission(MISSION_ROUTE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pBestPlot);
getGroup()->pushMission(MISSION_BUILD, eBestBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pBestPlot);
return true;
}
return false;
}
bool CvUnitAI::AI_fortTerritory(bool bCanal, bool bAirbase)
{
PROFILE_FUNC();
int iBestValue = 0;
BuildTypes eBestBuild = NO_BUILD;
CvPlot* pBestPlot = NULL;
CvPlayerAI& kOwner = GET_PLAYER(getOwnerINLINE());
for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE()) // XXX team???
{
if (pLoopPlot->getImprovementType() == NO_IMPROVEMENT)
{
int iValue = 0;
iValue += bCanal ? kOwner.AI_getPlotCanalValue(pLoopPlot) : 0;
iValue += bAirbase ? kOwner.AI_getPlotAirbaseValue(pLoopPlot) : 0;
if (iValue > 0)
{
int iBestTempBuildValue = MAX_INT;
BuildTypes eBestTempBuild = NO_BUILD;
for (int iJ = 0; iJ < GC.getNumBuildInfos(); iJ++)
{
BuildTypes eBuild = ((BuildTypes)iJ);
FAssertMsg(eBuild < GC.getNumBuildInfos(), "Invalid Build");
if (GC.getBuildInfo(eBuild).getImprovement() != NO_IMPROVEMENT)
{
if (GC.getImprovementInfo((ImprovementTypes)(GC.getBuildInfo(eBuild).getImprovement())).isActsAsCity())
{
if (GC.getImprovementInfo((ImprovementTypes)(GC.getBuildInfo(eBuild).getImprovement())).getDefenseModifier() > 0)
{
if (canBuild(pLoopPlot, eBuild))
{
iValue = 10000;
iValue /= (GC.getBuildInfo(eBuild).getTime() + 1);
if (iValue < iBestTempBuildValue)
{
iBestTempBuildValue = iValue;
eBestTempBuild = eBuild;
}
}
}
}
}
}
if (eBestTempBuild != NO_BUILD)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
bool bValid = true;
if (GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_LEAVE_FORESTS))
{
if (pLoopPlot->getFeatureType() != NO_FEATURE)
{
if (GC.getBuildInfo(eBestTempBuild).isFeatureRemove(pLoopPlot->getFeatureType()))
{
if (GC.getFeatureInfo(pLoopPlot->getFeatureType()).getYieldChange(YIELD_PRODUCTION) > 0)
{
bValid = false;
}
}
}
}
if (bValid)
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BUILD, getGroup(), 3) == 0)
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuild = eBestTempBuild;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssertMsg(eBestBuild != NO_BUILD, "BestBuild is not assigned a valid value");
FAssertMsg(eBestBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
getGroup()->pushMission(MISSION_ROUTE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pBestPlot);
getGroup()->pushMission(MISSION_BUILD, eBestBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pBestPlot);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_improveBonus(int iMinValue, CvPlot** ppBestPlot, BuildTypes* peBestBuild, int* piBestValue)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
ImprovementTypes eImprovement;
BuildTypes eBuild;
BuildTypes eBestBuild;
BuildTypes eBestTempBuild;
BonusTypes eNonObsoleteBonus;
int iPathTurns;
int iValue;
int iBestValue;
int iBestTempBuildValue;
int iBestResourceValue;
int iI, iJ;
bool bBestBuildIsRoute = false;
bool bCanRoute;
bool bIsConnected;
iBestValue = 0;
iBestResourceValue = 0;
eBestBuild = NO_BUILD;
pBestPlot = NULL;
bCanRoute = canBuildRoute();
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE() && AI_plotValid(pLoopPlot))
{
bool bCanImprove = (pLoopPlot->area() == area());
if (!bCanImprove)
{
if (DOMAIN_SEA == getDomainType() && pLoopPlot->isWater() && plot()->isAdjacentToArea(pLoopPlot->area()))
{
bCanImprove = true;
}
}
if (bCanImprove)
{
eNonObsoleteBonus = pLoopPlot->getNonObsoleteBonusType(getTeam());
if (eNonObsoleteBonus != NO_BONUS)
{
bIsConnected = pLoopPlot->isConnectedToCapital(getOwnerINLINE());
if ((pLoopPlot->getWorkingCity() != NULL) || (bIsConnected || bCanRoute))
{
eImprovement = pLoopPlot->getImprovementType();
bool bDoImprove = false;
if (eImprovement == NO_IMPROVEMENT)
{
bDoImprove = true;
}
else if (GC.getImprovementInfo(eImprovement).isActsAsCity() || GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus))
{
bDoImprove = false;
}
else if (eImprovement == (ImprovementTypes)(GC.getDefineINT("RUINS_IMPROVEMENT")))
{
bDoImprove = true;
}
else if (!GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_SAFE_AUTOMATION))
{
bDoImprove = true;
}
iBestTempBuildValue = MAX_INT;
eBestTempBuild = NO_BUILD;
if (bDoImprove)
{
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) || (!pLoopPlot->isCityRadius() && GC.getImprovementInfo((ImprovementTypes) GC.getBuildInfo(eBuild).getImprovement()).isActsAsCity()))
{
if (canBuild(pLoopPlot, eBuild))
{
if ((pLoopPlot->getFeatureType() == NO_FEATURE) || !GC.getBuildInfo(eBuild).isFeatureRemove(pLoopPlot->getFeatureType()) || !GET_PLAYER(getOwnerINLINE()).isOption(PLAYEROPTION_LEAVE_FORESTS))
{
iValue = 10000;
iValue /= (GC.getBuildInfo(eBuild).getTime() + 1);
// XXX feature production???
if (iValue < iBestTempBuildValue)
{
iBestTempBuildValue = iValue;
eBestTempBuild = eBuild;
}
}
}
}
}
}
}
if (eBestTempBuild == NO_BUILD)
{
bDoImprove = false;
}
if ((eBestTempBuild != NO_BUILD) || (bCanRoute && !bIsConnected))
{
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
iValue = GET_PLAYER(getOwnerINLINE()).AI_bonusVal(eNonObsoleteBonus);
if (bDoImprove)
{
eImprovement = (ImprovementTypes)GC.getBuildInfo(eBestTempBuild).getImprovement();
FAssert(eImprovement != NO_IMPROVEMENT);
//iValue += (GC.getImprovementInfo((ImprovementTypes) GC.getBuildInfo(eBestTempBuild).getImprovement()))
iValue += 5 * pLoopPlot->calculateImprovementYieldChange(eImprovement, YIELD_FOOD, getOwnerINLINE(), false);
iValue += 5 * pLoopPlot->calculateNatureYield(YIELD_FOOD, getTeam(), (pLoopPlot->getFeatureType() == NO_FEATURE) ? true : GC.getBuildInfo(eBestTempBuild).isFeatureRemove(pLoopPlot->getFeatureType()));
}
iValue += std::max(0, 100 * GC.getBonusInfo(eNonObsoleteBonus).getAIObjective());
if (GET_PLAYER(getOwnerINLINE()).getNumTradeableBonuses(eNonObsoleteBonus) == 0)
{
iValue *= 2;
}
int iMaxWorkers = 1;
if ((eBestTempBuild != NO_BUILD) && (!GC.getBuildInfo(eBestTempBuild).isKill()))
{
//allow teaming.
iMaxWorkers = AI_calculatePlotWorkersNeeded(pLoopPlot, eBestTempBuild);
if (getPathLastNode()->m_iData1 == 0)
{
iMaxWorkers = std::min((iMaxWorkers + 1) / 2, 1 + GET_PLAYER(getOwnerINLINE()).AI_baseBonusVal(eNonObsoleteBonus) / 20);
}
}
if ((GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BUILD, getGroup()) < iMaxWorkers)
&& (!bDoImprove || (pLoopPlot->getBuildTurnsLeft(eBestTempBuild, 0, 0) > (iPathTurns * 2 - 1))))
{
if (bDoImprove)
{
iValue *= 1000;
if (atPlot(pLoopPlot))
{
iValue *= 3;
}
iValue /= (iPathTurns + 1);
if (pLoopPlot->isCityRadius())
{
iValue *= 2;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuild = eBestTempBuild;
pBestPlot = pLoopPlot;
bBestBuildIsRoute = false;
iBestResourceValue = iValue;
}
}
else
{
FAssert(bCanRoute && !bIsConnected);
eImprovement = pLoopPlot->getImprovementType();
if ((eImprovement != NO_IMPROVEMENT) && (GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus)))
{
iValue *= 1000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuild = NO_BUILD;
pBestPlot = pLoopPlot;
bBestBuildIsRoute = true;
}
}
}
}
}
}
}
}
}
}
}
if ((iBestValue < iMinValue) && (NULL != ppBestPlot))
{
FAssert(NULL != peBestBuild);
FAssert(NULL != piBestValue);
*ppBestPlot = pBestPlot;
*peBestBuild = eBestBuild;
*piBestValue = iBestResourceValue;
}
if (pBestPlot != NULL)
{
if (eBestBuild != NO_BUILD)
{
FAssertMsg(!bBestBuildIsRoute, "BestBuild should not be a route");
FAssertMsg(eBestBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
MissionTypes eBestMission = MISSION_MOVE_TO;
if ((pBestPlot->getWorkingCity() == NULL) || !pBestPlot->getWorkingCity()->isConnectedToCapital())
{
eBestMission = MISSION_ROUTE_TO;
}
else
{
int iDistance = stepDistance(getX_INLINE(), getY_INLINE(), pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
int iPathTurns;
if (generatePath(pBestPlot, 0, false, &iPathTurns))
{
if (iPathTurns >= iDistance)
{
eBestMission = MISSION_ROUTE_TO;
}
}
}
eBestBuild = AI_betterPlotBuild(pBestPlot, eBestBuild);
getGroup()->pushMission(eBestMission, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pBestPlot);
getGroup()->pushMission(MISSION_BUILD, eBestBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pBestPlot);
return true;
}
else if (bBestBuildIsRoute)
{
if (AI_connectPlot(pBestPlot))
{
return true;
}
/*else
{
// the plot may be connected, but not connected to capital, if capital is not on same area, or if civ has no capital (like barbarians)
FAssertMsg(false, "Expected that a route could be built to eBestPlot");
}*/
}
else
{
FAssert(false);
}
}
return false;
}
//returns true if a mission is pushed
//if eBuild is NO_BUILD, assumes a route is desired.
bool CvUnitAI::AI_improvePlot(CvPlot* pPlot, BuildTypes eBuild)
{
FAssert(pPlot != NULL);
if (eBuild != NO_BUILD)
{
FAssertMsg(eBuild < GC.getNumBuildInfos(), "BestBuild is assigned a corrupt value");
eBuild = AI_betterPlotBuild(pPlot, eBuild);
if (!atPlot(pPlot))
{
getGroup()->pushMission(MISSION_MOVE_TO, pPlot->getX_INLINE(), pPlot->getY_INLINE(), 0, false, false, MISSIONAI_BUILD, pPlot);
}
getGroup()->pushMission(MISSION_BUILD, eBuild, -1, 0, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pPlot);
return true;
}
else if (canBuildRoute())
{
if (AI_connectPlot(pPlot))
{
return true;
}
}
return false;
}
BuildTypes CvUnitAI::AI_betterPlotBuild(CvPlot* pPlot, BuildTypes eBuild)
{
FAssert(pPlot != NULL);
FAssert(eBuild != NO_BUILD);
bool bBuildRoute = false;
bool bClearFeature = false;
FeatureTypes eFeature = pPlot->getFeatureType();
CvBuildInfo& kOriginalBuildInfo = GC.getBuildInfo(eBuild);
if (kOriginalBuildInfo.getRoute() != NO_ROUTE)
{
return eBuild;
}
int iWorkersNeeded = AI_calculatePlotWorkersNeeded(pPlot, eBuild);
/********************************************************************************/
/* BETTER_BTS_AI_MOD 7/31/08 jdog5000 */
/* */
/* Bugfix */
/********************************************************************************/
//if ((pPlot->getBonusType() == NO_BONUS) && (pPlot->getWorkingCity() != NULL))
if ((pPlot->getNonObsoleteBonusType(getTeam()) == NO_BONUS) && (pPlot->getWorkingCity() != NULL))
{
iWorkersNeeded = std::max(1, std::min(iWorkersNeeded, pPlot->getWorkingCity()->AI_getWorkersHave()));
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (eFeature != NO_FEATURE)
{
CvFeatureInfo& kFeatureInfo = GC.getFeatureInfo(eFeature);
if (kOriginalBuildInfo.isFeatureRemove(eFeature))
{
if ((kOriginalBuildInfo.getImprovement() == NO_IMPROVEMENT) || (!pPlot->isBeingWorked() || (kFeatureInfo.getYieldChange(YIELD_FOOD) + kFeatureInfo.getYieldChange(YIELD_PRODUCTION)) <= 0))
{
bClearFeature = true;
}
}
if ((kFeatureInfo.getMovementCost() > 1) && (iWorkersNeeded > 1))
{
bBuildRoute = true;
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 7/31/08 jdog5000 */
/* */
/* Bugfix */
/********************************************************************************/
//if (pPlot->getBonusType() != NO_BONUS)
if (pPlot->getNonObsoleteBonusType(getTeam()) != NO_BONUS)
{
bBuildRoute = true;
}
else if (pPlot->isHills())
{
if ((GC.getHILLS_EXTRA_MOVEMENT() > 0) && (iWorkersNeeded > 1))
{
bBuildRoute = true;
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (pPlot->getRouteType() != NO_ROUTE)
{
bBuildRoute = false;
}
BuildTypes eBestBuild = NO_BUILD;
int iBestValue = 0;
for (int iBuild = 0; iBuild < GC.getNumBuildInfos(); iBuild++)
{
BuildTypes eBuild = ((BuildTypes)iBuild);
CvBuildInfo& kBuildInfo = GC.getBuildInfo(eBuild);
RouteTypes eRoute = (RouteTypes)kBuildInfo.getRoute();
if ((bBuildRoute && (eRoute != NO_ROUTE)) || (bClearFeature && kBuildInfo.isFeatureRemove(eFeature)))
{
if (canBuild(pPlot, eBuild))
{
int iValue = 10000;
if (bBuildRoute && (eRoute != NO_ROUTE))
{
iValue *= (1 + GC.getRouteInfo(eRoute).getValue());
iValue /= 2;
/********************************************************************************/
/* BETTER_BTS_AI_MOD 7/31/08 jdog5000 */
/* */
/* Bugfix */
/********************************************************************************/
//if if (pPlot->getBonusType() != NO_BONUS)
if (pPlot->getNonObsoleteBonusType(getTeam()) != NO_BONUS)
{
iValue *= 2;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (pPlot->getWorkingCity() != NULL)
{
iValue *= 2 + iWorkersNeeded + ((pPlot->isHills() && (iWorkersNeeded > 1)) ? 2 * GC.getHILLS_EXTRA_MOVEMENT() : 0);
iValue /= 3;
}
ImprovementTypes eImprovement = (ImprovementTypes)kOriginalBuildInfo.getImprovement();
if (eImprovement != NO_IMPROVEMENT)
{
int iRouteMultiplier = ((GC.getImprovementInfo(eImprovement).getRouteYieldChanges(eRoute, YIELD_FOOD)) * 100);
iRouteMultiplier += ((GC.getImprovementInfo(eImprovement).getRouteYieldChanges(eRoute, YIELD_PRODUCTION)) * 100);
iRouteMultiplier += ((GC.getImprovementInfo(eImprovement).getRouteYieldChanges(eRoute, YIELD_COMMERCE)) * 60);
iValue *= 100 + iRouteMultiplier;
iValue /= 100;
}
int iPlotGroupId = -1;
for (int iDirection = 0; iDirection < NUM_DIRECTION_TYPES; iDirection++)
{
CvPlot* pLoopPlot = plotDirection(pPlot->getX_INLINE(), pPlot->getY_INLINE(), (DirectionTypes)iDirection);
if (pLoopPlot != NULL)
{
if (pPlot->isRiver() || (pLoopPlot->getRouteType() != NO_ROUTE))
{
CvPlotGroup* pLoopGroup = pLoopPlot->getPlotGroup(getOwnerINLINE());
if (pLoopGroup != NULL)
{
if (pLoopGroup->getID() != -1)
{
if (pLoopGroup->getID() != iPlotGroupId)
{
//This plot bridges plot groups, so route it.
iValue *= 4;
break;
}
else
{
iPlotGroupId = pLoopGroup->getID();
}
}
}
}
}
}
}
iValue /= (kBuildInfo.getTime() + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestBuild = eBuild;
}
}
}
}
if (eBestBuild == NO_BUILD)
{
return eBuild;
}
return eBestBuild;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_connectBonus(bool bTestTrade)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
BonusTypes eNonObsoleteBonus;
int iI;
// XXX how do we make sure that we can build roads???
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE()) // XXX team???
{
eNonObsoleteBonus = pLoopPlot->getNonObsoleteBonusType(getTeam());
if (eNonObsoleteBonus != NO_BONUS)
{
if (!(pLoopPlot->isConnectedToCapital()))
{
if (!bTestTrade || ((pLoopPlot->getImprovementType() != NO_IMPROVEMENT) && (GC.getImprovementInfo(pLoopPlot->getImprovementType()).isImprovementBonusTrade(eNonObsoleteBonus))))
{
if (AI_connectPlot(pLoopPlot))
{
return true;
}
}
}
}
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_connectCity()
{
PROFILE_FUNC();
CvCity* pLoopCity;
int iLoop;
// XXX how do we make sure that we can build roads???
pLoopCity = plot()->getWorkingCity();
if (pLoopCity != NULL)
{
if (AI_plotValid(pLoopCity->plot()))
{
if (!(pLoopCity->isConnectedToCapital()))
{
if (AI_connectPlot(pLoopCity->plot(), 1))
{
return true;
}
}
}
}
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
if (!(pLoopCity->isConnectedToCapital()))
{
if (AI_connectPlot(pLoopCity->plot(), 1))
{
return true;
}
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_routeCity()
{
PROFILE_FUNC();
CvCity* pRouteToCity;
CvCity* pLoopCity;
int iLoop;
FAssert(canBuildRoute());
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units before generating path
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
pRouteToCity = pLoopCity->AI_getRouteToCity();
if (pRouteToCity != NULL)
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (!(pRouteToCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pRouteToCity->plot(), MISSIONAI_BUILD, getGroup()) == 0)
{
if (generatePath(pLoopCity->plot(), MOVE_SAFE_TERRITORY, true))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (generatePath(pRouteToCity->plot(), MOVE_SAFE_TERRITORY, true))
{
getGroup()->pushMission(MISSION_ROUTE_TO, pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_BUILD, pRouteToCity->plot());
getGroup()->pushMission(MISSION_ROUTE_TO, pRouteToCity->getX_INLINE(), pRouteToCity->getY_INLINE(), MOVE_SAFE_TERRITORY, (getGroup()->getLengthMissionQueue() > 0), false, MISSIONAI_BUILD, pRouteToCity->plot());
return true;
}
}
}
}
}
}
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_routeTerritory(bool bImprovementOnly)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
ImprovementTypes eImprovement;
RouteTypes eBestRoute;
bool bValid;
int iPathTurns;
int iValue;
int iBestValue;
int iI, iJ;
// XXX how do we make sure that we can build roads???
FAssert(canBuildRoute());
iBestValue = 0;
pBestPlot = NULL;
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->getOwnerINLINE() == getOwnerINLINE()) // XXX team???
{
eBestRoute = GET_PLAYER(getOwnerINLINE()).getBestRoute(pLoopPlot);
if (eBestRoute != NO_ROUTE)
{
if (eBestRoute != pLoopPlot->getRouteType())
{
if (bImprovementOnly)
{
bValid = false;
eImprovement = pLoopPlot->getImprovementType();
if (eImprovement != NO_IMPROVEMENT)
{
for (iJ = 0; iJ < NUM_YIELD_TYPES; iJ++)
{
if (GC.getImprovementInfo(eImprovement).getRouteYieldChanges(eBestRoute, iJ) > 0)
{
bValid = true;
break;
}
}
}
}
else
{
bValid = true;
}
if (bValid)
{
if (!(pLoopPlot->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_BUILD, getGroup(), 1) == 0)
{
if (generatePath(pLoopPlot, MOVE_SAFE_TERRITORY, true, &iPathTurns))
{
iValue = 10000;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_ROUTE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_SAFE_TERRITORY, false, false, MISSIONAI_BUILD, pBestPlot);
return true;
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_travelToUpgradeCity()
{
PROFILE_FUNC();
// is there a city which can upgrade us?
CvCity* pUpgradeCity = getUpgradeCity(/*bSearch*/ true);
if (pUpgradeCity != NULL)
{
// cache some stuff
CvPlot* pPlot = plot();
bool bSeaUnit = (getDomainType() == DOMAIN_SEA);
bool bCanAirliftUnit = (getDomainType() == DOMAIN_LAND);
bool bShouldSkipToUpgrade = (getDomainType() != DOMAIN_AIR);
// if we at the upgrade city, stop, wait to get upgraded
if (pUpgradeCity->plot() == pPlot)
{
if (!bShouldSkipToUpgrade)
{
return false;
}
getGroup()->pushMission(MISSION_SKIP);
return true;
}
if (DOMAIN_AIR == getDomainType())
{
FAssert(!atPlot(pUpgradeCity->plot()));
getGroup()->pushMission(MISSION_MOVE_TO, pUpgradeCity->getX_INLINE(), pUpgradeCity->getY_INLINE());
return true;
}
// find the closest city
CvCity* pClosestCity = pPlot->getPlotCity();
bool bAtClosestCity = (pClosestCity != NULL);
if (pClosestCity == NULL)
{
pClosestCity = pPlot->getWorkingCity();
}
if (pClosestCity == NULL)
{
pClosestCity = GC.getMapINLINE().findCity(getX_INLINE(), getY_INLINE(), NO_PLAYER, getTeam(), true, bSeaUnit);
}
// can we path to the upgrade city?
int iUpgradeCityPathTurns;
CvPlot* pThisTurnPlot = NULL;
bool bCanPathToUpgradeCity = generatePath(pUpgradeCity->plot(), 0, true, &iUpgradeCityPathTurns);
if (bCanPathToUpgradeCity)
{
pThisTurnPlot = getPathEndTurnPlot();
}
// if we close to upgrade city, head there
if (NULL != pThisTurnPlot && NULL != pClosestCity && (pClosestCity == pUpgradeCity || iUpgradeCityPathTurns < 4))
{
FAssert(!atPlot(pThisTurnPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pThisTurnPlot->getX_INLINE(), pThisTurnPlot->getY_INLINE());
return true;
}
// check for better airlift choice
if (bCanAirliftUnit && NULL != pClosestCity && pClosestCity->getMaxAirlift() > 0)
{
// if we at the closest city, then do the airlift, or wait
if (bAtClosestCity)
{
// can we do the airlift this turn?
if (canAirliftAt(pClosestCity->plot(), pUpgradeCity->getX_INLINE(), pUpgradeCity->getY_INLINE()))
{
getGroup()->pushMission(MISSION_AIRLIFT, pUpgradeCity->getX_INLINE(), pUpgradeCity->getY_INLINE());
return true;
}
// wait to do it next turn
else
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
int iClosestCityPathTurns;
CvPlot* pThisTurnPlotForAirlift = NULL;
bool bCanPathToClosestCity = generatePath(pClosestCity->plot(), 0, true, &iClosestCityPathTurns);
if (bCanPathToClosestCity)
{
pThisTurnPlotForAirlift = getPathEndTurnPlot();
}
// is the closest city closer pathing? If so, move toward closest city
if (NULL != pThisTurnPlotForAirlift && (!bCanPathToUpgradeCity || iClosestCityPathTurns < iUpgradeCityPathTurns))
{
FAssert(!atPlot(pThisTurnPlotForAirlift));
getGroup()->pushMission(MISSION_MOVE_TO, pThisTurnPlotForAirlift->getX_INLINE(), pThisTurnPlotForAirlift->getY_INLINE());
return true;
}
}
// did not have better airlift choice, go ahead and path to the upgrade city
if (NULL != pThisTurnPlot)
{
FAssert(!atPlot(pThisTurnPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pThisTurnPlot->getX_INLINE(), pThisTurnPlot->getY_INLINE());
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_retreatToCity(bool bPrimary, bool bAirlift, int iMaxPath)
{
PROFILE_FUNC();
CvCity* pCity;
CvCity* pLoopCity;
CvPlot* pBestPlot = NULL;
int iPathTurns;
int iValue;
int iBestValue = MAX_INT;
int iPass;
int iLoop;
int iCurrentDanger = GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot());
pCity = plot()->getPlotCity();
if (0 == iCurrentDanger)
{
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (!bPrimary || GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pCity->area()))
{
if (!bAirlift || (pCity->getMaxAirlift() > 0))
{
if (!(pCity->plot()->isVisibleEnemyUnit(this)))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
}
}
}
}
for (iPass = 0; iPass < 4; iPass++)
{
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
if (!bPrimary || GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pLoopCity->area()))
{
if (!bAirlift || (pLoopCity->getMaxAirlift() > 0))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units before generating path
if( !bAirlift && (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), ((iPass > 1) ? MOVE_IGNORE_DANGER : 0), true, &iPathTurns))
{
if (iPathTurns <= ((iPass == 2) ? 1 : iMaxPath))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
if ((iPass > 0) || (getGroup()->canFight() || GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pLoopCity->plot()) < iCurrentDanger))
*/
// Water units can't defend a city
// Any unthreatened city acceptable on 0th pass, solves problem where sea units
// would oscillate in and out of threatened city because they had iCurrentDanger = 0
// on turns outside city
bool bCheck = (iPass > 0) || (getGroup()->canDefend());
if( !bCheck )
{
int iLoopDanger = GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pLoopCity->plot());
bCheck = (iLoopDanger == 0) || (iLoopDanger < iCurrentDanger
//Fuyu: try to avoid doomed cities
&& iLoopDanger < 2*(pLoopCity->plot()->getNumDefenders(getOwnerINLINE())) );
}
if( bCheck )
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
iValue = iPathTurns;
if (AI_getUnitAIType() == UNITAI_SETTLER_SEA)
{
iValue *= 1 + std::max(0, GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(pLoopCity->area(), UNITAI_SETTLE) - GET_PLAYER(getOwnerINLINE()).AI_totalAreaUnitAIs(pLoopCity->area(), UNITAI_SETTLER_SEA));
}
if (iValue < iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/27/08 jdog5000 */
/* */
/* Bugfix */
/************************************************************************************************/
// Not sure what can go wrong here, it seems somehow m_iData1 (moves) was set to 0
// for first node in path so m_iData2 (turns) incremented
if( atPlot(pBestPlot) )
{
//FAssert(false);
pBestPlot = getGroup()->getPathFirstPlot();
FAssert(!atPlot(pBestPlot));
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
break;
}
else if (iPass == 0)
{
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (!bPrimary || GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pCity->area()))
{
if (!bAirlift || (pCity->getMaxAirlift() > 0))
{
if (!(pCity->plot()->isVisibleEnemyUnit(this)))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
}
}
}
}
if (getGroup()->alwaysInvisible())
{
break;
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), ((iPass > 0) ? MOVE_IGNORE_DANGER : 0));
return true;
}
if (pCity != NULL)
{
if (pCity->getTeam() == getTeam())
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/15/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
bool CvUnitAI::AI_pickup(UnitAITypes eUnitAI)
*/
bool CvUnitAI::AI_pickup(UnitAITypes eUnitAI, bool bCountProduction, int iMaxPath)
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
PROFILE_FUNC();
CvCity* pCity;
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestPickupPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
FAssert(cargoSpace() > 0);
if (0 == cargoSpace())
{
return false;
}
pCity = plot()->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/23/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
/* original bts code
if (pCity->plot()->plotCount(PUF_isUnitAIType, eUnitAI, -1, getOwnerINLINE()) > 0)
{
if ((AI_getUnitAIType() != UNITAI_ASSAULT_SEA) || pCity->AI_isDefended(-1))
{
*/
if( (GC.getGameINLINE().getGameTurn() - pCity->getGameTurnAcquired()) > 15 || (GET_TEAM(getTeam()).countEnemyPowerByArea(pCity->area()) == 0) )
{
bool bConsider = false;
if(AI_getUnitAIType() == UNITAI_ASSAULT_SEA)
{
// Improve island hopping
if( pCity->area()->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE )
{
bConsider = false;
}
else if( eUnitAI == UNITAI_ATTACK_CITY && !(pCity->AI_isDanger()) )
{
bConsider = (pCity->plot()->plotCount(PUF_canDefend, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isDomainType, DOMAIN_LAND) > pCity->AI_neededDefenders());
}
else
{
bConsider = pCity->AI_isDefended(-1);
}
}
else if(AI_getUnitAIType() == UNITAI_SETTLER_SEA)
{
if( eUnitAI == UNITAI_CITY_DEFENSE )
{
bConsider = (pCity->plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isCityAIType) > 1);
}
else
{
bConsider = true;
}
}
else
{
bConsider = true;
}
if ( bConsider )
{
// only count units which are available to load
int iCount = pCity->plot()->plotCount(PUF_isAvailableUnitAITypeGroupie, eUnitAI, -1, getOwnerINLINE(), NO_TEAM, PUF_isFiniteRange);
if (bCountProduction && (pCity->getProductionUnitAI() == eUnitAI))
{
if( pCity->getProductionTurnsLeft() < 4 )
{
CvUnitInfo& kUnitInfo = GC.getUnitInfo(pCity->getProductionUnit());
if ((kUnitInfo.getDomainType() != DOMAIN_AIR) || kUnitInfo.getAirRange() > 0)
{
iCount++;
}
}
}
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCity->plot(), MISSIONAI_PICKUP, getGroup()) < ((iCount + (cargoSpace() - 1)) / cargoSpace()))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_PICKUP, pCity->plot());
return true;
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
iBestValue = 0;
pBestPlot = NULL;
pBestPickupPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 01/23/09 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
if( (GC.getGameINLINE().getGameTurn() - pLoopCity->getGameTurnAcquired()) > 15 || (GET_TEAM(getTeam()).countEnemyPowerByArea(pLoopCity->area()) == 0) )
{
bool bConsider = false;
if(AI_getUnitAIType() == UNITAI_ASSAULT_SEA)
{
if( pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE )
{
bConsider = false;
}
else if( eUnitAI == UNITAI_ATTACK_CITY && !(pLoopCity->AI_isDanger()) )
{
// Improve island hopping
bConsider = (pLoopCity->plot()->plotCount(PUF_canDefend, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isDomainType, DOMAIN_LAND) > pLoopCity->AI_neededDefenders());
}
else
{
bConsider = pLoopCity->AI_isDefended(-1);
}
}
else if(AI_getUnitAIType() == UNITAI_SETTLER_SEA)
{
if( eUnitAI == UNITAI_CITY_DEFENSE )
{
bConsider = (pLoopCity->plot()->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE(), NO_TEAM, PUF_isCityAIType) > 1);
}
else
{
bConsider = true;
}
}
else
{
bConsider = true;
}
if ( bConsider )
{
// only count units which are available to load, have had a chance to move since being built
int iCount = pLoopCity->plot()->plotCount(PUF_isAvailableUnitAITypeGroupie, eUnitAI, -1, getOwnerINLINE(), NO_TEAM, (bCountProduction ? PUF_isFiniteRange : PUF_isFiniteRangeAndNotJustProduced));
iValue = iCount * 10;
if (bCountProduction && (pLoopCity->getProductionUnitAI() == eUnitAI))
{
CvUnitInfo& kUnitInfo = GC.getUnitInfo(pLoopCity->getProductionUnit());
if ((kUnitInfo.getDomainType() != DOMAIN_AIR) || kUnitInfo.getAirRange() > 0)
{
iValue++;
iCount++;
}
}
if (iValue > 0)
{
iValue += pLoopCity->getPopulation();
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_PICKUP, getGroup()) < ((iCount + (cargoSpace() - 1)) / cargoSpace()))
{
if( !(pLoopCity->AI_isDanger()) )
{
if (!atPlot(pLoopCity->plot()) && generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
if( AI_getUnitAIType() == UNITAI_ASSAULT_SEA )
{
if( pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT )
{
iValue *= 4;
}
else if( pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT_ASSIST )
{
iValue *= 2;
}
}
iValue *= 1000;
iValue /= (iPathTurns + 3);
if( (iValue > iBestValue) && (iPathTurns <= iMaxPath) )
{
iBestValue = iValue;
// Do one turn along path, then reevaluate
// Causes update of destination based on troop movement
//pBestPlot = pLoopCity->plot();
pBestPlot = getPathEndTurnPlot();
pBestPickupPlot = pLoopCity->plot();
if( pBestPlot == NULL || atPlot(pBestPlot) )
{
//FAssert(false);
pBestPlot = pBestPickupPlot;
}
}
}
}
}
}
}
}
}
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if ((pBestPlot != NULL) && (pBestPickupPlot != NULL))
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_PICKUP, pBestPickupPlot);
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Naval AI */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_pickupStranded(UnitAITypes eUnitAI, int iMaxPath)
{
PROFILE_FUNC();
CvUnit* pBestUnit;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
int iCount;
FAssert(cargoSpace() > 0);
if (0 == cargoSpace())
{
return false;
}
if( isBarbarian() )
{
return false;
}
iBestValue = 0;
pBestUnit = NULL;
int iI;
CvSelectionGroup* pLoopGroup = NULL;
CvUnit* pHeadUnit = NULL;
CvPlot* pLoopPlot = NULL;
CvPlot* pPickupPlot = NULL;
CvPlot* pAdjacentPlot = NULL;
CvPlayerAI& kPlayer = GET_PLAYER(getOwnerINLINE());
for(pLoopGroup = kPlayer.firstSelectionGroup(&iLoop); pLoopGroup != NULL; pLoopGroup = kPlayer.nextSelectionGroup(&iLoop))
{
if( pLoopGroup->isStranded() )
{
pHeadUnit = pLoopGroup->getHeadUnit();
if( pHeadUnit == NULL )
{
continue;
}
if( (eUnitAI != NO_UNITAI) && (pHeadUnit->AI_getUnitAIType() != eUnitAI) )
{
continue;
}
pLoopPlot = pHeadUnit->plot();
if( pLoopPlot == NULL )
{
continue;
}
if( !(pLoopPlot->isCoastalLand()) && !canMoveAllTerrain() )
{
continue;
}
// Units are stranded, attempt rescue
iCount = pLoopGroup->getNumUnits();
if( 1000*iCount > iBestValue )
{
pPickupPlot = NULL;
if( atPlot(pLoopPlot) )
{
pPickupPlot = pLoopPlot;
iPathTurns = 0;
}
else if( AI_plotValid(pLoopPlot) && generatePath(pLoopPlot, 0, true, &iPathTurns) )
{
pPickupPlot = pLoopPlot;
}
else
{
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL && atPlot(pLoopPlot))
{
pPickupPlot = pAdjacentPlot;
iPathTurns = 0;
break;
}
}
if (pPickupPlot == NULL)
{
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL && AI_plotValid(pAdjacentPlot))
{
if( generatePath(pAdjacentPlot, 0, true, &iPathTurns) )
{
pPickupPlot = pAdjacentPlot;
break;
}
}
}
}
}
if( pPickupPlot != NULL && iPathTurns <= iMaxPath )
{
MissionAITypes eMissionAIType = MISSIONAI_PICKUP;
iCount -= GET_PLAYER(getOwnerINLINE()).AI_unitTargetMissionAIs(pHeadUnit, &eMissionAIType, 1, getGroup(), iPathTurns) * cargoSpace();
iValue = 1000*iCount;
iValue /= (iPathTurns + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestUnit = pHeadUnit;
}
}
}
}
}
if ((pBestUnit != NULL))
{
if( atPlot(pBestUnit->plot()) )
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_PICKUP, pBestUnit->plot());
return true;
}
else
{
FAssert(!atPlot(pBestUnit->plot()));
getGroup()->pushMission(MISSION_MOVE_TO_UNIT, pBestUnit->getOwnerINLINE(), pBestUnit->getID(), MOVE_AVOID_ENEMY_WEIGHT_3, false, false, MISSIONAI_PICKUP, NULL, pBestUnit);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_airOffensiveCity()
{
//PROFILE_FUNC();
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iI;
FAssert(canAirAttack() || nukeRange() >= 0);
iBestValue = 0;
pBestPlot = NULL;
/********************************************************************************/
/* BETTER_BTS_AI_MOD 04/25/08 jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
/* original BTS code
*/
for (iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
{
CvPlot* pLoopPlot = GC.getMapINLINE().plotByIndexINLINE(iI);
// Limit to cities and forts, true for any city but only this team's forts
if (pLoopPlot->isCity(true, getTeam()))
{
if (pLoopPlot->getTeam() == getTeam() || (pLoopPlot->isOwned() && GET_TEAM(pLoopPlot->getTeam()).isVassal(getTeam())))
{
if (atPlot(pLoopPlot) || canMoveInto(pLoopPlot))
{
iValue = AI_airOffenseBaseValue( pLoopPlot );
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
if (pBestPlot != NULL)
{
if (!atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_SAFE_TERRITORY);
return true;
}
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
return false;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 04/25/10 jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
// Function for ranking the value of a plot as a base for offensive air units
int CvUnitAI::AI_airOffenseBaseValue( CvPlot* pPlot )
{
if( pPlot == NULL || pPlot->area() == NULL )
{
return 0;
}
CvCity* pNearestEnemyCity = NULL;
int iRange = 0;
int iTempValue = 0;
int iOurDefense = 0;
int iOurOffense = 0;
int iEnemyOffense = 0;
int iEnemyDefense = 0;
int iDistance = 0;
CvPlot* pLoopPlot = NULL;
CvCity* pCity = pPlot->getPlotCity();
int iDefenders = pPlot->plotCount(PUF_canDefend, -1, -1, pPlot->getOwner());
int iAttackAirCount = pPlot->plotCount(PUF_canAirAttack, -1, -1, NO_PLAYER, getTeam());
iAttackAirCount += 2 * pPlot->plotCount(PUF_isUnitAIType, UNITAI_ICBM, -1, NO_PLAYER, getTeam());
if (atPlot(pPlot))
{
iAttackAirCount += canAirAttack() ? -1 : 0;
iAttackAirCount += (nukeRange() >= 0) ? -2 : 0;
}
if( pPlot->isCoastalLand(GC.getMIN_WATER_SIZE_FOR_OCEAN()) )
{
iDefenders -= 1;
}
if( pCity != NULL )
{
if( pCity->getDefenseModifier(true) < 40 )
{
iDefenders -= 1;
}
if( pCity->getOccupationTimer() > 1 )
{
iDefenders -= 1;
}
}
// Consider threat from nearby enemy territory
iRange = 1;
int iBorderDanger = 0;
for (int iDX = -(iRange); iDX <= iRange; iDX++)
{
for (int iDY = -(iRange); iDY <= iRange; iDY++)
{
pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (pLoopPlot->area() == pPlot->area() && pLoopPlot->isOwned())
{
iDistance = stepDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE());
if( pLoopPlot->getTeam() != getTeam() && !(GET_TEAM(pLoopPlot->getTeam()).isVassal(getTeam())) )
{
if( iDistance == 1 )
{
iBorderDanger++;
}
if (atWar(pLoopPlot->getTeam(), getTeam()))
{
if (iDistance == 1)
{
iBorderDanger += 2;
}
else if ((iDistance == 2) && (pLoopPlot->isRoute()))
{
iBorderDanger += 2;
}
}
}
}
}
}
}
iDefenders -= std::min(2,(iBorderDanger + 1)/3);
// Don't put more attack air units on plot than effective land defenders ... too large a risk
if (iAttackAirCount >= (iDefenders) || iDefenders <= 0)
{
return 0;
}
bool bAnyWar = (GET_TEAM(getTeam()).getAnyWarPlanCount(true) > 0);
int iValue = 0;
if( bAnyWar )
{
// Don't count assault assist, don't want to weight defending colonial coasts when homeland might be under attack
bool bAssault = (pPlot->area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT) || (pPlot->area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT_MASSING);
// Loop over operational range
iRange = airRange();
for (int iDX = -(iRange); iDX <= iRange; iDX++)
{
for (int iDY = -(iRange); iDY <= iRange; iDY++)
{
pLoopPlot = plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY);
if ((pLoopPlot != NULL && pLoopPlot->area() != NULL))
{
iDistance = plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE());
if( iDistance <= iRange )
{
bool bDefensive = pLoopPlot->area()->getAreaAIType(getTeam()) == AREAAI_DEFENSIVE;
bool bOffensive = pLoopPlot->area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE;
// Value system is based around 1 enemy military unit in our territory = 10 pts
iTempValue = 0;
if( pLoopPlot->isWater() )
{
if( pLoopPlot->isVisible(getTeam(),false) && !pLoopPlot->area()->isLake() )
{
// Defend ocean
iTempValue = 1;
if( pLoopPlot->isOwned() )
{
if( pLoopPlot->getTeam() == getTeam() )
{
iTempValue += 1;
}
else if ((pLoopPlot->getTeam() != getTeam()) && GET_TEAM(getTeam()).AI_getWarPlan(pLoopPlot->getTeam()) != NO_WARPLAN)
{
iTempValue += 1;
}
}
// Low weight for visible ships cause they will probably move
iTempValue += 2*pLoopPlot->getNumVisibleEnemyDefenders(this);
if( bAssault )
{
iTempValue *= 2;
}
}
}
else
{
if( !(pLoopPlot->isOwned()) )
{
if( iDistance < (iRange - 2) )
{
// Target enemy troops in neutral territory
iTempValue += 4*pLoopPlot->getNumVisibleEnemyDefenders(this);
}
}
else if( pLoopPlot->getTeam() == getTeam() )
{
iTempValue = 0;
if( iDistance < (iRange - 2) )
{
// Target enemy troops in our territory
iTempValue += 5*pLoopPlot->getNumVisibleEnemyDefenders(this);
if( pLoopPlot->getOwnerINLINE() == getOwnerINLINE() )
{
if( GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pLoopPlot->area()) )
{
iTempValue *= 3;
}
else
{
iTempValue *= 2;
}
}
if( bDefensive )
{
iTempValue *= 2;
}
}
}
else if ((pLoopPlot->getTeam() != getTeam()) && GET_TEAM(getTeam()).AI_getWarPlan(pLoopPlot->getTeam()) != NO_WARPLAN)
{
// Attack opponents land territory
iTempValue = 3;
CvCity* pLoopCity = pLoopPlot->getPlotCity();
if (pLoopCity != NULL)
{
// Target enemy cities
iTempValue += (3*pLoopCity->getPopulation() + 30);
if( canAirBomb(pPlot) && pLoopCity->isBombardable(this) )
{
iTempValue *= 2;
}
if( pLoopPlot->area()->getTargetCity(getOwnerINLINE()) == pLoopCity )
{
iTempValue *= 2;
}
if( pLoopCity->AI_isDanger() )
{
// Multiplier for nearby troops, ours, teammate's, and any other enemy of city
iTempValue *= 3;
}
}
else
{
if( iDistance < (iRange - 2) )
{
// Support our troops in enemy territory
iTempValue += 15*pLoopPlot->getNumDefenders(getOwnerINLINE());
// Target enemy troops adjacent to our territory
if( pLoopPlot->isAdjacentTeam(getTeam(),true) )
{
iTempValue += 7*pLoopPlot->getNumVisibleEnemyDefenders(this);
}
}
// Weight resources
if (canAirBombAt(pPlot, pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
if (pLoopPlot->getBonusType(getTeam()) != NO_BONUS)
{
iTempValue += 8*std::max(2, GET_PLAYER(pLoopPlot->getOwnerINLINE()).AI_bonusVal(pLoopPlot->getBonusType(getTeam()))/10);
}
}
}
if( (pLoopPlot->area()->getAreaAIType(getTeam()) == AREAAI_OFFENSIVE) )
{
// Extra weight for enemy territory in offensive areas
iTempValue *= 2;
}
if( GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pLoopPlot->area()) )
{
iTempValue *= 3;
iTempValue /= 2;
}
if( pLoopPlot->isBarbarian() )
{
iTempValue /= 2;
}
}
}
iValue += iTempValue;
}
}
}
}
// Consider available defense, direct threat to potential base
iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(pPlot,0,true,false,true);
iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(pPlot,2,false,false);
if( 3*iEnemyOffense > iOurDefense || iOurDefense == 0 )
{
iValue *= iOurDefense;
iValue /= std::max(1,3*iEnemyOffense);
}
// Value forts less, they are generally riskier bases
if( pCity == NULL )
{
iValue *= 2;
iValue /= 3;
}
}
else
{
if( pPlot->getOwnerINLINE() != getOwnerINLINE() )
{
// Keep planes at home when not in real wars
return 0;
}
// If no wars, use prior logic with added value to keeping planes safe from sneak attack
if (pCity != NULL)
{
iValue = (pCity->getPopulation() + 20);
iValue += pCity->AI_cityThreat();
}
else
{
if( iDefenders > 0 )
{
iValue = (pCity != NULL) ? 0 : GET_PLAYER(getOwnerINLINE()).AI_getPlotAirbaseValue(pPlot);
iValue /= 6;
}
}
iValue += std::min(24, 3*(iDefenders - iAttackAirCount));
if( GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pPlot->area()) )
{
iValue *= 4;
iValue /= 3;
}
// No real enemies, check for minor civ or barbarian cities where attacks could be supported
pNearestEnemyCity = GC.getMapINLINE().findCity(pPlot->getX_INLINE(), pPlot->getY_INLINE(), NO_PLAYER, NO_TEAM, false, false, getTeam());
if (pNearestEnemyCity != NULL)
{
iDistance = plotDistance(pPlot->getX_INLINE(), pPlot->getY_INLINE(), pNearestEnemyCity->getX_INLINE(), pNearestEnemyCity->getY_INLINE());
if (iDistance > airRange())
{
iValue /= 10 * (2 + airRange());
}
else
{
iValue /= 2 + iDistance;
}
}
}
if (pPlot->getOwnerINLINE() == getOwnerINLINE())
{
// Bases in our territory better than teammate's
iValue *= 2;
}
else if( pPlot->getTeam() == getTeam() )
{
// Our team's bases are better than vassal plots
iValue *= 3;
iValue /= 2;
}
return iValue;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_airDefensiveCity()
{
//PROFILE_FUNC();
CvCity* pCity;
CvCity* pLoopCity;
CvPlot* pBestPlot;
int iValue;
int iBestValue;
int iLoop;
FAssert(getDomainType() == DOMAIN_AIR);
FAssert(canAirDefend());
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/26/08 jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
if (canAirDefend() && getDamage() == 0)
{
pCity = plot()->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if ( !(pCity->AI_isAirDefended(false,+1)) )
{
// Stay if very short on planes, regardless of situation
getGroup()->pushMission(MISSION_AIRPATROL);
return true;
}
if( !(pCity->AI_isAirDefended(true,-1)) )
{
// Stay if city is threatened but not seriously threatened
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),2,false,false);
if (iEnemyOffense > 0)
{
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(plot(),0,true,false,true);
if( 3*iEnemyOffense < 4*iOurDefense )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return true;
}
}
}
}
}
}
iBestValue = 0;
pBestPlot = NULL;
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
if (canAirDefend(pLoopCity->plot()))
{
if (atPlot(pLoopCity->plot()) || canMoveInto(pLoopCity->plot()))
{
int iExistingAirDefenders = pLoopCity->plot()->plotCount(PUF_canAirDefend, -1, -1, pLoopCity->getOwnerINLINE(), NO_TEAM, PUF_isDomainType, DOMAIN_AIR);
if( atPlot(pLoopCity->plot()) )
{
iExistingAirDefenders -= 1;
}
int iNeedAirDefenders = pLoopCity->AI_neededAirDefenders();
if ( iNeedAirDefenders > iExistingAirDefenders )
{
iValue = pLoopCity->getPopulation() + pLoopCity->AI_cityThreat();
int iOurDefense = GET_TEAM(getTeam()).AI_getOurPlotStrength(pLoopCity->plot(),0,true,false,true);
int iEnemyOffense = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(pLoopCity->plot(),2,false,false);
iValue *= 100;
// Increase value of cities needing air defense more
iValue *= std::max(1, 3 + iNeedAirDefenders - iExistingAirDefenders);
if( GET_PLAYER(getOwnerINLINE()).AI_isPrimaryArea(pLoopCity->area()) )
{
iValue *= 4;
iValue /= 3;
}
// Reduce value of endangered city, it may be too late to help
if (3*iEnemyOffense > iOurDefense || iOurDefense == 0)
{
iValue *= iOurDefense;
iValue /= std::max(1,3*iEnemyOffense);
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
}
}
}
}
}
if (pBestPlot != NULL && !atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_airCarrier()
{
//PROFILE_FUNC();
CvUnit* pLoopUnit;
CvUnit* pBestUnit;
int iValue;
int iBestValue;
int iLoop;
if (getCargo() > 0)
{
return false;
}
if (isCargo())
{
if (canAirDefend())
{
getGroup()->pushMission(MISSION_AIRPATROL);
return true;
}
else
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
iBestValue = 0;
pBestUnit = NULL;
for(pLoopUnit = GET_PLAYER(getOwnerINLINE()).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER(getOwnerINLINE()).nextUnit(&iLoop))
{
if (canLoadUnit(pLoopUnit, pLoopUnit->plot()))
{
iValue = 10;
if (!(pLoopUnit->plot()->isCity()))
{
iValue += 20;
}
if (pLoopUnit->plot()->isOwned())
{
if (isEnemy(pLoopUnit->plot()->getTeam(), pLoopUnit->plot()))
{
iValue += 20;
}
}
else
{
iValue += 10;
}
iValue /= (pLoopUnit->getCargo() + 1);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestUnit = pLoopUnit;
}
}
}
if (pBestUnit != NULL)
{
if (atPlot(pBestUnit->plot()))
{
setTransportUnit(pBestUnit); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestUnit->getX_INLINE(), pBestUnit->getY_INLINE());
return true;
}
}
return false;
}
bool CvUnitAI::AI_missileLoad(UnitAITypes eTargetUnitAI, int iMaxOwnUnitAI, bool bStealthOnly)
{
//PROFILE_FUNC();
CvUnit* pBestUnit = NULL;
int iBestValue = 0;
int iLoop;
CvUnit* pLoopUnit;
for(pLoopUnit = GET_PLAYER(getOwnerINLINE()).firstUnit(&iLoop); pLoopUnit != NULL; pLoopUnit = GET_PLAYER(getOwnerINLINE()).nextUnit(&iLoop))
{
if (!bStealthOnly || pLoopUnit->getInvisibleType() != NO_INVISIBLE)
{
if (pLoopUnit->AI_getUnitAIType() == eTargetUnitAI)
{
if ((iMaxOwnUnitAI == -1) || (pLoopUnit->getUnitAICargo(AI_getUnitAIType()) <= iMaxOwnUnitAI))
{
if (canLoadUnit(pLoopUnit, pLoopUnit->plot()))
{
int iValue = 100;
iValue += GC.getGame().getSorenRandNum(100, "AI missile load");
iValue *= 1 + pLoopUnit->getCargo();
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestUnit = pLoopUnit;
}
}
}
}
}
}
if (pBestUnit != NULL)
{
if (atPlot(pBestUnit->plot()))
{
setTransportUnit(pBestUnit); // XXX is this dangerous (not pushing a mission...) XXX air units?
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestUnit->getX_INLINE(), pBestUnit->getY_INLINE());
setTransportUnit(pBestUnit);
return true;
}
}
return false;
}
// Returns true if a mission was pushed...
bool CvUnitAI::AI_airStrike()
{
//PROFILE_FUNC();
CvUnit* pDefender;
CvUnit* pInterceptor;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iDamage;
int iPotentialAttackers;
int iInterceptProb;
int iValue;
int iBestValue;
int iDX, iDY;
iSearchRange = airRange();
iBestValue = (isSuicide() && m_pUnitInfo->getProductionCost() > 0) ? (5 * m_pUnitInfo->getProductionCost()) / 6 : 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (canMoveInto(pLoopPlot, true))
{
iValue = 0;
iPotentialAttackers = GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pLoopPlot);
if (pLoopPlot->isCity())
{
iPotentialAttackers += GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopPlot, MISSIONAI_ASSAULT, getGroup(), 1) * 2;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 10/13/08 jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
/* original BTS code
if (pLoopPlot->isWater() || (iPotentialAttackers > 0) || pLoopPlot->isAdjacentTeam(getTeam()))
*/
// Bombers will always consider striking units adjacent to this team's territory
// to soften them up for potential attack. This situation doesn't apply if this team's adjacent
// territory is water, land units won't be able to reach easily for attack
if (pLoopPlot->isWater() || (iPotentialAttackers > 0) || pLoopPlot->isAdjacentTeam(getTeam(),true))
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
{
pDefender = pLoopPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true);
FAssert(pDefender != NULL);
FAssert(pDefender->canDefend());
// XXX factor in air defenses...
iDamage = airCombatDamage(pDefender);
iValue = std::max(0, (std::min((pDefender->getDamage() + iDamage), airCombatLimit()) - pDefender->getDamage()));
iValue += ((((iDamage * collateralDamage()) / 100) * std::min((pLoopPlot->getNumVisibleEnemyDefenders(this) - 1), collateralDamageMaxUnits())) / 2);
iValue *= (3 + iPotentialAttackers);
iValue /= 4;
pInterceptor = bestInterceptor(pLoopPlot);
if (pInterceptor != NULL)
{
iInterceptProb = isSuicide() ? 100 : pInterceptor->currInterceptionProbability();
iInterceptProb *= std::max(0, (100 - evasionProbability()));
iInterceptProb /= 100;
iValue *= std::max(0, 100 - iInterceptProb / 2);
iValue /= 100;
}
if (pLoopPlot->isWater())
{
iValue *= 3;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 9/16/08 jdog5000 */
/* */
/* Air AI */
/********************************************************************************/
// Air strike focused on weakening enemy stacks threatening our cities
// Returns true if a mission was pushed...
bool CvUnitAI::AI_defensiveAirStrike()
{
PROFILE_FUNC();
CvUnit* pDefender;
CvUnit* pInterceptor;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iDamage;
int iInterceptProb;
int iValue;
int iBestValue;
int iDX, iDY;
iSearchRange = airRange();
iBestValue = (isSuicide() && m_pUnitInfo->getProductionCost() > 0) ? (60 * m_pUnitInfo->getProductionCost()) : 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (canMoveInto(pLoopPlot, true)) // Only true of plots this unit can airstrike
{
// Only attack enemy land units near our cities
if( pLoopPlot->isPlayerCityRadius(getOwnerINLINE()) && !pLoopPlot->isWater() )
{
CvCity* pClosestCity = GC.getMapINLINE().findCity(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), getOwnerINLINE(), getTeam(), true, false);
if( pClosestCity != NULL )
{
// City and pLoopPlot forced to be in same area, check they're still close
int iStepDist = plotDistance(pClosestCity->getX_INLINE(), pClosestCity->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE());
if( iStepDist < 3 )
{
iValue = 0;
pDefender = pLoopPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true);
FAssert(pDefender != NULL);
FAssert(pDefender->canDefend());
iDamage = airCombatDamage(pDefender);
iValue = std::max(0, (std::min((pDefender->getDamage() + iDamage), airCombatLimit()) - pDefender->getDamage()));
iValue += ((((iDamage * collateralDamage()) / 100) * std::min((pLoopPlot->getNumVisibleEnemyDefenders(this) - 1), collateralDamageMaxUnits())) / 2);
iValue *= GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(pClosestCity->plot(),2,false,false);
iValue /= std::max(1, GET_TEAM(getTeam()).AI_getOurPlotStrength(pClosestCity->plot(),0,true,false,true));
if( iStepDist == 1 )
{
iValue *= 5;
iValue /= 4;
}
pInterceptor = bestInterceptor(pLoopPlot);
if (pInterceptor != NULL)
{
iInterceptProb = isSuicide() ? 100 : pInterceptor->currInterceptionProbability();
iInterceptProb *= std::max(0, (100 - evasionProbability()));
iInterceptProb /= 100;
iValue *= std::max(0, 100 - iInterceptProb / 2);
iValue /= 100;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
// Air strike around base city
// Returns true if a mission was pushed...
bool CvUnitAI::AI_defendBaseAirStrike()
{
PROFILE_FUNC();
CvUnit* pDefender;
CvUnit* pInterceptor;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iDamage;
int iInterceptProb;
int iValue;
int iBestValue;
int iDX, iDY;
// Only search around base
int iSearchRange = 2;
iBestValue = (isSuicide() && m_pUnitInfo->getProductionCost() > 0) ? (15 * m_pUnitInfo->getProductionCost()) : 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (canMoveInto(pLoopPlot, true) && !pLoopPlot->isWater()) // Only true of plots this unit can airstrike
{
if( plot()->area() == pLoopPlot->area() )
{
iValue = 0;
pDefender = pLoopPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, true);
FAssert(pDefender != NULL);
FAssert(pDefender->canDefend());
iDamage = airCombatDamage(pDefender);
iValue = std::max(0, (std::min((pDefender->getDamage() + iDamage), airCombatLimit()) - pDefender->getDamage()));
iValue += ((iDamage * collateralDamage()) * std::min((pLoopPlot->getNumVisibleEnemyDefenders(this) - 1), collateralDamageMaxUnits())) / (2*100);
// Weight towards stronger units
iValue *= (pDefender->currCombatStr(NULL,NULL,NULL) + 2000);
iValue /= 2000;
// Weight towards adjacent stacks
if( plotDistance(plot()->getX_INLINE(), plot()->getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()) == 1 )
{
iValue *= 5;
iValue /= 4;
}
pInterceptor = bestInterceptor(pLoopPlot);
if (pInterceptor != NULL)
{
iInterceptProb = isSuicide() ? 100 : pInterceptor->currInterceptionProbability();
iInterceptProb *= std::max(0, (100 - evasionProbability()));
iInterceptProb /= 100;
iValue *= std::max(0, 100 - iInterceptProb / 2);
iValue /= 100;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
bool CvUnitAI::AI_airBombPlots()
{
//PROFILE_FUNC();
CvUnit* pInterceptor;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iInterceptProb;
int iValue;
int iBestValue;
int iDX, iDY;
iSearchRange = airRange();
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (!pLoopPlot->isCity() && pLoopPlot->isOwned() && pLoopPlot != plot())
{
if (canAirBombAt(plot(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
iValue = 0;
if (pLoopPlot->getBonusType(pLoopPlot->getTeam()) != NO_BONUS)
{
iValue += AI_pillageValue(pLoopPlot, 15);
iValue += GC.getGameINLINE().getSorenRandNum(10, "AI Air Bomb");
}
else if (isSuicide())
{
//This should only be reached when the unit is desperate to die
iValue += AI_pillageValue(pLoopPlot);
// Guided missiles lean towards destroying resource-producing tiles as opposed to improvements like Towns
if (pLoopPlot->getBonusType(pLoopPlot->getTeam()) != NO_BONUS)
{
//and even more so if it's a resource
iValue += GET_PLAYER(pLoopPlot->getOwnerINLINE()).AI_bonusVal(pLoopPlot->getBonusType(pLoopPlot->getTeam()));
}
}
if (iValue > 0)
{
pInterceptor = bestInterceptor(pLoopPlot);
if (pInterceptor != NULL)
{
iInterceptProb = isSuicide() ? 100 : pInterceptor->currInterceptionProbability();
iInterceptProb *= std::max(0, (100 - evasionProbability()));
iInterceptProb /= 100;
iValue *= std::max(0, 100 - iInterceptProb / 2);
iValue /= 100;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRBOMB, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
bool CvUnitAI::AI_airBombDefenses()
{
//PROFILE_FUNC();
CvCity* pCity;
CvUnit* pInterceptor;
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPotentialAttackers;
int iInterceptProb;
int iValue;
int iBestValue;
int iDX, iDY;
iSearchRange = airRange();
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
pCity = pLoopPlot->getPlotCity();
if (pCity != NULL)
{
iValue = 0;
if (canAirBombAt(plot(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
iPotentialAttackers = GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pLoopPlot);
iPotentialAttackers += std::max(0, GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pCity->plot(), NO_MISSIONAI, getGroup(), 2) - 4);
if (iPotentialAttackers > 1)
{
iValue += std::max(0, (std::min((pCity->getDefenseDamage() + airBombCurrRate()), GC.getMAX_CITY_DEFENSE_DAMAGE()) - pCity->getDefenseDamage()));
iValue *= 4 + iPotentialAttackers;
if (pCity->AI_isDanger())
{
iValue *= 2;
}
if (pCity == pCity->area()->getTargetCity(getOwnerINLINE()))
{
iValue *= 2;
}
}
if (iValue > 0)
{
pInterceptor = bestInterceptor(pLoopPlot);
if (pInterceptor != NULL)
{
iInterceptProb = isSuicide() ? 100 : pInterceptor->currInterceptionProbability();
iInterceptProb *= std::max(0, (100 - evasionProbability()));
iInterceptProb /= 100;
iValue *= std::max(0, 100 - iInterceptProb / 2);
iValue /= 100;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_AIRBOMB, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
bool CvUnitAI::AI_exploreAir()
{
PROFILE_FUNC();
CvPlayer& kPlayer = GET_PLAYER(getOwnerINLINE());
int iLoop;
CvCity* pLoopCity;
CvPlot* pBestPlot = NULL;
int iBestValue = 0;
for (int iI = 0; iI < MAX_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive() && !GET_PLAYER((PlayerTypes)iI).isBarbarian())
{
if (GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam())
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if (!pLoopCity->isVisible(getTeam(), false))
{
if (canReconAt(plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
int iValue = 1 + GC.getGame().getSorenRandNum(15, "AI explore air");
if (isEnemy(GET_PLAYER((PlayerTypes)iI).getTeam()))
{
iValue += 10;
iValue += std::min(10, pLoopCity->area()->getNumAIUnits(getOwnerINLINE(), UNITAI_ATTACK_CITY));
iValue += 10 * kPlayer.AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_ASSAULT);
}
iValue *= plotDistance(getX_INLINE(), getY_INLINE(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE());
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_RECON, pBestPlot->getX(), pBestPlot->getY());
return true;
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 06/02/09 jdog5000 */
/* */
/* Player Interface */
/************************************************************************************************/
int CvUnitAI::AI_exploreAirPlotValue( CvPlot* pPlot )
{
int iValue = 0;
if (pPlot->isVisible(getTeam(), false))
{
iValue++;
if (!pPlot->isOwned())
{
iValue++;
}
if (!pPlot->isImpassable())
{
iValue *= 4;
if (pPlot->isWater() || pPlot->getArea() == getArea())
{
iValue *= 2;
}
}
}
return iValue;
}
bool CvUnitAI::AI_exploreAir2()
{
PROFILE_FUNC();
CvPlayer& kPlayer = GET_PLAYER(getOwner());
CvPlot* pLoopPlot = NULL;
CvPlot* pBestPlot = NULL;
int iBestValue = 0;
int iDX, iDY;
int iSearchRange = airRange();
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if( pLoopPlot != NULL )
{
if( !pLoopPlot->isVisible(getTeam(),false) )
{
if (canReconAt(plot(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
int iValue = AI_exploreAirPlotValue( pLoopPlot );
for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
DirectionTypes eDirection = (DirectionTypes) iI;
CvPlot* pAdjacentPlot = plotDirection(getX_INLINE(), getY_INLINE(), eDirection);
if (pAdjacentPlot != NULL)
{
if( !pAdjacentPlot->isVisible(getTeam(),false) )
{
iValue += AI_exploreAirPlotValue( pAdjacentPlot );
}
}
}
iValue += GC.getGame().getSorenRandNum(25, "AI explore air");
iValue *= std::min(7, plotDistance(getX_INLINE(), getY_INLINE(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()));
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_RECON, pBestPlot->getX(), pBestPlot->getY());
return true;
}
return false;
}
void CvUnitAI::AI_exploreAirMove()
{
if( AI_exploreAir() )
{
return;
}
if( AI_exploreAir2() )
{
return;
}
if( canAirDefend() )
{
getGroup()->pushMission(MISSION_AIRPATROL);
return;
}
getGroup()->pushMission(MISSION_SKIP);
return;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
// Returns true if a mission was pushed...
bool CvUnitAI::AI_nuke()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvCity* pBestCity;
int iValue;
int iBestValue;
int iLoop;
int iI;
pBestCity = NULL;
iBestValue = 0;
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive() && !GET_PLAYER((PlayerTypes)iI).isBarbarian())
{
if (isEnemy(GET_PLAYER((PlayerTypes)iI).getTeam()))
{
if (GET_PLAYER(getOwnerINLINE()).AI_getAttitude((PlayerTypes)iI) == ATTITUDE_FURIOUS)
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if (canNukeAt(plot(), pLoopCity->getX_INLINE(), pLoopCity->getY_INLINE()))
{
iValue = AI_nukeValue(pLoopCity);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestCity = pLoopCity;
FAssert(pBestCity->getTeam() != getTeam());
}
}
}
}
}
}
}
if (pBestCity != NULL)
{
getGroup()->pushMission(MISSION_NUKE, pBestCity->getX_INLINE(), pBestCity->getY_INLINE());
return true;
}
return false;
}
bool CvUnitAI::AI_nukeRange(int iRange)
{
CvPlot* pBestPlot = NULL;
int iBestValue = 0;
for (int iDX = -(iRange); iDX <= iRange; iDX++)
{
for (int iDY = -(iRange); iDY <= iRange; iDY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (canNukeAt(plot(), pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE()))
{
int iValue = -99;
for (int iDX2 = -(nukeRange()); iDX2 <= nukeRange(); iDX2++)
{
for (int iDY2 = -(nukeRange()); iDY2 <= nukeRange(); iDY2++)
{
CvPlot* pLoopPlot2 = plotXY(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), iDX2, iDY2);
if (pLoopPlot2 != NULL)
{
int iEnemyCount = 0;
int iTeamCount = 0;
int iNeutralCount = 0;
int iDamagedEnemyCount = 0;
CLLNode<IDInfo>* pUnitNode;
CvUnit* pLoopUnit;
pUnitNode = pLoopPlot2->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopPlot2->nextUnitNode(pUnitNode);
if (!pLoopUnit->isNukeImmune())
{
if (pLoopUnit->getTeam() == getTeam())
{
iTeamCount++;
}
else if (!pLoopUnit->isInvisible(getTeam(), false))
{
if (isEnemy(pLoopUnit->getTeam()))
{
iEnemyCount++;
if (pLoopUnit->getDamage() * 2 > pLoopUnit->maxHitPoints())
{
iDamagedEnemyCount++;
}
}
else
{
iNeutralCount++;
}
}
}
}
iValue += (iEnemyCount + iDamagedEnemyCount) * (pLoopPlot2->isWater() ? 25 : 12);
iValue -= iTeamCount * 15;
iValue -= iNeutralCount * 20;
int iMultiplier = 1;
if (pLoopPlot2->getTeam() == getTeam())
{
iMultiplier = -2;
}
else if (isEnemy(pLoopPlot2->getTeam()))
{
iMultiplier = 1;
}
else if (!pLoopPlot2->isOwned())
{
iMultiplier = 0;
}
else
{
iMultiplier = -10;
}
if (pLoopPlot2->getImprovementType() != NO_IMPROVEMENT)
{
iValue += iMultiplier * 10;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 7/31/08 jdog5000 */
/* */
/* Bugfix */
/********************************************************************************/
// This could also have been considered a minor AI cheat
//if (pLoopPlot2->getBonusType() != NO_BONUS)
if (pLoopPlot2->getNonObsoleteBonusType(getTeam()) != NO_BONUS)
{
iValue += iMultiplier * 20;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
if (pLoopPlot2->isCity())
{
iValue += std::max(0, iMultiplier * (-20 + 15 * pLoopPlot2->getPlotCity()->getPopulation()));
}
}
}
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
if (pBestPlot != NULL)
{
getGroup()->pushMission(MISSION_NUKE, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
bool CvUnitAI::AI_trade(int iValueThreshold)
{
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvPlot* pBestTradePlot;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
int iI;
iBestValue = 0;
pBestPlot = NULL;
pBestTradePlot = NULL;
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
if (GET_PLAYER((PlayerTypes)iI).isAlive())
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if (AI_plotValid(pLoopCity->plot()))
{
if (getTeam() != pLoopCity->getTeam())
{
iValue = getTradeGold(pLoopCity->plot());
if ((iValue >= iValueThreshold) && canTrade(pLoopCity->plot(), true))
{
if (!(pLoopCity->plot()->isVisibleEnemyUnit(this)))
{
if (generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
FAssert(iPathTurns > 0);
iValue /= (4 + iPathTurns);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
pBestTradePlot = pLoopCity->plot();
}
}
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestTradePlot != NULL))
{
if (atPlot(pBestTradePlot))
{
getGroup()->pushMission(MISSION_TRADE);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
}
return false;
}
bool CvUnitAI::AI_infiltrate()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
int iI;
iBestValue = 0;
pBestPlot = NULL;
if (canInfiltrate(plot()))
{
getGroup()->pushMission(MISSION_INFILTRATE);
return true;
}
for (iI = 0; iI < MAX_PLAYERS; iI++)
{
if ((GET_PLAYER((PlayerTypes)iI).isAlive()) && GET_PLAYER((PlayerTypes)iI).getTeam() != getTeam())
{
for (pLoopCity = GET_PLAYER((PlayerTypes)iI).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER((PlayerTypes)iI).nextCity(&iLoop))
{
if (canInfiltrate(pLoopCity->plot()))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check area for land units before generating path
if( (getDomainType() == DOMAIN_LAND) && (pLoopCity->area() != area()) && !(getGroup()->canMoveAllTerrain()) )
{
continue;
}
iValue = getEspionagePoints(pLoopCity->plot());
if (iValue > iBestValue)
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
if (generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
FAssert(iPathTurns > 0);
if (getPathLastNode()->m_iData1 == 0)
{
iPathTurns++;
}
iValue /= 1 + iPathTurns;
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopCity->plot();
}
}
}
}
}
}
}
if ((pBestPlot != NULL))
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_INFILTRATE);
return true;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
getGroup()->pushMission(MISSION_INFILTRATE, -1, -1, 0, (getGroup()->getLengthMissionQueue() > 0));
return true;
}
}
return false;
}
bool CvUnitAI::AI_reconSpy(int iRange)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
int iX, iY;
CvPlot* pBestPlot = NULL;
CvPlot* pBestTargetPlot = NULL;
int iBestValue = 0;
int iSearchRange = AI_searchRange(iRange);
for (iX = -iSearchRange; iX <= iSearchRange; iX++)
{
for (iY = -iSearchRange; iY <= iSearchRange; iY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iX, iY);
int iDistance = stepDistance(0, 0, iX, iY);
if ((iDistance > 0) && (pLoopPlot != NULL) && AI_plotValid(pLoopPlot))
{
int iValue = 0;
if (pLoopPlot->getPlotCity() != NULL)
{
iValue += GC.getGameINLINE().getSorenRandNum(4000, "AI Spy Scout City");
}
if (pLoopPlot->getBonusType(getTeam()) != NO_BONUS)
{
iValue += GC.getGameINLINE().getSorenRandNum(1000, "AI Spy Recon Bonus");
}
for (int iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
CvPlot* pAdjacentPlot = plotDirection(pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL)
{
if (!pAdjacentPlot->isRevealed(getTeam(), false))
{
iValue += 500;
}
else if (!pAdjacentPlot->isVisible(getTeam(), false))
{
iValue += 200;
}
}
}
if (iValue > 0)
{
int iPathTurns;
if (generatePath(pLoopPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= iRange)
{
// don't give each and every plot in range a value before generating the patch (performance hit)
iValue += GC.getGameINLINE().getSorenRandNum(250, "AI Spy Scout Best Plot");
iValue *= iDistance;
/* Can no longer perform missions after having moved
if (getPathLastNode()->m_iData2 == 1)
{
if (getPathLastNode()->m_iData1 > 0)
{
//Prefer to move and have movement remaining to perform a kill action.
iValue *= 2;
}
} */
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestTargetPlot = getPathEndTurnPlot();
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
if ((pBestPlot != NULL) && (pBestTargetPlot != NULL))
{
if (atPlot(pBestTargetPlot))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestTargetPlot->getX_INLINE(), pBestTargetPlot->getY_INLINE());
getGroup()->pushMission(MISSION_SKIP);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 10/25/09 jdog5000 */
/* */
/* Espionage AI */
/************************************************************************************************/
/// \brief Spy decision on whether to cause revolt in besieged city
///
/// Have spy breakdown city defenses if we have troops in position to capture city this turn.
bool CvUnitAI::AI_revoltCitySpy()
{
PROFILE_FUNC();
CvCity* pCity = plot()->getPlotCity();
FAssert(pCity != NULL);
if( pCity == NULL )
{
return false;
}
if( !(GET_TEAM(getTeam()).isAtWar(pCity->getTeam())) )
{
return false;
}
if( pCity->isDisorder() )
{
return false;
}
int iOurPower = GET_PLAYER(getOwnerINLINE()).AI_getOurPlotStrength(plot(),1,false,true);
int iEnemyDefensePower = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),0,true,false);
int iEnemyPostPower = GET_PLAYER(getOwnerINLINE()).AI_getEnemyPlotStrength(plot(),0,false,false);
if( iOurPower > 2*iEnemyDefensePower )
{
return false;
}
if( iOurPower < iEnemyPostPower )
{
return false;
}
if( 10*iEnemyDefensePower < 11*iEnemyPostPower )
{
return false;
}
for (int iMission = 0; iMission < GC.getNumEspionageMissionInfos(); ++iMission)
{
CvEspionageMissionInfo& kMissionInfo = GC.getEspionageMissionInfo((EspionageMissionTypes)iMission);
if ((kMissionInfo.getCityRevoltCounter() > 0) || (kMissionInfo.getPlayerAnarchyCounter() > 0))
{
if (!GET_PLAYER(getOwnerINLINE()).canDoEspionageMission((EspionageMissionTypes)iMission, pCity->getOwnerINLINE(), pCity->plot(), -1, this))
{
continue;
}
if (!espionage((EspionageMissionTypes)iMission, -1))
{
continue;
}
return true;
}
}
return false;
}
int CvUnitAI::AI_getEspionageTargetValue(CvPlot* pPlot, int iMaxPath)
{
PROFILE_FUNC();
CvTeamAI& kTeam = GET_TEAM(getTeam());
int iValue = 0;
if (pPlot->isOwned() && pPlot->getTeam() != getTeam() && !GET_TEAM(getTeam()).isVassal(pPlot->getTeam()))
{
if (AI_plotValid(pPlot))
{
CvCity* pCity = pPlot->getPlotCity();
if (pCity != NULL)
{
iValue += pCity->getPopulation();
iValue += pCity->plot()->calculateCulturePercent(getOwnerINLINE())/8;
// BBAI TODO: Should go to cities where missions will be cheaper ...
int iRand = GC.getGame().getSorenRandNum(6, "AI spy choose city");
iValue += iRand * iRand;
if( area()->getTargetCity(getOwnerINLINE()) == pCity )
{
iValue += 30;
}
if( GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pPlot, MISSIONAI_ASSAULT, getGroup()) > 0 )
{
iValue += 30;
}
// BBAI TODO: What else? If can see production, go for wonders and space race ...
}
else
{
BonusTypes eBonus = pPlot->getNonObsoleteBonusType(getTeam());
if (eBonus != NO_BONUS)
{
iValue += GET_PLAYER(pPlot->getOwnerINLINE()).AI_baseBonusVal(eBonus) - 10;
}
}
int iPathTurns;
if (generatePath(pPlot, 0, true, &iPathTurns))
{
if (iPathTurns <= iMaxPath)
{
if (kTeam.AI_getWarPlan(pPlot->getTeam()) == NO_WARPLAN)
{
iValue *= 1;
}
else if (kTeam.AI_isSneakAttackPreparing(pPlot->getTeam()))
{
iValue *= (pPlot->isCity()) ? 15 : 10;
}
else
{
iValue *= 3;
}
iValue *= 3;
iValue /= (3 + GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pPlot, MISSIONAI_ATTACK_SPY, getGroup()));
}
}
}
}
return iValue;
}
bool CvUnitAI::AI_cityOffenseSpy(int iMaxPath, CvCity* pSkipCity)
{
PROFILE_FUNC();
int iBestValue = 0;
CvPlot* pBestPlot = NULL;
for (int iPlayer = 0; iPlayer < MAX_CIV_PLAYERS; ++iPlayer)
{
CvPlayer& kLoopPlayer = GET_PLAYER((PlayerTypes)iPlayer);
if (kLoopPlayer.isAlive() && kLoopPlayer.getTeam() != getTeam() && !GET_TEAM(getTeam()).isVassal(kLoopPlayer.getTeam()))
{
// Only move to cities where we will run missions
if (GET_PLAYER(getOwnerINLINE()).AI_getAttitudeWeight((PlayerTypes)iPlayer) < (GC.getGameINLINE().isOption(GAMEOPTION_AGGRESSIVE_AI) ? 51 : 1)
|| GET_TEAM(getTeam()).AI_getWarPlan(kLoopPlayer.getTeam()) != NO_WARPLAN
|| GET_TEAM(getTeam()).getBestKnownTechScorePercent() < 85 )
{
int iLoop;
for (CvCity* pLoopCity = kLoopPlayer.firstCity(&iLoop); NULL != pLoopCity; pLoopCity = kLoopPlayer.nextCity(&iLoop))
{
if( pLoopCity == pSkipCity )
{
continue;
}
if (pLoopCity->area() == area() || canMoveAllTerrain())
{
CvPlot* pLoopPlot = pLoopCity->plot();
if (AI_plotValid(pLoopPlot))
{
int iValue = AI_getEspionageTargetValue(pLoopPlot, iMaxPath);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY );
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
}
return true;
}
return false;
}
bool CvUnitAI::AI_bonusOffenseSpy(int iRange)
{
PROFILE_FUNC();
CvPlot* pBestPlot = NULL;
int iBestValue = 10;
int iSearchRange = AI_searchRange(iRange);
for (int iX = -iSearchRange; iX <= iSearchRange; iX++)
{
for (int iY = -iSearchRange; iY <= iSearchRange; iY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iX, iY);
if (NULL != pLoopPlot && pLoopPlot->getBonusType(getTeam()) != NO_BONUS)
{
if( pLoopPlot->isOwned() && pLoopPlot->getTeam() != getTeam() )
{
// Only move to plots where we will run missions
if (GET_PLAYER(getOwnerINLINE()).AI_getAttitudeWeight(pLoopPlot->getOwner()) < (GC.getGameINLINE().isOption(GAMEOPTION_AGGRESSIVE_AI) ? 51 : 1)
|| GET_TEAM(getTeam()).AI_getWarPlan(pLoopPlot->getTeam()) != NO_WARPLAN )
{
int iValue = AI_getEspionageTargetValue(pLoopPlot, iRange);
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = pLoopPlot;
}
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), 0, false, false, MISSIONAI_ATTACK_SPY);
getGroup()->pushMission(MISSION_SKIP, -1, -1, 0, false, false, MISSIONAI_ATTACK_SPY);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
//Returns true if the spy performs espionage.
bool CvUnitAI::AI_espionageSpy()
{
PROFILE_FUNC();
if (!canEspionage(plot()))
{
return false;
}
EspionageMissionTypes eBestMission = NO_ESPIONAGEMISSION;
CvPlot* pTargetPlot = NULL;
PlayerTypes eTargetPlayer = NO_PLAYER;
int iExtraData = -1;
eBestMission = GET_PLAYER(getOwnerINLINE()).AI_bestPlotEspionage(plot(), eTargetPlayer, pTargetPlot, iExtraData);
if (NO_ESPIONAGEMISSION == eBestMission)
{
return false;
}
if (!GET_PLAYER(getOwnerINLINE()).canDoEspionageMission(eBestMission, eTargetPlayer, pTargetPlot, iExtraData, this))
{
return false;
}
if (!espionage(eBestMission, iExtraData))
{
return false;
}
return true;
}
bool CvUnitAI::AI_moveToStagingCity()
{
PROFILE_FUNC();
CvCity* pLoopCity;
CvPlot* pBestPlot;
int iPathTurns;
int iValue;
int iBestValue;
int iLoop;
iBestValue = 0;
pBestPlot = NULL;
int iWarCount = 0;
TeamTypes eTargetTeam = NO_TEAM;
CvTeam& kTeam = GET_TEAM(getTeam());
for (int iI = 0; iI < MAX_TEAMS; iI++)
{
if ((iI != getTeam()) && GET_TEAM((TeamTypes)iI).isAlive())
{
if (kTeam.AI_isSneakAttackPreparing((TeamTypes)iI))
{
eTargetTeam = (TeamTypes)iI;
iWarCount++;
}
}
}
if (iWarCount > 1)
{
eTargetTeam = NO_TEAM;
}
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/22/10 jdog5000 */
/* */
/* War tactics AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if ((pLoopCity->area() == area()) && AI_plotValid(pLoopCity->plot()))
{
// BBAI TODO: Need some knowledge of whether this is a good city to attack from ... only get that
// indirectly from threat.
iValue = pLoopCity->AI_cityThreat();
// Have attack stacks in assault areas move to coastal cities for faster loading
if( (area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT) || (area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT_MASSING) )
{
CvArea* pWaterArea = pLoopCity->waterArea();
if( pWaterArea != NULL && GET_TEAM(getTeam()).AI_isWaterAreaRelevant(pWaterArea) )
{
// BBAI TODO: Need a better way to determine which cities should serve as invasion launch locations
// Inertia so units don't just chase transports around the map
iValue = iValue/2;
if( pLoopCity->area()->getAreaAIType(getTeam()) == AREAAI_ASSAULT )
{
// If in assault, transports may be at sea ... tend to stay where they left from
// to speed reinforcement
iValue += pLoopCity->plot()->plotCount(PUF_isAvailableUnitAITypeGroupie, UNITAI_ATTACK_CITY, -1, getOwnerINLINE());
}
// Attraction to cities which are serving as launch/pickup points
iValue += 3*pLoopCity->plot()->plotCount(PUF_isUnitAIType, UNITAI_ASSAULT_SEA, -1, getOwnerINLINE());
iValue += 2*pLoopCity->plot()->plotCount(PUF_isUnitAIType, UNITAI_ESCORT_SEA, -1, getOwnerINLINE());
iValue += 5*GET_PLAYER(getOwnerINLINE()).AI_plotTargetMissionAIs(pLoopCity->plot(), MISSIONAI_PICKUP);
}
else
{
iValue = iValue/8;
}
}
if (iValue*200 > iBestValue)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
if (generatePath(pLoopCity->plot(), 0, true, &iPathTurns))
{
iValue *= 1000;
iValue /= (5 + iPathTurns);
if ((pLoopCity->plot() != plot()) && pLoopCity->isVisible(eTargetTeam, false))
{
iValue /= 2;
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
}
return false;
}
/*
bool CvUnitAI::AI_seaRetreatFromCityDanger()
{
if (plot()->isCity(true) && GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0) //prioritize getting outta there
{
if (AI_anyAttack(2, 40))
{
return true;
}
if (AI_anyAttack(4, 50))
{
return true;
}
if (AI_retreatToCity())
{
return true;
}
if (AI_safety())
{
return true;
}
}
return false;
}
bool CvUnitAI::AI_airRetreatFromCityDanger()
{
if (plot()->isCity(true))
{
CvCity* pCity = plot()->getPlotCity();
if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(plot(), 2) > 0 || (pCity != NULL && !pCity->AI_isDefended()))
{
if (AI_airOffensiveCity())
{
return true;
}
if (canAirDefend() && AI_airDefensiveCity())
{
return true;
}
}
}
return false;
}
bool CvUnitAI::AI_airAttackDamagedSkip()
{
if (getDamage() == 0)
{
return false;
}
bool bSkip = (currHitPoints() * 100 / maxHitPoints() < 40);
if (!bSkip)
{
int iSearchRange = airRange();
bool bSkiesClear = true;
for (int iDX = -iSearchRange; iDX <= iSearchRange && bSkiesClear; iDX++)
{
for (int iDY = -iSearchRange; iDY <= iSearchRange && bSkiesClear; iDY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (bestInterceptor(pLoopPlot) != NULL)
{
bSkiesClear = false;
break;
}
}
}
}
bSkip = !bSkiesClear;
}
if (bSkip)
{
getGroup()->pushMission(MISSION_SKIP);
return true;
}
return false;
}
*/
// Returns true if a mission was pushed or we should wait for another unit to bombard...
bool CvUnitAI::AI_followBombard()
{
CLLNode<IDInfo>* pUnitNode;
CvUnit* pLoopUnit;
CvPlot* pAdjacentPlot1;
CvPlot* pAdjacentPlot2;
int iI, iJ;
if (canBombard(plot()))
{
getGroup()->pushMission(MISSION_BOMBARD);
return true;
}
if (getDomainType() == DOMAIN_LAND)
{
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot1 = plotDirection(getX_INLINE(), getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot1 != NULL)
{
if (pAdjacentPlot1->isCity())
{
if (AI_potentialEnemy(pAdjacentPlot1->getTeam(), pAdjacentPlot1))
{
for (iJ = 0; iJ < NUM_DIRECTION_TYPES; iJ++)
{
pAdjacentPlot2 = plotDirection(pAdjacentPlot1->getX_INLINE(), pAdjacentPlot1->getY_INLINE(), ((DirectionTypes)iJ));
if (pAdjacentPlot2 != NULL)
{
pUnitNode = pAdjacentPlot2->headUnitNode();
while (pUnitNode != NULL)
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pAdjacentPlot2->nextUnitNode(pUnitNode);
if (pLoopUnit->getOwnerINLINE() == getOwnerINLINE())
{
if (pLoopUnit->canBombard(pAdjacentPlot2))
{
if (pLoopUnit->isGroupHead())
{
if (pLoopUnit->getGroup() != getGroup())
{
if (pLoopUnit->getGroup()->readyToMove())
{
return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
return false;
}
// Returns true if the unit has found a potential enemy...
bool CvUnitAI::AI_potentialEnemy(TeamTypes eTeam, const CvPlot* pPlot)
{
PROFILE_FUNC();
if (getGroup()->AI_isDeclareWar(pPlot))
{
return isPotentialEnemy(eTeam, pPlot);
}
else
{
return isEnemy(eTeam, pPlot);
}
}
// Returns true if this plot needs some defense...
bool CvUnitAI::AI_defendPlot(CvPlot* pPlot)
{
CvCity* pCity;
if (!canDefend(pPlot))
{
return false;
}
pCity = pPlot->getPlotCity();
if (pCity != NULL)
{
if (pCity->getOwnerINLINE() == getOwnerINLINE())
{
if (pCity->AI_isDanger())
{
return true;
}
}
}
else
{
if (pPlot->plotCount(PUF_canDefendGroupHead, -1, -1, getOwnerINLINE()) <= ((atPlot(pPlot)) ? 1 : 0))
{
if (pPlot->plotCount(PUF_cannotDefend, -1, -1, getOwnerINLINE()) > 0)
{
return true;
}
// if (pPlot->defenseModifier(getTeam(), false) >= 50 && pPlot->isRoute() && pPlot->getTeam() == getTeam())
// {
// return true;
// }
}
}
return false;
}
int CvUnitAI::AI_pillageValue(CvPlot* pPlot, int iBonusValueThreshold)
{
CvPlot* pAdjacentPlot;
ImprovementTypes eImprovement;
BonusTypes eNonObsoleteBonus;
int iValue;
int iTempValue;
int iBonusValue;
int iI;
FAssert(canPillage(pPlot) || canAirBombAt(plot(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) || (getGroup()->getCargo() > 0));
if (!(pPlot->isOwned()))
{
return 0;
}
iBonusValue = 0;
eNonObsoleteBonus = pPlot->getNonObsoleteBonusType(pPlot->getTeam());
if (eNonObsoleteBonus != NO_BONUS)
{
iBonusValue = (GET_PLAYER(pPlot->getOwnerINLINE()).AI_bonusVal(eNonObsoleteBonus));
}
if (iBonusValueThreshold > 0)
{
if (eNonObsoleteBonus == NO_BONUS)
{
return 0;
}
else if (iBonusValue < iBonusValueThreshold)
{
return 0;
}
}
iValue = 0;
if (getDomainType() != DOMAIN_AIR)
{
if (pPlot->isRoute())
{
iValue++;
if (eNonObsoleteBonus != NO_BONUS)
{
iValue += iBonusValue * 4;
}
for (iI = 0; iI < NUM_DIRECTION_TYPES; iI++)
{
pAdjacentPlot = plotDirection(getX_INLINE(), getY_INLINE(), ((DirectionTypes)iI));
if (pAdjacentPlot != NULL && pAdjacentPlot->getTeam() == pPlot->getTeam())
{
if (pAdjacentPlot->isCity())
{
iValue += 10;
}
if (!(pAdjacentPlot->isRoute()))
{
if (!(pAdjacentPlot->isWater()) && !(pAdjacentPlot->isImpassable()))
{
iValue += 2;
}
}
}
}
}
}
if (pPlot->getImprovementDuration() > ((pPlot->isWater()) ? 20 : 5))
{
eImprovement = pPlot->getImprovementType();
}
else
{
eImprovement = pPlot->getRevealedImprovementType(getTeam(), false);
}
if (eImprovement != NO_IMPROVEMENT)
{
if (pPlot->getWorkingCity() != NULL)
{
iValue += (pPlot->calculateImprovementYieldChange(eImprovement, YIELD_FOOD, pPlot->getOwnerINLINE()) * 5);
iValue += (pPlot->calculateImprovementYieldChange(eImprovement, YIELD_PRODUCTION, pPlot->getOwnerINLINE()) * 4);
iValue += (pPlot->calculateImprovementYieldChange(eImprovement, YIELD_COMMERCE, pPlot->getOwnerINLINE()) * 3);
}
if (getDomainType() != DOMAIN_AIR)
{
iValue += GC.getImprovementInfo(eImprovement).getPillageGold();
}
if (eNonObsoleteBonus != NO_BONUS)
{
if (GC.getImprovementInfo(eImprovement).isImprovementBonusTrade(eNonObsoleteBonus))
{
iTempValue = iBonusValue * 4;
if (pPlot->isConnectedToCapital() && (pPlot->getPlotGroupConnectedBonus(pPlot->getOwnerINLINE(), eNonObsoleteBonus) == 1))
{
iTempValue *= 2;
}
iValue += iTempValue;
}
}
}
return iValue;
}
int CvUnitAI::AI_nukeValue(CvCity* pCity)
{
PROFILE_FUNC();
FAssertMsg(pCity != NULL, "City is not assigned a valid value");
for (int iI = 0; iI < MAX_TEAMS; iI++)
{
CvTeam& kLoopTeam = GET_TEAM((TeamTypes)iI);
if (kLoopTeam.isAlive() && !isEnemy((TeamTypes)iI))
{
if (isNukeVictim(pCity->plot(), ((TeamTypes)iI)))
{
// Don't start wars with neutrals
return 0;
}
}
}
int iValue = 1;
iValue += GC.getGameINLINE().getSorenRandNum((pCity->getPopulation() + 1), "AI Nuke City Value");
iValue += std::max(0, pCity->getPopulation() - 10);
iValue += ((pCity->getPopulation() * (100 + pCity->calculateCulturePercent(pCity->getOwnerINLINE()))) / 100);
iValue += -(GET_PLAYER(getOwnerINLINE()).AI_getAttitudeVal(pCity->getOwnerINLINE()) / 3);
for (int iDX = -(nukeRange()); iDX <= nukeRange(); iDX++)
{
for (int iDY = -(nukeRange()); iDY <= nukeRange(); iDY++)
{
CvPlot* pLoopPlot = plotXY(pCity->getX_INLINE(), pCity->getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (pLoopPlot->getImprovementType() != NO_IMPROVEMENT)
{
iValue++;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD 7/31/08 jdog5000 */
/* */
/* Bugfix */
/********************************************************************************/
//if (pLoopPlot->getBonusType() != NO_BONUS)
if (pLoopPlot->getNonObsoleteBonusType(getTeam()) != NO_BONUS)
{
iValue++;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
}
}
}
if (!(pCity->isEverOwned(getOwnerINLINE())))
{
iValue *= 3;
iValue /= 2;
}
if (!GET_TEAM(pCity->getTeam()).isAVassal())
{
iValue *= 2;
}
if (pCity->plot()->isVisible(getTeam(), false))
{
iValue += 2 * pCity->plot()->getNumVisibleEnemyDefenders(this);
}
else
{
iValue += 6;
}
return iValue;
}
int CvUnitAI::AI_searchRange(int iRange)
{
if (iRange == 0)
{
return 0;
}
if (flatMovementCost() || (getDomainType() == DOMAIN_SEA))
{
return (iRange * baseMoves());
}
else
{
return ((iRange + 1) * (baseMoves() + 1));
}
}
// XXX at some point test the game with and without this function...
bool CvUnitAI::AI_plotValid(CvPlot* pPlot)
{
PROFILE_FUNC();
if (m_pUnitInfo->isNoRevealMap() && willRevealByMove(pPlot))
{
return false;
}
switch (getDomainType())
{
case DOMAIN_SEA:
if (pPlot->isWater() || canMoveAllTerrain())
{
return true;
}
else if (pPlot->isFriendlyCity(*this, true) && pPlot->isCoastalLand())
{
return true;
}
break;
case DOMAIN_AIR:
FAssert(false);
break;
case DOMAIN_LAND:
if (pPlot->getArea() == getArea() || canMoveAllTerrain())
{
return true;
}
break;
case DOMAIN_IMMOBILE:
FAssert(false);
break;
default:
FAssert(false);
break;
}
return false;
}
int CvUnitAI::AI_finalOddsThreshold(CvPlot* pPlot, int iOddsThreshold)
{
PROFILE_FUNC();
CvCity* pCity;
int iFinalOddsThreshold;
iFinalOddsThreshold = iOddsThreshold;
pCity = pPlot->getPlotCity();
if (pCity != NULL)
{
if (pCity->getDefenseDamage() < ((GC.getMAX_CITY_DEFENSE_DAMAGE() * 3) / 4))
{
iFinalOddsThreshold += std::max(0, (pCity->getDefenseDamage() - pCity->getLastDefenseDamage() - (GC.getDefineINT("CITY_DEFENSE_DAMAGE_HEAL_RATE") * 2)));
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/29/10 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
/* original bts code
if (pPlot->getNumVisiblePotentialEnemyDefenders(this) == 1)
{
if (pCity != NULL)
{
iFinalOddsThreshold *= 2;
iFinalOddsThreshold /= 3;
}
else
{
iFinalOddsThreshold *= 7;
iFinalOddsThreshold /= 8;
}
}
if ((getDomainType() == DOMAIN_SEA) && !getGroup()->hasCargo())
{
iFinalOddsThreshold *= 3;
iFinalOddsThreshold /= 2 + getGroup()->getNumUnits();
}
else
{
iFinalOddsThreshold *= 6;
iFinalOddsThreshold /= (3 + GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pPlot, true) + ((stepDistance(getX_INLINE(), getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) > 1) ? 1 : 0) + ((AI_isCityAIType()) ? 2 : 0));
}
*/
int iDefenders = pPlot->getNumVisiblePotentialEnemyDefenders(this);
// More aggressive if only one enemy defending city
if (iDefenders == 1 && pCity != NULL)
{
iFinalOddsThreshold *= 2;
iFinalOddsThreshold /= 3;
}
if ((getDomainType() == DOMAIN_SEA) && !getGroup()->hasCargo())
{
iFinalOddsThreshold *= 3 + (iDefenders/2);
iFinalOddsThreshold /= 2 + getGroup()->getNumUnits();
}
else
{
iFinalOddsThreshold *= 6 + (iDefenders/((pCity != NULL) ? 1 : 2));
int iDivisor = 3;
iDivisor += GET_PLAYER(getOwnerINLINE()).AI_adjacentPotentialAttackers(pPlot, true);
iDivisor += ((stepDistance(getX_INLINE(), getY_INLINE(), pPlot->getX_INLINE(), pPlot->getY_INLINE()) > 1) ? getGroup()->getNumUnits() : 0);
iDivisor += (AI_isCityAIType() ? 2 : 0);
iFinalOddsThreshold /= iDivisor;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
return range(iFinalOddsThreshold, 1, 99);
}
int CvUnitAI::AI_stackOfDoomExtra()
{
return ((AI_getBirthmark() % (1 + GET_PLAYER(getOwnerINLINE()).getCurrentEra())) + 4);
}
bool CvUnitAI::AI_stackAttackCity(int iRange, int iPowerThreshold, bool bFollow)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
FAssert(canMove());
if (bFollow)
{
iSearchRange = 1;
}
else
{
iSearchRange = AI_searchRange(iRange);
}
iBestValue = 0;
pBestPlot = NULL;
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot))
{
if (pLoopPlot->isCity() || (pLoopPlot->isCity(true) && pLoopPlot->isVisibleEnemyUnit(this)))
{
if (AI_potentialEnemy(pLoopPlot->getTeam(), pLoopPlot))
{
if (!atPlot(pLoopPlot) && ((bFollow) ? canMoveInto(pLoopPlot, /*bAttack*/ true, /*bDeclareWar*/ true) : (generatePath(pLoopPlot, 0, true, &iPathTurns) && (iPathTurns <= iRange))))
{
iValue = getGroup()->AI_compareStacks(pLoopPlot, /*bPotentialEnemy*/ true, /*bCheckCanAttack*/ true, /*bCheckCanMove*/ true);
if (iValue >= iPowerThreshold)
{
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = ((bFollow) ? pLoopPlot : getPathEndTurnPlot());
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/05/10 jdog5000 */
/* */
/* AI logging */
/************************************************************************************************/
if( gUnitLogLevel >= 1 && pBestPlot->getPlotCity() != NULL )
{
logBBAI(" Stack for player %d (%S) decides to attack city %S with stack ratio %d", getOwner(), GET_PLAYER(getOwner()).getCivilizationDescription(0), pBestPlot->getPlotCity()->getName(0).GetCString(), iBestValue );
logBBAI(" City %S has defense modifier %d, %d with ignore building", pBestPlot->getPlotCity()->getName(0).GetCString(), pBestPlot->getPlotCity()->getDefenseModifier(false), pBestPlot->getPlotCity()->getDefenseModifier(true) );
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), ((bFollow) ? MOVE_DIRECT_ATTACK : 0));
return true;
}
return false;
}
bool CvUnitAI::AI_moveIntoCity(int iRange)
{
PROFILE_FUNC();
CvPlot* pLoopPlot;
CvPlot* pBestPlot;
int iSearchRange = iRange;
int iPathTurns;
int iValue;
int iBestValue;
int iDX, iDY;
FAssert(canMove());
iBestValue = 0;
pBestPlot = NULL;
if (plot()->isCity())
{
return false;
}
iSearchRange = AI_searchRange(iRange);
for (iDX = -(iSearchRange); iDX <= iSearchRange; iDX++)
{
for (iDY = -(iSearchRange); iDY <= iSearchRange; iDY++)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iDX, iDY);
if (pLoopPlot != NULL)
{
if (AI_plotValid(pLoopPlot) && (!isEnemy(pLoopPlot->getTeam(), pLoopPlot)))
{
if (pLoopPlot->isCity() || (pLoopPlot->isCity(true)))
{
if (canMoveInto(pLoopPlot, false) && (generatePath(pLoopPlot, 0, true, &iPathTurns) && (iPathTurns <= 1)))
{
iValue = 1;
if (pLoopPlot->getPlotCity() != NULL)
{
iValue += pLoopPlot->getPlotCity()->getPopulation();
}
if (iValue > iBestValue)
{
iBestValue = iValue;
pBestPlot = getPathEndTurnPlot();
FAssert(!atPlot(pBestPlot));
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
return false;
}
//bolsters the culture of the weakest city.
//returns true if a mission is pushed.
bool CvUnitAI::AI_artistCultureVictoryMove()
{
bool bGreatWork = false;
bool bJoin = true;
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/08/10 jdog5000 */
/* */
/* Victory Strategy AI */
/************************************************************************************************/
if (!(GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_CULTURE1)))
{
return false;
}
if (GET_PLAYER(getOwnerINLINE()).AI_isDoVictoryStrategy(AI_VICTORY_CULTURE3))
{
//Great Work
bGreatWork = true;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
int iCultureCitiesNeeded = GC.getGameINLINE().culturalVictoryNumCultureCities();
FAssertMsg(iCultureCitiesNeeded > 0, "CultureVictory Strategy should not be true");
CvCity* pLoopCity;
CvPlot* pBestPlot;
CvCity* pBestCity;
SpecialistTypes eBestSpecialist;
int iLoop, iValue, iBestValue;
pBestPlot = NULL;
eBestSpecialist = NO_SPECIALIST;
pBestCity = NULL;
iBestValue = 0;
iLoop = 0;
int iTargetCultureRank = iCultureCitiesNeeded;
while (iTargetCultureRank > 0 && pBestCity == NULL)
{
for (pLoopCity = GET_PLAYER(getOwnerINLINE()).firstCity(&iLoop); pLoopCity != NULL; pLoopCity = GET_PLAYER(getOwnerINLINE()).nextCity(&iLoop))
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/19/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
// BBAI efficiency: check same area
if ((pLoopCity->area() == area()) && AI_plotValid(pLoopCity->plot()))
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
{
// instead of commerce rate rank should use the culture on tile...
if (pLoopCity->findCommerceRateRank(COMMERCE_CULTURE) == iTargetCultureRank)
{
// if the city is a fledgling, probably building culture, try next higher city
if (pLoopCity->getCultureLevel() < 2)
{
break;
}
// if we cannot path there, try the next higher culture city
if (!generatePath(pLoopCity->plot(), 0, true))
{
break;
}
pBestCity = pLoopCity;
pBestPlot = pLoopCity->plot();
if (bGreatWork)
{
if (canGreatWork(pBestPlot))
{
break;
}
}
for (int iI = 0; iI < GC.getNumSpecialistInfos(); iI++)
{
if (canJoin(pBestPlot, ((SpecialistTypes)iI)))
{
iValue = pLoopCity->AI_specialistValue(((SpecialistTypes)iI), pLoopCity->AI_avoidGrowth(), false);
if (iValue > iBestValue)
{
iBestValue = iValue;
eBestSpecialist = ((SpecialistTypes)iI);
}
}
}
if (eBestSpecialist == NO_SPECIALIST)
{
bJoin = false;
if (canGreatWork(pBestPlot))
{
bGreatWork = true;
break;
}
bGreatWork = false;
}
break;
}
}
}
iTargetCultureRank--;
}
FAssertMsg(bGreatWork || bJoin, "This wasn't a Great Artist");
if (pBestCity == NULL)
{
//should try to airlift there...
return false;
}
if (atPlot(pBestPlot))
{
if (bGreatWork)
{
getGroup()->pushMission(MISSION_GREAT_WORK);
return true;
}
if (bJoin)
{
getGroup()->pushMission(MISSION_JOIN, eBestSpecialist);
return true;
}
FAssert(false);
return false;
}
else
{
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE());
return true;
}
}
bool CvUnitAI::AI_poach()
{
CvPlot* pLoopPlot;
int iX, iY;
int iBestPoachValue = 0;
CvPlot* pBestPoachPlot = NULL;
TeamTypes eBestPoachTeam = NO_TEAM;
if (!GC.getGameINLINE().isOption(GAMEOPTION_AGGRESSIVE_AI))
{
return false;
}
if (GET_TEAM(getTeam()).getNumMembers() > 1)
{
return false;
}
int iNoPoachRoll = GET_PLAYER(getOwnerINLINE()).AI_totalUnitAIs(UNITAI_WORKER);
iNoPoachRoll += GET_PLAYER(getOwnerINLINE()).getNumCities();
iNoPoachRoll = std::max(0, (iNoPoachRoll - 1) / 2);
if (GC.getGameINLINE().getSorenRandNum(iNoPoachRoll, "AI Poach") > 0)
{
return false;
}
if (GET_TEAM(getTeam()).getAnyWarPlanCount(true) > 0)
{
return false;
}
FAssert(canAttack());
int iRange = 1;
//Look for a unit which is non-combat
//and has a capture unit type
for (iX = -iRange; iX <= iRange; iX++)
{
for (iY = -iRange; iY <= iRange; iY++)
{
if (iX != 0 && iY != 0)
{
pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iX, iY);
if ((pLoopPlot != NULL) && (pLoopPlot->getTeam() != getTeam()) && pLoopPlot->isVisible(getTeam(), false))
{
int iPoachCount = 0;
int iDefenderCount = 0;
CvUnit* pPoachUnit = NULL;
CLLNode<IDInfo>* pUnitNode = pLoopPlot->headUnitNode();
while (pUnitNode != NULL)
{
CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
pUnitNode = pLoopPlot->nextUnitNode(pUnitNode);
if ((pLoopUnit->getTeam() != getTeam())
&& GET_TEAM(getTeam()).canDeclareWar(pLoopUnit->getTeam()))
{
if (!pLoopUnit->canDefend())
{
if (pLoopUnit->getCaptureUnitType(getCivilizationType()) != NO_UNIT)
{
iPoachCount++;
pPoachUnit = pLoopUnit;
}
}
else
{
iDefenderCount++;
}
}
}
if (pPoachUnit != NULL)
{
if (iDefenderCount == 0)
{
int iValue = iPoachCount * 100;
iValue -= iNoPoachRoll * 25;
if (iValue > iBestPoachValue)
{
iBestPoachValue = iValue;
pBestPoachPlot = pLoopPlot;
eBestPoachTeam = pPoachUnit->getTeam();
}
}
}
}
}
}
}
if (pBestPoachPlot != NULL)
{
//No war roll.
if (!GET_TEAM(getTeam()).AI_performNoWarRolls(eBestPoachTeam))
{
GET_TEAM(getTeam()).declareWar(eBestPoachTeam, true, WARPLAN_LIMITED);
FAssert(!atPlot(pBestPoachPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPoachPlot->getX_INLINE(), pBestPoachPlot->getY_INLINE(), MOVE_DIRECT_ATTACK);
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/31/10 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
bool CvUnitAI::AI_choke(int iRange, bool bDefensive)
{
PROFILE_FUNC();
bool bNoDefensiveBonus = noDefensiveBonus();
if( getGroup()->getNumUnits() > 1 )
{
CLLNode<IDInfo>* pUnitNode = getGroup()->headUnitNode();
CvUnit* pLoopUnit = NULL;
while( pUnitNode != NULL )
{
pLoopUnit = ::getUnit(pUnitNode->m_data);
bNoDefensiveBonus = (bNoDefensiveBonus && pLoopUnit->noDefensiveBonus());
pUnitNode = getGroup()->nextUnitNode(pUnitNode);
}
}
CvPlot* pBestPlot = NULL;
int iBestValue = 0;
for (int iX = -iRange; iX <= iRange; iX++)
{
for (int iY = -iRange; iY <= iRange; iY++)
{
CvPlot* pLoopPlot = plotXY(getX_INLINE(), getY_INLINE(), iX, iY);
if (pLoopPlot != NULL)
{
if (isEnemy(pLoopPlot->getTeam()) && !(pLoopPlot->isVisibleEnemyUnit(this)))
{
CvCity* pWorkingCity = pLoopPlot->getWorkingCity();
if ((pWorkingCity != NULL) && (pWorkingCity->getTeam() == pLoopPlot->getTeam()))
{
int iValue = (bDefensive ? pLoopPlot->defenseModifier(getTeam(), false) : -15);
if (pLoopPlot->getBonusType(getTeam()) != NO_BONUS)
{
iValue += GET_PLAYER(pLoopPlot->getOwnerINLINE()).AI_bonusVal(pLoopPlot->getBonusType(), 0);
}
iValue += pLoopPlot->getYield(YIELD_PRODUCTION) * 10;
iValue += pLoopPlot->getYield(YIELD_FOOD) * 10;
iValue += pLoopPlot->getYield(YIELD_COMMERCE) * 5;
if (bNoDefensiveBonus)
{
iValue *= std::max(0, ((baseCombatStr() * 120) - GC.getGame().getBestLandUnitCombat()));
}
else
{
iValue *= pLoopPlot->defenseModifier(getTeam(), false);
}
if (iValue > 0)
{
if( !bDefensive )
{
iValue *= 10;
iValue /= std::max(1, (pLoopPlot->getNumDefenders(getOwnerINLINE()) + ((pLoopPlot == plot()) ? 0 : getGroup()->getNumUnits())));
}
if (generatePath(pLoopPlot))
{
pBestPlot = getPathEndTurnPlot();
iBestValue = iValue;
}
}
}
}
}
}
}
if (pBestPlot != NULL)
{
if (atPlot(pBestPlot))
{
if(canPillage(plot())) getGroup()->pushMission(MISSION_PILLAGE);
getGroup()->pushMission(MISSION_SKIP);
return true;
}
else
{
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX(), pBestPlot->getY());
return true;
}
}
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
bool CvUnitAI::AI_solveBlockageProblem(CvPlot* pDestPlot, bool bDeclareWar)
{
PROFILE_FUNC();
FAssert(pDestPlot != NULL);
if (pDestPlot != NULL)
{
FAStarNode* pStepNode;
CvPlot* pSourcePlot = plot();
if (gDLL->getFAStarIFace()->GeneratePath(&GC.getStepFinder(), pSourcePlot->getX_INLINE(), pSourcePlot->getY_INLINE(), pDestPlot->getX_INLINE(), pDestPlot->getY_INLINE(), false, 0, true))
{
pStepNode = gDLL->getFAStarIFace()->GetLastNode(&GC.getStepFinder());
while (pStepNode != NULL)
{
CvPlot* pStepPlot = GC.getMapINLINE().plotSorenINLINE(pStepNode->m_iX, pStepNode->m_iY);
if (canMoveOrAttackInto(pStepPlot) && generatePath(pStepPlot, 0, true))
{
if (bDeclareWar && pStepNode->m_pPrev != NULL)
{
CvPlot* pPlot = GC.getMapINLINE().plotSorenINLINE(pStepNode->m_pPrev->m_iX, pStepNode->m_pPrev->m_iY);
if (pPlot->getTeam() != NO_TEAM)
{
if (!canMoveInto(pPlot, true, true))
{
if (!isPotentialEnemy(pPlot->getTeam(), pPlot))
{
CvTeamAI& kTeam = GET_TEAM(getTeam());
if (kTeam.canDeclareWar(pPlot->getTeam()))
{
WarPlanTypes eWarPlan = WARPLAN_LIMITED;
WarPlanTypes eExistingWarPlan = kTeam.AI_getWarPlan(pDestPlot->getTeam());
if (eExistingWarPlan != NO_WARPLAN)
{
if ((eExistingWarPlan == WARPLAN_TOTAL) || (eExistingWarPlan == WARPLAN_PREPARING_TOTAL))
{
eWarPlan = WARPLAN_TOTAL;
}
if (!kTeam.isAtWar(pDestPlot->getTeam()))
{
kTeam.AI_setWarPlan(pDestPlot->getTeam(), NO_WARPLAN);
}
}
kTeam.AI_setWarPlan(pPlot->getTeam(), eWarPlan, true);
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 03/29/10 jdog5000 */
/* */
/* War tactics AI */
/************************************************************************************************/
/* original bts code
return (AI_targetCity());
*/
return (AI_goToTargetCity(MOVE_AVOID_ENEMY_WEIGHT_2));
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
}
}
}
}
if (pStepPlot->isVisibleEnemyUnit(this))
{
FAssert(canAttack());
CvPlot* pBestPlot = pStepPlot;
//To prevent puppeteering attempt to barge through
//if quite close
if (getPathLastNode()->m_iData2 > 3)
{
pBestPlot = getPathEndTurnPlot();
}
FAssert(!atPlot(pBestPlot));
getGroup()->pushMission(MISSION_MOVE_TO, pBestPlot->getX_INLINE(), pBestPlot->getY_INLINE(), MOVE_DIRECT_ATTACK);
return true;
}
}
pStepNode = pStepNode->m_pParent;
}
}
}
return false;
}
int CvUnitAI::AI_calculatePlotWorkersNeeded(CvPlot* pPlot, BuildTypes eBuild)
{
int iBuildTime = pPlot->getBuildTime(eBuild) - pPlot->getBuildProgress(eBuild);
int iWorkRate = workRate(true);
if (iWorkRate <= 0)
{
FAssert(false);
return 1;
}
int iTurns = iBuildTime / iWorkRate;
if (iBuildTime > (iTurns * iWorkRate))
{
iTurns++;
}
int iNeeded = std::max(1, (iTurns + 2) / 3);
/********************************************************************************/
/* BETTER_BTS_AI_MOD 7/31/08 jdog5000 */
/* */
/* Bugfix */
/********************************************************************************/
//if (pPlot->getBonusType() != NO_BONUS)
if (pPlot->getNonObsoleteBonusType(getTeam()) != NO_BONUS)
{
iNeeded *= 2;
}
/********************************************************************************/
/* BETTER_BTS_AI_MOD END */
/********************************************************************************/
return iNeeded;
}
bool CvUnitAI::AI_canGroupWithAIType(UnitAITypes eUnitAI) const
{
if (eUnitAI != AI_getUnitAIType())
{
switch (eUnitAI)
{
case (UNITAI_ATTACK_CITY):
if (plot()->isCity() && (GC.getGame().getGameTurn() - plot()->getPlotCity()->getGameTurnAcquired()) <= 1)
{
return false;
}
break;
default:
break;
}
}
return true;
}
bool CvUnitAI::AI_allowGroup(const CvUnit* pUnit, UnitAITypes eUnitAI) const
{
CvSelectionGroup* pGroup = pUnit->getGroup();
CvPlot* pPlot = pUnit->plot();
if (pUnit == this)
{
return false;
}
if (!pUnit->isGroupHead())
{
return false;
}
if (pGroup == getGroup())
{
return false;
}
if (pUnit->isCargo())
{
return false;
}
if (pUnit->AI_getUnitAIType() != eUnitAI)
{
return false;
}
switch (pGroup->AI_getMissionAIType())
{
case MISSIONAI_GUARD_CITY:
// do not join groups that are guarding cities
// intentional fallthrough
case MISSIONAI_LOAD_SETTLER:
case MISSIONAI_LOAD_ASSAULT:
case MISSIONAI_LOAD_SPECIAL:
// do not join groups that are loading into transports (we might not fit and get stuck in loop forever)
return false;
break;
default:
break;
}
if (pGroup->getActivityType() == ACTIVITY_HEAL)
{
// do not attempt to join groups which are healing this turn
// (healing is cleared every turn for automated groups, so we know we pushed a heal this turn)
return false;
}
if (!canJoinGroup(pPlot, pGroup))
{
return false;
}
if (eUnitAI == UNITAI_SETTLE)
{
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 08/20/09 jdog5000 */
/* */
/* Unit AI, Efficiency */
/************************************************************************************************/
//if (GET_PLAYER(getOwnerINLINE()).AI_getPlotDanger(pPlot, 3) > 0)
if (GET_PLAYER(getOwnerINLINE()).AI_getAnyPlotDanger(pPlot, 3))
{
return false;
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
}
else if (eUnitAI == UNITAI_ASSAULT_SEA)
{
if (!pGroup->hasCargo())
{
return false;
}
}
if ((getGroup()->getHeadUnitAI() == UNITAI_CITY_DEFENSE))
{
if (plot()->isCity() && (plot()->getTeam() == getTeam()) && plot()->getBestDefender(getOwnerINLINE())->getGroup() == getGroup())
{
return false;
}
}
if (plot()->getOwnerINLINE() == getOwnerINLINE())
{
CvPlot* pTargetPlot = pGroup->AI_getMissionAIPlot();
if (pTargetPlot != NULL)
{
if (pTargetPlot->isOwned())
{
if (isPotentialEnemy(pTargetPlot->getTeam(), pTargetPlot))
{
//Do not join groups which have debarked on an offensive mission
return false;
}
}
}
}
if (pUnit->getInvisibleType() != NO_INVISIBLE)
{
if (getInvisibleType() == NO_INVISIBLE)
{
return false;
}
}
return true;
}
void CvUnitAI::read(FDataStreamBase* pStream)
{
CvUnit::read(pStream);
uint uiFlag=0;
pStream->Read(&uiFlag); // flags for expansion
pStream->Read(&m_iBirthmark);
pStream->Read((int*)&m_eUnitAIType);
pStream->Read(&m_iAutomatedAbortTurn);
}
void CvUnitAI::write(FDataStreamBase* pStream)
{
CvUnit::write(pStream);
uint uiFlag=0;
pStream->Write(uiFlag); // flag for expansion
pStream->Write(m_iBirthmark);
pStream->Write(m_eUnitAIType);
pStream->Write(m_iAutomatedAbortTurn);
}
// Private Functions...
/************************************************************************************************/
/* BETTER_BTS_AI_MOD 02/21/10 jdog5000 */
/* */
/* Lead From Behind */
/************************************************************************************************/
// From Lead From Behind by UncutDragon
void CvUnitAI::LFBgetBetterAttacker(CvUnit** ppAttacker, const CvPlot* pPlot, bool bPotentialEnemy, int& iAIAttackOdds, int& iAttackerValue) const
{
CvUnit* pThis = (CvUnit*)this;
CvUnit* pAttacker = (*ppAttacker);
CvUnit* pDefender;
int iOdds;
int iValue;
int iAIOdds;
pDefender = pPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), this, !bPotentialEnemy, bPotentialEnemy);
iValue = LFBgetAttackerRank(pDefender, iOdds);
// Combat odds are out of 1000, but the AI routines need odds out of 100, and when called from AI_getBestGroupAttacker
// we return this value. Note that I'm not entirely sure if/how that return value is actually used ... but just in case I
// want to make sure I'm returning something consistent with what was there before
iAIOdds = (iOdds + 5) / 10;
iAIOdds += GET_PLAYER(getOwnerINLINE()).AI_getAttackOddsChange();
iAIOdds = std::max(1, std::min(iAIOdds, 99));
if (collateralDamage() > 0)
{
int iPossibleTargets = std::min((pPlot->getNumVisibleEnemyDefenders(pThis) - 1), collateralDamageMaxUnits());
if (iPossibleTargets > 0)
{
iValue *= (100 + ((collateralDamage() * iPossibleTargets) / 5));
iValue /= 100;
}
}
// Nothing to compare against - we're obviously better
if (!pAttacker)
{
(*ppAttacker) = pThis;
iAIAttackOdds = iAIOdds;
iAttackerValue = iValue;
return;
}
// Compare our adjusted value with the current best
if (iValue >= iAttackerValue)
{
(*ppAttacker) = pThis;
iAIAttackOdds = iAIOdds;
iAttackerValue = iValue;
}
}
/************************************************************************************************/
/* BETTER_BTS_AI_MOD END */
/************************************************************************************************/
| [
"jdog5000@31ee56aa-37e8-4f44-8bdf-1f84a3affbab",
"fim-fuyu@31ee56aa-37e8-4f44-8bdf-1f84a3affbab"
]
| [
[
[
1,
24
],
[
35,
176
],
[
182,
183
],
[
187,
428
],
[
438,
438
],
[
440,
440
],
[
445,
455
],
[
457,
457
],
[
462,
462
],
[
466,
772
],
[
789,
811
],
[
814,
815
],
[
823,
830
],
[
848,
863
],
[
874,
1126
],
[
1132,
1140
],
[
1142,
1143
],
[
1145,
1145
],
[
1153,
1153
],
[
1156,
1158
],
[
1162,
1162
],
[
1168,
1169
],
[
1190,
1227
],
[
1301,
1302
],
[
1316,
1345
],
[
1351,
1354
],
[
1359,
1363
],
[
1377,
1389
],
[
1395,
1399
],
[
1403,
1404
],
[
1408,
1420
],
[
1426,
1436
],
[
1440,
1458
],
[
1471,
1485
],
[
1491,
1492
],
[
1496,
1520
],
[
1522,
1528
],
[
1534,
1540
],
[
1544,
1834
],
[
1840,
1856
],
[
1860,
1892
],
[
1898,
1904
],
[
1908,
1927
],
[
1933,
1934
],
[
1941,
1945
],
[
1949,
1976
],
[
1988,
1990
],
[
1999,
2019
],
[
2036,
2038
],
[
2042,
2095
],
[
2103,
2107
],
[
2109,
2109
],
[
2118,
2130
],
[
2169,
2171
],
[
2173,
2177
],
[
2179,
2179
],
[
2183,
2186
],
[
2199,
2228
],
[
2230,
2322
],
[
2324,
2325
],
[
2327,
2327
],
[
2332,
2333
],
[
2349,
2377
],
[
2379,
2399
],
[
2412,
2420
],
[
2434,
2434
],
[
2436,
2440
],
[
2442,
2450
],
[
2452,
2452
],
[
2454,
2486
],
[
2488,
2541
],
[
2543,
2543
],
[
2548,
2562
],
[
2566,
2675
],
[
2681,
2693
],
[
2697,
2706
],
[
2712,
2715
],
[
2722,
2722
],
[
2724,
2724
],
[
2726,
2730
],
[
2742,
2742
],
[
2747,
2759
],
[
2761,
2761
],
[
2763,
2763
],
[
2765,
2768
],
[
2770,
2770
],
[
2773,
2773
],
[
2775,
2775
],
[
2777,
2779
],
[
2782,
2782
],
[
2784,
2785
],
[
2787,
2787
],
[
2846,
2847
],
[
2849,
2849
],
[
2861,
2861
],
[
2982,
2984
],
[
2989,
2989
],
[
2991,
2991
],
[
2993,
2994
],
[
2997,
2997
],
[
2999,
3004
],
[
3006,
3011
],
[
3013,
3062
],
[
3071,
3073
],
[
3083,
3120
],
[
3122,
3125
],
[
3137,
3140
],
[
3142,
3144
],
[
3146,
3146
],
[
3192,
3194
],
[
3211,
3227
],
[
3229,
3229
],
[
3240,
3261
],
[
3263,
3264
],
[
3266,
3272
],
[
3274,
3274
],
[
3279,
3303
],
[
3316,
3325
],
[
3329,
3347
],
[
3357,
3450
],
[
3456,
3457
],
[
3461,
3474
],
[
3480,
3486
],
[
3490,
3502
],
[
3508,
3519
],
[
3522,
3522
],
[
3524,
3640
],
[
3644,
3650
],
[
3656,
3657
],
[
3661,
3678
],
[
3684,
3690
],
[
3694,
3782
],
[
3788,
3789
],
[
3793,
3811
],
[
3817,
3823
],
[
3827,
3841
],
[
3847,
3863
],
[
3866,
3886
],
[
3888,
3888
],
[
3890,
3890
],
[
3892,
3892
],
[
3894,
3894
],
[
3896,
3896
],
[
3904,
3904
],
[
3912,
3912
],
[
3923,
3928
],
[
3931,
3931
],
[
3933,
3939
],
[
3941,
3949
],
[
3961,
3969
],
[
3972,
3977
],
[
3979,
3979
],
[
3981,
3981
],
[
3983,
3983
],
[
3988,
3988
],
[
3993,
4018
],
[
4022,
4028
],
[
4034,
4035
],
[
4045,
4046
],
[
4048,
4051
],
[
4055,
4123
],
[
4125,
4151
],
[
4169,
4172
],
[
4179,
4180
],
[
4185,
4185
],
[
4187,
4188
],
[
4191,
4193
],
[
4198,
4201
],
[
4206,
4211
],
[
4217,
4223
],
[
4227,
4243
],
[
4249,
4255
],
[
4259,
4357
],
[
4361,
4430
],
[
4436,
4440
],
[
4444,
4454
],
[
4460,
4466
],
[
4470,
4527
],
[
4533,
4539
],
[
4543,
4610
],
[
4616,
4617
],
[
4621,
4633
],
[
4639,
4645
],
[
4649,
4721
],
[
4727,
4728
],
[
4732,
4744
],
[
4750,
4756
],
[
4760,
4837
],
[
4843,
4844
],
[
4848,
4860
],
[
4866,
4872
],
[
4876,
4916
],
[
4923,
4929
],
[
4937,
4977
],
[
4981,
5053
],
[
5059,
5060
],
[
5064,
5076
],
[
5082,
5088
],
[
5092,
5164
],
[
5170,
5171
],
[
5175,
5187
],
[
5193,
5199
],
[
5203,
5212
],
[
5218,
5225
],
[
5227,
5236
],
[
5238,
5240
],
[
5242,
5261
],
[
5263,
5267
],
[
5275,
5275
],
[
5290,
5293
],
[
5296,
5296
],
[
5300,
5301
],
[
5320,
5320
],
[
5322,
5322
],
[
5324,
5332
],
[
5334,
5334
],
[
5336,
5336
],
[
5341,
5345
],
[
5347,
5363
],
[
5365,
5367
],
[
5369,
5370
],
[
5372,
5385
],
[
5388,
5388
],
[
5390,
5404
],
[
5408,
5448
],
[
5472,
5509
],
[
5515,
5516
],
[
5520,
5620
],
[
5624,
5688
],
[
5690,
5718
],
[
5720,
5740
],
[
5746,
5759
],
[
5761,
5762
],
[
5764,
5838
],
[
5842,
5848
],
[
5852,
5869
],
[
5871,
5874
],
[
5880,
5881
],
[
5885,
5900
],
[
5902,
5933
],
[
5939,
5939
],
[
5942,
5947
],
[
5949,
5952
],
[
5978,
5978
],
[
5981,
5981
],
[
5984,
5985
],
[
5987,
5987
],
[
6010,
6014
],
[
6018,
6030
],
[
6036,
6083
],
[
6087,
6101
],
[
6107,
6113
],
[
6117,
6150
],
[
6154,
6171
],
[
6177,
6178
],
[
6182,
6185
],
[
6187,
6202
],
[
6204,
6225
],
[
6231,
6232
],
[
6236,
6239
],
[
6245,
6281
],
[
6285,
6290
],
[
6296,
6299
],
[
6303,
6321
],
[
6327,
6331
],
[
6335,
6391
],
[
6395,
6412
],
[
6414,
6429
],
[
6431,
6443
],
[
6447,
6476
],
[
6478,
6518
],
[
6524,
6539
],
[
6543,
6553
],
[
6559,
6565
],
[
6571,
6576
],
[
6580,
6600
],
[
6604,
6636
],
[
6638,
6687
],
[
6691,
6774
],
[
6780,
6962
],
[
6975,
6985
],
[
6987,
6987
],
[
6995,
7089
],
[
7091,
7094
],
[
7096,
7162
],
[
7168,
7188
],
[
7192,
7278
],
[
7281,
7332
],
[
7335,
7337
],
[
7339,
7342
],
[
7344,
7399
],
[
7401,
7429
],
[
7433,
7441
],
[
7445,
7483
],
[
7485,
7501
],
[
7507,
7536
],
[
7540,
7540
],
[
7546,
7560
],
[
7564,
7577
],
[
7583,
7583
],
[
7587,
7619
],
[
7625,
7662
],
[
7666,
7676
],
[
7682,
7791
],
[
7795,
7820
],
[
7824,
7854
],
[
7856,
7872
],
[
7878,
7891
],
[
7895,
7927
],
[
7931,
7961
],
[
7963,
7990
],
[
7996,
8009
],
[
8013,
8038
],
[
8042,
8071
],
[
8073,
8163
],
[
8167,
8179
],
[
8181,
8196
],
[
8198,
8219
],
[
8223,
8228
],
[
8230,
8260
],
[
8264,
8427
],
[
8429,
8466
],
[
8470,
8571
],
[
8573,
8590
],
[
8592,
8604
],
[
8608,
8687
],
[
8689,
8697
],
[
8701,
8875
],
[
8877,
8887
],
[
8889,
8993
],
[
8997,
9012
],
[
9014,
9105
],
[
9111,
9112
],
[
9116,
9189
],
[
9195,
9196
],
[
9200,
9516
],
[
9522,
9523
],
[
9525,
9527
],
[
9531,
9553
],
[
9563,
9563
],
[
9567,
9870
],
[
9872,
10036
],
[
10042,
10045
],
[
10049,
10057
],
[
10063,
10066
],
[
10070,
10109
],
[
10115,
10116
],
[
10118,
10154
],
[
10165,
10200
],
[
10204,
10204
],
[
10206,
10206
],
[
10209,
10211
],
[
10213,
10213
],
[
10215,
10216
],
[
10218,
10218
],
[
10222,
10222
],
[
10230,
10230
],
[
10232,
10232
],
[
10235,
10268
],
[
10272,
10283
],
[
10285,
10332
],
[
10334,
10374
],
[
10380,
10380
],
[
10382,
10408
],
[
10410,
10451
],
[
10524,
10524
],
[
10528,
10539
],
[
10545,
10550
],
[
10570,
10573
],
[
10575,
10599
],
[
10603,
10660
],
[
10666,
10670
],
[
10674,
10799
],
[
10805,
10809
],
[
10813,
10883
],
[
10889,
10893
],
[
10897,
11361
],
[
11367,
11373
],
[
11395,
11398
],
[
11400,
11405
],
[
11407,
11412
],
[
11414,
11415
],
[
11420,
11461
],
[
11469,
11749
],
[
11754,
11809
],
[
11813,
12028
],
[
12038,
12092
],
[
12098,
12107
],
[
12109,
12139
],
[
12141,
12150
],
[
12152,
12154
],
[
12158,
12171
],
[
12177,
12177
],
[
12181,
12277
],
[
12283,
12283
],
[
12287,
12314
],
[
12321,
12321
],
[
12327,
12335
],
[
12341,
12343
],
[
12347,
12353
],
[
12359,
12360
],
[
12364,
12369
],
[
12375,
12375
],
[
12379,
12466
],
[
12472,
12472
],
[
12476,
12560
],
[
12566,
12570
],
[
12574,
12665
],
[
12671,
12675
],
[
12679,
12799
],
[
12805,
12811
],
[
12827,
12827
],
[
12829,
12829
],
[
12831,
12831
],
[
12833,
12833
],
[
12835,
12835
],
[
12837,
12837
],
[
12864,
12873
],
[
12885,
12888
],
[
12896,
12905
],
[
12909,
12934
],
[
12940,
12945
],
[
12949,
12968
],
[
12974,
12975
],
[
12979,
13004
],
[
13010,
13010
],
[
13014,
13051
],
[
13057,
13057
],
[
13061,
13067
],
[
13071,
13071
],
[
13073,
13073
],
[
13076,
13076
],
[
13079,
13079
],
[
13095,
13116
],
[
13122,
13122
],
[
13126,
13221
],
[
13227,
13228
],
[
13232,
13238
],
[
13244,
13244
],
[
13248,
13293
],
[
13299,
13299
],
[
13303,
13328
],
[
13334,
13335
],
[
13339,
13345
],
[
13351,
13351
],
[
13355,
13383
],
[
13389,
13389
],
[
13393,
13535
],
[
13541,
13552
],
[
13556,
13618
],
[
13624,
13656
],
[
13658,
13693
],
[
13697,
13724
],
[
13731,
13731
],
[
13737,
13845
],
[
13851,
13854
],
[
13858,
14225
],
[
14232,
14232
],
[
14238,
14273
],
[
14280,
14280
],
[
14286,
14400
],
[
14407,
14407
],
[
14413,
14495
],
[
14503,
14519
],
[
14522,
14531
],
[
14533,
14535
],
[
14537,
14550
],
[
14571,
14580
],
[
14585,
14587
],
[
14590,
14591
],
[
14594,
14594
],
[
14596,
14600
],
[
14602,
14618
],
[
14640,
14648
],
[
14650,
14662
],
[
14664,
14672
],
[
14678,
14697
],
[
14699,
14702
],
[
14704,
14715
],
[
14717,
14832
],
[
14929,
14950
],
[
14952,
14956
],
[
14958,
14958
],
[
14960,
14962
],
[
14964,
14964
],
[
14966,
14968
],
[
14985,
14985
],
[
14987,
14988
],
[
14990,
14990
],
[
14992,
14996
],
[
15000,
15003
],
[
15007,
15080
],
[
15086,
15086
],
[
15088,
15127
],
[
15129,
15129
],
[
15131,
15131
],
[
15133,
15133
],
[
15135,
15135
],
[
15140,
15140
],
[
15147,
15165
],
[
15170,
15272
],
[
15281,
15281
],
[
15286,
15466
],
[
15469,
15527
],
[
15533,
15536
],
[
15540,
15652
],
[
15658,
15661
],
[
15665,
15668
],
[
15674,
15677
],
[
15681,
15749
],
[
15753,
15754
],
[
15756,
15781
],
[
15783,
15790
],
[
15794,
15817
],
[
15819,
15822
],
[
15828,
15832
],
[
15836,
15876
],
[
15878,
15943
],
[
15951,
15961
],
[
15964,
15964
],
[
15971,
15971
],
[
15975,
15975
],
[
15977,
15977
],
[
15985,
15985
],
[
15987,
15991
],
[
15995,
16236
],
[
16243,
16243
],
[
16249,
16280
],
[
16293,
16297
],
[
16310,
16446
],
[
16452,
16476
],
[
16480,
16483
],
[
16489,
16492
],
[
16496,
16546
],
[
16552,
16560
],
[
16564,
16607
],
[
16613,
16620
],
[
16624,
16669
],
[
16699,
16707
],
[
16713,
16716
],
[
16720,
16725
],
[
16731,
16734
],
[
16738,
16744
],
[
16750,
16795
],
[
16797,
16905
],
[
16920,
16920
],
[
16923,
17149
],
[
17171,
17193
],
[
17197,
17264
],
[
17270,
17280
],
[
17284,
17684
],
[
17691,
17691
],
[
17697,
17808
],
[
17815,
17815
],
[
17817,
17817
],
[
17821,
17902
],
[
17908,
17915
],
[
17917,
17917
],
[
17919,
17919
],
[
17923,
17923
],
[
17927,
17927
],
[
17929,
17929
],
[
17931,
17931
],
[
17933,
17933
],
[
17937,
17937
],
[
17952,
17958
],
[
17960,
17960
],
[
17964,
17964
],
[
17967,
17967
],
[
17969,
17969
],
[
17972,
17972
],
[
17975,
17975
],
[
17982,
17982
],
[
17991,
17998
],
[
18002,
18078
],
[
18084,
18088
],
[
18092,
18114
],
[
18120,
18124
],
[
18128,
18380
],
[
18386,
18407
],
[
18409,
18409
],
[
18411,
18411
],
[
18416,
18416
],
[
18432,
18432
],
[
18436,
19097
],
[
19101,
19107
],
[
19109,
19127
],
[
19131,
19144
],
[
19146,
19173
],
[
19177,
19183
],
[
19185,
19350
],
[
19356,
19367
],
[
19369,
19369
],
[
19371,
19371
],
[
19373,
19373
],
[
19377,
19654
],
[
19660,
19664
],
[
19668,
19672
],
[
19678,
19689
],
[
19693,
19695
],
[
19699,
19710
],
[
19716,
19723
],
[
19727,
19788
],
[
19794,
19797
],
[
19801,
19824
],
[
19830,
19895
],
[
19899,
19909
],
[
19915,
20019
],
[
20023,
20033
],
[
20039,
20098
],
[
20101,
20102
],
[
20104,
20105
],
[
20112,
20120
],
[
20132,
20132
],
[
20136,
20136
],
[
20142,
20146
],
[
20148,
20148
],
[
20152,
20155
],
[
20157,
20182
],
[
20186,
20202
],
[
20208,
20232
],
[
20234,
20237
],
[
20239,
20241
],
[
20245,
20249
],
[
20253,
20343
],
[
20345,
20352
],
[
20354,
20553
],
[
20559,
20600
],
[
20602,
20619
],
[
20623,
20714
],
[
20716,
20898
],
[
20902,
20910
],
[
20912,
20970
],
[
20974,
21170
],
[
21172,
21408
],
[
21414,
21521
],
[
21525,
21668
],
[
21672,
21679
],
[
21681,
21812
],
[
21818,
21825
],
[
21830,
21974
],
[
22047,
22057
],
[
22060,
22060
],
[
22067,
22067
],
[
22080,
22106
],
[
22110,
22118
],
[
22120,
22130
],
[
22135,
22135
],
[
22138,
22138
],
[
22140,
22140
],
[
22148,
22148
],
[
22155,
22165
],
[
22167,
22169
],
[
22172,
22183
],
[
22186,
22196
],
[
22198,
22198
],
[
22210,
22217
],
[
22220,
22223
],
[
22226,
22231
],
[
22235,
22298
],
[
22300,
22307
],
[
22313,
22318
],
[
22320,
22346
],
[
22353,
22759
],
[
22763,
22769
],
[
22771,
22883
],
[
22890,
22902
],
[
22904,
22913
],
[
22941,
23012
],
[
23027,
23108
],
[
23115,
23118
],
[
23120,
23123
],
[
23128,
23149
],
[
23155,
23156
],
[
23160,
23360
],
[
23367,
23369
],
[
23385,
23393
],
[
23395,
23398
],
[
23400,
23408
],
[
23410,
23419
],
[
23426,
23440
],
[
23442,
23453
],
[
23457,
23506
],
[
23512,
23514
],
[
23519,
23568
],
[
23572,
23578
],
[
23580,
23666
],
[
23672,
23676
],
[
23680,
23753
]
],
[
[
25,
34
],
[
177,
181
],
[
184,
186
],
[
429,
437
],
[
439,
439
],
[
441,
444
],
[
456,
456
],
[
458,
461
],
[
463,
465
],
[
773,
788
],
[
812,
813
],
[
816,
822
],
[
831,
847
],
[
864,
873
],
[
1127,
1131
],
[
1141,
1141
],
[
1144,
1144
],
[
1146,
1152
],
[
1154,
1155
],
[
1159,
1161
],
[
1163,
1167
],
[
1170,
1189
],
[
1228,
1300
],
[
1303,
1315
],
[
1346,
1350
],
[
1355,
1358
],
[
1364,
1376
],
[
1390,
1394
],
[
1400,
1402
],
[
1405,
1407
],
[
1421,
1425
],
[
1437,
1439
],
[
1459,
1470
],
[
1486,
1490
],
[
1493,
1495
],
[
1521,
1521
],
[
1529,
1533
],
[
1541,
1543
],
[
1835,
1839
],
[
1857,
1859
],
[
1893,
1897
],
[
1905,
1907
],
[
1928,
1932
],
[
1935,
1940
],
[
1946,
1948
],
[
1977,
1987
],
[
1991,
1998
],
[
2020,
2035
],
[
2039,
2041
],
[
2096,
2102
],
[
2108,
2108
],
[
2110,
2117
],
[
2131,
2168
],
[
2172,
2172
],
[
2178,
2178
],
[
2180,
2182
],
[
2187,
2198
],
[
2229,
2229
],
[
2323,
2323
],
[
2326,
2326
],
[
2328,
2331
],
[
2334,
2348
],
[
2378,
2378
],
[
2400,
2411
],
[
2421,
2433
],
[
2435,
2435
],
[
2441,
2441
],
[
2451,
2451
],
[
2453,
2453
],
[
2487,
2487
],
[
2542,
2542
],
[
2544,
2547
],
[
2563,
2565
],
[
2676,
2680
],
[
2694,
2696
],
[
2707,
2711
],
[
2716,
2721
],
[
2723,
2723
],
[
2725,
2725
],
[
2731,
2741
],
[
2743,
2746
],
[
2760,
2760
],
[
2762,
2762
],
[
2764,
2764
],
[
2769,
2769
],
[
2771,
2772
],
[
2774,
2774
],
[
2776,
2776
],
[
2780,
2781
],
[
2783,
2783
],
[
2786,
2786
],
[
2788,
2845
],
[
2848,
2848
],
[
2850,
2860
],
[
2862,
2981
],
[
2985,
2988
],
[
2990,
2990
],
[
2992,
2992
],
[
2995,
2996
],
[
2998,
2998
],
[
3005,
3005
],
[
3012,
3012
],
[
3063,
3070
],
[
3074,
3082
],
[
3121,
3121
],
[
3126,
3136
],
[
3141,
3141
],
[
3145,
3145
],
[
3147,
3191
],
[
3195,
3210
],
[
3228,
3228
],
[
3230,
3239
],
[
3262,
3262
],
[
3265,
3265
],
[
3273,
3273
],
[
3275,
3278
],
[
3304,
3315
],
[
3326,
3328
],
[
3348,
3356
],
[
3451,
3455
],
[
3458,
3460
],
[
3475,
3479
],
[
3487,
3489
],
[
3503,
3507
],
[
3520,
3521
],
[
3523,
3523
],
[
3641,
3643
],
[
3651,
3655
],
[
3658,
3660
],
[
3679,
3683
],
[
3691,
3693
],
[
3783,
3787
],
[
3790,
3792
],
[
3812,
3816
],
[
3824,
3826
],
[
3842,
3846
],
[
3864,
3865
],
[
3887,
3887
],
[
3889,
3889
],
[
3891,
3891
],
[
3893,
3893
],
[
3895,
3895
],
[
3897,
3903
],
[
3905,
3911
],
[
3913,
3922
],
[
3929,
3930
],
[
3932,
3932
],
[
3940,
3940
],
[
3950,
3960
],
[
3970,
3971
],
[
3978,
3978
],
[
3980,
3980
],
[
3982,
3982
],
[
3984,
3987
],
[
3989,
3992
],
[
4019,
4021
],
[
4029,
4033
],
[
4036,
4044
],
[
4047,
4047
],
[
4052,
4054
],
[
4124,
4124
],
[
4152,
4168
],
[
4173,
4178
],
[
4181,
4184
],
[
4186,
4186
],
[
4189,
4190
],
[
4194,
4197
],
[
4202,
4205
],
[
4212,
4216
],
[
4224,
4226
],
[
4244,
4248
],
[
4256,
4258
],
[
4358,
4360
],
[
4431,
4435
],
[
4441,
4443
],
[
4455,
4459
],
[
4467,
4469
],
[
4528,
4532
],
[
4540,
4542
],
[
4611,
4615
],
[
4618,
4620
],
[
4634,
4638
],
[
4646,
4648
],
[
4722,
4726
],
[
4729,
4731
],
[
4745,
4749
],
[
4757,
4759
],
[
4838,
4842
],
[
4845,
4847
],
[
4861,
4865
],
[
4873,
4875
],
[
4917,
4922
],
[
4930,
4936
],
[
4978,
4980
],
[
5054,
5058
],
[
5061,
5063
],
[
5077,
5081
],
[
5089,
5091
],
[
5165,
5169
],
[
5172,
5174
],
[
5188,
5192
],
[
5200,
5202
],
[
5213,
5217
],
[
5226,
5226
],
[
5237,
5237
],
[
5241,
5241
],
[
5262,
5262
],
[
5268,
5274
],
[
5276,
5289
],
[
5294,
5295
],
[
5297,
5299
],
[
5302,
5319
],
[
5321,
5321
],
[
5323,
5323
],
[
5333,
5333
],
[
5335,
5335
],
[
5337,
5340
],
[
5346,
5346
],
[
5364,
5364
],
[
5368,
5368
],
[
5371,
5371
],
[
5386,
5387
],
[
5389,
5389
],
[
5405,
5407
],
[
5449,
5471
],
[
5510,
5514
],
[
5517,
5519
],
[
5621,
5623
],
[
5689,
5689
],
[
5719,
5719
],
[
5741,
5745
],
[
5760,
5760
],
[
5763,
5763
],
[
5839,
5841
],
[
5849,
5851
],
[
5870,
5870
],
[
5875,
5879
],
[
5882,
5884
],
[
5901,
5901
],
[
5934,
5938
],
[
5940,
5941
],
[
5948,
5948
],
[
5953,
5977
],
[
5979,
5980
],
[
5982,
5983
],
[
5986,
5986
],
[
5988,
6009
],
[
6015,
6017
],
[
6031,
6035
],
[
6084,
6086
],
[
6102,
6106
],
[
6114,
6116
],
[
6151,
6153
],
[
6172,
6176
],
[
6179,
6181
],
[
6186,
6186
],
[
6203,
6203
],
[
6226,
6230
],
[
6233,
6235
],
[
6240,
6244
],
[
6282,
6284
],
[
6291,
6295
],
[
6300,
6302
],
[
6322,
6326
],
[
6332,
6334
],
[
6392,
6394
],
[
6413,
6413
],
[
6430,
6430
],
[
6444,
6446
],
[
6477,
6477
],
[
6519,
6523
],
[
6540,
6542
],
[
6554,
6558
],
[
6566,
6570
],
[
6577,
6579
],
[
6601,
6603
],
[
6637,
6637
],
[
6688,
6690
],
[
6775,
6779
],
[
6963,
6974
],
[
6986,
6986
],
[
6988,
6994
],
[
7090,
7090
],
[
7095,
7095
],
[
7163,
7167
],
[
7189,
7191
],
[
7279,
7280
],
[
7333,
7334
],
[
7338,
7338
],
[
7343,
7343
],
[
7400,
7400
],
[
7430,
7432
],
[
7442,
7444
],
[
7484,
7484
],
[
7502,
7506
],
[
7537,
7539
],
[
7541,
7545
],
[
7561,
7563
],
[
7578,
7582
],
[
7584,
7586
],
[
7620,
7624
],
[
7663,
7665
],
[
7677,
7681
],
[
7792,
7794
],
[
7821,
7823
],
[
7855,
7855
],
[
7873,
7877
],
[
7892,
7894
],
[
7928,
7930
],
[
7962,
7962
],
[
7991,
7995
],
[
8010,
8012
],
[
8039,
8041
],
[
8072,
8072
],
[
8164,
8166
],
[
8180,
8180
],
[
8197,
8197
],
[
8220,
8222
],
[
8229,
8229
],
[
8261,
8263
],
[
8428,
8428
],
[
8467,
8469
],
[
8572,
8572
],
[
8591,
8591
],
[
8605,
8607
],
[
8688,
8688
],
[
8698,
8700
],
[
8876,
8876
],
[
8888,
8888
],
[
8994,
8996
],
[
9013,
9013
],
[
9106,
9110
],
[
9113,
9115
],
[
9190,
9194
],
[
9197,
9199
],
[
9517,
9521
],
[
9524,
9524
],
[
9528,
9530
],
[
9554,
9562
],
[
9564,
9566
],
[
9871,
9871
],
[
10037,
10041
],
[
10046,
10048
],
[
10058,
10062
],
[
10067,
10069
],
[
10110,
10114
],
[
10117,
10117
],
[
10155,
10164
],
[
10201,
10203
],
[
10205,
10205
],
[
10207,
10208
],
[
10212,
10212
],
[
10214,
10214
],
[
10217,
10217
],
[
10219,
10221
],
[
10223,
10229
],
[
10231,
10231
],
[
10233,
10234
],
[
10269,
10271
],
[
10284,
10284
],
[
10333,
10333
],
[
10375,
10379
],
[
10381,
10381
],
[
10409,
10409
],
[
10452,
10523
],
[
10525,
10527
],
[
10540,
10544
],
[
10551,
10569
],
[
10574,
10574
],
[
10600,
10602
],
[
10661,
10665
],
[
10671,
10673
],
[
10800,
10804
],
[
10810,
10812
],
[
10884,
10888
],
[
10894,
10896
],
[
11362,
11366
],
[
11374,
11394
],
[
11399,
11399
],
[
11406,
11406
],
[
11413,
11413
],
[
11416,
11419
],
[
11462,
11468
],
[
11750,
11753
],
[
11810,
11812
],
[
12029,
12037
],
[
12093,
12097
],
[
12108,
12108
],
[
12140,
12140
],
[
12151,
12151
],
[
12155,
12157
],
[
12172,
12176
],
[
12178,
12180
],
[
12278,
12282
],
[
12284,
12286
],
[
12315,
12320
],
[
12322,
12326
],
[
12336,
12340
],
[
12344,
12346
],
[
12354,
12358
],
[
12361,
12363
],
[
12370,
12374
],
[
12376,
12378
],
[
12467,
12471
],
[
12473,
12475
],
[
12561,
12565
],
[
12571,
12573
],
[
12666,
12670
],
[
12676,
12678
],
[
12800,
12804
],
[
12812,
12826
],
[
12828,
12828
],
[
12830,
12830
],
[
12832,
12832
],
[
12834,
12834
],
[
12836,
12836
],
[
12838,
12863
],
[
12874,
12884
],
[
12889,
12895
],
[
12906,
12908
],
[
12935,
12939
],
[
12946,
12948
],
[
12969,
12973
],
[
12976,
12978
],
[
13005,
13009
],
[
13011,
13013
],
[
13052,
13056
],
[
13058,
13060
],
[
13068,
13070
],
[
13072,
13072
],
[
13074,
13075
],
[
13077,
13078
],
[
13080,
13094
],
[
13117,
13121
],
[
13123,
13125
],
[
13222,
13226
],
[
13229,
13231
],
[
13239,
13243
],
[
13245,
13247
],
[
13294,
13298
],
[
13300,
13302
],
[
13329,
13333
],
[
13336,
13338
],
[
13346,
13350
],
[
13352,
13354
],
[
13384,
13388
],
[
13390,
13392
],
[
13536,
13540
],
[
13553,
13555
],
[
13619,
13623
],
[
13657,
13657
],
[
13694,
13696
],
[
13725,
13730
],
[
13732,
13736
],
[
13846,
13850
],
[
13855,
13857
],
[
14226,
14231
],
[
14233,
14237
],
[
14274,
14279
],
[
14281,
14285
],
[
14401,
14406
],
[
14408,
14412
],
[
14496,
14502
],
[
14520,
14521
],
[
14532,
14532
],
[
14536,
14536
],
[
14551,
14570
],
[
14581,
14584
],
[
14588,
14589
],
[
14592,
14593
],
[
14595,
14595
],
[
14601,
14601
],
[
14619,
14639
],
[
14649,
14649
],
[
14663,
14663
],
[
14673,
14677
],
[
14698,
14698
],
[
14703,
14703
],
[
14716,
14716
],
[
14833,
14928
],
[
14951,
14951
],
[
14957,
14957
],
[
14959,
14959
],
[
14963,
14963
],
[
14965,
14965
],
[
14969,
14984
],
[
14986,
14986
],
[
14989,
14989
],
[
14991,
14991
],
[
14997,
14999
],
[
15004,
15006
],
[
15081,
15085
],
[
15087,
15087
],
[
15128,
15128
],
[
15130,
15130
],
[
15132,
15132
],
[
15134,
15134
],
[
15136,
15139
],
[
15141,
15146
],
[
15166,
15169
],
[
15273,
15280
],
[
15282,
15285
],
[
15467,
15468
],
[
15528,
15532
],
[
15537,
15539
],
[
15653,
15657
],
[
15662,
15664
],
[
15669,
15673
],
[
15678,
15680
],
[
15750,
15752
],
[
15755,
15755
],
[
15782,
15782
],
[
15791,
15793
],
[
15818,
15818
],
[
15823,
15827
],
[
15833,
15835
],
[
15877,
15877
],
[
15944,
15950
],
[
15962,
15963
],
[
15965,
15970
],
[
15972,
15974
],
[
15976,
15976
],
[
15978,
15984
],
[
15986,
15986
],
[
15992,
15994
],
[
16237,
16242
],
[
16244,
16248
],
[
16281,
16292
],
[
16298,
16309
],
[
16447,
16451
],
[
16477,
16479
],
[
16484,
16488
],
[
16493,
16495
],
[
16547,
16551
],
[
16561,
16563
],
[
16608,
16612
],
[
16621,
16623
],
[
16670,
16698
],
[
16708,
16712
],
[
16717,
16719
],
[
16726,
16730
],
[
16735,
16737
],
[
16745,
16749
],
[
16796,
16796
],
[
16906,
16919
],
[
16921,
16922
],
[
17150,
17170
],
[
17194,
17196
],
[
17265,
17269
],
[
17281,
17283
],
[
17685,
17690
],
[
17692,
17696
],
[
17809,
17814
],
[
17816,
17816
],
[
17818,
17820
],
[
17903,
17907
],
[
17916,
17916
],
[
17918,
17918
],
[
17920,
17922
],
[
17924,
17926
],
[
17928,
17928
],
[
17930,
17930
],
[
17932,
17932
],
[
17934,
17936
],
[
17938,
17951
],
[
17959,
17959
],
[
17961,
17963
],
[
17965,
17966
],
[
17968,
17968
],
[
17970,
17971
],
[
17973,
17974
],
[
17976,
17981
],
[
17983,
17990
],
[
17999,
18001
],
[
18079,
18083
],
[
18089,
18091
],
[
18115,
18119
],
[
18125,
18127
],
[
18381,
18385
],
[
18408,
18408
],
[
18410,
18410
],
[
18412,
18415
],
[
18417,
18431
],
[
18433,
18435
],
[
19098,
19100
],
[
19108,
19108
],
[
19128,
19130
],
[
19145,
19145
],
[
19174,
19176
],
[
19184,
19184
],
[
19351,
19355
],
[
19368,
19368
],
[
19370,
19370
],
[
19372,
19372
],
[
19374,
19376
],
[
19655,
19659
],
[
19665,
19667
],
[
19673,
19677
],
[
19690,
19692
],
[
19696,
19698
],
[
19711,
19715
],
[
19724,
19726
],
[
19789,
19793
],
[
19798,
19800
],
[
19825,
19829
],
[
19896,
19898
],
[
19910,
19914
],
[
20020,
20022
],
[
20034,
20038
],
[
20099,
20100
],
[
20103,
20103
],
[
20106,
20111
],
[
20121,
20131
],
[
20133,
20135
],
[
20137,
20141
],
[
20147,
20147
],
[
20149,
20151
],
[
20156,
20156
],
[
20183,
20185
],
[
20203,
20207
],
[
20233,
20233
],
[
20238,
20238
],
[
20242,
20244
],
[
20250,
20252
],
[
20344,
20344
],
[
20353,
20353
],
[
20554,
20558
],
[
20601,
20601
],
[
20620,
20622
],
[
20715,
20715
],
[
20899,
20901
],
[
20911,
20911
],
[
20971,
20973
],
[
21171,
21171
],
[
21409,
21413
],
[
21522,
21524
],
[
21669,
21671
],
[
21680,
21680
],
[
21813,
21817
],
[
21826,
21829
],
[
21975,
22046
],
[
22058,
22059
],
[
22061,
22066
],
[
22068,
22079
],
[
22107,
22109
],
[
22119,
22119
],
[
22131,
22134
],
[
22136,
22137
],
[
22139,
22139
],
[
22141,
22147
],
[
22149,
22154
],
[
22166,
22166
],
[
22170,
22171
],
[
22184,
22185
],
[
22197,
22197
],
[
22199,
22209
],
[
22218,
22219
],
[
22224,
22225
],
[
22232,
22234
],
[
22299,
22299
],
[
22308,
22312
],
[
22319,
22319
],
[
22347,
22352
],
[
22760,
22762
],
[
22770,
22770
],
[
22884,
22889
],
[
22903,
22903
],
[
22914,
22940
],
[
23013,
23026
],
[
23109,
23114
],
[
23119,
23119
],
[
23124,
23127
],
[
23150,
23154
],
[
23157,
23159
],
[
23361,
23366
],
[
23370,
23384
],
[
23394,
23394
],
[
23399,
23399
],
[
23409,
23409
],
[
23420,
23425
],
[
23441,
23441
],
[
23454,
23456
],
[
23507,
23511
],
[
23515,
23518
],
[
23569,
23571
],
[
23579,
23579
],
[
23667,
23671
],
[
23677,
23679
],
[
23754,
23811
]
]
]
|
a4459c5995f9f9bcabe8e88ed6972c83a740bd62 | 2aa5cc5456b48811b7e4dee09cd7d1b019e3f7cc | /engine/component/jstimercomponent.cpp | 2034ebd9274ed5602f19628926ec46b0a349c745 | []
| no_license | tstivers/eXistenZ | eb2da9d6d58926b99495319080e13f780862fca0 | 2f5df51fb71d44c3e2689929c9249d10223f8d56 | refs/heads/master | 2021-09-02T22:50:36.733142 | 2010-11-16T06:47:24 | 2018-01-04T00:51:21 | 116,196,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,650 | cpp | #include "precompiled.h"
#include "component/jstimercomponent.h"
#include "component/jscomponent.h"
#include "entity/jsentity.h"
#include "script/jsfunction.h"
using namespace jscomponent;
using namespace component;
using namespace script;
namespace jsscript
{
inline jsval to_jsval(JSContext* cx, function<void(Component*)> action)
{
// TODO: figure out how to handle this
return JSVAL_NULL;
}
inline bool jsval_to_(JSContext* cx, jsval v, function<void(Component*)>* out)
{
if(!JSVAL_IS_OBJECT(v) || !JS_ObjectIsFunction(cx, JSVAL_TO_OBJECT(v)))
{
JS_ReportError(cx, "action must be a function");
return false;
}
shared_ptr<jsscript::jsfunction<void(Component*)>> call(new jsscript::jsfunction<void(Component*)>(cx, NULL, v));
*out = bind(&jsscript::jsfunction<void(Component*)>::operator(), call, _1);
return true;
}
inline jsval to_jsval(JSContext* cx, component::Component* object)
{
return object ? OBJECT_TO_JSVAL(object->getScriptObject()) : JSVAL_NULL;
}
}
namespace jscomponent
{
static bool parseDesc(JSContext* cx, JSObject* obj, TimerComponent::desc_type& desc);
// method declarations
// static JSBool classMethod(JSContext *cx, uintN argc, jsval *vp);
// property declarations
// static JSBool propGetter(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
static JSClass class_ops =
{
"TimerComponent",
JSCLASS_HAS_RESERVED_SLOTS(1),
JS_PropertyStub, JS_PropertyStub,
JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JS_FinalizeStub
};
static JSPropertySpec class_properties[] =
{
// {"name", id, flags, getter, setter},
{"started", 1, JSPROP_PERMANENT | JSPROP_ENUMERATE | JSPROP_SHARED | JSPROP_READONLY, PropertyGetter<TimerComponent, bool, &TimerComponent::isStarted>, NULL},
{"delay", 2, JSPROP_PERMANENT | JSPROP_ENUMERATE | JSPROP_SHARED, PropertyGetter<TimerComponent, float, &TimerComponent::getDelay>,
PropertySetter<TimerComponent, float, &TimerComponent::setDelay>},
{"frequency", 3, JSPROP_PERMANENT | JSPROP_ENUMERATE | JSPROP_SHARED, PropertyGetter<TimerComponent, float, &TimerComponent::getFrequency>,
PropertySetter<TimerComponent, float, &TimerComponent::setFrequency>},
{"action", 4, JSPROP_PERMANENT | JSPROP_ENUMERATE | JSPROP_SHARED, PropertyGetter<TimerComponent, function<void(Component*)>, &TimerComponent::getAction>,
PropertySetter<TimerComponent, function<void(Component*)>, &TimerComponent::setAction>},
JS_PS_END
};
static JSFunctionSpec class_methods[] =
{
// JS_FN("name", function, nargs, flags, minargs),
JS_FN("start", WRAP_FASTNATIVE(TimerComponent::start), 0, 0),
JS_FN("stop", WRAP_FASTNATIVE(TimerComponent::stop), 0, 0),
JS_FN("restart", WRAP_FASTNATIVE(TimerComponent::restart), 0, 0),
JS_FN("fire", WRAP_FASTNATIVE(TimerComponent::restart), 0, 0),
JS_FS_END
};
}
ScriptedObject::ScriptClass TimerComponent::m_scriptClass =
{
&class_ops,
class_properties,
class_methods,
NULL
};
REGISTER_SCRIPT_INIT(TimerComponent, initClass, 20);
static void initClass(ScriptEngine* engine)
{
RegisterScriptClass<TimerComponent, Component>(engine);
jsentity::RegisterCreateFunction(engine, "createTimerComponent", createComponent<TimerComponent>);
}
bool jscomponent::parseDesc(JSContext* cx, JSObject* obj, TimerComponent::desc_type& desc)
{
GetProperty(cx, obj, "delay", desc.delay);
GetProperty(cx, obj, "frequency", desc.frequency);
GetProperty(cx, obj, "start", desc.start);
GetProperty(cx, obj, "action", desc.action);
return true;
}
| [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
b814eba1099435d0110bf90b9c9bac0c017ef2d8 | bda7b365b5952dc48827a8e8d33d11abd458c5eb | /Runnable_PS3/old/texture.cpp | ea5bacdc91c65693e9b62fa4f8ee203102a9e552 | []
| no_license | MrColdbird/gameservice | 3bc4dc3906d16713050612c1890aa8820d90272e | 009d28334bdd8f808914086e8367b1eb9497c56a | refs/heads/master | 2021-01-25T09:59:24.143855 | 2011-01-31T07:12:24 | 2011-01-31T07:12:24 | 35,889,912 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 10,784 | cpp | /* SCE CONFIDENTIAL */
/* PlayStation(R)3 Programmer Tool Runtime Library 330.001 */
/* Copyright (C) 2006 Sony Computer Entertainment Inc. */
/* All Rights Reserved. */
#include <stdio.h>
#include <assert.h>
#include <sys/return_code.h>
#include <cell/gcm.h>
#include "cellutil.h"
#include "gcmutil.h"
void cellUtilGenerateGradationTexture(uint8_t *texture,
const uint32_t width,
const uint32_t height,
const uint32_t depth)
{
for (size_t x = 0; x < width; ++x) {
for (size_t y = 0; y < height; ++y) {
texture[depth*(width*y+x)] = 255;
texture[depth*(width*y+x)+1] = 255;
texture[depth*(width*y+x)+2] = (uint8_t)(int)floorf(x*256.f/width);
texture[depth*(width*y+x)+3] = (uint8_t)(int)floorf(y*256.f/height);
}
}
}
void cellUtilGenerateSwizzledGradationTexture(uint8_t *texture,
const uint32_t width,
const uint32_t height,
const uint32_t depth)
{
uint8_t *p = (uint8_t*)malloc(width*height*depth);
assert(p != NULL);
cellUtilGenerateGradationTexture(p, width, height, depth);
cellUtilConvertLinearToSwizzle(texture, p, width, height, depth);
free(p);
}
void cellUtilGenerateGradationTextureFP16(uint8_t *texture,
const uint32_t width,
const uint32_t height)
{
uint16_t *buf = (uint16_t*)texture;
for (size_t x = 0; x < width; ++x) {
for (size_t y = 0; y < height; ++y) {
buf[4*(width*y+x)] = cellUtilFloatToHalf(1.0f); // R
buf[4*(width*y+x)+1] = cellUtilFloatToHalf((float)x/width); // G
buf[4*(width*y+x)+2] = cellUtilFloatToHalf((float)y/height); // B
buf[4*(width*y+x)+3] = cellUtilFloatToHalf(1.0f); // A
}
}
}
void cellUtilGenerateSwizzledGradationTextureFP16(uint8_t *texture,
const uint32_t width,
const uint32_t height)
{
uint8_t *p = (uint8_t*)malloc(width*height*4*2); // half float size = 2
assert(p != NULL);
cellUtilGenerateGradationTextureFP16(p, width, height);
cellUtilConvertLinearToSwizzle(texture, p, width * 2, height, 4*2);
free(p);
}
void cellUtilGenerateGradationTextureFP32(uint8_t *texture,
const uint32_t width,
const uint32_t height)
{
float *buf = (float*)texture;
for (size_t x = 0; x < width; ++x) {
for (size_t y = 0; y < height; ++y) {
buf[4*(width*y+x)] = 1.0f; // R
buf[4*(width*y+x)+1] = (float)x/width; // G
buf[4*(width*y+x)+2] = (float)y/height; // B
buf[4*(width*y+x)+3] = 1.0f; // A
}
}
}
void cellUtilGenerateSwizzledGradationTextureFP32(uint8_t *texture,
const uint32_t width,
const uint32_t height)
{
uint8_t *p = (uint8_t*)malloc(width*height*4*sizeof(float));
assert(p != NULL);
cellUtilGenerateGradationTextureFP32(p, width, height);
cellUtilConvertLinearToSwizzle(texture, p, width * sizeof(float), height,
4 * sizeof(float));
free(p);
}
void cellUtilGenerateGridTexture(uint8_t *texture,
const uint32_t width, const uint32_t height,
const uint32_t depth,
const uint32_t linewidth,
const uint32_t linefreq)
{
for (size_t y = 0; y < height; ++y) {
for (size_t x = 0; x < width; ++x) {
texture[depth*(width*y+x)] = 255;
texture[depth*(width*y+x)+1] = 255;
texture[depth*(width*y+x)+2] = 255;
texture[depth*(width*y+x)+3] = 255;
}
}
for (size_t y = 0; y < height; y++) {
if ((y / linewidth % linefreq) == 0) {
for (size_t x = 0; x < width; ++x) {
texture[depth*(width*y+x)] = 255;
texture[depth*(width*y+x)+1] = 0;
texture[depth*(width*y+x)+2] = 0;
texture[depth*(width*y+x)+3] = 0;
}
}
else {
for (size_t x = 0; x < width; x += linewidth*linefreq) {
if ((x / linewidth % linefreq) == 0) {
for (size_t i = 0; i < linewidth; ++i) {
texture[depth*(width*y+x+i)] = 255;
texture[depth*(width*y+x+i)+1] = 0;
texture[depth*(width*y+x+i)+2] = 0;
texture[depth*(width*y+x+i)+3] = 0;
}
}
}
}
}
}
void cellUtilGenerateMipmap(uint8_t *texture,
const uint32_t width, const uint32_t height,
const uint32_t depth)
{
uint32_t stride = width;
uint32_t offset = stride*height*depth;
uint32_t prevOffset = 0;
uint32_t maxMipmap = ((cellUtilLog2(width)>cellUtilLog2(height)) ?
cellUtilLog2(width) : cellUtilLog2(height))+1;
uint32_t textureWidth = width;
uint32_t textureHeight = height;
if (textureWidth != 1) {
textureWidth /= 2;
}
if (textureHeight != 1) {
textureHeight /= 2;
}
for (uint32_t k = 1; k < maxMipmap; ++k) {
for (uint32_t y = 0; y < textureHeight; ++y) {
for (uint32_t x = 0; x < textureWidth; ++x) {
for (uint32_t i = 0; i < depth; ++i) {
uint32_t tmp = 0;
tmp += texture[prevOffset+depth*(stride*y*2+x*2)+i];
tmp += texture[prevOffset+depth*(stride*y*2+x*2+1)+i];
tmp += texture[prevOffset+depth*(stride*(y*2+1)+x*2)+i];
tmp += texture[prevOffset+depth*(stride*(y*2+1)+x*2+1)+i];
texture[offset+depth*(stride*y+x)+i] = tmp / 4;
}
}
}
prevOffset = offset; // save offset of last mipmap
// for linear texture, stride is used instead of width
offset += stride*textureHeight*depth;
if (textureWidth != 1) {
textureWidth /= 2;
}
if (textureHeight != 1) {
textureHeight /= 2;
}
}
}
void cellUtilGenerateCubeMap(uint8_t *texture,
const uint32_t width, const uint32_t height,
const uint32_t depth, const uint32_t swizzled)
{
uint32_t stride = width;
uint32_t offset = 0;
uint32_t colormap[6][3] = { // colorbar's color
{ 255, 255, 0 }, { 0, 255, 255 },
{ 0, 255, 0 }, { 255, 0, 255 },
{ 255, 0, 0 }, { 0, 0, 255 },
};
uint8_t *p = (uint8_t*)malloc(width*height*depth);
assert(p != NULL);
for (uint32_t k = 0; k < 6; ++k) {
for (uint32_t y = 0; y < height; ++y) {
for (uint32_t x = 0; x < width; ++x) {
p[depth*(stride*y+x)] = 255;
p[depth*(stride*y+x)+1] = colormap[k][0];
p[depth*(stride*y+x)+2] = colormap[k][1];
p[depth*(stride*y+x)+3] = colormap[k][2];
}
}
if (swizzled != 0) {
cellUtilConvertLinearToSwizzle(&texture[offset], p,
width, height, depth);
}
// for linear texture, stride is used instead of width
offset += stride*height*depth;
}
free(p);
}
int cellGcmUtilGetTextureAttribute(const uint32_t glFormat,
uint32_t *gcmFormat, uint32_t *remap,
const uint32_t swizzle, const uint32_t normalize)
{
switch (glFormat) {
case CELL_GCM_UTIL_ARGB8: // GL_ARGB8
*gcmFormat = CELL_GCM_TEXTURE_A8R8G8B8;
if (swizzle == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_LN;
}
if (normalize == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_UN;
}
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_B << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_A;
break;
case CELL_GCM_UTIL_RGBA8: // GL_RGBA8
*gcmFormat = CELL_GCM_TEXTURE_A8R8G8B8;
if (swizzle == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_LN;
}
if (normalize == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_UN;
}
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_A << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_B;
break;
case CELL_GCM_UTIL_BGRA8: // GL_BGRA8
*gcmFormat = CELL_GCM_TEXTURE_A8R8G8B8;
if (swizzle == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_LN;
}
if (normalize == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_UN;
}
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_A << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_B;
break;
case CELL_GCM_UTIL_DXT1: // GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
*gcmFormat = CELL_GCM_TEXTURE_COMPRESSED_DXT1 |
CELL_GCM_TEXTURE_SZ | CELL_GCM_TEXTURE_NR;
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_B << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_A;
break;
case CELL_GCM_UTIL_DXT3: // GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
*gcmFormat = CELL_GCM_TEXTURE_COMPRESSED_DXT23 |
CELL_GCM_TEXTURE_SZ | CELL_GCM_TEXTURE_NR;
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_B << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_A;
break;
case CELL_GCM_UTIL_DXT5: // GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
*gcmFormat = CELL_GCM_TEXTURE_COMPRESSED_DXT45 |
CELL_GCM_TEXTURE_SZ | CELL_GCM_TEXTURE_NR;
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_B << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_A;
break;
case CELL_GCM_UTIL_FP16: // GL_RGBA16F_ARB
case CELL_GCM_UTIL_FP32: // GL_RGBA32F_ARB
if (glFormat == CELL_GCM_UTIL_FP16) {
*gcmFormat = CELL_GCM_TEXTURE_W16_Z16_Y16_X16_FLOAT;
}
else {
*gcmFormat = CELL_GCM_TEXTURE_W32_Z32_Y32_X32_FLOAT;
}
if (swizzle == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_LN;
}
if (normalize == 0) {
*gcmFormat |= CELL_GCM_TEXTURE_UN;
}
*remap = CELL_GCM_TEXTURE_REMAP_REMAP << 14 |
CELL_GCM_TEXTURE_REMAP_REMAP << 12 |
CELL_GCM_TEXTURE_REMAP_REMAP << 10 |
CELL_GCM_TEXTURE_REMAP_REMAP << 8 |
CELL_GCM_TEXTURE_REMAP_FROM_B << 6 |
CELL_GCM_TEXTURE_REMAP_FROM_G << 4 |
CELL_GCM_TEXTURE_REMAP_FROM_R << 2 |
CELL_GCM_TEXTURE_REMAP_FROM_A;
break;
default:
printf("format:%x\n", glFormat);
assert(false); // invalid texture format
break;
}
return 0;
}
| [
"leavesmaple@383b229b-c81f-2bc2-fa3f-61d2d0c0fe69"
]
| [
[
[
1,
342
]
]
]
|
ac786df32b0512d855f246da57c86beb328d5c99 | 1493997bb11718d3c18c6632b6dd010535f742f5 | /direct_ui/UIlib/UILabel.cpp | ba667af3487a7f6d874afe7c017e5b0f25e7a201 | []
| no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | cpp |
#include "StdAfx.h"
#include "UILabel.h"
/////////////////////////////////////////////////////////////////////////////////////
//
//
CLabelPanelUI::CLabelPanelUI() : m_cxWidth(0), m_uTextStyle(DT_VCENTER)
{
}
LPCTSTR CLabelPanelUI::GetClass() const
{
return _T("LabelPanelUI");
}
void CLabelPanelUI::SetText(LPCTSTR pstrText)
{
// Automatic assignment of keyboard shortcut
if( _tcschr(pstrText, '&') != NULL ) m_chShortcut = *(_tcschr(pstrText, '&') + 1);
CControlUI::SetText(pstrText);
}
void CLabelPanelUI::SetWidth(int cx)
{
m_cxWidth = cx;
UpdateLayout();
}
void CLabelPanelUI::SetTextStyle(UINT uStyle)
{
m_uTextStyle = uStyle;
Invalidate();
}
void CLabelPanelUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("align")) == 0 ) {
if( _tcsstr(pstrValue, _T("center")) != NULL ) m_uTextStyle |= DT_CENTER;
if( _tcsstr(pstrValue, _T("right")) != NULL ) m_uTextStyle |= DT_RIGHT;
}
else if( _tcscmp(pstrName, _T("width")) == 0 ) SetWidth(_ttoi(pstrValue));
else CControlUI::SetAttribute(pstrName, pstrValue);
}
SIZE CLabelPanelUI::EstimateSize(SIZE /*szAvailable*/)
{
return CSize(m_cxWidth, m_pManager->GetThemeFontInfo(UIFONT_NORMAL).tmHeight + 4);
}
void CLabelPanelUI::DoPaint(HDC hDC, const RECT& rcPaint)
{
RECT rcText = m_rcItem;
int nLinks = 0;
CBlueRenderEngineUI::DoPaintPrettyText(hDC, m_pManager, rcText, m_sText, UICOLOR_EDIT_TEXT_NORMAL, UICOLOR__INVALID, NULL, nLinks, DT_SINGLELINE | m_uTextStyle);
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
LPCTSTR CGreyTextHeaderUI::GetClass() const
{
return _T("GreyTextHeaderUI");
}
SIZE CGreyTextHeaderUI::EstimateSize(SIZE /*szAvailable*/)
{
return CSize(0, 12 + m_pManager->GetThemeFontInfo(UIFONT_BOLD).tmHeight + 12);
}
void CGreyTextHeaderUI::DoPaint(HDC hDC, const RECT& /*rcPaint*/)
{
COLORREF clrDarkText = m_pManager->GetThemeColor(UICOLOR_DIALOG_TEXT_DARK);
RECT rcLine = { m_rcItem.left, m_rcItem.bottom - 6, m_rcItem.right, m_rcItem.bottom - 5 };
CBlueRenderEngineUI::DoFillRect(hDC, m_pManager, rcLine, UICOLOR_DIALOG_TEXT_DARK);
CBlueRenderEngineUI::DoPaintQuickText(hDC, m_pManager, m_rcItem, m_sText, UICOLOR_DIALOG_TEXT_DARK, UIFONT_BOLD, DT_SINGLELINE);
}
| [
"[email protected]"
]
| [
[
[
1,
82
]
]
]
|
a4c184f03a95b0019c0f5444f7421627cbf9b9c9 | be78c6c17e74febd81d3f89e88347a0d009f4c99 | /src/GoIO_console2/Win32/GoIO_consoleDoc.h | 62220bd32e93ebd78e87da68f51bf41211950d91 | []
| 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 | UTF-8 | C++ | false | false | 3,064 | h | // GoIO_consoleDoc.h : interface of the CGoIO_consoleDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_GOIO_CONSOLEDOC_H__8FDFDA77_BC76_45A1_AFCD_CB8D9A631AE5__INCLUDED_)
#define AFX_GOIO_CONSOLEDOC_H__8FDFDA77_BC76_45A1_AFCD_CB8D9A631AE5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "GoIO_DLL_interface.h"
#define MAX_NUM_MEASUREMENTS_IN_CIRBUF 501
class CGoIO_consoleDoc : public CDocument
{
protected: // create from serialization only
CGoIO_consoleDoc();
DECLARE_DYNCREATE(CGoIO_consoleDoc)
// Attributes
public:
GOIO_SENSOR_HANDLE GetOpenDevicePtr() { return m_pDevice; }
// Operations
public:
GOIO_SENSOR_HANDLE OpenDevice(int vendorId, int productId, LPCSTR pDeviceName);
void CloseDevice();
void AddMeasurementToCirbuf(double measurement)
{
if (MAX_NUM_MEASUREMENTS_IN_CIRBUF == m_numMeasurementsInCirbuf)
{
m_firstCirbufMeasurementIndex++;
m_firstCirbufMeasurementIndex = m_firstCirbufMeasurementIndex % MAX_NUM_MEASUREMENTS_IN_CIRBUF;
m_numMeasurementsInCirbuf--;
}
m_measurements_cirbuf[(m_firstCirbufMeasurementIndex + m_numMeasurementsInCirbuf) % MAX_NUM_MEASUREMENTS_IN_CIRBUF]
= measurement;
m_numMeasurementsInCirbuf++;
}
int GetNumMeasurementsInCirbuf() { return m_numMeasurementsInCirbuf; }
void ClearMeasurementCirbuf()
{
m_firstCirbufMeasurementIndex = 0;
m_numMeasurementsInCirbuf = 0;
}
double GetNthMeasurementInCirbuf(int N) //(N == 0) => first measurement.
{
if (N >= m_numMeasurementsInCirbuf)
return 0.0;
else
return m_measurements_cirbuf[(m_firstCirbufMeasurementIndex + N) % MAX_NUM_MEASUREMENTS_IN_CIRBUF];
}
void SetMeasurementPeriodInSeconds(double period) { m_measPeriodInSeconds = period; }
double GetMeasurementPeriodInSeconds() { return m_measPeriodInSeconds; }
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGoIO_consoleDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CGoIO_consoleDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CGoIO_consoleDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
GOIO_SENSOR_HANDLE m_pDevice;
double m_measurements_cirbuf[MAX_NUM_MEASUREMENTS_IN_CIRBUF];
int m_numMeasurementsInCirbuf;
int m_firstCirbufMeasurementIndex;
double m_measPeriodInSeconds;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GOIO_CONSOLEDOC_H__8FDFDA77_BC76_45A1_AFCD_CB8D9A631AE5__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
faf40eebbdb2fa867baeb26aae45fe9570c35a21 | 48c6de8cb63cf11147049ce07b2bd7e020d0d12b | /gcc/opencollada/include/COLLADAStreamWriter/include/COLLADASWPrerequisites.h | 4a1d120df95789fe675dfa822644ba410fd0e20d | []
| 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 | 816 | h | /*
Copyright (c) 2008-2009 NetAllied Systems GmbH
This file is part of COLLADAStreamWriter.
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 __COLLADASTREAMWRITER_PREREQUISITES_H__
#define __COLLADASTREAMWRITER_PREREQUISITES_H__
#include <string>
#include "COLLADABUURI.h"
#include "COLLADABUNativeString.h"
#include "Math/COLLADABUMathUtils.h"
namespace COLLADASW
{
typedef COLLADABU::URI URI;
typedef COLLADABU::Utils Utils;
typedef COLLADABU::NativeString NativeString;
typedef COLLADABU::Math::Utils MathUtils;
typedef std::string String;
typedef std::wstring WideString;
}
#endif //__COLLADASTREAMWRITER_PREREQUISITES_H__
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
ec46c82c146d357a820f9c98161e4dd12ced6b4e | b9a650e3db9d68b0796864ea4123e56c6aa0829c | /vmxroot.cpp | b193ebe19421ba374a0e484b09df4c1eaf1e85ce | []
| no_license | pyq881120/termovtx | c765cd4edd09ec872ce236737e9d5406bb1f38fc | 06de06e325e2984853b31ed7c87a4ec31170c77d | refs/heads/master | 2021-01-10T04:48:30.679016 | 2009-04-10T10:08:06 | 2009-04-10T10:08:06 | 50,425,025 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 6,875 | cpp | #include "common.h"
#include "vmxroot.h"
#include "cpuarch.hxx"
namespace vmxroot
{
using namespace ntl::intrinsic;
namespace msrs = ntl::km::MSR::IA32;
using namespace detail;
cpu CheckCPU()
{
TraceFunction();
int32_t cpuid[4];
// check cpu model
__cpuid(cpuid, 0);
// intel
if(cpuid[regEbx] != 'uneG'){
// amd
if(cpuid[regEbx] != 'htuA'){
dbg::error("Unsupported cpu type\n");
return unsup;
}
return Athlon;
}
return Intel;
}
namespace vmxintel
{
bool CheckHardware()
{
TraceFunction();
int32_t cpuid[4];
// check features
uint8_t model, family;
bool vmxpresent = false;
__cpuid(cpuid, 1);
model = uint8_t((cpuid[regEax] >> 4) & 0xF);
family =uint8_t((cpuid[regEax] >> 8) & 0xF);
vmxpresent = ((cpuid[regEcx]>>5) & 1) != 0; //VMX avalability
if(family == 0x06 && model >= 0x07){
// core2+
g_drv->cpu = drv_t::Core2;
}
dbg::info.printf("cpu family %X, model %X;", family, model);
dbg::info.printf("VMX bit is: %d\n", vmxpresent);
return vmxpresent;
}
void Entering()
{
TraceFunction();
cpuarch::CR4 cr4; cr4.value = __readcr4();
if (cr4.SMXE)
{
dbg::error("SMXE bit is set\n");
return;
}
if (cr4.VMXE)
{
dbg::error("VMXE bit is set\n");
return;
}
cpuarch::CR0 cr0; cr0.value = __readcr0();
if (!cr0.PE&&!cr0.NE&&!cr0.PG)
{
dbg::error("VMX can`t be execute. CR0(PE,NE,PG) bit is clear\n");
return;
}
dbg::info.printf("cpu.CR4:: SMXE = %d, VMXE = %d\n", cr4.SMXE, cr4.VMXE);
dbg::info.printf("cpu CR0:: PE = %d, NE = %d, PG = %d\n", cr0.PE, cr0.NE, cr0.PG);
msrs::feature_control fctrl_msr;
fctrl_msr.value = __readmsr(msrs::Core2::FeatureControl);
dbg::info.printf("cpu MSR.feature_ctrl:: VmxLock = %X, EnableInsideSmx = %X, EnableOutsideSmx = %X",
fctrl_msr.VmxLock,fctrl_msr.EnableInsideSmx,fctrl_msr.EnableOutsideSmx);
if (fctrl_msr.VmxLock&fctrl_msr.EnableOutsideSmx)
{
dbg::error("VMX can`t be execute. MSR feature control bit is clear\n");
return;
}
msrs::vmx_basic vmx_basic_msr;
vmx_basic_msr.value = __readmsr(msrs::VmxBasic);
dbg::info.printf("cpu MSR.vmx_basic:: RevID = %X",vmx_basic_msr.Revision);
//LONG_PTR pVMCS_VA;
//....
//memcpy(pVMCS_VA,&vmx_basic_msr.Revision,sizeof(vmx_basic_msr.Revision));
//physical_address VMCS_PA = MmGetPhysicalAddress(pVMCS_VA);
//__vmx_on(&VMCS_PA);
//dbg::info.printf("VMX is ON");
}
void Leaving()
{
TraceFunction();
__vmx_off();
cpuarch::CR4 cr4; cr4.value = __readcr4();
cr4.VMXE = 0;
__writecr4(cr4.value);
dbg::info.printf("VMX is OFF\n cpu.CR4:: SMXE = %d, VMXE = %d\n", cr4.SMXE, cr4.VMXE);
}
} //vmxintel
namespace msrs_amd = ntl::km::AMD;
namespace vmxamd
{
bool CheckHardware()
{
TraceFunction();
int32_t cpuid[4];
// check features
uint8_t model, family;
bool svmpresent = false;
__cpuid(cpuid, 1);
model = uint8_t((cpuid[regEax] >> 4) & 0xF);
family =uint8_t((cpuid[regEax] >> 8) & 0xF);
__cpuid(cpuid, 0x80000001);
svmpresent = ((cpuid[regEcx]>>2) & 1) != 0; //VMX avalability
if(family == 0x0F && model >= 0x08){
// Athlon X2 +
g_drv->cpu = drv_t::AthlonX2;
}
dbg::info.printf("cpu family %X, model %X;", family, model);
dbg::info.printf("SVM bit is: %d\n", svmpresent);
return svmpresent;
}
void Entering()
{
TraceFunction();
cpuarch::CR0 cr0; cr0.value = __readcr0();
if (!cr0.PE&&!cr0.NE&&!cr0.PG)
{
dbg::error("VMX can`t be execute. CR0(PE,NE,PG) bit is clear\n");
return;
}
dbg::info.printf("cpu CR0:: PE = %d, NE = %d, PG = %d\n", cr0.PE, cr0.NE, cr0.PG);
msrs_amd::vm_cr vm_cr_msr;
vm_cr_msr.value = __readmsr(msrs_amd::VM_CR);
if (vm_cr_msr.SVMDIS)
{
dbg::error("SVM is not allowed\n");
return;
}
int32_t cpuid[4];
__cpuid(cpuid, 0x8000000A);
if (((cpuid[regEcx]>>2) & 1) !=0)
{
dbg::error("SVM is LOCK. Ņonsult the BIOS or TPM to unlock SVM\n");
return;
}
msrs_amd::efer efer_msr;
efer_msr.value = __readmsr(msrs_amd::Efer);
dbg::info.printf("cpu.efer_msr:: SVME = %d\n", efer_msr.SVME);
if (efer_msr.SVME==1)
{
dbg::error("SVME bit is set..exit\n");
return;
}
dbg::info.printf("Write SVME bit...\n");
efer_msr.SVME = 1;
__writemsr(msrs_amd::Efer,efer_msr.value);
if (efer_msr.SVME==0)
{
dbg::error("SVME bit set is falure\n");
return;
}
dbg::info.printf("cpu.efer_msr:: SVME = %d after wtire bit\n", efer_msr.SVME);
msrs_amd::vmcb* NewVMCB = new(nonpaged) msrs_amd::vmcb;
uintptr_t VMCS_PA = (uintptr_t)MmGetPhysicalAddress(NewVMCB);
std::memset(NewVMCB,0,sizeof(msrs_amd::vmcb));
__svm_vmrun(VMCS_PA);
dbg::info.printf("SVM is ON");
}
void Leaving()
{
TraceFunction();
msrs_amd::efer efer_msr;
efer_msr.value = __readmsr(msrs_amd::Efer);
if (efer_msr.SVME==0)
{
dbg::error("SVME bit is alredy clear\n");
return;
}
dbg::info.printf("Clears the global interrupt flag...\n");
__svm_clgi();
__sti();
dbg::info.printf("Write SVME bit...\n");
efer_msr.SVME = 0;
__writemsr(msrs_amd::Efer,efer_msr.value);
if (efer_msr.SVME)
{
dbg::error("SVME bit set is falure, Can`t disable SVM\n");
return;
}
dbg::info.printf("cpu.efer_msr:: SVME = %d after wtire bit\n", efer_msr.SVME);
}
}
} // vmxroot | [
"termo.sintez@7e32d97e-22cc-11de-8096-4f48778bd5c7"
]
| [
[
[
1,
233
]
]
]
|
86a7fe2f7e0bee8c8d68cbd071771ca5491555cd | 9433cf978aa6b010903c134d77c74719f22efdeb | /src/SerialPort.h | 80779e953eee4d27a19facc8f8b5bd6f1793c562 | []
| no_license | brandonagr/gpstracktime | 4666575cb913db2c9b3b8aa6b40a3ba1a3defb2f | 842bfd9698ec48debb6756a9acb2f40fd6041f9c | refs/heads/master | 2021-01-20T07:10:58.579764 | 2008-09-24T05:44:56 | 2008-09-24T05:44:56 | 32,090,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,399 | h | #pragma once
// SerialPort.h : header file
//
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <string>
#include <windows.h>
typedef unsigned char BYTE;
typedef std::string CString;
typedef unsigned long DWORD;
/////////////////////////////////////////////////////////////////////////////
// CSerialPort window
//////////////////////////////////////////////////////////////////////
// SerialPort.h: implementation of the CSerialPort class.
// Written by Shibu K.V ([email protected])
// Copyright (c) 2002
//
// To use CSerialPort, follow these steps:
// - Copy the files SerialPort.h & SerialPort.cpp and paste it in your
// Projects Directory.
// - Take Project tab from your VC++ IDE,Take Add to Project->Files.Select files
// SerialPort.h & SerialPort.cpp and click ok
// - Add the line #include "SerialPort.h" at the top of your Dialog's Header File.
// - Create an instance of CSerialPort in your dialogs header File.Say
// CSerialPort port;
// Warning: this code hasn't been subject to a heavy testing, so
// use it on your own risk. The author accepts no liability for the
// possible damage caused by this code.
//
// Version 1.0 7 Sept 2002.
//////////////////////////////////////////////////////////////////////
class CSerialPort
{
// Construction
public:
CSerialPort();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSerialPort)
//}}AFX_VIRTUAL
// Implementation
public:
void ClosePort();
BOOL ReadByte(BYTE &resp);
BOOL WriteByte(BYTE bybyte);
BOOL OpenPort(CString portname);
BOOL SetCommunicationTimeouts(DWORD ReadIntervalTimeout,DWORD ReadTotalTimeoutMultiplier,DWORD ReadTotalTimeoutConstant,DWORD WriteTotalTimeoutMultiplier,DWORD WriteTotalTimeoutConstant);
BOOL ConfigurePort(DWORD BaudRate,BYTE ByteSize,DWORD fParity,BYTE Parity,BYTE StopBits);
HANDLE hComm;
DCB m_dcb;
COMMTIMEOUTS m_CommTimeouts;
BOOL m_bPortReady;
BOOL bWriteRC;
BOOL bReadRC;
DWORD iBytesWritten;
DWORD iBytesRead;
DWORD dwBytesRead;
virtual ~CSerialPort();
// Generated message map functions
protected:
//{{AFX_MSG(CSerialPort)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
//DECLARE_MESSAGE_MAP()
};
| [
"BrandonAGr@0fd8bb18-9850-0410-888e-21b4c4172e3e"
]
| [
[
[
1,
82
]
]
]
|
3bbb14ceba44efb4ce62b26e97520feae96461ad | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Applications/Physics/GelatinBlob/PhysicsModule.cpp | 2ede6cedeaaefac98978d3565f43d161c65d2fea | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Game Physics source code is supplied under the terms of the license
// agreement http://www.magic-software.com/License/GamePhysics.pdf and may not
// be copied or disclosed except in accordance with the terms of that
// agreement.
#include "PhysicsModule.h"
//----------------------------------------------------------------------------
PhysicsModule::PhysicsModule (int iNumParticles, int iNumSprings, float fStep,
float fViscosity)
:
MassSpringArbitrary3f(iNumParticles,iNumSprings,fStep)
{
m_fViscosity = fViscosity;
}
//----------------------------------------------------------------------------
PhysicsModule::~PhysicsModule ()
{
}
//----------------------------------------------------------------------------
Vector3f PhysicsModule::ExternalImpulse (int i, float fTime,
const Vector3f* akPosition, const Vector3f* akVelocity)
{
Vector3f kImpulse = -m_fViscosity*akVelocity[i];
return kImpulse;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
8515a71c80af88b51223e016d8b16c458eadf02b | 3bfe835203f793ee00bdf261c26992b1efea69ed | /misc/bezier/bezier/BezierWnd.cpp | a51128cc54daa0a743e94298e8915317c035db69 | []
| no_license | yxrkt/DigiPen | 0bdc1ed3ee06e308b4942a0cf9de70831c65a3d3 | e1bb773d15f63c88ab60798f74b2e424bcc80981 | refs/heads/master | 2020-06-04T20:16:05.727685 | 2009-11-18T00:26:56 | 2009-11-18T00:26:56 | 814,145 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 11,316 | cpp | #include <sstream>
#include <process.h>
#include <math.h>
#include "BezierWnd.h"
// ============================================================================
// Constructor for main window
// ============================================================================
CBezierWnd::CBezierWnd() : m_bRunning( true ),
m_Grabbed( m_Points.end() ),
m_bDrawPoly( false ),
m_bBernstein( true )
{
if ( !Create( NULL, "Bezier Curve Canvas" ) )
MessageBox( "Creating window failed.", NULL, MB_ICONERROR );
RECT rcWnd;
GetClientRect( &rcWnd );
m_DimWnd.width = rcWnd.right - rcWnd.left;
m_DimWnd.height = rcWnd.bottom - rcWnd.top - TOOLBAR_HEIGHT;
BITMAPINFOHEADER bmpinfo = { sizeof( BITMAPINFOHEADER ),
m_DimWnd.width, m_DimWnd.height,
1, 32, BI_RGB, 0L, 0L, 0L, 0, 0 };
m_BitmapDC = CreateCompatibleDC( CreateDC( "Display", 0, 0, 0 ) );
m_Bitmap = CreateDIBSection( m_BitmapDC, ( BITMAPINFO *) &bmpinfo,
DIB_RGB_COLORS, ( void **) &m_Surface,
NULL, NULL );
SelectObject( m_BitmapDC, m_Bitmap );
memset( m_Surface, 0xFF, sizeof( int ) * m_DimWnd.width * m_DimWnd.height );
pThis = this;
AfxBeginThread( sUpdate, NULL );
}
CBezierWnd::~CBezierWnd()
{
//delete m_Surface;
}
bool CBezierWnd::bDone = false;
HANDLE CBezierWnd::hMutex;
CBezierWnd *CBezierWnd::pThis;
unsigned CBezierWnd::sUpdate( void *pMyID )
{
while ( pThis->m_bRunning )
pThis->Update();
bDone = true;
return 0;
}
// ============================================================================
// Updates window's bitmaps
// ============================================================================
void CBezierWnd::Update()
{
BitBlt( GetDC()->m_hDC,
0,
TOOLBAR_HEIGHT,
m_DimWnd.width,
m_DimWnd.height,
m_BitmapDC,
0,
0,
SRCCOPY
);
memset( m_Surface, 0xFF, sizeof( int ) * m_DimWnd.width * m_DimWnd.height );
Draw();
}
// ============================================================================
// Draw points and curves
// ============================================================================
void CBezierWnd::Draw()
{
// Draw control point handles and labels
for ( PointSetIt i = m_Points.begin(); i != m_Points.end(); ++i )
{
DrawHandle( *i );
DrawLabel( *i );
}
if ( m_Points.size() < 3)
return;
// Draw curve
PointList lPoints;
for ( PointSetIt i = m_Points.begin(); i != m_Points.end(); ++i )
lPoints.push_back( *i );
CPoint2D p2DStart = *m_Points.begin();
float fStep = 1.f / ( 10.f * ( float ) lPoints.size() );
for ( float i = 0.f; i <= 1.f; i+= fStep )
{
CPoint2D p2D = GetBezierPoint( lPoints, i );
DrawLine( p2DStart, p2D );
p2DStart = p2D;
}
DrawLine( p2DStart, lPoints.back() );
// Draw control polygon
if ( m_bDrawPoly )
{
PointSetIt i = m_Points.begin(), iPrev = i++;
do {
DrawLine( *iPrev, *i );
iPrev = i++;
} while ( i != m_Points.end() );
}
}
// ============================================================================
// Get point on the curve at time t
// ============================================================================
CPoint2D CBezierWnd::GetBezierPoint( const PointList &points, float t )
{
return m_bBernstein ? Bernstein( points, t ) : deCasteljau( points, t );
}
// ============================================================================
// Get point using Bernstein polynomials
// ============================================================================
CPoint2D CBezierWnd::Bernstein( const PointList &points, float t )
{
CPoint2D final( 0.f, 0.f );
int nDegree = (int) points.size() - 1;
PointListItC pointIter = points.begin();
for ( int i = 0; i <= nDegree; ++i )
{
float coef = (float) Choose( nDegree, i ) * pow( ( 1.f - t ), nDegree - i ) * pow( t, i );
final += ( coef * ( *pointIter ) );
++pointIter;
}
return final;
}
// ============================================================================
// Get point using de Casteljau's algorithm
// ============================================================================
CPoint2D CBezierWnd::deCasteljau( const PointList &points, float t )
{
size_t nPoints = points.size();
if ( nPoints > 1 )
{
PointList next_points;
PointListItC i = points.begin(), iPrev = i++;
do {
next_points.push_back( *iPrev + t * ( *i - *iPrev ) );
iPrev = i;
} while ( ++i != points.end() );
return GetBezierPoint( next_points, t );
}
else
return points.front();
}
// ============================================================================
// Mathematical choose function
// ============================================================================
int CBezierWnd::Choose( int lhs, int rhs ) const
{
if ( rhs == 0 || lhs == rhs )
return 1;
return Factorial( lhs ) / ( Factorial( rhs ) * Factorial( lhs - rhs ) );
}
// ============================================================================
// Mathematical choose function
// ============================================================================
int CBezierWnd::Factorial( int lhs ) const
{
int final = lhs;
for ( int i = 2; i < lhs; ++i )
final *= i;
return final;
}
// ============================================================================
// Draws circles around a control point
// ============================================================================
void CBezierWnd::DrawHandle( const CPoint2D &point )
{
int x = point.GetXi();
int y = point.GetYi();
SetPixel( x - 1, y - 2 );
SetPixel( x , y - 2 );
SetPixel( x + 1, y - 2 );
SetPixel( x - 1, y + 2 );
SetPixel( x , y + 2 );
SetPixel( x + 1, y + 2 );
SetPixel( x - 2, y - 1 );
SetPixel( x - 2, y );
SetPixel( x - 2, y + 1 );
SetPixel( x + 2, y - 1 );
SetPixel( x + 2, y );
SetPixel( x + 2, y + 1 );
}
// ============================================================================
// Draws text labeling a control point
// ============================================================================
void CBezierWnd::DrawLabel( const CPoint2D &point )
{
}
// ============================================================================
// Draws a line between two points
// ============================================================================
void CBezierWnd::DrawLine( const CPoint2D &start, const CPoint2D &finish )
{
if ( m_Points.size() < 2 )
return;
float dx = finish.x - start.x;
float dy = finish.y - start.y;
float m = dy / dx;
float m_i = 1.f / m;
int xstep = dx > 0 ? 1 : -1;
int ystep = dy > 0 ? 1 : -1;
if ( m >= -1 && m <= 1 )
{
float y = start.y + .5f;
int iX = finish.GetXi();
for ( int x = start.GetXi(); x != iX; x += xstep )
{
y += ( dx > 0 ? m : -m );
SetPixel( x, (int) y );
}
}
else
{
float x = start.x + .5f;
int iY = finish.GetYi();
for ( int y = start.GetYi(); y != iY; y += ystep )
{
x += ( dy > 0 ? m_i : -m_i );
SetPixel( (int) x, y );
}
}
}
// ============================================================================
// Change the color of a pixel
// ============================================================================
void CBezierWnd::SetPixel( int x, int y, Color32 c )
{
if ( x < 0 || x >= m_DimWnd.width || y < 1 || y >= m_DimWnd.height )
return;
//m_Surface[ ( y * m_DimWnd.width ) + x ] = c; // right handed
m_Surface[ ( ( m_DimWnd.height - y ) * m_DimWnd.width ) + x ] = c; // left handed
}
unsigned CBezierPoint::nCurrIndex = 0;
// ============================================================================
// Message map and definitions for main window
// ============================================================================
BEGIN_MESSAGE_MAP( CBezierWnd, CFrameWnd )
ON_WM_CREATE()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONDOWN()
ON_WM_MBUTTONDOWN()
ON_WM_MBUTTONUP()
ON_WM_SIZE()
ON_WM_CLOSE()
ON_WM_CHAR()
ON_COMMAND( ID_HIDE_POLYGON, OnHidePolygon )
ON_COMMAND( ID_SHOW_POLYGON, OnShowPolygon )
ON_COMMAND( ID_DECASTELJAU, OnDeCasteljau )
ON_COMMAND( ID_BERNSTEIN, OnBernstein )
END_MESSAGE_MAP()
// Window is created
int CBezierWnd::OnCreate( LPCREATESTRUCT )
{
if ( !m_Toolbar.CreateEx( this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE
| CBRS_TOP | CBRS_GRIPPER | CBRS_FLYBY | CBRS_SIZE_DYNAMIC ) )
{
AfxMessageBox( "Creating toolbar failed." );
return -1;
}
if ( !m_Toolbar.LoadToolBar( IDR_TOOLBAR1 ) )
{
AfxMessageBox( "Loading toolbar failed." );
return -1;
}
m_Toolbar.EnableDocking( CBRS_ALIGN_ANY );
EnableDocking( CBRS_ALIGN_ANY );
DockControlBar( &m_Toolbar );
return 0;
}
// Moving mouse
void CBezierWnd::OnMouseMove( UINT nFlags, CPoint point )
{
point.y -= TOOLBAR_HEIGHT;
if ( m_Grabbed != m_Points.end() )
{
m_Grabbed->x = ( float ) point.x;
m_Grabbed->y = ( float ) point.y;
}
}
// Left clicking
void CBezierWnd::OnLButtonDown( UINT nFlags, CPoint point )
{
point.y -= TOOLBAR_HEIGHT;
m_Points.insert( CBezierPoint( point ) );
//CEdit label;
//label.SetParent( this );
//std::stringstream ss;
//ss << "p_" << m_Points.size();
//label.SetWindowTextA( ss.str().c_str() );
//CEdit l2(label);
}
// Middle clicking
void CBezierWnd::OnMButtonDown( UINT nFlags, CPoint point )
{
point.y -= TOOLBAR_HEIGHT;
for ( PointSetIt i = m_Points.begin(); i != m_Points.end(); ++i )
{
if ( abs( i->GetXi() - point.x ) < HANDLE_RANGE && abs( i->GetYi() - point.y ) < HANDLE_RANGE )
{
m_Grabbed = i;
break;
}
}
}
// Releasing middle click
void CBezierWnd::OnMButtonUp( UINT nFlags, CPoint point )
{
m_Grabbed = m_Points.end();
}
// Resizing window
void CBezierWnd::OnSize( UINT nType, int cx, int cy )
{
m_DimWnd.width = cx;
m_DimWnd.height = cy - TOOLBAR_HEIGHT;
}
// Pressing a key
void CBezierWnd::OnChar( UINT nChar, UINT nRepCnt, UINT nFlags )
{
switch ( nChar )
{
case 99:
m_Points.clear();
break;
}
}
// End update thread
void CBezierWnd::OnClose()
{
m_bRunning = false;
while ( !bDone )
; // wait for update thread to finish
this->DestroyWindow();
}
//*****************************************************************************
// WM_COMMAND messages
// hide polygon button is pressed
void CBezierWnd::OnHidePolygon()
{
m_bDrawPoly = false;
}
// show polygon button is pressed
void CBezierWnd::OnShowPolygon()
{
m_bDrawPoly = true;
}
// draw curve using de Casteljau's algorithm
void CBezierWnd::OnDeCasteljau()
{
m_bBernstein = false;
}
// draw curve using bernstein polynomials
void CBezierWnd::OnBernstein()
{
m_bBernstein = true;
}
| [
"[email protected]"
]
| [
[
[
1,
410
]
]
]
|
0eb5863b2b55359a6a8783f0363a5f71b5a4be54 | 611fc0940b78862ca89de79a8bbeab991f5f471a | /src/Options.cpp | a3852fb8e8d6c5176efc870cce40b0845b1e666b | []
| no_license | LakeIshikawa/splstage2 | df1d8f59319a4e8d9375b9d3379c3548bc520f44 | b4bf7caadf940773a977edd0de8edc610cd2f736 | refs/heads/master | 2021-01-10T21:16:45.430981 | 2010-01-29T08:57:34 | 2010-01-29T08:57:34 | 37,068,575 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,279 | cpp | #include "Options.h"
Options* Options::mInstance = new Options();
/**
標準コンストラクタ
自動的に呼ばれます
*/
Options::Options()
{
}
/**
標準デストラクタ
*/
Options::~Options()
{}
/************************************************************//**
* オプションを追加する
* \param rKey オプションのID(唯一)
* \param rVal オプションの値
* see Option
****************************************************************/
void Options::Add(string key, Option val)
{
mMapOptions[key] = val;
}
/************************************************************//**
* オプションを参照する
* \param rKey オプションのID(唯一)
* \return オプションの値
****************************************************************/
Options::Option Options::GetOption(string key)
{
return mMapOptions[key];
}
/************************************************************//**
* オプションが存在するかを尋ねる
* \param rKey オプションのID(唯一)
* \return 指定のオプションが存在するか
****************************************************************/
bool Options::IsOptionSet(string key)
{
return (mMapOptions.find(key) != mMapOptions.end());
} | [
"lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b"
]
| [
[
[
1,
48
]
]
]
|
2a1f5dafb5ceb6d53881ffed2756f22d54e28878 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/Assignment/CG_2nd/LightColor.cpp | 21d5f389739df14ed0a62406cc9d56548f29c66c | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,792 | cpp | // LightColor.cpp : 구현 파일입니다.
//
#include "stdafx.h"
#include "CG_2nd.h"
#include "LightColor.h"
// LightColor 대화 상자입니다.
IMPLEMENT_DYNAMIC(LightColor, CDialog)
LightColor::LightColor(CWnd* pParent /*=NULL*/)
: CDialog(LightColor::IDD, pParent)
{
f_ambientR = 0.2, f_ambientG = 0.2, f_ambientB = 0.2, f_ambientA = 1.0;
f_diffuseR = 0.6, f_diffuseG = 0.6, f_diffuseB = 0.6, f_diffuseA = 1.0;
f_specularR = 1.0, f_specularG = 1.0, f_specularB = 0.5, f_specularA = 1.0;
}
LightColor::~LightColor()
{
}
void LightColor::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_AMBIENT_R, f_ambientR);
DDX_Text(pDX, IDC_EDIT_AMBIENT_G, f_ambientG);
DDX_Text(pDX, IDC_EDIT_AMBIENT_B, f_ambientB);
DDX_Text(pDX, IDC_EDIT_AMBIENT_A, f_ambientA);
DDX_Text(pDX, IDC_EDIT_DIFFUSE_R, f_diffuseR);
DDX_Text(pDX, IDC_EDIT_DIFFUSE_G, f_diffuseG);
DDX_Text(pDX, IDC_EDIT_DIFFUSE_B, f_diffuseB);
DDX_Text(pDX, IDC_EDIT_DIFFUSE_A, f_diffuseA);
DDX_Text(pDX, IDC_EDIT_SPECULAR_R, f_specularR);
DDX_Text(pDX, IDC_EDIT_SPECULAR_G, f_specularG);
DDX_Text(pDX, IDC_EDIT_SPECULAR_B, f_specularB);
DDX_Text(pDX, IDC_EDIT_SPECULAR_A, f_specularA);
}
BEGIN_MESSAGE_MAP(LightColor, CDialog)
ON_BN_CLICKED(IDC_BUTTON_OK, &LightColor::OnBnClickedButtonOk)
ON_BN_CLICKED(IDC_BUTTON_CANCEL, &LightColor::OnBnClickedButtonCancel)
END_MESSAGE_MAP()
// LightColor 메시지 처리기입니다.
void LightColor::OnBnClickedButtonOk()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
UpdateData(TRUE);
OnOK();
}
void LightColor::OnBnClickedButtonCancel()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
OnCancel();
}
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
5951cc7ddac373af852550ce2b5f585cc6ac0f4c | d5fbc7df10c7397adae2437638d7b9f20552ad8d | /qcadlib/src/clippoly/poly.cc | 72704882c30da5beb6a4e7424778f2b0c8a14e0b | []
| no_license | Akaur/qdraw | 59997fcc1c0dde32f39c1ce130b40fe025e6d401 | 72d873b21c2fd549d9696caeab990bb2f3c26372 | refs/heads/master | 2020-12-01T01:12:31.608840 | 2009-03-19T02:33:35 | 2009-03-19T02:33:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,637 | cc | static const char rcs_id[] = "$Header: /cvsroot/clippoly/clippoly/poly.cc,v 1.7 2005/03/11 14:18:21 klamer Exp $";
// nclip: a polygon clip library
// Copyright (C) 1993 University of Twente
// [email protected]
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// $Log: poly.cc,v $
// Revision 1.7 2005/03/11 14:18:21 klamer
// Fixed namespace clash for abs(double) happening in RedHat 7.2 linux i386.
//
// Revision 1.6 2005/02/28 21:12:05 klamer
// Made changes such that gcc 3.4.2 compiles silent with -ansi -pedantic -Wall.
//
// Revision 1.5 2005/02/28 17:21:12 klamer
// Changed to have g++ 3.2.3 run silently using g++ -ansi -pedantic -Wall -Wno-unused -Wno-reorder.
// Change use of (libg++) String to ANSI C++ string.
//
// Revision 1.2 1994/01/04 12:55:37 klamer
// Made copy constructor of PolyNode a dummy, and added one which also
// sets parent.
// Make orientation use area rather than angles.
// Added Poly::revert() member.
// PolyIter::add: start with check whether current point already is in
// polygon.
// PolyIter::add_point(): now returns number of nodes added.
// ConstPolyIter::parent(const Poly &): Changed conditions.
//
// Revision 1.1 1993/10/27 14:44:07 klamer
// Initial revision
//
// Revision 1.1 1992/12/07 10:46:35 klamer
// Initial revision
//
#ifdef __GNUG__
#pragma implementation
#endif
#include <assert.h>
#include <err.h>
#include "poly.h"
#include "posadder.h"
//#include "boundingbox.h"
//#include "poly_use.h"
static const char h_rcs_id[] = POLY_H;
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
PolyNode::PolyNode( const PolyNode &)
{
// Argh! use constructor which sets parent!
error("This should not happen %s %d\n", __FILE__, __LINE__ );
}
PolyNode::PolyNode( const PolyNode © , const Poly *parent )
: p(copy.p), prev(0), _link(0), _parent_poly( parent), _edgestate( Unknown )
{
if (copy.next)
next = new PolyNode( *copy.next, parent );
else
next = 0;
}
PolyNode::~PolyNode()
{
if (next)
delete next;
}
const Poly *
PolyNode::parent_poly() const
{
assert(_parent_poly != 0);
return _parent_poly;
}
NodePEdge::NodePEdge( const DirPolyIter &dpi )
{
const PolyNode *node = dpi.node(),
*link = node->link();
if (link)
if (link < node)
n1 = link;
else
n1 = node;
else
n1 = node;
node = dpi.nextnode();
link = node->link();
if (link)
if (link < node)
n2 = link;
else
n2 = node;
else
n2 = node;
}
void
Poly::make_prev() const
{
PolyIter iter(*(Poly *)this);
PolyNode *last = 0;
while(iter())
{
iter.node()->prev = last;
last = iter.node();
}
((Poly *)this)->prev = last;
}
const PolyNode *
Poly::nextnode(const PolyNode *node) const
{
if (node->next)
return node->next;
return list;
}
const PolyNode *
Poly::prevnode(const PolyNode *node) const
{
assert(prev);
if (node->prev)
return node->prev;
return prev;
}
void
Poly::add( const Point &p, const Poly *parent, EdgeState edgestate )
{
if (!prev)
make_prev();
PolyNode *new_node = new PolyNode( p, parent, edgestate );
new_node->prev = prev;
new_node->next = 0;
assert( prev->next == 0 );
prev->next = new_node;
prev = new_node;
}
Orientation
Poly::orientation() const
{
if (!prev)
make_prev();
ConstPolyIter iter(*this);
double tot_angle = 0;
double area = 0;
Point first;
int first_flag = 1;
while(iter())
{
tot_angle += angle( iter.prevpoint(), iter.point(),
iter.nextpoint() ) - M_PI;
if (first_flag)
{
first_flag = 0;
first = iter.point();
continue;
}
// Point &p1 = iter.point(), &p2 = iter.nextpoint();
// NOTE: last step in iter also is not needed!
Point p1 = iter.point() - first,
p2 = iter.nextpoint() - first;
area += p1.x() * p2.y() - p2.x() * p1.y();
}
area /= 2.0;
assert(area != 0);
assert((area * tot_angle > 0) ||
(fabs(fabs(tot_angle) - M_PI * 2.0) > 0.0001));
#ifndef notdef
if (area < 0)
return ClockWise;
else
return CounterClockWise;
#else
if (tot_angle < 0)
{
assert(tot_angle < -M_PI * 1.9999);
assert(tot_angle > -M_PI * 2.0001);
return ClockWise;
} else {
assert(tot_angle > M_PI * 1.9999);
assert(tot_angle < M_PI * 2.0001);
return CounterClockWise;
}
#endif
}
double
Poly::area() const
{
if (!prev)
make_prev();
ConstPolyIter iter(*this);
double ret = 0;
Point first;
int first_flag = 1;
while(iter())
{
if (first_flag)
{
first_flag = 0;
first = iter.point();
continue;
}
Point p1 = iter.point() - first,
p2 = iter.nextpoint() - first;
ret += p1.x() * p2.y() - p2.x() * p1.y();
}
return ret / 2.0;
}
void
Poly::revert()
{
if (!prev)
make_prev();
PolyNode *next;
for(PolyNode *cur = list; cur != 0; cur = next)
{
next = cur->next;
cur->next = cur->prev;
cur->prev = next;
}
PolyNode *tmp = prev;
prev = list;
list = tmp;
// warning("NYI %s %d\n", __FILE__, __LINE__);
}
int
intersect_right( const Edge &edge, const Point &point )
{
if ((edge.p1().y() >= point.y()) && (edge.p2().y() >= point.y()))
return 0;
if ((edge.p1().y() < point.y()) && (edge.p2().y() < point.y()))
return 0;
if (edge.p1().y() == edge.p2().y())
return 0; // Tricky! This could give errors!
double x = (point.y() - edge.p1().y()) *
(edge.p2().x() - edge.p1().x()) / (edge.p2().y() - edge.p1().y())
+ edge.p1().x();
if (x > point.x()) // Tricky! Is >= better?
return 1;
return 0;
}
// is point inside *this?
int
Poly::has_point( const Point &point ) const
{
PolyIter iter( *(Poly *)((void *)this) );
int cnt = 0;
while(iter())
cnt += intersect_right( iter.edge(), point );
return cnt % 2;
}
double
Poly::xmin() const
{
ConstPolyIter iter(*this);
iter();
double res = iter.point().x();
while(iter())
{
double c = iter.point().x();
if (c < res)
res = c;
}
return res;
}
double
Poly::xmax() const
{
ConstPolyIter iter(*this);
iter();
double res = iter.point().x();
while(iter())
{
double c = iter.point().x();
if (c > res)
res = c;
}
return res;
}
double
Poly::ymin() const
{
ConstPolyIter iter(*this);
iter();
double res = iter.point().y();
while(iter())
{
double c = iter.point().y();
if (c < res)
res = c;
}
return res;
}
double
Poly::ymax() const
{
ConstPolyIter iter(*this);
iter();
double res = iter.point().y();
while(iter())
{
double c = iter.point().y();
if (c > res)
res = c;
}
return res;
}
PolyIter::PolyIter( Poly &_poly )
: poly(_poly), app_next(poly.list)
{
}
int
PolyIter::operator() ()
{
cur = app_next;
if (cur != 0)
{
app_next = cur->next;
return 1;
} else
return 0;
}
PolyNode *
PolyIter::add( const Point &point, int &new_point )
{
PolyIter chk(poly);
while(chk())
if (point == chk.node()->point())
return chk.node();
if (point == cur->p)
warning("This should not happen! %s, %d\n", __FILE__, __LINE__ );
// return cur;
double d = len( cur->p - point );
assert( d <= len( cur->p - AppNext()->p ) );
PolyNode *last = cur, *p = next( cur );
for( ;d > len( cur->p - p->p ); last = p, p = next( p ))
; // Go to next node, as next node is on same side as current node
if (p->p == point)
warning("This should not happen! %s, %d\n", __FILE__, __LINE__ );
// return p;
p = new PolyNode( point, &poly, last->next );
new_point++;
last->next = p;
if (p->next)
p->next->prev = p;
else if (poly.prev)
{
assert(poly.prev == last);
poly.prev = p;
}
p->prev = last;
return p;
}
int
PolyIter::add_point( PolyIter &a, PolyIter &b, const Point &p )
{
int res = 0;
PolyNode *node_a = a.add( p, res );
PolyNode *node_b = b.add( p, res );
assert((node_a->_link == 0) || (node_a->_link == node_b));
node_a->_link = node_b;
assert((node_b->_link == 0) || (node_b->_link == node_a));
node_b->_link = node_a;
return res;
}
ConstPolyIter::ConstPolyIter( const Poly &_poly )
: polyiter( *(Poly *)(void *)&_poly )
{
}
LogicStates
ConstPolyIter::parent(const Poly &poly)
{
switch(node()->edgestate())
{case None:
if (&poly == node()->parent_poly())
return True;
else
{
if (node()->link() != 0)
return UnKnown; // Prob. True
else
return False;
}
case Shared:
return UnKnown;
case Inside:
if (&poly == node()->parent_poly())
return UnKnown;
else {
if (node()->link() != 0)
return UnKnown;
else
return True;
}
case Unknown:
default:
fatal("This should not happen %s %d\n", __FILE__, __LINE__);
}
return UnKnown;
}
DirPolyIter::DirPolyIter( const Poly &poly, const PolyNode *node,
const Poly &link, IterDirection dir )
: _poly(poly), _linkpoly(link), _dir(dir), _node(node)
{
if (! _poly.prev)
_poly.make_prev();
if (!_linkpoly.prev)
_linkpoly.make_prev();
}
DirPolyIter::DirPolyIter( const DirPolyIter &dpi, IterDirection dir )
: _poly(dpi.linkpoly()), _linkpoly( dpi._poly ), _dir(dir),
_node( dpi.node()->link() )
{
if (! _poly.prev)
_poly.make_prev();
if (!_linkpoly.prev)
_linkpoly.make_prev();
}
const PolyNode *
DirPolyIter::nextnode() const
{
switch(dir())
{case FORWARD:
return _poly.nextnode(node());
case BACKWARD:
return _poly.prevnode(node());
default:
assert(0);
}
return 0; // Should not be reached
}
const PolyNode *
DirPolyIter::prevnode() const
{
switch(dir())
{case FORWARD:
return _poly.prevnode(node());
case BACKWARD:
return _poly.nextnode(node());
default:
assert(0);
}
return 0; // Should not be reached
}
EdgeState
DirPolyIter::edgestate() const
{
if (dir() == FORWARD)
return node()->edgestate();
return nextnode()->edgestate();
}
#ifdef notdef
int
Poly::intersect_table( int hor, Vec &intersection_table, double h )
{
ConstPolyIter iter(*this);
iter();
BoundingBox bbox(iter.point());
while(iter())
bbox.add(iter.point());
Point left( hor ? bbox.xmin()-1 : 0, hor ? 0 : bbox.ymin()-1 ),
right( hor ? bbox.xmax()+1 : 0, hor ? 0 : bbox.ymax()+1 );
if (hor)
left.y() = right.y() = h;
else
left.x() = right.x() = h;
int nr_inters;
if (hor)
create_intersection_table(*this, left, right,
nr_inters, intersection_table, x, y );
else
create_intersection_table(*this, left, right,
nr_inters, intersection_table, y, x );
return nr_inters;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
585
]
]
]
|
fa879201aa23b46d79ae165e1d7bf3e857168fa1 | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/ReportAsistent/GenerateDialog.h | 3793159067f9f1e4378f1232d86468893a47d8dc | []
| no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,275 | h | #if !defined(AFX_GENERATEDIALOG_H__B6BE28EE_6665_4B0C_82E9_8F658541580A__INCLUDED_)
#define AFX_GENERATEDIALOG_H__B6BE28EE_6665_4B0C_82E9_8F658541580A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// GenerateDialog.h : header file
//
/*
This file is part of LM Report Asistent.
Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova
LM Report Asistent 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.
LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/////////////////////////////////////////////////////////////////////////////
// CGenerateDialog dialog
/**
* class CGenerateDialog: Class of the Generation dialog.
*
* @author
*/
class CGenerateDialog : public CDialog
{
// Construction
public:
CGenerateDialog(CSkeletonDoc & DocumentToGenerate, CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CGenerateDialog)
enum { IDD = IDD_GENERATE_DIALOG };
BOOL m_bNewWordChecked;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGenerateDialog)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CGenerateDialog)
afx_msg void OnGenerateButton();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
CSkeletonDoc & m_SkeletonDocument;
virtual BOOL OnInitDialog();
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_GENERATEDIALOG_H__B6BE28EE_6665_4B0C_82E9_8F658541580A__INCLUDED_)
| [
"dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0",
"chrzm@fded5620-0c03-0410-a24c-85322fa64ba0",
"ibart@fded5620-0c03-0410-a24c-85322fa64ba0"
]
| [
[
[
1,
8
],
[
11,
11
],
[
28,
31
],
[
37,
73
]
],
[
[
9,
10
],
[
12,
27
],
[
32,
32
],
[
34,
36
]
],
[
[
33,
33
]
]
]
|
6bff376238ec85a8d9c3f9fd16efc04b785cfb3c | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEApplications/SE_OGLES2_Application/SEOGLES2Application/SEConsoleApplication.cpp | aeda36d379e008da93298e5e32a51006370b7cc8 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,661 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEOGLES2ApplicationPCH.h"
#include "SEConsoleApplication.h"
using namespace Swing;
//----------------------------------------------------------------------------
SEConsoleApplication::SEConsoleApplication()
{
}
//----------------------------------------------------------------------------
SEConsoleApplication::~SEConsoleApplication()
{
}
//----------------------------------------------------------------------------
int SEConsoleApplication::Run(int iArgCount, char** apcArgument)
{
SEConsoleApplication* pTheApp = (SEConsoleApplication*)TheApplication;
return pTheApp->Main(iArgCount, apcArgument);
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
41
]
]
]
|
738d4f467850feb7d058e20042edd9f5cedf3f29 | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/shared/so2/weapon_m4a1.cpp | 77ebe578cc19d89b58bd1c7c7ba248d403a60818 | []
| no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,213 | cpp | #include "cbase.h"
#include "weapon_sobase_machinegun.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef CLIENT_DLL
#define CWeaponM4A1 C_WeaponM4A1
#endif
class CWeaponM4A1 : public CSOMachineGun
{
public:
DECLARE_CLASS( CWeaponM4A1, CSOMachineGun );
CWeaponM4A1();
DECLARE_NETWORKCLASS();
DECLARE_PREDICTABLE();
void AddViewKick( void );
int GetMinBurst( void ) { return 1; }
int GetMaxBurst( void ) { return 1; }
float GetFireRate( void ) { return 0.075f; } // about 13.333 (repeating, of course) Hz
Activity GetPrimaryAttackActivity( void );
virtual const Vector& GetBulletSpread( void )
{
static Vector cone;
cone = VECTOR_CONE_4DEGREES;
return cone;
}
const WeaponProficiencyInfo_t *GetProficiencyValues();
// Add support for CS:S player animations
const char *GetWeaponSuffix( void ) { return "M4"; }
private:
CWeaponM4A1( const CWeaponM4A1 & );
};
IMPLEMENT_NETWORKCLASS_ALIASED( WeaponM4A1, DT_WeaponM4A1 )
BEGIN_NETWORK_TABLE( CWeaponM4A1, DT_WeaponM4A1 )
END_NETWORK_TABLE()
BEGIN_PREDICTION_DATA( CWeaponM4A1 )
END_PREDICTION_DATA()
LINK_ENTITY_TO_CLASS( weapon_m4a1, CWeaponM4A1 );
PRECACHE_WEAPON_REGISTER( weapon_m4a1 );
CWeaponM4A1::CWeaponM4A1()
{
m_fMinRange1 = 0; // in inches; no minimum range
m_fMaxRange1 = 23622; // in inches; about 600 meters
}
Activity CWeaponM4A1::GetPrimaryAttackActivity( void )
{
return ACT_VM_PRIMARYATTACK;
}
void CWeaponM4A1::AddViewKick( void )
{
CBasePlayer *pPlayer = ToBasePlayer( GetOwner() );
if ( !pPlayer )
return;
#define EASY_DAMPEN 0.5f
#define MAX_VERTICAL_KICK 8.0f // in degrees
#define SLIDE_LIMIT 3.0f // in seconds
DoMachineGunKick( pPlayer, EASY_DAMPEN, MAX_VERTICAL_KICK, m_fFireDuration, SLIDE_LIMIT );
}
const WeaponProficiencyInfo_t *CWeaponM4A1::GetProficiencyValues()
{
static WeaponProficiencyInfo_t proficiencyTable[] =
{
{ 7.0, 0.75 },
{ 5.00, 0.75 },
{ 3.0, 0.85 },
{ 5.0/3.0, 0.75 },
{ 1.00, 1.0 },
};
COMPILE_TIME_ASSERT( ARRAYSIZE(proficiencyTable) == WEAPON_PROFICIENCY_PERFECT + 1 );
return proficiencyTable;
}
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
]
| [
[
[
1,
94
]
]
]
|
b9548326cfb593f871f2d5c1c667a4ffbbdfce5e | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_gui_basics/widgets/juce_TableListBox.cpp | ec474f61bd5b96720f724728dedddbc31698f949 | []
| 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 | 15,608 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
class TableListRowComp : public Component,
public TooltipClient
{
public:
TableListRowComp (TableListBox& owner_)
: owner (owner_), row (-1), isSelected (false)
{
}
void paint (Graphics& g)
{
TableListBoxModel* const model = owner.getModel();
if (model != nullptr)
{
model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
const TableHeaderComponent& header = owner.getHeader();
const int numColumns = header.getNumColumns (true);
for (int i = 0; i < numColumns; ++i)
{
if (columnComponents[i] == nullptr)
{
const int columnId = header.getColumnIdOfIndex (i, true);
const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
Graphics::ScopedSaveState ss (g);
g.reduceClipRegion (columnRect);
g.setOrigin (columnRect.getX(), 0);
model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
}
}
}
}
void update (const int newRow, const bool isNowSelected)
{
jassert (newRow >= 0);
if (newRow != row || isNowSelected != isSelected)
{
row = newRow;
isSelected = isNowSelected;
repaint();
}
TableListBoxModel* const model = owner.getModel();
if (model != nullptr && row < owner.getNumRows())
{
const Identifier columnProperty ("_tableColumnId");
const int numColumns = owner.getHeader().getNumColumns (true);
for (int i = 0; i < numColumns; ++i)
{
const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
Component* comp = columnComponents[i];
if (comp != nullptr && columnId != (int) comp->getProperties() [columnProperty])
{
columnComponents.set (i, nullptr);
comp = nullptr;
}
comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
columnComponents.set (i, comp, false);
if (comp != nullptr)
{
comp->getProperties().set (columnProperty, columnId);
addAndMakeVisible (comp);
resizeCustomComp (i);
}
}
columnComponents.removeRange (numColumns, columnComponents.size());
}
else
{
columnComponents.clear();
}
}
void resized()
{
for (int i = columnComponents.size(); --i >= 0;)
resizeCustomComp (i);
}
void resizeCustomComp (const int index)
{
Component* const c = columnComponents.getUnchecked (index);
if (c != nullptr)
c->setBounds (owner.getHeader().getColumnPosition (index)
.withY (0).withHeight (getHeight()));
}
void mouseDown (const MouseEvent& e)
{
isDragging = false;
selectRowOnMouseUp = false;
if (isEnabled())
{
if (! isSelected)
{
owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
const int columnId = owner.getHeader().getColumnIdAtX (e.x);
if (columnId != 0 && owner.getModel() != nullptr)
owner.getModel()->cellClicked (row, columnId, e);
}
else
{
selectRowOnMouseUp = true;
}
}
}
void mouseDrag (const MouseEvent& e)
{
if (isEnabled() && owner.getModel() != nullptr && ! (e.mouseWasClicked() || isDragging))
{
const SparseSet<int> selectedRows (owner.getSelectedRows());
if (selectedRows.size() > 0)
{
const var dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
if (! (dragDescription.isVoid() || (dragDescription.isString() && dragDescription.toString().isEmpty())))
{
isDragging = true;
owner.startDragAndDrop (e, dragDescription);
}
}
}
}
void mouseUp (const MouseEvent& e)
{
if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
{
owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
const int columnId = owner.getHeader().getColumnIdAtX (e.x);
if (columnId != 0 && owner.getModel() != nullptr)
owner.getModel()->cellClicked (row, columnId, e);
}
}
void mouseDoubleClick (const MouseEvent& e)
{
const int columnId = owner.getHeader().getColumnIdAtX (e.x);
if (columnId != 0 && owner.getModel() != nullptr)
owner.getModel()->cellDoubleClicked (row, columnId, e);
}
String getTooltip()
{
const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
if (columnId != 0 && owner.getModel() != nullptr)
return owner.getModel()->getCellTooltip (row, columnId);
return String::empty;
}
Component* findChildComponentForColumn (const int columnId) const
{
return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
}
private:
TableListBox& owner;
OwnedArray<Component> columnComponents;
int row;
bool isSelected, isDragging, selectRowOnMouseUp;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
};
//==============================================================================
class TableListBoxHeader : public TableHeaderComponent
{
public:
TableListBoxHeader (TableListBox& owner_)
: owner (owner_)
{
}
void addMenuItems (PopupMenu& menu, int columnIdClicked)
{
if (owner.isAutoSizeMenuOptionShown())
{
menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
menu.addSeparator();
}
TableHeaderComponent::addMenuItems (menu, columnIdClicked);
}
void reactToMenuItem (int menuReturnId, int columnIdClicked)
{
switch (menuReturnId)
{
case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
case autoSizeAllId: owner.autoSizeAllColumns(); break;
default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
}
}
private:
TableListBox& owner;
enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
};
//==============================================================================
TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
: ListBox (name, nullptr),
header (nullptr),
model (model_),
autoSizeOptionsShown (true)
{
ListBox::model = this;
setHeader (new TableListBoxHeader (*this));
}
TableListBox::~TableListBox()
{
}
void TableListBox::setModel (TableListBoxModel* const newModel)
{
if (model != newModel)
{
model = newModel;
updateContent();
}
}
void TableListBox::setHeader (TableHeaderComponent* newHeader)
{
jassert (newHeader != nullptr); // you need to supply a real header for a table!
Rectangle<int> newBounds (0, 0, 100, 28);
if (header != nullptr)
newBounds = header->getBounds();
header = newHeader;
header->setBounds (newBounds);
setHeaderComponent (header);
header->addListener (this);
}
int TableListBox::getHeaderHeight() const
{
return header->getHeight();
}
void TableListBox::setHeaderHeight (const int newHeight)
{
header->setSize (header->getWidth(), newHeight);
resized();
}
void TableListBox::autoSizeColumn (const int columnId)
{
const int width = model != nullptr ? model->getColumnAutoSizeWidth (columnId) : 0;
if (width > 0)
header->setColumnWidth (columnId, width);
}
void TableListBox::autoSizeAllColumns()
{
for (int i = 0; i < header->getNumColumns (true); ++i)
autoSizeColumn (header->getColumnIdOfIndex (i, true));
}
void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
{
autoSizeOptionsShown = shouldBeShown;
}
bool TableListBox::isAutoSizeMenuOptionShown() const
{
return autoSizeOptionsShown;
}
Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
const bool relativeToComponentTopLeft) const
{
Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
if (relativeToComponentTopLeft)
headerCell.translate (header->getX(), 0);
return getRowPosition (rowNumber, relativeToComponentTopLeft)
.withX (headerCell.getX())
.withWidth (headerCell.getWidth());
}
Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
{
TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
return rowComp != nullptr ? rowComp->findChildComponentForColumn (columnId) : 0;
}
void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
{
ScrollBar* const scrollbar = getHorizontalScrollBar();
if (scrollbar != nullptr)
{
const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
double x = scrollbar->getCurrentRangeStart();
const double w = scrollbar->getCurrentRangeSize();
if (pos.getX() < x)
x = pos.getX();
else if (pos.getRight() > x + w)
x += jmax (0.0, pos.getRight() - (x + w));
scrollbar->setCurrentRangeStart (x);
}
}
int TableListBox::getNumRows()
{
return model != nullptr ? model->getNumRows() : 0;
}
void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
{
}
Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
{
if (existingComponentToUpdate == nullptr)
existingComponentToUpdate = new TableListRowComp (*this);
static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
return existingComponentToUpdate;
}
void TableListBox::selectedRowsChanged (int row)
{
if (model != nullptr)
model->selectedRowsChanged (row);
}
void TableListBox::deleteKeyPressed (int row)
{
if (model != nullptr)
model->deleteKeyPressed (row);
}
void TableListBox::returnKeyPressed (int row)
{
if (model != nullptr)
model->returnKeyPressed (row);
}
void TableListBox::backgroundClicked()
{
if (model != nullptr)
model->backgroundClicked();
}
void TableListBox::listWasScrolled()
{
if (model != nullptr)
model->listWasScrolled();
}
void TableListBox::tableColumnsChanged (TableHeaderComponent*)
{
setMinimumContentWidth (header->getTotalWidth());
repaint();
updateColumnComponents();
}
void TableListBox::tableColumnsResized (TableHeaderComponent*)
{
setMinimumContentWidth (header->getTotalWidth());
repaint();
updateColumnComponents();
}
void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
{
if (model != nullptr)
model->sortOrderChanged (header->getSortColumnId(),
header->isSortedForwards());
}
void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
{
columnIdNowBeingDragged = columnIdNowBeingDragged_;
repaint();
}
void TableListBox::resized()
{
ListBox::resized();
header->resizeAllColumnsToFit (getVisibleContentWidth());
setMinimumContentWidth (header->getTotalWidth());
}
void TableListBox::updateColumnComponents() const
{
const int firstRow = getRowContainingPosition (0, 0);
for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
{
TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
if (rowComp != nullptr)
rowComp->resized();
}
}
//==============================================================================
void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
void TableListBoxModel::backgroundClicked() {}
void TableListBoxModel::sortOrderChanged (int, const bool) {}
int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
void TableListBoxModel::selectedRowsChanged (int) {}
void TableListBoxModel::deleteKeyPressed (int) {}
void TableListBoxModel::returnKeyPressed (int) {}
void TableListBoxModel::listWasScrolled() {}
String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
var TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return var::null; }
Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
{
(void) existingComponentToUpdate;
jassert (existingComponentToUpdate == nullptr); // indicates a failure in the code the recycles the components
return nullptr;
}
END_JUCE_NAMESPACE
| [
"ow3nskip"
]
| [
[
[
1,
490
]
]
]
|
46b0191f1a2d7d1124cacfc1520fbe098fc276ed | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXCustomizePage.h | c2da7e2c278a08082af5aa5aa99df4e8f5a55d90 | []
| no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 14,564 | h | // ==========================================================================
// Class Specification: COXCustomizePage
// ==========================================================================
// Header file : OXCustomizePage.h
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
/*
Overview
COXCustomizePage is the base CWnd-derived class of any customize page. It defines the
way interface of a page. Using this interface Customize manager
(see COXCustomizeManager class documentation for details) can retrieve informaton on
how this page will be displayed in the Customize manager shortcut bar control. Also
this interface defines a way of communication between the manager and customize pages
it includes.
COXCustomizePage interface is defined as a set of virtual functions that can be
overridden in a derived class (and in some cases they must be overridden in order to
get a consumable results). The default implementation of these functions don't do
a lot and, generally speaking, COXCustomizePage can be considered as a template
for implementing any specific customize page.
A customize page is usually responsible for customization of a particular aspect of
an application and doesn't depend on other customize pages. It is always displayed
as a child window of the customize manager window and it should support resizing
functionality as long as customize manager is resizable. Customize page is created on
the base of dialog template that is associated with it. COXCustomizePage includes
the following function that creates the page window:
virtual BOOL Create(LPCTSTR lpszTemplateName, CWnd* pParentWnd,
CRect rect, UINT nID, DWORD dwStyle=WS_VISIBLE|WS_CHILD);
Usage
You will use COXCustomizePage in the case you need to create your own customize page.
In order to do that follow these steps:
1) In the derived class implement the following virtual functions that define the
location of the page in the customize manager shortcut bar:
virtual CString GetTitle() const;
virtual LPCTSTR GetImageResource() const;
virtual COLORREF GetImageMask() const;
virtual CString GetTooltip() const;
virtual CString GetGroup() const;
2) Implement these functions in order to support "Apply" button in Customize manager:
virtual BOOL ApplyChanges();
virtual BOOL IsSupportingApplyChanges();
3) Override this function:
virtual void OnInitDialog();
in order to initialize internal controls once right after the customize page
window was created (the same like for CDialog derived classes)
4) Override the following two functions in order to handle the activation and
deactivation events (Customize manager displays only one customize page at a
time, such page is called active):
virtual BOOL Load(const COXCustomizeManager* pCustomizeManager);
virtual void Unload();
5) And, finally, if you need to save any settings defined in the page that has been
changed you must implement the following function:
virtual BOOL SaveWorkspaceState();
These are the steps that you should take in order to implement any custom made
customize page.
Customize Manager Framework wouldn't be such a valuable part of the library if it
didn't include some predefined customize pages (we call them standard customize
pages) with implemented customization functionality. And we have plenty of them.
In order to include a standard page in customize manager you only have to add a
corresponding define to your stdafx.h file. Below you will find brief description
of the standard pages and the name of the corresponding defines that should be used
in order to include them in the customize manager. You have to refer to corresponding
classes documentation for the details on a particular customize page classes. This
information will only give you an overview of the available standard customize pages.
1) Customize Toolbars
Allows you to customize the appearance of the toolbars in the application. Also
you can add new toolbars, delete existing ones or rename them.
COXCustomizeToolbarsPage class implements this page.
The following define must be put in your stdafx.h file in order to include the
page in the customize manager
#define OX_CUSTOMIZE_TOOLBARS
The following function defined in COXCustomizeManager class must be called
from WM_CREATE handler of the application main window where customize manager
object is defined. It initializes toolbars page settings
BOOL InitializeToolbars(BOOL bCoolLook=TRUE, BOOL bShowGripper=TRUE,
BOOL bShowTooltips=TRUE, int nBorderSize=0,
LPCTSTR lpszProfileName=_T("CustomizeToolbars"));
2) Customize Commands
Allows you to customize the contents of the toolbars and menus in the application.
The apparance of the menu items and toolbar buttons can be changed as well.
The updated contents can be saved to registry. Next time your application runs
the saved contents will be applied.
COXCustomizeCommandsPage class implements this page.
The following define must be put in your stdafx.h file in order to include the
page in the customize manager
#define OX_CUSTOMIZE_COMMANDS
The following function defined in COXCustomizeManager class must be called
from WM_CREATE handler of the application main window where customize manager
object is defined. It initializes commands set and applies the toolbars and menu
saved data
BOOL InitializeCommands(LPCTSTR lpszCustomImagesResource,
COLORREF clrMask=RGB(192,192,192),
BOOL bShowIconsInMenu=TRUE,
LPCTSTR lpszProfileName=_T("CustomizeCommands"));
The best way of learning about Customize manager capabilities is to take look at the
VisualStudioLikeDemo sample that can be found in the
.\Samples\Advanced\VisualStudioLikeDemo subdirectory of your Ultimate Toolbox
directory. In the sample menu choose "View"-"Customize" in order to display the
Customize manager window.
Dependency:
#include "OXCustomizePage.h"
Source code files:
"OXCustomizePage.cpp"
"OXLayoutManager.cpp"
*/
#if !defined(_OXCUSTOMIZEPAGE_H__)
#define _OXCUSTOMIZEPAGE_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "OXDllExt.h"
#include "OXLayoutManager.h"
#include "OXMainRes.h"
#ifndef DEFAULT_CUSTOMIZE_GROUP
#define DEFAULT_CUSTOMIZE_GROUP _T("Customize")
#endif // DEFAULT_CUSTOMIZE_GROUP
class COXCustomizeManager;
/////////////////////////////////////////////////////////////////////////////
// helper class
class COXHelperWnd : public CWnd
{
public: COXHelperWnd(){}
protected:
virtual void PostNCDestroy()
{
delete this;
}
};
/////////////////////////////////////////////////////////////////////////////
// COXCustomizePage window
class OX_CLASS_DECL COXCustomizePage : public CWnd
{
DECLARE_DYNCREATE(COXCustomizePage)
// Construction
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Constructs the object
COXCustomizePage();
// Attributes
public:
protected:
// pointer to the owner
COXCustomizeManager* m_pCustomizeManager;
// dialog resource ID for the page
UINT m_nDialogID;
// layout manager object that can be used in order to resize child controls
// on the page whenever size of the page is changed
COXLayoutManager m_LayoutManager;
// name of the profile name or registry hive where the page's state info
// might be saved
CString m_sProfileName;
// flag that is set when a page is fully initialized
BOOL m_bInitialized;
// Operations
public:
// --- In : lpszTemplateName - contains a null-terminated string that is
// the name of a page template resource
// pParentWnd - points to the parent window object (of
// type CWnd) to which the page object
// belongs. If it is NULL, the page objectís
// parent window is set to the main
// application window
// rect - the size and position of the page,
// in client coordinates of pParentWnd.
// nID - the ID of the child window
// dwStyle - specifies the window style attributes
// --- Out :
// --- Returns: TRUE if successful; FALSE otherwise
// --- Effect : Create page window from specified template.
virtual BOOL Create(LPCTSTR lpszTemplateName, CWnd* pParentWnd,
CRect rect, UINT nID, DWORD dwStyle=WS_VISIBLE|WS_CHILD);
// --- In : pCustomizeManager - a pointer to COXCustomizeManager object
// that contains this page and is about to
// load it
// --- Out :
// --- Returns: TRUE if page was successfully loaded; FALSE otherwise
// --- Effect : Called by customize manager while activating the page.
// This function might be called multiple times. Before
// activating another page customize manager will call
// Unload() function
virtual BOOL Load(const COXCustomizeManager* pCustomizeManager);
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Called by customize manager when currently active page is about
// to be deactivated. Matches Load() function call
virtual void Unload();
// --- In : bIsOk - TRUE if the customize manager window is being closed
// as a result of pressing "OK" button; FALSE otherwise
// --- Out :
// --- Returns: TRUE if the page was successfully closed; FALSE otherwise
// --- Effect : Called by customize manager to close the page. Advanced
// overridable, use your own implementation in the case you
// need to handle the close event.
virtual BOOL OnCloseManager(BOOL bIsOk)
{
UNREFERENCED_PARAMETER(bIsOk);
return TRUE;
}
// --- In :
// --- Out :
// --- Returns: TRUE if the state of the subject this customize page responsible
// for was saved in the registry successfully; FALSE otherwise
// --- Effect : Saves in the registry the state of the subject this customize
// page responsible for. Called internally by customize manager.
virtual BOOL SaveWorkspaceState();
// --- In :
// --- Out :
// --- Returns: TRUE if changes were applied successfully; FALSE otherwise
// --- Effect : Applies the changes. Called internally by customize manager when
// "Apply" button is pressed.
virtual BOOL ApplyChanges() { return TRUE; }
// --- In :
// --- Out :
// --- Returns: TRUE if changes can be applied immediately; FALSE otherwise
// --- Effect : Retrieves the flag that specifies that changes can be applied
// immediately to the subject this customize page responsible for.
// Called internally by customize manager in order to enable/disable
// the "Apply" button.
virtual BOOL IsSupportingApplyChanges() { return TRUE; }
// --- In :
// --- Out :
// --- Returns: The title of the page as it appears in customize manager's
// shortcut bar
// --- Effect : Retrieves the title of the page. This string will appear on the
// corresponding item in the customize manager's shortcut bar
virtual CString GetTitle() const { return _T(""); }
// --- In :
// --- Out :
// --- Returns: The resource string of the image of the page as it appears in
// customize manager's shortcut bar
// --- Effect : Retrieves the resource string of the image of the page.
// This image will appear on the corresponding item in the customize
// manager's shortcut bar
virtual LPCTSTR GetImageResource() const { return NULL; }
// --- In :
// --- Out :
// --- Returns: The mask color for the bitmap that specifies the image of the page
// --- Effect : Retrieves the mask color for the bitmap that specifies the image
// of the page
virtual COLORREF GetImageMask() const { return RGB(192,192,192); }
// --- In :
// --- Out :
// --- Returns: The tooltip for the page item as it appears in customize manager's
// shortcut bar
// --- Effect : Retrieves the tooltip for the page item.
virtual CString GetTooltip() const { return _T(""); }
// --- In :
// --- Out :
// --- Returns: The name of the group this page belongs to.
// --- Effect : Retrieves the name of the group this page belongs to.
virtual CString GetGroup() const { return DEFAULT_CUSTOMIZE_GROUP; }
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COXCustomizePage)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra,
AFX_CMDHANDLERINFO* pHandlerInfo);
//}}AFX_VIRTUAL
// Implementation
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Destructs the object
virtual ~COXCustomizePage();
protected:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Called internally just after the page window was created.
// Override this function in order to initialize the controls
// on the page. Don't forget to call the default implementation
// unless you duplicate it in your code
virtual void OnInitDialog()
{
UpdateData(FALSE);
m_LayoutManager.Attach(this);
}
#ifndef _AFX_NO_OCC_SUPPORT
// data and functions necessary for OLE control containment
_AFX_OCC_DIALOG_INFO* m_pOccDialogInfo;
virtual BOOL SetOccDialogInfo(_AFX_OCC_DIALOG_INFO* pOccDialogInfo);
#endif
// Generated message map functions
protected:
//{{AFX_MSG(COXCustomizePage)
afx_msg void OnDestroy();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(_OXCUSTOMIZEPAGE_H__)
| [
"[email protected]"
]
| [
[
[
1,
405
]
]
]
|
4c09227ef12952cb3bb393703175977ef2a1ec42 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Applications/Application3/WmlGlutApplication.cpp | 606001561f8b4f4cbc22d2f05dc439ab8795dde3 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,548 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifdef WML_USE_GLUT
#include "WmlApplication.h"
#include "WmlGlutRenderer.h"
#include "WmlOpenGLCamera.h"
#ifdef WIN32
// The DirectShow header dshow.h includes windowsx.h. The latter header file
// #define-s GetWindowID(hwnd) to be GetDlgCtrlID(hwnd). I received a report
// that WmlGlutApplication.cpp fails to compile using VC 7.1, the failure
// being that the #define interferes with Application::GetWindowID. I was
// not able to reproduce the problem, but just in case...
#ifdef GetWindowID
#undef GetWindowID
#endif
#pragma comment(lib,"opengl32.lib")
#pragma comment(lib,"glu32.lib")
#pragma comment(lib,"glut32.lib")
#pragma comment(lib,"WildMagic2.lib")
#pragma comment(lib,"WmlRenderer.lib")
#endif
using namespace Wml;
const int Application::KEY_ESCAPE = 0x1B;
const int Application::KEY_LEFT_ARROW = GLUT_KEY_LEFT;
const int Application::KEY_RIGHT_ARROW = GLUT_KEY_RIGHT;
const int Application::KEY_UP_ARROW = GLUT_KEY_UP;
const int Application::KEY_DOWN_ARROW = GLUT_KEY_DOWN;
const int Application::KEY_HOME = GLUT_KEY_HOME;
const int Application::KEY_END = GLUT_KEY_END;
const int Application::KEY_PAGE_UP = GLUT_KEY_PAGE_UP;
const int Application::KEY_PAGE_DOWN = GLUT_KEY_PAGE_DOWN;
const int Application::KEY_INSERT = GLUT_KEY_INSERT;
const int Application::KEY_DELETE = 0x2E;
const int Application::KEY_F1 = GLUT_KEY_F1;
const int Application::KEY_F2 = GLUT_KEY_F2;
const int Application::KEY_F3 = GLUT_KEY_F3;
const int Application::KEY_F4 = GLUT_KEY_F4;
const int Application::KEY_F5 = GLUT_KEY_F5;
const int Application::KEY_F6 = GLUT_KEY_F6;
const int Application::KEY_F7 = GLUT_KEY_F7;
const int Application::KEY_F8 = GLUT_KEY_F8;
const int Application::KEY_F9 = GLUT_KEY_F9;
const int Application::KEY_F10 = GLUT_KEY_F10;
const int Application::KEY_F11 = GLUT_KEY_F11;
const int Application::KEY_F12 = GLUT_KEY_F12;
const int Application::KEY_SHIFT = GLUT_ACTIVE_SHIFT;
const int Application::KEY_CONTROL = GLUT_ACTIVE_CTRL;
const int Application::KEY_ALT = GLUT_ACTIVE_ALT;
const int Application::KEY_COMMAND = 0;
const int Application::MOUSE_LEFT_BUTTON = GLUT_LEFT_BUTTON;
const int Application::MOUSE_MIDDLE_BUTTON = GLUT_MIDDLE_BUTTON;
const int Application::MOUSE_RIGHT_BUTTON = GLUT_RIGHT_BUTTON;
const int Application::MOUSE_UP = GLUT_UP;
const int Application::MOUSE_DOWN = GLUT_DOWN;
// Reading the state of the modifiers from GLUT cannot be done within
// the motion callback. Hence, we cache it here.
static unsigned int gs_uiGLUTModifiers = 0;
//----------------------------------------------------------------------------
void Application::RequestTermination ()
{
exit(0);
}
//----------------------------------------------------------------------------
float Application::GetTimeInSeconds ()
{
float fTime = 0.001f*glutGet((GLenum)GLUT_ELAPSED_TIME);
return fTime;
}
//----------------------------------------------------------------------------
float Application::StringWidth (const char* acText)
{
assert( acText && strlen(acText) > 0 );
return 8.0f*strlen(acText);
}
//----------------------------------------------------------------------------
float Application::CharWidth (const char)
{
return 8.0f;
}
//----------------------------------------------------------------------------
float Application::FontHeight ()
{
return 13.0f;
}
//----------------------------------------------------------------------------
static void ReshapeCallback (int iWidth, int iHeight)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnReshape(iWidth,iHeight);
}
//----------------------------------------------------------------------------
static void DisplayCallback ()
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnDisplay();
}
//----------------------------------------------------------------------------
static void IdleCallback ()
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnIdle();
}
//----------------------------------------------------------------------------
static void KeyDownCallback (unsigned char ucKey, int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnKeyDown(ucKey,iX,iY);
}
//----------------------------------------------------------------------------
static void KeyUpCallback (unsigned char ucKey, int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnKeyUp(ucKey,iX,iY);
}
//----------------------------------------------------------------------------
static void SpecialKeyDownCallback (int iKey, int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnSpecialKeyDown(iKey,iX,iY);
}
//----------------------------------------------------------------------------
static void SpecialKeyUpCallback (int iKey, int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnSpecialKeyUp(iKey,iX,iY);
}
//----------------------------------------------------------------------------
static void MouseClickCallback (int iButton, int iState, int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
{
int iModifiers = glutGetModifiers();
gs_uiGLUTModifiers = *(unsigned int*)&iModifiers;
pkTheApp->OnMouseClick(iButton,iState,iX,iY,gs_uiGLUTModifiers);
}
}
//----------------------------------------------------------------------------
static void MotionCallback (int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnMotion(iX,iY,gs_uiGLUTModifiers);
}
//----------------------------------------------------------------------------
static void PassiveMotionCallback (int iX, int iY)
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
pkTheApp->OnPassiveMotion(iX,iY);
}
//----------------------------------------------------------------------------
static void Terminate ()
{
Application* pkTheApp = Application::GetApplication();
if ( pkTheApp )
{
pkTheApp->OnTerminate();
glutDestroyWindow(pkTheApp->GetWindowID());
}
}
//----------------------------------------------------------------------------
int main (int iQuantity, char** apcArgument)
{
// The unique Application object must be created pre-main by a
// constuctor call in the application source file.
Application* pkTheApp = Application::GetApplication();
assert( pkTheApp );
if ( !pkTheApp )
return -1;
if ( atexit(Terminate) != 0 )
return -2;
glutInit(&iQuantity,apcArgument);
pkTheApp->SetCommand(new Command(iQuantity,apcArgument));
if ( !pkTheApp->OnPrecreate() )
return -3;
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize(pkTheApp->GetWidth(),pkTheApp->GetHeight());
pkTheApp->SetWindowID(glutCreateWindow(pkTheApp->GetWindowTitle()));
pkTheApp->SetRenderer(new GlutRenderer(pkTheApp->GetWindowID(),
pkTheApp->GetWidth(),pkTheApp->GetHeight()));
pkTheApp->SetCamera(new OpenGLCamera(pkTheApp->GetWidth(),
pkTheApp->GetHeight()));
if ( !pkTheApp->OnInitialize() )
return -4;
glutReshapeFunc(ReshapeCallback);
glutDisplayFunc(DisplayCallback);
glutIdleFunc(IdleCallback);
glutKeyboardFunc(KeyDownCallback);
glutKeyboardUpFunc(KeyUpCallback);
glutSpecialFunc(SpecialKeyDownCallback);
glutSpecialUpFunc(SpecialKeyUpCallback);
glutMouseFunc(MouseClickCallback);
glutMotionFunc(MotionCallback);
glutPassiveMotionFunc(PassiveMotionCallback);
glutMainLoop();
return 0;
}
//----------------------------------------------------------------------------
#endif
| [
"[email protected]"
]
| [
[
[
1,
237
]
]
]
|
4ca0e2b0a3cdcea0a0aa2f61ce14ef9e3a2f5cff | 09ea547305ed8be9f8aa0dc6a9d74752d660d05d | /Tests/TestApp/TestAppMain.cpp | 5df3773a2f8e71036a2fc8d003dac474964a8494 | []
| no_license | SymbianSource/oss.FCL.sf.mw.socialmobilefw | 3c49e1d1ae2db8703e7c6b79a4c951216c9c5019 | 7020b195cf8d1aad30732868c2ed177e5459b8a8 | refs/heads/master | 2021-01-13T13:17:24.426946 | 2010-10-12T09:53:52 | 2010-10-12T09:53:52 | 72,676,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | cpp | #include <QApplication>
#include <Mainwindow.h>
#include<qfile.h>
#include<qtextstream.h>
void debugOutput(QtMsgType type, const char *msg)
{
QFile logFile("c://data//TestAppLog.txt");
Q_ASSERT(logFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append ));
QTextStream stream(&logFile);
switch (type)
{
case QtDebugMsg:
stream<<msg<<"\n";
break;
case QtWarningMsg:
stream<<"Warning: ";
stream<<msg<<"\n";
break;
case QtCriticalMsg:
stream<<"Critical: ";
stream<<msg<<"\n";
break;
case QtFatalMsg:
stream<<"Fatal: ";
stream<<msg<<"\n";
break;
default:;
}
}
int main(int argc,char *argv[])
{
qInstallMsgHandler(debugOutput);
QApplication app(argc,argv);
MainWindow *mainWnd = new MainWindow();
mainWnd->showMaximized();
return app.exec();
}
| [
"none@none"
]
| [
[
[
1,
44
]
]
]
|
62ec0639d1d4d19a15ec976f6ea926efed4773aa | a5cc77a18ce104eefd5d117ac21a623461fe98ca | /domainsdockwidget.cpp | bfdc4f6aa0d1e910cb4c8b1e373cd6874e1f531b | []
| no_license | vinni-au/yax | 7267ccaba9ce8e207a0a2ea60f3c61b2602895f9 | 122413eefc71a31f4e6700cc958406d244bf9a8f | refs/heads/master | 2016-09-10T03:16:43.293156 | 2011-12-15T19:37:53 | 2011-12-15T19:37:53 | 32,195,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,404 | cpp | #include "domainsdockwidget.hpp"
DomainsWidget::DomainsWidget(QWidget *parent) :
QSplitter(parent)
{
m_domainsList = new QListView;
m_valuesList = new QListView;
QGroupBox* lwidget = new QGroupBox(tr("Домены"));
QGroupBox* rwidget = new QGroupBox(tr("Значения"));
QVBoxLayout* lvlayout = new QVBoxLayout;
QHBoxLayout* lhlayout = new QHBoxLayout;
m_btnDomainAdd = new QPushButton(tr("Добавить"));
m_btnDomainChange = new QPushButton(tr("Изменить"));
m_btnDomainDelete = new QPushButton(tr("Удалить"));
m_btnDomainUp = new QPushButton(tr("Выше"));
m_btnDomainDown = new QPushButton(tr("Ниже"));
lvlayout->setSpacing(5);
lvlayout->addWidget(m_btnDomainAdd);
lvlayout->addWidget(m_btnDomainChange);
lvlayout->addWidget(m_btnDomainDelete);
lvlayout->addStretch();
lvlayout->addWidget(m_btnDomainUp);
lvlayout->addWidget(m_btnDomainDown);
lhlayout->addWidget(m_domainsList);
lhlayout->addLayout(lvlayout);
lwidget->setLayout(lhlayout);
QVBoxLayout* rvlayout = new QVBoxLayout;
QHBoxLayout* rhlayout = new QHBoxLayout;
m_btnValueAdd = new QPushButton(tr("Добавить"));
m_btnValueChange = new QPushButton(tr("Изменить"));
m_btnValueDelete = new QPushButton(tr("Удалить"));
m_btnValueUp = new QPushButton(tr("Выше"));
m_btnValueDown = new QPushButton(tr("Ниже"));
rvlayout->setSpacing(5);
rvlayout->addWidget(m_btnValueAdd);
rvlayout->addWidget(m_btnValueChange);
rvlayout->addWidget(m_btnValueDelete);
rvlayout->addStretch();
rvlayout->addWidget(m_btnValueUp);
rvlayout->addWidget(m_btnValueDown);
rhlayout->addWidget(m_valuesList);
rhlayout->addLayout(rvlayout);
rwidget->setLayout(rhlayout);
addWidget(lwidget);
addWidget(rwidget);
QObject::connect(m_btnDomainAdd, SIGNAL(clicked()),
SLOT(domainAdd()));
QObject::connect(m_btnDomainChange, SIGNAL(clicked()),
SLOT(domainChange()));
QObject::connect(m_btnDomainDelete, SIGNAL(clicked()),
SLOT(domainDelete()));
QObject::connect(m_btnDomainUp, SIGNAL(clicked()),
SLOT(domainUp()));
QObject::connect(m_btnDomainDown, SIGNAL(clicked()),
SLOT(domainDown()));
QObject::connect(m_btnValueAdd, SIGNAL(clicked()),
SLOT(valueAdd()));
QObject::connect(m_btnValueChange, SIGNAL(clicked()),
SLOT(valueChange()));
QObject::connect(m_btnValueDelete, SIGNAL(clicked()),
SLOT(valueDelete()));
QObject::connect(m_btnValueUp, SIGNAL(clicked()),
SLOT(valueUp()));
QObject::connect(m_btnValueDown, SIGNAL(clicked()),
SLOT(valueDown()));
m_domainsList->setModel(YAXModels::instance()->domainModel());
m_valuesList->setModel(YAXModels::instance()->currentValuesModel());
connectSlots();
}
void DomainsWidget::connectSlots()
{
QObject::connect(m_domainsList->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
YAXModels::instance()->domainModel(), SLOT(domainSelectionChanged(QItemSelection,QItemSelection)));
QObject::connect(YAXModels::instance()->currentValuesModel(), SIGNAL(viewUpdateNeeded()),
SLOT(updateValuesView()));
}
void DomainsWidget::domainAdd()
{
YAXDomainsModel* model = yaxModels()->domainModel();
QItemSelectionModel* selected = m_domainsList->selectionModel();
int index;
int count = model->rowCount();
if (selected->selectedRows().count() == 0) {
index = model->rowCount();
} else index = selected->selectedRows().at(0).row();
model->insertRow(index);
m_domainsList->edit(model->index(index));
if (count == model->rowCount() + 1) {
selected->clear();
selected->select(model->index(index), QItemSelectionModel::Select);
DomainAddCommand* cmd = new DomainAddCommand(model->domainsList().at(index)->name, index);
undoStack()->push(cmd);
}
}
void DomainsWidget::domainChange()
{
QItemSelectionModel* selected = m_domainsList->selectionModel();
int count = selected->selectedRows().count();
if (count == 1)
m_domainsList->edit(selected->selectedRows().at(0));
}
void DomainsWidget::domainDelete()
{
YAXDomainsModel* model = YAXModels::instance()->domainModel();
QItemSelectionModel* selected = m_domainsList->selectionModel();
int count = selected->selectedRows().count();
for (int i = 0; i < count; ++i)
model->removeRow(selected->selectedRows().at(i).row(), QModelIndex());
selected->clear();
}
void DomainsWidget::domainUp()
{
YAXDomainsModel* model = YAXModels::instance()->domainModel();
QItemSelectionModel* selected = m_domainsList->selectionModel();
int count = model->rowCount();
if (selected->selectedRows().count()) {
int row = selected->selectedRows().at(0).row();
model->exchange(row, row - 1);
selected->clear();
int rows = 0;
if (row - 1 < count && row - 1 >= 0)
rows = row - 1;
else rows = row;
selected->select(model->index(rows), QItemSelectionModel::Select);
}
}
void DomainsWidget::domainDown()
{
YAXDomainsModel* model = YAXModels::instance()->domainModel();
QItemSelectionModel* selected = m_domainsList->selectionModel();
int count = model->rowCount();
if (selected->selectedRows().count()) {
int row = selected->selectedRows().at(0).row();
model->exchange(row, row + 1);
selected->clear();
int rows = 0;
if (row + 1 < count && row + 1 >= 0)
rows = row + 1;
else rows = row;
selected->select(model->index(rows), QItemSelectionModel::Select);
}
}
void DomainsWidget::valueAdd()
{
YAXValuesModel* model = yaxModels()->currentValuesModel();
int count = model->rowCount();
model->insertRow(count);
m_valuesList->edit(model->index(count));
}
void DomainsWidget::valueChange()
{
QItemSelectionModel* selected = m_valuesList->selectionModel();
int count = selected->selectedRows().count();
if (count == 1)
m_valuesList->edit(selected->selectedRows().at(0));
}
void DomainsWidget::valueDelete()
{
YAXValuesModel* model = YAXModels::instance()->currentValuesModel();
QItemSelectionModel* selected = m_valuesList->selectionModel();
int count = selected->selectedRows().count();
for (int i = 0; i < count; ++i)
model->removeRow(selected->selectedRows().at(i).row(), QModelIndex());
}
void DomainsWidget::valueUp()
{
YAXValuesModel* model = YAXModels::instance()->currentValuesModel();
QItemSelectionModel* selected = m_valuesList->selectionModel();
int count = model->rowCount();
if (selected->selectedRows().count()) {
int row = selected->selectedRows().at(0).row();
model->exchange(row, row - 1);
selected->clear();
int rows = 0;
if (row - 1 < count && row - 1 >= 0)
rows = row - 1;
else rows = row;
selected->select(model->index(rows), QItemSelectionModel::Select);
}
}
void DomainsWidget::valueDown()
{
YAXValuesModel* model = YAXModels::instance()->currentValuesModel();
QItemSelectionModel* selected = m_valuesList->selectionModel();
int count = model->rowCount();
if (selected->selectedRows().count()) {
int row = selected->selectedRows().at(0).row();
model->exchange(row, row + 1);
selected->clear();
int rows = 0;
if (row + 1 < count && row + 1 >= 0)
rows = row + 1;
else rows = row;
selected->select(model->index(rows), QItemSelectionModel::Select);
}
}
void DomainsWidget::updateValuesView()
{
m_valuesList->setFocus();
m_domainsList->setFocus();
}
DomainsDockWidget::DomainsDockWidget(QString title):
QDockWidget(title)
{
setWidget(m_widget = new DomainsWidget);
}
void DomainsDockWidget::connectSlots()
{
m_widget->connectSlots();
}
| [
"[email protected]"
]
| [
[
[
1,
242
]
]
]
|
503293cd57da3aafd0f1c91ac55927b167518ff9 | 9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e | /src/MainFrm.h | d28d63344fccee41dcefc361b020af922276c03d | []
| no_license | correosdelbosque/veryie | e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff | 6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1 | refs/heads/master | 2021-01-10T13:17:59.755108 | 2010-06-16T04:23:26 | 2010-06-16T04:23:26 | 53,365,953 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 34,366 | h | // MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__19E497C1_4ECF_11D3_9B1D_0000E85300AE__INCLUDED_)
#define AFX_MAINFRM_H__19E497C1_4ECF_11D3_9B1D_0000E85300AE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//########################################################
#include "StatusBarWithProgress.h"
#include "VeryIEView.h"
#include "ChildFrm.h"
#include "BaseExpObj.h"
//#include "OOExToolBar.hpp"
#include "ChevBar.h"
#include "MenuBar.h"
#include "AddressBarEx.h"
#include "TabDropTarget.h"
#include "ProxyList.h"
#include "AnimateIcon.h" // Added by ClassView
#include "AdvTabCtrl.h"
//add new
#include "ComboBar.h"
#include "macro.h"
#include "function.h"
//########################################################
//Define the CommandTarget ids
#define HTMLID_FIND 1
#define HTMLID_VIEWSOURCE 2
#define HTMLID_OPTIONS 3
//toolbar id
#define ID_TOOLBAR_ADDRESS AFX_IDW_TOOLBAR+1
#define ID_TOOLBAR_TAB AFX_IDW_TOOLBAR+2
#define ID_TOOLBAR_SEARCH AFX_IDW_TOOLBAR+3
#define ID_TOOLBAR_STATUS AFX_IDW_TOOLBAR+4
//some else put here
#define WSM_TRAY WM_USER+3
#define BORDER 2
#define DEFAULT_PROPERTY 0xFFFFFFFF
#define MAX_UNDO 24 //0x1a
#define MAX_HISTORY 10
//##############################################################
//window list
#define B_WINDOW 0xC00 //512
#define E_WINDOW 0xDFF
//external tool
#define B_EX_TOOL 0xE00 //256
#define E_EX_TOOL 0xEFF
//skin
#define B_SKIN 0xF00 //256
#define E_SKIN 0xFFF
//open all fav
#define B_OPEN_FAV 0x1000 //256
#define E_OPEN_FAV 0x10FF
//translation
#define B_TRANS 0x1100 //256
#define E_TRANS 0x11FF
//web proxy
#define B_WEB_PROXY 0x1200 //256
#define E_WEB_PROXY 0x12FF
//open all fav most
#define B_OPEN_FAV_MOST 0x1300 //256
#define E_OPEN_FAV_MOST 0x13FF
//open fav item
#define B_FAV 0x1400 //19455
#define E_FAV 0x5FFF
//open group
#define B_OPEN_GROUP 0x6000 //256
#define E_OPEN_GROUP 0x60FF
//addto group
#define B_ADDTO_GROUP 0x6100 //256
#define E_ADDTO_GROUP 0x61FF
//undo close
#define B_UNDO 0x6200 //256
#define E_UNDO 0x62FF
//addto this fav
#define B_ADDTO_FAV 0x6300 //256
#define E_ADDTO_FAV 0x63FF
//proxy server
#define B_PROXY 0x6400 //512
#define E_PROXY 0x65FF
//open group item
#define B_GROUP 0x6600 //4096
#define E_GROUP 0x75FF
//search item
#define B_SEARCH 0x7600 //512
#define E_SEARCH 0x77FF
//search item for drag menu
#define B_SEARCH_DRAG 0x7800 //512
#define E_SEARCH_DRAG 0x79FF
//go up
#define B_GO_UP 0x7A00 //256
#define E_GO_UP 0x7AFF
//sort save
#define B_SORT_SAVE 0x7B00 //256
#define E_SORT_SAVE 0x7BFF
//go back forward history
#define B_HISTORY 0x7C00 //256
#define E_HISTORY 0x7CFF
//not max 0x8000 !!!!
//for that: #define ID_FILE_NEW_BLANK 32772
//########################################################
//open in new window active option
#define INW_NORMAL 0x1
#define INW_ACTIVE 0x2
#define INW_INACTIVE 0x4
#define INW_OTHER_SIDE 0x8 //open to other side
//right click option
#define RC_NOT_FILTER 2
//########################################################
//tab icon
#define TI_NO -1 //no icon
#define TI_0 0 //blank page
#define TI_1 1 //progress 1 0 ~ 33%
#define TI_2 2 //progress 2 33% ~ 66%
#define TI_3 3 //progress 3 66% ~ 99%
#define TI_LOCK 4
#define TI_100 5 //100%
#define TI_PROTECT 6
#define TI_SAVE 7
#define TI_CLOSE 8
#define TI_READ 9
#define TI_MARK 10
#define TI_MAX TI_MARK
#define TI_COUNT 11
#define IS_TABICON(nIcon) (nIcon<TI_COUNT)
#define IS_FAVICON(nIcon) (nIcon>TI_MAX)
//########################################################
//work threads
UINT _cdecl SendDocuments(LPVOID file);
typedef struct stagDocuments
{
char filename[256];
BOOL IsLocalFile;
}sDocuments;
UINT _cdecl QuickSaveDocuments(LPVOID savefiles);
typedef struct stagSaveFiles
{
CString base;
CString filename;
CMapStringToString mapDLFiles;
CString root;
}sSaveFiles;
UINT _cdecl TSaveConfig(LPVOID con);
//########################################################
class CCollectorDlg;
class CLinkListDlg;
class CMonitor;
class CMainFrame;
//########################################################
extern CMainFrame* pmf;
extern CStringArray g_astrLinks;
extern CStringArray g_astrFavs;
extern const UINT MSWHELL_ROLLMSG;
extern float g_fSeed;
extern char g_szFile[1024];
extern char* g_strLngBuf;
extern BSTR g_bstrYes;
extern int g_nPercent;
extern int g_bMax;
extern int g_nMaxWins;
extern int g_nNextTab;
extern int g_nDefFontSize;
extern int g_nTrayIconID;
extern BOOL g_bSilent;
extern BOOL g_bDisScrollText;
extern BOOL g_bFilteBlank;
extern BOOL g_bLinkInNewWindow, g_bFileInNewWindow, g_bFavInNewWindow, g_bHisInNewWindow;
extern BOOL g_bConfirmCloseLock;
extern BOOL g_bForbidMult;
extern BOOL g_bVerbose;
extern BOOL g_bLockHomepage;
extern BOOL g_bProxyDirty;
extern BOOL g_bShowIndex;
extern BOOL g_bClickClose;
extern BOOL g_bShowDot;
extern BOOL g_bShowRead;
extern BOOL g_bShowFavIcon;
extern BOOL g_bRTab;
extern BOOL g_bKillPop,g_bKillAutoWin,g_bKillListWin,g_bKillDupWin;
//########################################################
class CMainFrame : public CMDIFrameWnd
{
DECLARE_DYNAMIC(CMainFrame)
public:
CMainFrame();
// Attributes
public:
BOOL m_bTopTab;
BOOL m_bReloadUnShownImage;
BOOL m_bKillBlank;
BOOL m_bNotFilterClickDialog;
BOOL m_bUseTargetFrameName;
BOOL m_bSimuDragLink;
BOOL m_bUseIeKey;
BOOL m_bFilterRefresh;
BOOL m_bShowGesture;
BOOL m_bNotSaveKeyword;
BOOL m_bShowSortSaveDlg;
BOOL m_bNameByTitle;
BOOL m_bSavePageByDate;
BOOL m_bActiveNewAddress;
BOOL m_bBlankMonitorClip;
BOOL m_nTabStyle;
BOOL m_bTabDefaultColor;
BOOL m_bConfirmUnsafePage;
BOOL m_bShowPageReadedIcon;
BOOL m_bAutoRunExternal;
BOOL m_bKeepOnePage;
BOOL m_bShowScriptResult;
BOOL m_bSearchMatchCase;
BOOL m_bSearchMatchWhole;
BOOL m_bOutputAutoClean;
BOOL m_bOutputSaveFilter;
BOOL m_bOutputSaveUrlFilter;
BOOL m_bOutputSaveImg;
BOOL m_bOutputSavePage;
BOOL m_bOutputSaveText;
BOOL m_bOutputSaveTime;
BOOL m_bCollectorAddtoBottom;
BOOL m_bForbidMainTitle;
BOOL m_bAutoRefreshActive;//enable auto refresh current
BOOL m_bNotShowRightMenu;
BOOL m_bEncryptStringItem;
BOOL m_bCloseCleanCache;
BOOL m_bCloseCleanCookies;
BOOL m_bCloseCleanFormData;
BOOL m_bCloseCleanHistory;
BOOL m_bCloseCleanTypedAddress;
BOOL m_bCloseCleanTypedSearch;
BOOL m_bCloseCleanUndoClose;
BOOL m_bDisableBackground;
BOOL m_bDirectOpenFile;
BOOL m_bOpenInNew;
BOOL m_bCloseAllBeforeNewGroup;
BOOL m_bFavShowUrl;
BOOL m_bComboShowIcon;
BOOL m_bGoProxyMenu;
BOOL m_bGroupMenuShowMember;
BOOL m_bMenuLoadLastClose;
BOOL m_bNotConfirmPopupFilter;
BOOL m_bPlayPopupFilterSound;
BOOL m_bShowToolbarLabel,m_bShowAddressBarButton;
BOOL m_bShowSearchBarButton;
BOOL m_bAutoPopWin;
BOOL m_bWheelTab,m_bWheelOnTab;
BOOL m_bUseDefaultFavPath;
BOOL m_bUseDefaultLinkPath;
BOOL m_bMinimizeToTray, m_bCloseToTray;
BOOL m_bShowTrayIcon;
BOOL m_bCloseAllWhenCloseToTray;
BOOL m_bOpenFolderOut;
BOOL m_bActiveFileNew;
BOOL m_bUrlFilterDirty;
BOOL m_bIsAutoSave;
int m_nLDbClickTabBlank;
int m_nRDbClickTabBlank;
int m_nFtpOpenType;//0:self,1:explorer,2:else
int m_nCleanAllMode;
int m_nManagerIndex;//download manager name
int m_nSearchBarAction;
int m_nPopFiltered;
int m_nCollectorTrans;
int m_nMonitorTrans;
DWORD m_dwFsShow;//full screen
DWORD m_dwAhShow;//auto hide
DWORD m_dwDefaultProperty;
POINT m_ptMouseDown;//last mouse down point
CTime m_tStartTime;
double m_nPopDelay;
COLORREF m_crUnSelColor;
COLORREF m_crUnSelFontColor;
COLORREF m_crSelFontColor;
COLORREF m_crSepColor;
CString m_strBlankContent;
CString m_strLastNavUrl;
CString m_strSortSaveFolder;
CString m_strFtpExePath;//ftp url open application path
CString m_strFormMainPwd;
CString m_strManagerScript;//download manager script
CString m_strManagerType;//download manager type
CString m_strStatusStringFormat;
CString m_strAutoSavePath;
CString m_strHomePage;
CString m_strFavPath;
CString m_strLinkPath;
CStringList m_astrTypedSearch;
CStringList m_astrFavoriteFolders;
CStringList m_astrPopup;
CStringList m_astrUnPopup;
CStringArray m_astrGroup;
CStringArray m_astrUrlFilter;
CStringArray m_astrUrlUnFilter;
// Operations
public:
BOOL DoSpecialUrl(CString str);
BOOL PromptMenuCommand(UINT nID);
BOOL NeedUrlFilter(CString strUrl);
BOOL NeedUnUrlFilter(CString strUrl);
BOOL UrlFilterStar(CStringArray &pattern, CString url);
BOOL NeedPopFilter(CString strUrl);
BOOL NeedUnPopFilter(CString strUrl);
BOOL PopFilterStar(CStringList &astr, CString url);
BOOL DoKeyMsg(MSG* pMsg);
BOOL DoMouseMsg(MSG* pMsg);
BOOL ActiveViewSetFocus();
BOOL IsDownloadAble(CString strUrl);
BOOL IsDownloading();
BOOL IsImageType(LPCTSTR lpszText);
BOOL GetScriptLangCode(CString &strCode, CString &strLang);
BOOL ConfirmPopupFilter(CString url, BOOL bConfirm);
//
int FindCacheFavIcon(CString strRoot);
int GetFavIcon(CString strUrl);
int GetPageKeyWordCount();
int IsMonitorVisible();
//
void SetAllTabFavIcon(CString strRoot, int nIcon);
void LoadGroup();
void SaveFilterList2File(BOOL bUrlFilter);
void AdjustMenuWidth(CString &str);
void DragDropLink(CString str, BOOL bActive);
void DragDropUrl(CString str, BOOL bActive);
void UpdateFilter(BOOL bEnable);
void OpenMenuUrl(UINT nID, CString strUrl, DWORD dwProperty, int nAutoRunCmd);
void DeleteFav(HMENU hSubMenu, UINT nID, int nButtonIndex, int nBarType);
void UpdateBandInfo(CToolBar *pBar, UINT uBandID);
void RefreshKillFlyingCode();
void RefreshKillBlankCode();
void RunKillFlying(CChildFrame* tcf);
void RunKillBlank(CChildFrame* tcf);
void RunReloadUnloadImage(CChildFrame* tcf);
void ClickPoint(int nInNewWindow);
void ReloadTabMenu();
void ShowBarLabel();
void SetAsDefaultBrowser();
void RunDownManagerScript(CString strNavigate,CChildFrame* tcf);
void HideSelectBars(DWORD dwShow);
void ShowSelectBars(DWORD dwShow);
void SaveSearchKey();
void MarkTab(CChildFrame *tcf);
void CloseAllKindPage(CChildFrame *tcf, int kind);
void RunScript(CString strCode);
void RunScriptByFrame(CString strCode,CString strLang,CChildFrame* tcf);
void RunOneScript(CString strCode,CChildFrame* tcf);
void CloseAllTabDirect();
void LockTab(CChildFrame *tcf);
void DoWithImgUrl(int type);
void DoWithLinkUrl(int type,CString strUrl,CString strText);
void DoWithText(int type,CString strUrl);
void OpenJumpUrl(CString strUrl);
void AddToCollector(CString strMsg, int type);
void InitToolBarImage(BOOL bReplaceIcon=FALSE);
void InitMainAnimIcon();
void InitLinkBarImage();
void InitFavBarImage();
void InitSystemBarImage();
void InitMenuBarImage();
void InitGoImage();
void InitTaskBarImage();
void SetMessageText(LPCTSTR lpszText);
void SearchKey(CString keyw, CString url);
void GetHtmlSelectedText(CString &str);
void GetGroupNameByIndex(int index, CString &strGroupName);
void OnToolsCollector(BOOL bShow);
void AddToPopList(CString url, int type);
void CollectorDrop(COleDataObject* pDataObject, DROPEFFECT dropEffect);
void DropFiles(HDROP hDropInfo);
void SetHomePage(CString strUrl);
void InitialUrlFilter();
DWORD GetDefaultProperty();
CString GetImageUrlByPoint(CPoint pt);
CString GetHomePage();
HBITMAP GetBitmap(LPCTSTR lpszText);
CChildFrame* GetChildFrameByUrl(CChildFrame* tcfCurrent, CString strUrl);
CChildFrame* GetChildFrameByTarget(CChildFrame* tcfCurrent, CString strTarget);
friend CTxtDropTarget;
private:
BOOL m_bLastIB;
int m_nBaseWidth;
int m_nNeedIB;
HICON m_hNormalIcon;
HICON m_hSecuIcon;
CLinkListDlg* m_pLinkListDlg;
CMonitor* m_pMonitor;
CCollectorDlg* m_pCollectDlg;
CTabDropTarget* ms_TabDropTarget;
BOOL GetAllLinks(CVeryIEView* pView);
BOOL IsBrowsing();
void OnGoUpPage();
void SessionHistory(CMenu* pMenu, int ID, CChildFrame* pcf);
void BuildWinButtons();
void ChangTabPos(int npos);
void SaveForm(BOOL bIsGeneral);
void LaunchEditor(LPCSTR editor, LPCSTR file);
void LaunchEmail(LPCSTR mailclient);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
public:
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
//control used by search
// Implementation
public:
BOOL m_bAllScroll;
BOOL m_bLockToolbar;
BOOL m_bShowHiddenFav;
BOOL m_bUseUrlFilter;
BOOL m_bUseFlyingFilter;
BOOL m_bUseDialogFilter;
BOOL m_bDisDownActivex;
BOOL m_bMouseCtrlScrSpeed;
BOOL m_bAnimatIcon;
BOOL m_bCateWithSite;
BOOL m_bImgCateWithSite;
BOOL m_bIsSecure, m_bLastIsSecure;
BOOL m_bSmallToolBar;
BOOL m_bDisplayOpenAll, m_bDisplayAddFav;
BOOL m_bSaveConfig;
BOOL m_bDefScrollAfterDL;
BOOL m_bDefUseAutoScroll;
BOOL m_bRemPsw;
BOOL m_bNoModemSpeed;
BOOL m_bAutoTab;
BOOL m_bColorIcon;
BOOL m_bMultiLineTab;
BOOL m_bFavDirty;
BOOL m_bFullScreenMode;
BOOL m_bFullScreened;
BOOL m_bAutoHideMode;
BOOL m_bAutoHided;
BOOL m_bEnProxy;
BOOL m_bIsOffline;//if offline state
BOOL m_abWinButtons[6];
BOOL m_bStatusBlank;
BOOL m_bRMouseDrag;
BOOL m_bRMouseGesture;
BOOL m_bActiveNewWindow;
BOOL m_bPopRightMenu;
int m_nMaxTabWidth;
int m_nMinTabWidth;
int m_nTextLabel; //0-no label, 1-show label, 2-selective text
int m_nNewSequence;
int m_nPreLines;
int m_nDialogFilterCount;
int m_nEnableFilter;
int m_nScrollArrowH;
int m_nScrollWidth;
int m_nAutoSave;
int m_nDefRefreshInterval;
int m_nExpWidth;
int m_nAllowDBC, m_nAllowMC, m_nAllowRC;
int m_nNewWindow;
int m_nUndoStart, m_nUndoEnd;
int m_nDefSrSpeed; //1-slow, 2-medium, 3-fast
int m_nAutoScrollPage;
int m_nInterval;
int m_nProtectNum;
int m_nCloseSequence; //0-default, 1-next, 2- pre
int m_nMenuWidth;
int m_nDownAll;//page download all
int m_nDefaultCharSet;
int m_nMenuStyle;
int m_nLDbClick;//left dbclick
int m_nLButtonDown;//left button down action
int m_nMButtonDown;//middle button down action
int m_nRButtonDown;//right button down action
int m_nLeftRight;//left right
int m_nRightLeft;//right left
int m_nImgUp;
int m_nImgDown;
int m_nImgLeft;
int m_nImgRight;
int m_nLinkUp;
int m_nLinkDown;
int m_nLinkLeft;
int m_nLinkRight;
int m_nTextUp;
int m_nTextDown;
int m_nTextLeft;
int m_nTextRight;
int m_nRTabID;
int m_nSwitch;
UINT m_nTitleLen;
UINT m_nState;
UINT m_nWin;
UINT m_nFavSize;
UINT m_nTimerID, m_nUpdateTimer, m_nAnimateIconTimer;
CString m_strCSE2;
CString m_strCSE1;
CString m_strCE2;
CString m_strCE1;
CString m_strSE1;
CString m_strSE2;
CString m_strShortCuts[12];
CString m_strSkinName;
CString m_strStartFavFolder;
CString m_strStartGroup;
CString m_strUndoURL[MAX_UNDO];
CString m_strUndoName[MAX_UNDO];
CString m_strProtectPwd;
CString m_strDefaultWebProxy;
CString m_strProxyByPass;
CString m_strCurProxy, m_strCurProxyName;
CString m_strIeProxy,m_strIeProxyByPass;
CString m_strHostName;
CString m_strDomain;
CString m_strBGColor;
CStringList m_astrOpenAll;
CStringList m_astrSkins;
DWORD m_dwWebProxyFrom;
CTime m_tLastRes;
CTime m_tLastIPUpdate;
HBITMAP m_bmBGPic;
CRect m_rMainRect;
COLORREF m_crPageBackColor;
CSearchList m_SearchList;//search list
CLinkList m_LinkList;//link list
CGestureList m_GestureList;
CFavIconList m_FavIconList;
CStatusBarWithProgress m_wndStatusBar;
CAdvTabCtrl m_wndTab;
CChevBar m_wndReBar;
CChevBar m_wndReBar2;
baseCMyBar m_wndInstantBar;
CBaseExpObj* m_pwndExpObj;
CToolBar m_wndToolBar;
CComboBoxEx* m_wndAddress;
CComboBoxEx* m_wndSearch;
CAddressBarEx m_AddressBar;
CComboBar m_SearchBar;
CToolBar m_SysMenuBar;
CProxyCategory m_aProxyCategories;
CAnimateIcon m_animIcon;
IInternetSession* m_pSession;
IClassFactory* m_pFactory;
CVeryIEView* m_pCurView;
//#######################################################
BOOL DecodeEscap(CString& strUrl);
BOOL GetFavoriteFolder(CString& strFav);
BOOL SetDefault(LPCSTR lpszKey, BOOL setdef);
BOOL HasExpBar(int nStr);
BOOL ResolveLink(LPCSTR lpszLinkFile, LPSTR lpszPath);
BOOL GetProxySetting(CString& proxy, CString& bypass);
BOOL DelTempFiles(DWORD CacheType, BOOL op=TRUE);
int AdjustTabWidth(BOOL bNoReCalSize = FALSE);
int GetUrlType(LPCTSTR URL);
int GetTabIcon(int nItem);
int FindDupURL(LPCSTR lpszURL, CChildFrame* pSelf);
int OpenAllFavs(LPCSTR lpszPath);
int FindTab(CChildFrame* lpFrame, BOOL bCleanBlank=FALSE);
int AddNewTab(CChildFrame* tcf, int CurID=-1, LPTSTR label=NULL, BOOL bAddLast=TRUE);
int BuildFavoritesMenu(LPCTSTR pszPath, int nStartPos, CMenu* pMenu, int nFixMenu /*=0*/, int FirstLevel /*= FALSE*/, int& nFavs);
void SetTabIcon(int nIcon, int nItem, CVeryIEView* pView);
void GetProfileReBarBandsState();
void WriteProfileReBarBandsState();
void UpdateUndoMenu();
void SaveLastClose();
void OpenLastClose();
void StopView(int nTabID);
void AddTrayIcon();
void DelTrayIcon();
void GetIeProxy();
void UpdateProxy();
void BuildGoUpMenu(CMenu *pPopup);
void BuildProxyMenu(CMenu *pPopup);
void BuildSearchMenu(BOOL bMenuBreak);
void BuildTextDropSearchMenu(CMenu *pPopup);
void OnEncode();
void MenuAppendSeparator(CMenu *pMenu);
void MenuInsertSeparator(CMenu *pMenu, UINT nPosition);
void MenuAppendOwnerItem(CMenu *pMenu, UINT nFlags, UINT nIDNewItem, CString str);
void MenuAppendOwnerUrl(CMenu *pMenu, UINT nFlags, UINT nIDNewItem, CString str, CString strUrl);
void MenuInserOwnerItem(CMenu *pMenu,UINT nPosition, UINT nFlags, UINT nIDNewItem,LPCTSTR lpszNewItem,int icon);
void GetSiteName(CString& site);
void UpdateTabTitleIndex(int nItem);
void OnOptionTabStyle();
void FixToolbar(BOOL bFixed);
void UninitialNameSpace();
void InitialNameSpace();
void BuildWebProxyMenu(CMenu* pMenu, int nType);
void StartUtil(int i);
void DefaultMail(LPCSTR mailto);
void SaveLastVisit(BOOL bVisiting);
void AddtoFavorite(BSTR bstrURL, VARIANT* pTitle);
void OpenGroup(LPCSTR gname);
void AddtoGroup(LPCSTR pszName, LPCSTR pszURL, UINT nID);
void MenuLoadGroupList(CMenu *pMenu, int type);
void MenuLoadGroupURL(CMenu *pMenu, CString strItem, int index);
void InitGroups();
void ToolBarSetCheck(CCmdUI* pCmdUI, BOOL bCheck);
void FavMenuAddURL(LPCSTR path, LPCSTR root, BOOL FirstLevel, BOOL IsLink, CMenu *pMenu, int nPos);
void FavMenuAddFolder(LPCSTR path, LPCSTR root, BOOL FirstLevel, BOOL IsLink, CMenu* pMenu, int& nEndPos);
void OnOptionMultiTab();
void OnOptionAutotab();
void InitToolBar(BOOL bReplaceIcon=FALSE);
void ShowBackground(BOOL bDisable = FALSE);
void ShowSkin();
void AddFavorite(CChildFrame* tcf);
void FullScreenModeOff(BOOL bOnlyBar=FALSE);
void FullScreenModeOn(BOOL bOnlyBar=FALSE);
void AutoHideModeOff();
void AutoHideModeOn();
void RemoveExp();
void BuildExpBar(LPCSTR lpszTitle);
void BuildUtilMenu();
void GetNetWorkInfo();
void AddToPopup(CChildFrame* pChFrm);
void AddMenuBreak(CMenu * pMenu,BOOL bFavMenu=TRUE);
void InitFavorites(BOOL bOnlyLink=FALSE);
void SaveTypedURL();
void LoadTypedURL();
void LoadTypedSearch();
void SetTabTitle(LPCSTR lpszTitle, int nItem);
void SetAddress(LPCTSTR lpszUrl);
CWnd* GetBandWnd(int id);
CString GetBandTitle(int id);
CString GetStandUrl( CString url );
CString GetProxyName(CString& proxy);
CMenu* GetMenu();
CChildFrame* NewChildWindow(int nIniLevel=1, int nOpenType=1, LPCSTR strUrl=NULL, CVeryIEView * pParentView=NULL, BOOL bForceActive=FALSE);
HRESULT ExecCmdTarget(DWORD nCmdID,CFixedHtmlView* pHVW);
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CMenu m_TabMenu;
CMenu m_TrayMenu;
CToolBar m_LinkBar;
CMenuBar m_wndMenuBar;
CToolBar m_FavBar;
HINSTANCE m_hResInst;
CString m_strMenuUrl, m_strMenuText;
CString GetLocalIP();
CString GetNetSpeed(int kind);
CString GetNetStat(int kind);
CString GetMemory();
CString GetOnlineTime();
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnFileNewBlank();
afx_msg void OnFileNewCurrentpage();
afx_msg void OnViewAddressbar();
afx_msg void OnViewTaskbar();
afx_msg void OnFileCloseall();
afx_msg void OnFileWorkoffline();
afx_msg void OnClose();
afx_msg void OnViewSource();
afx_msg void OnFileClose();
afx_msg void OnFileClose2();
afx_msg void OnToolsInternetoptions();
afx_msg void OnFavoritesAddtofavorites();
afx_msg void OnFavoritesOrgnizefavorites();
afx_msg void OnToolsAddtopopupfilter();
afx_msg void OnRtabAddtopopupfilter();
afx_msg void OnToolsEditpopupfilterlist();
afx_msg void OnUpdateFileWorkoffline(CCmdUI* pCmdUI);
afx_msg void OnUpdateMenu(CCmdUI* pCmdUI);
afx_msg void OnToolsEmail();
afx_msg void OnToolsAddr();
afx_msg void OnUpdateOptionsUseProxy(CCmdUI* pCmdUI);
afx_msg void OnOptionsUseProxy();
afx_msg void OnToolsCleanCookie();
afx_msg void OnToolsCache();
afx_msg void OnToolsAll();
afx_msg void OnToolsHistory();
afx_msg void OnOptionsSetProxy();
afx_msg void OnViewHis();
afx_msg void OnUpdateViewExp(CCmdUI* pCmdUI);
afx_msg void OnViewFullscreen();
afx_msg void OnUpdateViewFullscreen(CCmdUI* pCmdUI);
afx_msg void OnAddrDrop();
afx_msg void OnAddrFocus();
afx_msg void OnFileNew();
afx_msg void OnHelpHelp();
afx_msg void OnOptionsActivenewwindow();
afx_msg void OnUpdateOptionsActivenewwindow(CCmdUI* pCmdUI);
afx_msg void OnRtabAddfav();
afx_msg void OnViewLinks();
afx_msg void OnViewToolbar();
afx_msg void OnUpdateViewToolbar(CCmdUI* pCmdUI);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnFileCloseKeepcur();
afx_msg void OnViewRefreshall();
afx_msg void OnViewStopAll();
afx_msg void OnFileNewClip();
afx_msg void OnWindowCascade();
afx_msg void OnWindowTileHorz();
afx_msg void OnWindowTileVert();
afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct);
afx_msg void OnWindowRestore();
afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct);
afx_msg void OnWindowMin();
afx_msg void OnViewMenubar();
afx_msg void OnToolsSetSkin(UINT nID);
afx_msg void OnUpdateToolsSetSkin(CCmdUI* pCmdUI);
afx_msg void OnFileNewVeryIE();
afx_msg void OnFileOpen();
afx_msg void OnViewToolbartextlabel();
afx_msg void OnUpdateViewToolbartextlabel(CCmdUI* pCmdUI);
afx_msg void OnChangeProxy(UINT nID);
afx_msg void OnChangeWebProxy(UINT nID);
afx_msg void OnF2(UINT nID);
afx_msg void OnShortcutUseSc();
afx_msg void OnUpdateShortcutUseSc(CCmdUI* pCmdUI);
afx_msg void OnShortcutSc();
afx_msg void OnShortcutAlias();
afx_msg void OnUpdateShortcutAlias(CCmdUI* pCmdUI);
afx_msg void OnShortcutManalias();
afx_msg void OnViewToolbarsCustomize();
afx_msg void OnOptionsVeryIEoptions();
afx_msg void OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu);
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnNotifyTray(WPARAM wParam, LPARAM lParam);
afx_msg void OnSelTab(WPARAM wParam, LPARAM lParam);
afx_msg void OnRtabStickname();
afx_msg void OnTabPre();
afx_msg void OnTabNext();
//{{AFX_MSG(CMainFrame)
afx_msg void OnOptionsUrlinstatus();
afx_msg void OnUpdateOptionsUrlinstatus(CCmdUI* pCmdUI);
afx_msg void OnViewFavs();
afx_msg void OnViewProtect();
afx_msg void OnViewExTool();
afx_msg void OnViewSearch();
afx_msg void OnDropFiles(HDROP hDropInfo);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnFileStopOpenall();
afx_msg void OnUpdateFileStopOpenall(CCmdUI* pCmdUI);
afx_msg void OnFileHide();
afx_msg void OnViewFolder();
afx_msg void OnOptionsOpenlinkinnewwindow();
afx_msg void OnUpdateOptionsOpenlinkinnewwindow(CCmdUI* pCmdUI);
afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt);
afx_msg void OnEditUndoclose();
afx_msg void OnUpdateEditUndoclose(CCmdUI* pCmdUI);
afx_msg void OnEditEdit();
afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);
afx_msg void OnOrggroup();
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
afx_msg void OnNewwindow();
afx_msg void OnFileSendpagebyemail();
afx_msg void OnFileQuicksave();
afx_msg void OnFileSendlinkbyemail();
afx_msg void OnRtabAutoref();
afx_msg void OnUpdateRtabAutoref(CCmdUI* pCmdUI);
afx_msg void OnRtabReffre();
afx_msg void OnToolsQuicksearch();
afx_msg void OnToolsSync();
afx_msg void OnScFillform();
afx_msg void OnScSaveform();
afx_msg void OnScSavegenform();
afx_msg void OnToolsCollect();
afx_msg void OnToolsCleanaddr();
afx_msg void OnAllPageLinks();
afx_msg void OnViewEncodingAuto();
afx_msg void OnUpdateViewEncodingAuto(CCmdUI* pCmdUI);
afx_msg void OnSaveasGroup();
afx_msg void OnToolCleanVeryIEform();
afx_msg void OnRtabAddalias();
afx_msg void OnRtabAddsc();
afx_msg void OnRtabAutosave();
afx_msg void OnToolsMouseScr();
afx_msg void OnUpdateToolsMouseScr(CCmdUI* pCmdUI);
afx_msg void OnToolsUrlFilter();
afx_msg void OnUpdateToolsUrlFilter(CCmdUI* pCmdUI);
afx_msg void OnViewLocktoolbar();
afx_msg void OnUpdateViewLocktoolbar(CCmdUI* pCmdUI);
afx_msg void OnToolsAutoscrollAll();
afx_msg void OnUpdateToolsAutoscrollAll(CCmdUI* pCmdUI);
afx_msg void OnFileNewSelect();
afx_msg void OnOptionsUseIeProxy();
afx_msg void OnUpdateOptionsUseIeProxy(CCmdUI* pCmdUI);
afx_msg void OnCleanTypedSearch();
afx_msg void OnViewAutoHide();
afx_msg void OnUpdateViewAutohide(CCmdUI* pCmdUI);
afx_msg void OnViewSysMenuBar();
afx_msg void OnToolsMonitor();
afx_msg void OnUpdateToolsMonitor(CCmdUI* pCmdUI);
afx_msg void DoGroup();
afx_msg void OnViewLock();
afx_msg void OnEndSession(BOOL bEnding);
afx_msg void OnToolsSearchText();
afx_msg void OnLastVisited();
afx_msg void OnWindowManager();
afx_msg void OnUpdateWindowManager(CCmdUI* pCmdUI);
afx_msg void OnFileNewSelectedLink();
afx_msg void OnFileAutoSaveAll();
afx_msg void OnUpdateFileAutoSaveAll(CCmdUI* pCmdUI);
afx_msg void OnFileNewCurrentHomePage();
afx_msg void OnFileNewCurrentUpPage();
afx_msg void OnGoStartPage();
afx_msg void OnScSetFormData();
afx_msg void OnViewFontsIncrease();
afx_msg void OnViewFontsDecrease();
afx_msg void OnViewMarkKind();
afx_msg void OnViewMark();
afx_msg void OnToolsNoBackground();
afx_msg void OnUpdateToolsNoBackground(CCmdUI* pCmdUI);
afx_msg void OnViewSetUndoClose();
afx_msg void OnToolsCleanUndoClose();
afx_msg void OnAddtoIe();
afx_msg void OnFileCloseAlikeTitle();
afx_msg void OnFileCloseAllLeft();
afx_msg void OnFileCloseAllRight();
afx_msg void OnFileCloseAlikeUrl();
afx_msg void OnFileCloseMarkedUrl();
afx_msg void OnOptionsAllowAnimate();
afx_msg void OnUpdateOptionsAllowAnimate(CCmdUI* pCmdUI);
afx_msg void OnOptionsDisableFlash();
afx_msg void OnUpdateOptionsDisableFlash(CCmdUI* pCmdUI);
afx_msg void OnToolsSearchCase();
afx_msg void OnUpdateToolsSearchCase(CCmdUI* pCmdUI);
afx_msg void OnToolsSearchWhole();
afx_msg void OnUpdateToolsSearchWhole(CCmdUI* pCmdUI);
afx_msg void OnUpdateToolsQuickSearch(CCmdUI* pCmdUI);
afx_msg void OnToolsExternalAutorun();
afx_msg void OnUpdateToolsExternalAutorun(CCmdUI* pCmdUI);
afx_msg void OnViewCompletelyRefresh();
afx_msg void OnTextAutoSave();
afx_msg void OnTextCopy();
afx_msg void OnTextEdit();
afx_msg void OnTextSave();
afx_msg void OnTextSearch();
afx_msg void OnUrlCopy();
afx_msg void OnUrlEdit();
afx_msg void OnUrlFilter();
afx_msg void OnUrlOpen();
afx_msg void OnUrlOpenActive();
afx_msg void OnUrlOpenIe();
afx_msg void OnUrlOpenJump();
afx_msg void OnUrlShow();
afx_msg void OnTextHighLight();
afx_msg void OnTextFind();
afx_msg void OnTextOpenLinks();
afx_msg void OnUrlAddtoFav();
afx_msg void OnUrlCollector();
afx_msg void OnTextCollector();
afx_msg void OnToolsSearchDelete();
afx_msg void OnProxyImport();
afx_msg void OnProxyExport();
afx_msg void OnUrlOpenInactive();
afx_msg void OnRtabSortSave();
afx_msg void OnViewSelectLang();
afx_msg void OnRtabNewWindow();
afx_msg void OnGoPageUp();
afx_msg void OnGoPageDown();
afx_msg void OnGoPageBottom();
afx_msg void OnGoPageTop();
afx_msg void OnHighlightSelectedText();
afx_msg void OnFindNextSelectedText();
afx_msg void OnOpenLink();
afx_msg void OnOpenLinkActive();
afx_msg void OnOpenLinkDeactive();
afx_msg void OnFindPrevSelectedText();
afx_msg void OnNotSaveKey();
afx_msg void OnUpdateNotSaveKey(CCmdUI* pCmdUI);
afx_msg void OnUrlOpenOtherSide();
afx_msg void OnUrlOpenFtp();
afx_msg void OnViewForbidAutoNav();
afx_msg void OnRtabProtect();
afx_msg void OnRtabForbidAutoNav();
afx_msg void OnRtabLock();
afx_msg void OnRtabMark();
afx_msg void OnGoPageRight();
afx_msg void OnGoPageLeft();
afx_msg void OnUrlShowImg();
afx_msg void OnRtabCloseKeepcur();
afx_msg void OnToolsFlyFilter();
afx_msg void OnUpdateToolsFlyFilter(CCmdUI* pCmdUI);
afx_msg void OnToolsDisDownActivex();
afx_msg void OnUpdateToolsDisDownActivex(CCmdUI* pCmdUI);
afx_msg void OnToolsDialogFilter();
afx_msg void OnUpdateToolsDialogFilter(CCmdUI* pCmdUI);
afx_msg void OnEditImgUrl();
afx_msg void OnFavoritesResetOrder();
//}}AFX_MSG
afx_msg void DoFont();
afx_msg void OnNewTab();
afx_msg void OnUpdateNewTab(CCmdUI* pCmdUI);
afx_msg void OnViewWinCust(UINT nID);
afx_msg void OnUpdateViewWinCust(CCmdUI* pCmdUI);
afx_msg void OnNewAddress();
afx_msg void DoNothing();
afx_msg void OnNewAddressEnter();
afx_msg void OnNewSearchEnter();
afx_msg CString GetMenuItemUrl(UINT nItemID, HMENU hSysMenu,BOOL bRealUrl=TRUE);
afx_msg void OpenMenuItem(UINT nID);
afx_msg void OpenGoUpMenuItem(UINT nID);
afx_msg void OnSortSaveItem(UINT nID);
afx_msg void OnDropDown(NMHDR* pNotifyStruct, LRESULT* pResult);
afx_msg void OnSelChange(NMHDR* pNotifyStruct, LRESULT* pResult);
afx_msg void OnRClick(NMHDR* pNotifyStruct, LRESULT* pResult);
afx_msg void OnRClickElse(NMHDR* pNotifyStruct, LRESULT* pResult);
afx_msg void OnRClickStatusToolbar(NMHDR* pNotifyStruct, LRESULT* pResult);
afx_msg void OnEncoding(UINT nID);
afx_msg void OnFonts(UINT nID);
afx_msg void OnSearch(UINT nID);
afx_msg void OnShellOpen(WPARAM wParam,LPARAM);
afx_msg void OnViewFavorite();
afx_msg void OnLinkPopup();
afx_msg void OnFavPopup();
afx_msg void OnUpdateFav(WPARAM wParam,LPARAM);
afx_msg void OnUpdateTab(WPARAM wParam,LPARAM);
afx_msg void OnDelayLoadConfig(WPARAM wParam,LPARAM);
afx_msg void OnAllFav(UINT nID);
afx_msg void OnUpdateTabTips(WPARAM wParam,LPARAM);
afx_msg void OnTabNeedText(NMHDR* pNotifyStruct, LRESULT* pResult);
afx_msg void OnUpdateToolbar(WPARAM wParam,LPARAM);
afx_msg void OnMenuSelect(UINT nItemID, UINT nFlags, HMENU hSysMenu);
afx_msg void OnSwitchWins(UINT nID);
afx_msg void OnRtabRefresh();
afx_msg void OnRtabStop();
afx_msg void OnActivateWindow(WPARAM wParam, LPARAM lParam);
afx_msg void OnHotKey(WPARAM wParam,LPARAM);
afx_msg void OnScRll(WPARAM wParam, LPARAM lParam);
afx_msg void OnToolsAutoscrollSpeed(UINT nID);
afx_msg void OnToolsAutoscrollPage(UINT nID);
afx_msg void OnViewStop();
afx_msg void OnViewRefresh();
afx_msg void OnFilePrintpreview();
afx_msg void OnFilePrint();
afx_msg void OnOpenGroup(UINT nID);
afx_msg void OnAddtoGroup(UINT nID);
afx_msg void OnWindowList(UINT nID);
afx_msg void OnUndoList(UINT nID);
afx_msg void OnAddThisFav(UINT nID);
//add
afx_msg void OnRMouseDrag();
afx_msg void OnRMouseGesture();
afx_msg void OnToolsEnablePopFilter();
afx_msg void OnUpdateToolsEnablePopFilter(CCmdUI* pCmdUI);
afx_msg void OnEnableFilter();
afx_msg void OnUpdateEnableFilter(CCmdUI* pCmdUI);
afx_msg void OnFindSearchBar();
afx_msg void OnHighLightSearchBar();
afx_msg BOOL OnToolTipText(UINT nID, NMHDR* pNMHDR, LRESULT* pResult);
afx_msg LRESULT OnAppCommand(WPARAM wParam,LPARAM lParam);
afx_msg LRESULT OnMenuRButtonUp(WPARAM w,LPARAM l);
void OnUpdateRMouseDrag(CCmdUI* pCmdUI);
void OnUpdateRMouseGesture(CCmdUI* pCmdUI);
void OnUpdateProgress(CCmdUI* pCmdUI);
void OnUpdateMsg(CCmdUI* pCmdUI);
void OnUpdateDisp(CCmdUI* pCmdUI);
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
class CFindWnd
{
private:
//////////////////
// This private function is used with EnumChildWindows to find the child
// with a given class name. Returns FALSE if found (to stop enumerating).
//
static BOOL CALLBACK FindChildClassHwnd(HWND hwndParent, LPARAM lParam)
{
CFindWnd *pfw = (CFindWnd*)lParam;
HWND hwnd = FindWindowEx(hwndParent, NULL, pfw->m_classname, NULL);
if (hwnd)
{
pfw->m_hWnd = hwnd; // found: save it
return FALSE; // stop enumerating
}
EnumChildWindows(hwndParent, FindChildClassHwnd, lParam); // recurse
return TRUE; // keep looking
}
public:
LPCSTR m_classname; // class name to look for
HWND m_hWnd; // HWND if found
// ctor does the work--just instantiate and go
CFindWnd(HWND hwndParent, LPCSTR classname) : m_hWnd(NULL), m_classname(classname)
{
FindChildClassHwnd(hwndParent, (LPARAM)this);
}
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__19E497C1_4ECF_11D3_9B1D_0000E85300AE__INCLUDED_)
| [
"songbohr@af2e6244-03f2-11de-b556-9305e745af9e"
]
| [
[
[
1,
1055
]
]
]
|
3e5840b9f59dcab9c6f5c51e2d97aa05071d81f0 | 38763b01d06c87ff1164877f57fc22d0da2927e4 | /src/imageb/frmCorteSinal.h | 2e7bf698a1bab8651f217b01c9fd8784d51811b5 | []
| no_license | JPSGoncalves/ImageB | 48b31b83bb1c032394c14e1df5ed90e2a285a521 | 135ccb9847f9e3394f2391417885d753a5b3a930 | refs/heads/master | 2023-03-17T03:57:10.299812 | 2011-07-20T16:59:41 | 2011-07-20T16:59:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,076 | h | #ifndef FRMCORTESINAL_H
#define FRMCORTESINAL_H
#include "ui_frmCorteSinal.h"
#include "imageproc.h"
#include "imageb.h"
#include "setupsinal.h"
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
//! global variable
extern SetupSinal signal_setup;
using namespace std;
//! A signal time cut class
/*!
this class provides methods that togheter SignalSetup object could perform time cut operation over
the RF signal. Here the data can be cutted of from the begining or ending of signal.
*/
class frmCorteSinal : public QWidget, private Ui::frmCorteSinal
{
Q_OBJECT
public:
frmCorteSinal(QWidget *parent = 0);
void loadData();
void configPlots();
void writeMatrixData(Matrix, string);
private:
//! class for image processing
ImageProc imgproc;
//! the RF data points of signal
Matrix rfdata;
//! object that stores signal processing information
SetupSinal ssetup;
signals:
void setupChanged();
private slots:
void chgData();
void botApplyClicked();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
9b370e67ea068fdad86462bda9fdcc2546e9a30d | 2d22825193eacf3669ac8bd7a857791745a9ead4 | /HairSimulation/HairSimulation/DynamicsLib/Vector3.h | 4c1715666ce627e9cfcbc32a98cb1c68393e1906 | []
| no_license | dtbinh/com-animation-classprojects | 557ba550b575c3d4efc248f7984a3faac8f052fd | 37dc800a6f2bac13f5aa4fc7e0e96aa8e9cec29e | refs/heads/master | 2021-01-06T20:45:42.613604 | 2009-01-20T00:23:11 | 2009-01-20T00:23:11 | 41,496,905 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 3,823 | h | /********************************************************
* Vec3 class
* 三度空間的向量
*
* 修改日期:
* 2008-12-06
* 2008-12-08 發現內積寫錯了 operator* -> 改正;
* 2009-1-12
* 為了和 OGRE AppVector3 match
* cross() => crossProduct()
* dot() => dotProduct()
* 拿掉 dot 內積的 overloaded operator
*********************************************************/
#include <iostream>
#ifndef VEC3_H
#define VEC3_H
class AppVector3
{
friend AppVector3 operator-( AppVector3 &); // -v;
friend AppVector3 operator-( const AppVector3 &, const AppVector3 & ); // v - w
friend AppVector3 operator+( const AppVector3 &, const AppVector3 & ); // v + w
//friend float operator*( const AppVector3 &, const AppVector3 & ); // v dot w
friend AppVector3 operator*( float , const AppVector3 & ); // s* v s:scalar
friend AppVector3 operator*( const AppVector3 &, float ); // v * s s:scalar
friend AppVector3 operator/( const AppVector3 &, float ); // v / s s:scalar
friend void operator-=( AppVector3 &v, const AppVector3 &w);
friend void operator+=( AppVector3 &v, const AppVector3 &w);
friend void operator*=( AppVector3 &v, const float& s);
friend void operator/=( AppVector3 &v, const float &s);
friend AppVector3 add( AppVector3 &, AppVector3 &);
friend AppVector3 subtract( AppVector3 &, AppVector3 & );
friend float dotProduct( const AppVector3 &, const AppVector3 & ); // v dot w
friend AppVector3 scale( float , AppVector3 & );
friend AppVector3 negate( AppVector3 & );
friend AppVector3 crossProduct(const AppVector3 &, const AppVector3 &); // v cross w
friend AppVector3 normalize( AppVector3 &);
friend float length( AppVector3 & );
public:
union{
struct{
float x, y, z;
};
/*struct{
float r, g, b;
};*/
float ptr[3];
};
/** constructors */
AppVector3 (float *v)
{
for (int i=0;i<3;i++)
ptr[i] = v[i];
}
AppVector3( float x, float y, float z )
{
ptr[0] = x;
ptr[1] = y;
ptr[2] = z;
}
AppVector3()
{
ptr[0] = ptr[1] = ptr[2] = 0;
}
// copy constructor: T( const T &)
AppVector3( const AppVector3 & copy )
{
x = copy.x;
y = copy.y;
z = copy.z;
}
//subscript operator for non-const objects returns modifiable lvalue
float& operator[](int index)
{
return ptr[index]; //reference
}
float operator[]( int index ) const
{
return ptr[index]; //copy of this element
}
inline void printInfo()
{
printf("(%.3f,%.3f,%.3f)", x, y, z);
}
inline void printInfo( FILE * fp )
{
fprintf(fp,"(%.3f,%.3f,%.3f)", x, y, z);
}
float length() const;
void normalize();
inline float distance(const AppVector3& rhs) const
{
return (*this - rhs).length();
}
float squaredLength () const;
float squaredDistance(const AppVector3& rhs) const;
};
void VecAdd( AppVector3 &a, AppVector3 &b, AppVector3 &result );
void VecSub( AppVector3 &a, AppVector3 &b, AppVector3 &result );
float VecDot( AppVector3 &a, AppVector3 &b );
void VecCross( AppVector3 &a, AppVector3 &b, AppVector3 &result );
void VecScale( AppVector3 &a, float s, AppVector3 &result );
float VecLength( AppVector3 &a );
void NormalizeVec( AppVector3 &a );
void NegateVec( AppVector3 &a );
class Vec4{
public:
union{
struct{
float x, y, z, w;
};
struct{
float r, g, b, a;
};
float xyzw[4];
float ptr[4];
};
Vec4(){
x = y = z = 0;
};
Vec4( float x1, float x2, float x3, float x4 ){
x = x1; y = x2; z = x3; w = x4;
}
float& operator[](int index)
{
return xyzw[index];
}
};
void VecAdd( Vec4 &a, Vec4 &b, Vec4 &result );
void VecSub( Vec4 &a, Vec4 &b, Vec4 &result );
void VecScale( Vec4 &a, float s, Vec4 &result );
void NormalizeVec( Vec4 &a );
#endif | [
"grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4"
]
| [
[
[
1,
151
]
]
]
|
068fe83b91f5e680853a088eb4c70e2931748266 | 3e26aae1108ef3ae02c3a74126e84c3a9256adc4 | /CsTI/CsTI/CsTI/CsTI.cpp | 14eef0a4cab025c9c721efb440bd6366005f312b | []
| no_license | indigos33k3r/dotnetmtf | 169421fd1c6d5633b29b87b0be4ec876fa45d925 | 38ce3f74c84344e63910fcbd63fb8d62e4b38c5d | refs/heads/master | 2020-04-13T22:30:08.534869 | 2007-10-02T01:22:10 | 2007-10-02T01:22:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,753 | cpp | #include "stdafx.h"
#include "CsTI.h"
#include "Feedback.h"
//this is a singleton class
namespace TouchlibWrapper
{
CsTI* CsTI::Instance()
{
if (_instance == 0)
{
_instance = new CsTI;
}
return _instance;
}
//protected constructor
CsTI::CsTI()
{
std::cout << "RAN CONSTRUCTOR" << std::endl;
}
//standard destructor
CsTI::~CsTI()
{
delete m_pUnmanaged;
delete m_pFeedback;
}
void CsTI::startScreen()
{
m_pFeedback = new Feedback( this );
m_pUnmanaged = new CTouchlibWrapper( m_pFeedback );
}
//fingerDown
//this part adds/removes/raises the events for .net
void CsTI::add_fingerDown( fingerDownHandler* pfingerDown )
{
m_pFingerDown = static_cast< fingerDownHandler* >(Delegate::Combine( m_pFingerDown, pfingerDown ));
}
void CsTI::remove_fingerDown( fingerDownHandler* pfingerDown )
{
m_pFingerDown = static_cast< fingerDownHandler* >(Delegate::Remove( m_pFingerDown, pfingerDown ));
}
void CsTI::raise_fingerDown( int ID, int tagID, float X, float Y , float angle, float area, float height, float width, float dX, float dY )
{
if( m_pFingerDown != 0 )
m_pFingerDown->Invoke( ID, tagID, X, Y , angle, area, height, width, dX, dY );
}
//-------end fingerDown--------//
//fingerUp
//this part adds/removes/raises the events for .net
void CsTI::add_fingerUp( fingerUpHandler* pfingerUp )
{
m_pFingerUp = static_cast< fingerUpHandler* > (Delegate::Combine( m_pFingerUp, pfingerUp ));
}
void CsTI::remove_fingerUp( fingerUpHandler* pfingerUp )
{
m_pFingerUp = static_cast< fingerUpHandler* > (Delegate::Remove( m_pFingerUp, pfingerUp ));
}
void CsTI::raise_fingerUp( int ID, int tagID, float X, float Y , float angle, float area, float height, float width, float dX, float dY )
{
if( m_pFingerUp != 0 )
m_pFingerUp->Invoke( ID, tagID, X, Y , angle, area, height, width, dX, dY);
}
//-------end fingerDown--------//
//fingerUpdate
//this part adds/removes/raises the events for .net
void CsTI::add_fingerUpdate( fingerUpdateHandler* pfingerUpdate )
{
m_pFingerUpdate = static_cast< fingerUpdateHandler* > (Delegate::Combine( m_pFingerUpdate, pfingerUpdate ));
}
void CsTI::remove_fingerUpdate( fingerUpdateHandler* pfingerUpdate )
{
m_pFingerUpdate = static_cast< fingerUpdateHandler* > (Delegate::Remove( m_pFingerUpdate, pfingerUpdate ));
}
void CsTI::raise_fingerUpdate( int ID, int tagID, float X, float Y , float angle, float area, float height, float width, float dX, float dY )
{
if( m_pFingerUpdate != 0 )
m_pFingerUpdate->Invoke( ID, tagID, X, Y , angle, area, height, width, dX, dY );
}
//-------end fingerDown--------//
}
| [
"[email protected]@d488c44d-5b3b-0410-b124-79cd89526495"
]
| [
[
[
1,
100
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.