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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a0eea7e530e2d2b0685f781f3e5874e213086193 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/ContentTools/Common/Filters/FilterScene/ConvertTexturesToPng/hctConvertTexturesToPNGFilter.h | e8ee35cd348072e71b9fcfc759615324aeb6fc86 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,316 | h | /*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HAVOK_FILTER_TEXTURES_TO_PNG__H
#define HAVOK_FILTER_TEXTURES_TO_PNG__H
#include <ContentTools/Common/Filters/FilterScene/ConvertTexturesToPng/hctConvertTexturesToPNGOptions.h>
class hctConvertTexturesToPNGFilter : public hctFilterInterface
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_EXPORT);
hctConvertTexturesToPNGFilter(const hctFilterManagerInterface* owner);
/*virtual*/ ~hctConvertTexturesToPNGFilter();
/*virtual*/ void setOptions(const void* optionData, int optionDataSize, unsigned int version);
/*virtual*/ HWND showOptions(HWND owner);
/*virtual*/ void process( class hkRootLevelContainer& data );
/// Option ptr only valid until the filter is deleted and/or the filter dll is unloaded
/*virtual*/ int getOptionsSize() const;
/*virtual*/ void getOptions(void* optionData) const;
virtual void hideOptions();
void updateOptions();
// filter options
hctConvertTexturesToPNGOptions m_options;
// A buffer for storing the options in XML form.
mutable hkArray<char> m_optionsBuf;
// dialog
HWND m_optionsDialog;
};
class hctConvertTexturesToPNGFilterDesc : public hctFilterDescriptor
{
public:
/*virtual*/ unsigned int getID() const { return 0x52829ba7; }
/*virtual*/ FilterCategory getCategory() const { return HK_CATEGORY_GRAPHICS; }
/*virtual*/ FilterBehaviour getFilterBehaviour() const { return HK_DATA_MUTATES_INPLACE; }
/*virtual*/ const char* getShortName() const { return "Convert To Png"; }
/*virtual*/ const char* getLongName() const { return "Convert any textures that are not PNGs into PNGs, inplace in the file. Uses GDI+ at the moment."; }
/*virtual*/ unsigned int getFilterVersion() const { return HCT_FILTER_VERSION(1,1,1); }
/*virtual*/ hctFilterInterface* createFilter(const hctFilterManagerInterface* owner) const { return new hctConvertTexturesToPNGFilter(owner); }
/*virtual*/ HavokComponentMask getRequiredHavokComponents () const { return HK_COMPONENT_COMMON; }
};
extern hctConvertTexturesToPNGFilterDesc g_convertTexturesToPNGDesc;
#endif // HAVOK_FILTER_TEXTURES_TO_PNG__H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
30c0411eb2b4c1eeab8b3e682b500b0ea041f4a7 | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/06112002/Include/Mesh/Mesh.h | 3c8ac7fcac67daff71a2510c306c0669b5de62ef | []
| no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,754 | h | #ifndef _MESH_H_
#define _MESH_H_
#include <Mesh/Vertex.h>
#include <Mesh/Colour.h>
#include <Graphics/IVertexBuffer.h>
#include <vector>
/** @ingroup Mesh_Graphics_Group
* @brief A set of components which affect how a mesh looks
*/
struct Material{
Colour4f colour; /**< Base colour */
float diffuse; /**< Diffuse */
float luminocity; /**< Luminocity */
float specular; /**< Specular */
float reflective; /**< Reflective */
float transparency; /**< Transparent */
float translucent; /**< Translucent */
float glossiness; /**< Glossiness */
float sharpness; /**< Sharpness */
float bump; /**< Bumpmapping */
};
/** @ingroup Mesh_Graphics_Group
* @brief Structure to hold temporary polygon data
*/
struct TempPolygon{
int numvertex; /**< The number of vertices in this polygon */
int *index; /**< An array of vertex indices */
};
typedef std::vector<TempPolygon *> polygonlist_t;
/** @ingroup Mesh_Graphics_Group
* @brief The base class for all Mesh objects
*/
class Mesh{
protected:
/** @var int m_numvertex
* @brief The number of vertices in this mesh
*/
int m_numvertex;
/** @var int m_numvb
* @brief The number of VertexBuffers used to represent the mesh object
*/
int m_numvb;
/** @var Vertex3f *m_position
* @brief An array of vertex data
*/
Vertex3f *m_position;
/** @var Vertex3f *m_normal
* @brief An array of normal data
*/
Vertex3f *m_normal;
/** @var Vertex2f *m_texcoord
* @brief An array of texture coordinate data
*/
Vertex2f *m_texcoord;
/** @var VertexBuffer **VertexBuffer
* @brief An array of VertexBuffer objects representing parts of the mesh
*/
IVertexBuffer **m_vertexbuffer;
public:
Mesh ();
virtual ~Mesh ();
virtual void Initialise (int numvertex);
virtual void SetPosition (Vertex3f *p);
virtual void SetNormal (Vertex3f *n);
virtual void SetTexcoord (Vertex2f *t);
virtual Vertex3f * GetPosition (void);
virtual Vertex3f * GetNormal (void);
virtual Vertex2f * GetTexcoord (void);
virtual int GetNumVertex (void);
virtual void Finalise (void);
virtual void GenerateNormals (int i=0,int j=1,int k=2);
virtual IVertexBuffer * AddVertexBuffer (void);
virtual void AddVertexBuffer (IVertexBuffer *v);
virtual int NumVertexBuffer (void);
virtual void Render (void);
virtual IVertexBuffer * GetVertexBuffer (unsigned int index);
virtual void operator= (Mesh &m);
virtual void Scale (float x, float y, float z);
};
#endif // #ifndef _MESH_H_
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
103
]
]
]
|
44c99a0dac176f73a56d8304ebe024a064dcccd5 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Graphics/WmlVertexShader.cpp | ad1f76730a54a0054aaf8d4ab2e444fca155258c | []
| 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 | 6,047 | 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.
#include "WmlVertexShader.h"
using namespace Wml;
#include <fstream>
using namespace std;
WmlImplementRTTI(VertexShader,Object);
WmlImplementStream(VertexShader);
const int VertexShader::NONE = -1;
const int VertexShader::MAX_TEXCOORDS = 8;
//----------------------------------------------------------------------------
VertexShader::VertexShader (ShaderConstants* pkConstTemplate,
int iVertexRegHint, int iNormalRegHint, int iColorRegHint,
int iTexCoord0RegHint, int iTexCoord1RegHint, int iTexCoord2RegHint,
int iTexCoord3RegHint, int iTexCoord4RegHint, int iTexCoord5RegHint,
int iTexCoord6RegHint, int iTexCoord7RegHint)
:
Shader(pkConstTemplate)
{
m_iVertexRegHint = iVertexRegHint;
m_iNormalRegHint = iNormalRegHint;
m_iColorRegHint = iColorRegHint;
m_aiTexCoordRegHint[0] = iTexCoord0RegHint;
m_aiTexCoordRegHint[1] = iTexCoord1RegHint;
m_aiTexCoordRegHint[2] = iTexCoord2RegHint;
m_aiTexCoordRegHint[3] = iTexCoord3RegHint;
m_aiTexCoordRegHint[4] = iTexCoord4RegHint;
m_aiTexCoordRegHint[5] = iTexCoord5RegHint;
m_aiTexCoordRegHint[6] = iTexCoord6RegHint;
m_aiTexCoordRegHint[7] = iTexCoord7RegHint;
}
//----------------------------------------------------------------------------
VertexShader::VertexShader ()
:
Shader(NULL)
{
// internal constructor, for use with load
}
//----------------------------------------------------------------------------
VertexShader* VertexShader::Load (const char* acFilename)
{
// open stream, load
ifstream kIStr(acFilename,ios::in|ios::binary);
if ( !kIStr )
return NULL;
VertexShader* pkShader = new VertexShader;
pkShader->Read(kIStr);
kIStr.close();
return pkShader;
}
//----------------------------------------------------------------------------
VertexShader::~VertexShader ()
{
}
//----------------------------------------------------------------------------
void VertexShader::Write (const char* acFilename)
{
ofstream kOStr(acFilename,ios::out|ios::binary|ios::trunc);
assert(kOStr.is_open());
Write(kOStr);
kOStr.close();
}
//----------------------------------------------------------------------------
void VertexShader::Write (ostream& rkOStr)
{
#ifdef WML_BIG_ENDIAN
int iDummy = m_iVertexRegHint;
System::SwapBytes(sizeof(int),&iDummy);
rkOStr.write((const char*)&iDummy,sizeof(int));
iDummy = m_iNormalRegHint;
System::SwapBytes(sizeof(int),&iDummy);
rkOStr.write((const char*)&iDummy,sizeof(int));
iDummy = m_iColorRegHint;
System::SwapBytes(sizeof(int),&iDummy);
rkOStr.write((const char*)&iDummy,sizeof(int));
for (int i = 0; i < 8; i++)
{
iDummy = m_aiTexCoordRegHint[i];
System::SwapBytes(sizeof(int),&iDummy);
rkOStr.write((const char*)&iDummy,sizeof(int));
}
#else
rkOStr.write((const char*)&m_iVertexRegHint,sizeof(int));
rkOStr.write((const char*)&m_iNormalRegHint,sizeof(int));
rkOStr.write((const char*)&m_iColorRegHint,sizeof(int));
rkOStr.write((const char*)m_aiTexCoordRegHint,8*sizeof(int));
#endif
Shader::Write(rkOStr);
}
//----------------------------------------------------------------------------
void VertexShader::Read (istream& rkIStr)
{
rkIStr.read((char*)&m_iVertexRegHint,sizeof(int));
rkIStr.read((char*)&m_iNormalRegHint,sizeof(int));
rkIStr.read((char*)&m_iColorRegHint,sizeof(int));
rkIStr.read((char*)m_aiTexCoordRegHint,sizeof(int)*8);
#ifdef WML_BIG_ENDIAN
System::SwapBytes(sizeof(int),&m_iVertexRegHint);
System::SwapBytes(sizeof(int),&m_iNormalRegHint);
System::SwapBytes(sizeof(int),&m_iColorRegHint);
System::SwapBytes(sizeof(int),8,m_aiTexCoordRegHint);
#endif
Shader::Read(rkIStr);
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
Object* VertexShader::Factory (Stream&)
{
// fix later
return NULL;
}
//----------------------------------------------------------------------------
void VertexShader::Load (Stream& rkStream, Stream::Link* pkLink)
{
Object::Load(rkStream,pkLink);
// fix later
}
//----------------------------------------------------------------------------
void VertexShader::Link (Stream& rkStream, Stream::Link* pkLink)
{
// fix later
Object::Link(rkStream,pkLink);
}
//----------------------------------------------------------------------------
bool VertexShader::Register (Stream& rkStream)
{
// fix later
return Object::Register(rkStream);
}
//----------------------------------------------------------------------------
void VertexShader::Save (Stream& rkStream)
{
Object::Save(rkStream);
// native data
// fix later
}
//----------------------------------------------------------------------------
StringTree* VertexShader::SaveStrings ()
{
// fix later
return NULL;
}
//----------------------------------------------------------------------------
int VertexShader::GetMemoryUsed () const
{
// fix later
int iTotalSize = Object::GetMemoryUsed();
return iTotalSize;
}
//----------------------------------------------------------------------------
int VertexShader::GetDiskUsed () const
{
// fix later
return Object::GetDiskUsed();
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
181
]
]
]
|
677dee09042611b267fe346c99a10eb49f1f618d | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/Profiler.cpp | 5375a96b16ed1b63a7633ea8af8040f28d6cc520 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,862 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: Profiler.cpp
Version: 0.03
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "Profiler.h"
namespace nGENE
{
TypeInfo Profiler::Type(L"Profiler", &BaseClass::Type);
Profiler::Profiler():
m_nSamplesNum(0),
m_nCurNestLevel(0),
m_bEnabled(true)
{
init();
}
//----------------------------------------------------------------------
Profiler::~Profiler()
{
cleanup();
}
//----------------------------------------------------------------------
void Profiler::init()
{
// Create timer
m_pTimer.setPointer(new Timer(false));
}
//----------------------------------------------------------------------
void Profiler::cleanup()
{
while(!m_SamplesStack.empty())
m_SamplesStack.pop();
if(!m_Samples.empty())
m_Samples.clear();
m_nCurNestLevel = 0;
m_nSamplesNum = 0;
}
//----------------------------------------------------------------------
void Profiler::beginSample(const wstring& sampleName)
{
// Exit, if profiler is disabled
if(!m_bEnabled)
return;
// If sample has not yet been added, add it and increase
// samples counter
if(m_Samples.find(sampleName) == m_Samples.end())
++m_nSamplesNum;
SSample& temp = m_Samples[sampleName];
temp.nStartTime = m_pTimer->getMicroseconds();
temp.stDescription = sampleName;
temp.nLevel = (++m_nCurNestLevel);
// Put the item on the stack
m_SamplesStack.push(sampleName);
}
//----------------------------------------------------------------------
void Profiler::endSample()
{
// Exit if profiler is disabled
if(!m_bEnabled)
return;
// Remove item from the stack
wstring sampleName = m_SamplesStack.top();
m_SamplesStack.pop();
// Update performance statistics
SSample& temp = m_Samples[sampleName];
temp.nEndTime = m_pTimer->getMicroseconds();
temp.nLastPerformance = temp.nEndTime - temp.nStartTime;
if(temp.bInit)
{
temp.nAvaragePerformance = ((temp.nAvaragePerformance +
temp.nLastPerformance) >> 1);
}
else
{
temp.nAvaragePerformance = temp.nLastPerformance;
temp.bInit = 1;
}
if(temp.nLastPerformance > temp.nMaxPerformance)
temp.nMaxPerformance = temp.nLastPerformance;
else if(temp.nLastPerformance < temp.nMinPerformance)
temp.nMinPerformance = temp.nLastPerformance;
// Decrease nesting level
--m_nCurNestLevel;
}
//----------------------------------------------------------------------
void Profiler::showResults()
{
}
//----------------------------------------------------------------------
}
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
113
]
]
]
|
11543b2a35d8a4d761574350eff258d9c2c0d77f | d87a855d1ae81cd3a27cf6ceb1b56f1c481f9a70 | /ungob.cpp | 12fc43715c8c3ca48793acabb1610a975aeee247 | []
| no_license | code-google-com/jktools | 779b1e5476d95c8cb0d45beaca79402996863c76 | 47dbfef6db90ca36e661940ec0341dc6f893440d | refs/heads/master | 2020-06-04T09:43:07.532188 | 2006-07-28T03:16:19 | 2006-07-28T03:16:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,332 | cpp | #include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <direct.h>
#include "gob.h"
static void make_dirs( const char* filepath )
{
char subpath[GOB_PATH_LENGTH];
const char* current = filepath;
while( *current != 0 )
{
while( *current && *current != '\\' )
current++;
if( *current == '\\' )
{
strncpy( subpath, filepath, current - filepath );
subpath[current - filepath] = 0;
mkdir( subpath );
current++;
}
}
}
int main( int argc, char* argv[] )
{
if( argc != 2 )
{
fprintf( stderr, "usage: %s <file>\n", argv[0] );
return -1;
}
FILE* f = fopen( argv[1], "rb" );
if( f )
{
gob_header hdr;
fread( &hdr, sizeof( gob_header ), 1, f );
for( int i = 0; i < hdr._numItems; i++ )
{
gob_item itm;
fread( &itm, sizeof( gob_item ), 1, f );
make_dirs( itm._name );
fprintf( stderr, "%s\n", itm._name );
FILE* of = fopen( itm._name, "wb" );
assert( of );
{
long pos = ftell( f );
fseek( f, itm._offset, SEEK_SET );
unsigned char* chunk = (unsigned char*)malloc( itm._length );
fread( chunk, 1, itm._length, f );
fwrite( chunk, 1, itm._length, of );
free( chunk );
fseek( f, pos, SEEK_SET );
}
fclose( of );
}
fclose( f );
}
return 0;
}
| [
"barrettcolin@c12101a6-9b19-0410-a86e-396b6ccb6ab3"
]
| [
[
[
1,
65
]
]
]
|
e9b9de2c56b9a5efbf992449343be570ff0c3768 | 32aae73d2e203fdac4b718f2113e7f399c3d07ef | /sand/src/configtool.cpp | 746d0a3172c41e508494573abc22c5fcaa6b6faf | []
| no_license | BackupTheBerlios/sandsimulation | d718688d03162c9bfb20617d6dd47696833f8b91 | b025cdb823c734723d53bbc632a17e23aaa009c3 | refs/heads/master | 2021-01-10T19:59:04.529749 | 2006-02-14T23:17:18 | 2006-02-14T23:17:18 | 40,039,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,191 | cpp | #include "configtool.h"
#include <fstream>
#include <iostream>
using namespace std;
void ConfigTool::Init(std::string _filename)
{
filename=_filename;
}
void ConfigTool::GetFileName(std::string &_filename)
{
_filename=filename;
}
void ConfigTool::Quit()
{
// if (Datanames != NULL) delete Datanames;
// if (Data != NULL) delete Data;
filename="";Count=0;Datanames=NULL;Data=NULL;
}
int ConfigTool::ReadFile()
{
char S[256];
int ch;
ifstream f;
int Zeilen;
f.open(filename.c_str(),ios::in);
if (f.fail()) return 1;
Zeilen=0;
while (!f.eof())
{
ch=f.get();
if (ch== '\n')Zeilen++;
}
f.close();
f.clear();
Count = Zeilen+2;
Datanames =new string [Count];
Data=new string[Count];
f.open(filename.c_str(),ios::in);
if (f.fail())
{ cout << "ERROR" << endl; return 2;}
for (Zeilen=0;Zeilen!=Count;Zeilen++)
{
f.getline(S,256,'=');
Datanames[Zeilen]=S;
Data[Zeilen]="";
while (true)
{
ch=f.get();
if (ch=='\n') break;
S[0]=ch;
S[1]=0;
Data[Zeilen]=Data[Zeilen]+S;
if (ch==EOF) break;
}
;
}
f.close();
return 0;
}
int ConfigTool::WriteFile()
{
ofstream f;
string S;
int i;
f.open(filename.c_str(),ios::out);
for (i=0;i!=Count;i++)
{
if (Datanames[i] != "")
{
S=Datanames[i]+"="+Data[i];
f << S << endl;
}
}
f.flush();
f.close();
return 0;
}
bool ConfigTool::ParseName(int &Number,std::string Name)
{
int i;
i=0;
if (Count==0) return false;
while (true)
{
if (Name==Datanames[i])
{
Number=i;
return true;
}
i++;
if (i==Count) break;
}
return false;
}
bool ConfigTool::Get(std::string Name, std::string &Val)
{
int i;
if (ParseName(i,Name)==false) return false;
Val = Data[i];
return true;
}
bool ConfigTool::Get(std::string Name, int &Val)
{
int i;
if (ParseName(i,Name)==false)
{
Val=0;
return false;
}
Val = atol(Data[i].c_str());
return true;
}
bool ConfigTool::Get(std::string Name, float &Val)
{
int i;
if (ParseName(i,Name)==false) return false;
Val = (float)atof(Data[i].c_str());
return true;
}
bool ConfigTool::Get(std::string Name, double &Val)
{
int i;
if (ParseName(i,Name)==false) return false;
Val = atof(Data[i].c_str());
return true;
}
bool ConfigTool::Get(std::string Name, bool &Val)
{
int _Val;
bool ret;
_Val = int(Val);
ret = Get(Name,_Val);
Val=(bool)_Val;
return ret;
}
/* bool ConfigTool::Get(std::string Name, void &(*DATA))
{
unsigned int i;
if (ParseName(i,Name)==false) return false;
// not ready yet
return true;
}*/
void ConfigTool::Add(const char *Name,const char *Val)
{
string *Datanames2,*Data2;
int i;
if (Count == 0)
{
Count++;
Datanames=new string [Count];
Data=new string[Count];
Datanames[Count-1]=Name;
Data[Count-1]=Val;
return;
}
Count++;
Datanames2 =new string [Count];
Data2=new string[Count];
for (i=0;i!=Count-1;i++)
{
Datanames2[i]=Datanames[i];
Data2[i]=Data[i];
}
delete Data;
delete Datanames;
Data=Data2;
Datanames=Datanames2;
Datanames[Count-1]=Name;
Data[Count-1]=Val;
}
void ConfigTool::Set(std::string Name, std::string Val)
{
Set(Name,Val.c_str());
}
void ConfigTool::Set(std::string Name, const char *Val)
{
int i;
if (Count==0)
{
Add(Name.c_str(),Val);
return;
}
if (ParseName(i,Name)==false)
{
Add(Name.c_str(),Val);
return;
};
Data[i] = Val;
}
void ConfigTool::Set(std::string Name, int Val)
{
char S[128];
sprintf(S,"%d",Val);
Set(Name,S);
}
void ConfigTool::Set(std::string Name, double Val)
{
char S[128];
sprintf(S,"%f",Val);
Set(Name,S);
}
void ConfigTool::Set(std::string Name, bool Val)
{
Set(Name,(int)Val);
}
void ConfigTool::Set(std::string Name, void *DATA, int _size)
{
char S[128];
int i;
int i2;
string S2;
sprintf(S,"%d",_size);
S2=S;
for (i=0;i!=_size;i++)
{
i2 = ((char*)DATA)[i];
sprintf(S,"%d",i2);
S2=S2+","+S;
}
Set(Name,S2.c_str());
}
unsigned long ConfigTool::GetCount()
{
return Count;
}
| [
"chrikle"
]
| [
[
[
1,
250
]
]
]
|
265890496b9c968fa78bba456fd2c6999f0577b4 | 729f72df96cd6f816d3a100b8b1346c98ba72457 | /source/FlourFile.cpp | 21752d2ad705698f9bca1c86deeb393432e4f8f0 | []
| no_license | yhzhu/flour | e2459c10a05bbb8e03fa2b18b61116825f91f36b | 10424d1ec6490cf8a07705beb6507201c36dcfbc | refs/heads/master | 2021-01-18T03:13:40.892264 | 2010-04-11T17:11:17 | 2010-04-11T17:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,078 | cpp | /** File: FlourFile.cpp
Created on: 09-Sept-09
Author: Robin Southern "betajaen"
Copyright (c) 2009 Robin Southern
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 "FlourFile.h"
#include <iostream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
FlourFile::FlourFile(const std::string& extension, const std::string& description, const std::string& opposite, FileType ft)
: mExtension(extension), mDescription(description), mOpposite(opposite), mType(ft)
{
}
FlourFile::~FlourFile()
{
}
NxOgre::MeshData* FlourFile::loadMesh(const std::string& path)
{
return 0;
}
void FlourFile::saveMesh(const std::string& path, NxOgre::MeshData*)
{
}
NxOgre::ManualHeightField* FlourFile::loadHeightfield(const std::string& path)
{
return 0;
}
void FlourFile::saveHeightfield(const std::string& path, NxOgre::HeightFieldData*)
{
}
NxOgre::Mesh* FlourFile::get(const std::string& path)
{
return 0; // virtual
}
| [
"[email protected]"
]
| [
[
[
1,
66
]
]
]
|
eb6ea61463834b1e9333cd3c35546ccdde9108cf | 48d325e5c8648382c8f790a5e8762b36ffd7c45a | /qtshoot/view.cpp | d1c6e803b9faa8832fc765e24a83122ca6c6c788 | []
| no_license | tomozh/qtshoot | 46184f4bf7ad9e36f4a358b862ec17e415a0ece0 | 332aaedc89c398cc9f79c908c77bd2dd6978ec44 | refs/heads/master | 2020-07-07T10:59:31.554012 | 2011-12-09T18:04:09 | 2011-12-09T18:04:09 | 2,948,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,470 | cpp | #include "view.h"
#include <math.h>
#include "common.h"
#include "texture.h"
#include "joystick.h"
#include "taskmanager.h"
#include "taskmain.h"
View::View(QWidget *parent) : QGLWidget(parent)
{
setFixedSize(SCR_X, SCR_Y);
setAutoFillBackground(false);
updateTimerId = startTimer(1000/60);
fpsTimerId = startTimer(1000);
frameCount = 0;
fps = 0;
TaskManager::inst()->addTask(new taskMain());
}
View::~View()
{
killTimer(updateTimerId);
}
void View::timerEvent(QTimerEvent* event)
{
if(event->timerId() == fpsTimerId)
{
// フレームカウンタリセット
fps = frameCount;
frameCount = 0;
}
else if(event->timerId() == updateTimerId)
{
// メイン処理
Joystick::inst()->pool();
TaskManager::inst()->oneFrame();
repaint();
frameCount++;
}
else
{
QGLWidget::timerEvent(event);
}
}
//! デバッグ表示
void View::renderDebug(QPainter* painter)
{
painter->setBackgroundMode(Qt::OpaqueMode);
painter->drawText(32, 32,
tr("%1 fps / %2 tasks")
.arg(fps)
.arg(TaskManager::inst()->getTaskCount())
);
}
void View::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
TaskManager::inst()->render(&painter);
renderDebug(&painter);
}
| [
"tomo@aspire.(none)"
]
| [
[
[
1,
69
]
]
]
|
02a36787616c85f3fb0e06a0d294206e0e9040a1 | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/DXGI/DXGIDevice.h | 29404b8b56160b08ca2b0595d5309bbc5f2525be | []
| no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,016 | h | //Copyright (c) Microsoft Corporation. All rights reserved.
#pragma once
#include "DXGIObject.h"
namespace Microsoft { namespace WindowsAPICodePack { namespace DirectX { namespace DXGI {
using namespace System;
ref class Surface;
ref class Adapter;
ref class DXGIResource;
/// <summary>
/// Implements a derived class for DXGI objects that produce image data.
/// <para>(Also see DirectX SDK: IDXGIDevice)</para>
/// </summary>
public ref class DXGIDevice :
public DXGIObject
{
public:
/// <summary>
/// Returns the adapter for the specified device.
/// <para>(Also see DirectX SDK: IDXGIDevice::GetAdapter)</para>
/// </summary>
Adapter^ GetAdapter();
/// <summary>
/// Sets or Gets the GPU thread priority.
/// <para>(Also see DirectX SDK: IDXGIDevice::GetGPUThreadPriority and IDXGIDevice::SetGPUThreadPriority)</para>
/// </summary>
property Int32 GPUThreadPriority
{
Int32 get();
void set(Int32 value);
}
/// <summary>
/// Gets the residency status of a colleciton of resources.
/// <para>Note: This method should not be called every frame as it incurs a non-trivial amount of overhead.</para>
/// <para>(Also see DirectX SDK: IDXGIDevice::QueryResourceResidency)</para>
/// </summary>
/// <param name="resources">A collection or array of DXGIResource interfaces.</param>
/// <returns>An array of residency flags. Each element describes the residency status for corresponding element in
/// the resources argument.</returns>
array<Residency>^ QueryResourceResidency(IEnumerable<DXGIResource^>^ resources);
internal:
DXGIDevice()
{
}
internal:
DXGIDevice(IDXGIDevice* pNativeIDXGIDevice)
{
Attach(pNativeIDXGIDevice);
}
};
} } } }
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
]
| [
[
[
1,
60
]
]
]
|
c5799fe35a428860e679fdf4bf6373e7952a7bba | bc4919e48aa47e9f8866dcfc368a14e8bbabbfe2 | /Open GL Basic Engine/source/glutFramework/glutFramework/fuzzyGraph.cpp | aa151918376e196d14f7d1ff5db4623e9355dd55 | []
| no_license | CorwinJV/rvbgame | 0f2723ed3a4c1a368fc3bac69052091d2d87de77 | a4fc13ed95bd3e5a03e3c6ecff633fe37718314b | refs/heads/master | 2021-01-01T06:49:33.445550 | 2009-11-03T23:14:39 | 2009-11-03T23:14:39 | 32,131,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cpp | #include "fuzzyGraph.h"
fuzzyGraph::fuzzyGraph(double low, double medStart, double medEnd, double high)
{
lowStart = low;
lowEnd = medStart;
mediumStart = low;
mediumMidStart = medStart;
mediumMidEnd = medEnd;
mediumEnd = high;
highStart = medEnd;
highEnd = high;
}
void fuzzyGraph::printDEBUG()
{
cout << "lowStart: " << lowStart << endl;
cout << "lowEnd: " << lowEnd << endl;
cout << "mediumStart: " << mediumStart << endl;
cout << "mediumMidStart: " << mediumMidStart << endl;
cout << "mediumMidEnd: " << mediumMidEnd << endl;
cout << "mediumEnd: " << mediumEnd << endl;
cout << "highStart: " << highStart << endl;
cout << "highEnd: " << highEnd << endl;
}
void fuzzyGraph::getFuzzyData(double input, double &outputLow, double &outputMed, double &outputHigh)
{
outputLow = FuzzyReverseGrade (input, lowStart, lowEnd);
outputMed = FuzzyTrapezoid (input, mediumStart, mediumMidStart, mediumMidEnd, mediumEnd);
outputHigh = FuzzyGrade (input, highStart, highEnd);
}
void fuzzyGraph::tweakFuzzyGraph(double newLow, double newMedStart, double newMedEnd, double newHigh)
{
lowStart = newLow;
lowEnd = newMedStart;
mediumStart = newLow;
mediumMidStart = newMedStart;
mediumMidEnd = newMedEnd;
mediumEnd = newHigh;
highStart = newMedEnd;
highEnd = newHigh;
}
| [
"davidbmoss@5457d560-9b84-11de-b17c-2fd642447241"
]
| [
[
[
1,
45
]
]
]
|
1dc4fb95794a0923d99d46b25ac9920b86290de4 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/src/ireon_client/paging_landscape/OgrePagingLandScapeData2D_Spline.cpp | 2ac57f52a7f9748f3191717326e038b3453b7010 | []
| no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,596 | cpp | /********************************************************************************
OgrePagingLandScapeData2D_Spline.cpp
*****************************************************************************
A NURBS-based heightfield generator for use with the paginglandscapeplugin
Note that it could easily be adapted for use as a general NURBS surface
generator.
*****************************************************************************
begin : Sat Nov 9 2003
copyright : (C) 2003 Chris "Antiarc" Heald
email : [email protected]
********************************************************************************/
/********************************************************************************
* *
* This program 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 of the License, or *
* (at your option) any later version. *
* *
********************************************************************************/
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgrePagingLandScapeData2D.h"
#include "OgrePagingLandScapeOptions.h"
#include "OgrePagingLandScapeData2D_Spline.h"
namespace Ogre
{
//-----------------------------------------------------------------------
PagingLandScapeData2D* PagingLandScapeData2D_Spline::newPage( )
{
return new PagingLandScapeData2D_Spline();
}
//-----------------------------------------------------------------------
PagingLandScapeData2D_Spline::PagingLandScapeData2D_Spline()
: PagingLandScapeData2D(),
mSurface (0),
mPoints (0)
{
mMaxheight = 256.0f * PagingLandScapeOptions::getSingleton().scale.y;
}
//-----------------------------------------------------------------------
PagingLandScapeData2D_Spline::~PagingLandScapeData2D_Spline()
{
delete mSurface;
delete[] mPoints;
}
//-------------------------------------------------------------------
void PagingLandScapeData2D_Spline::_save()
{
}
//-----------------------------------------------------------------------
bool PagingLandScapeData2D_Spline::_load(const uint mX, const uint mZ )
{
int resolution = PagingLandScapeOptions::getSingleton().PageSize;
mSize = resolution;
mMax = static_cast <uint> (mSize * mSize);
int pCount = 50;
int mDegree = 3;
Real MAX = 500;
int tessLevel = static_cast <uint> (mSize);
srand (time(NULL));
mPoints = new Point4D[pCount * pCount];
const int knotVecSize = pCount + mDegree + 1;
Real *knots = new Real[knotVecSize];
int i;
for (i = 0; i < knotVecSize; i++)
{
if (i < mDegree)
{
knots[i] = 0;
}
else if (i > knotVecSize - mDegree)
{
knots[i] = knotVecSize - (2 * mDegree) + 1;
}
else
{
knots[i] = i - mDegree + 1;
}
}
int dataSize = pCount * pCount;
for (i = 0; i < dataSize; i++)
{
mPoints[i].x = (int) (i/pCount);
mPoints[i].y = double (rand()) / MAX;
mPoints[i].w = 1;
mPoints[i].z = 0;//i % pCount;
}
mSurface = new CDRGNURBSSurface();
mSurface->Init(mDegree, mDegree,
pCount, pCount,
mPoints,
knots, knots,
tessLevel, tessLevel);
mSurface->TessellateSurface();
delete[] knots;
delete[] mPoints;
mXDimension = mSize;
mZDimension = mSize;
mMaxArrayPos = resolution * resolution;
mHeightData = new Real[mMaxArrayPos];
Real scale = PagingLandScapeOptions::getSingleton().scale.y;
mMaxheight = 0.0f;
uint k;
for (k = 0; k < mMaxArrayPos; k ++ )
{
Real h = static_cast<Real> (mSurface->getData(k).y * scale);
mHeightData[k] = h;
mMaxheight = std::max (h, mMaxheight);
}
mIsLoaded = true;
return true;
}
//-----------------------------------------------------------------------
void PagingLandScapeData2D_Spline::_load()
{
}
//-----------------------------------------------------------------------
void PagingLandScapeData2D_Spline::_unload()
{
delete mSurface;
mSurface = 0;
mIsLoaded = false;
}
} //namespace
| [
"[email protected]"
]
| [
[
[
1,
139
]
]
]
|
a0cabf47ea9c8771318625335d2fb9cd6127d837 | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Internet/EmailAddress.hpp | 0d54e5fe87e2c13f98045f27ef53acdc743d3200 | []
| no_license | saminigod/baseclasses-001 | 159c80d40f69954797f1c695682074b469027ac6 | 381c27f72583e0401e59eb19260c70ee68f9a64c | refs/heads/master | 2023-04-29T13:34:02.754963 | 2009-10-29T11:22:46 | 2009-10-29T11:22:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,876 | hpp | /*
© Vestris Inc., Geneva Switzerland
http://www.vestris.com, 1998, All Rights Reserved
__________________________________________________
written by Daniel Doubrovkine - [email protected]
*/
#ifndef BASE_EMAIL_ADDRESS_HPP_RFC822
#define BASE_EMAIL_ADDRESS_HPP_RFC822
#include <platform/include.hpp>
#include <String/String.hpp>
class CEmailAddress : public CObject {
property(bool, Valid);
property(CString, Dest);
property(CString, Mail);
property(CString, Error);
property(CString, Domain);
property(CString, User);
private:
int In(const char& What, const CString& Where);
int Parse(void);
CString MPAddress(const CString& iStr, int& curPos);
CString MPGroup(const CString& iStr, int& curPos);
CString MPMailbox(const CString& iStr, int& curPos);
CString MPPhrase(const CString& iStr, int& curPos);
CString MPRouteAddr(const CString& iStr, int& curPos);
CString MPRoute(const CString& iStr, int& curPos);
CString MPAddressSpec(const CString& iStr, int& curPos);
CString MPLocalPart(const CString& iStr, int& curPos);
CString MPWord(const CString& iStr, int& curPos);
CString MPQuotedString(const CString& iStr, int& curPos);
char MPQuotedPair(const CString& iStr, int& curPos);
char MPQText(const CString& iStr, int& curPos);
CString MPDomain(const CString& iStr, int& curPos);
CString MPSubDomain(const CString& iStr, int& curPos);
CString MPDomainRef(const CString&, int&);
char MPAtom(const CString& iStr, int& curPos);
CString MPAtomSequence(const CString& iStr, int& curPos);
char MPDtext(const CString& iStr, int& curPos);
char MPLinearWhiteSpace(const CString& iStr, int& curPos);
CString MPDomainLiteral(const CString& iStr, int& curPos);
public:
CEmailAddress(void);
CEmailAddress(const CString&);
virtual ~CEmailAddress(void);
void Set(const CString&);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
54
]
]
]
|
388f43c9c7daa918fc297e5b156f356a07e78e7f | 254c6f1867dd94d897a4543b7821580f9c616ac3 | /src/main.cpp | 1729d9bf600bdcad060542291a3fee8c6247a2d6 | []
| no_license | vardis/glraster | ee290080b9cf74d41ec824741d4513557ed8bedb | 239face23389467ace8bcba5e2171faec1753444 | refs/heads/master | 2016-08-06T23:35:12.282156 | 2010-08-03T20:24:01 | 2010-08-03T20:24:01 | 41,563,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,385 | cpp | #include "GLTutor.h"
#include "GLUtil.h"
#include "MaterialDB.h"
#include "Mesh.h"
#include "MeshModel.h"
#include "Billboard.h"
#include "RenderPrimitive.h"
#include "Entity.h"
#include "Viewport.h"
#include "RenderTargetTexture.h"
#include "PinholeCamera.h"
#include "OrthographicCamera.h"
#include "Lights.h"
#include "SceneManager.h"
#include "ILTextureManager.h"
#include "RenderablesRasterizer.h"
#include "MeshFactory.h"
#include "TTFont.h"
#include "Text.h"
#include "GLXTimer.h"
#include "ShaderGenerator.h"
#define ILUT_USE_OPENGL
#include <IL/il.h>
#include <IL/ilu.h>
#include <IL/ilut.h>
GLXTimer timer;
GLenum g_shadeModel = GL_SMOOTH;
GLfloat rotZ = 0.0f;
bool camMoved = false;
GLfloat camX = 0.0f, camY = 0.0f, camZ = -1.0f;
GLfloat focusX = 0.0f, focusY = 0.0f, focusZ = 1.0f;
// In degrees
GLfloat azimuth = 90.0f;
GLfloat elevation = 90.0f;
float yaw, pitch, roll;
GLfloat g_ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat g_diffuseLight[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat g_specularLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat g_posLight[] = { 10.0f, 0.0f, 0.0f, 0.0f };
// Vertex data
GLfloat vertices[] = { 0.0f, 0.2f, 0.0f, -0.2f, -0.2f, 0.0f, 0.2f, -0.2f, 0.0f };
unsigned short indices[] = { 0, 1, 2 };
// Colour data
GLfloat colours[] = { 1.0f, 0.0f, 0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f };
long g_lastTime;
MaterialDB g_matDB;
Mesh* bobMesh;
MeshModel* bobModel;
MeshModel* maleModel;
Entity* bobEntity;
Entity* billboardNMapEntity;
Entity* billboardEntity;
Entity* multiMat;
Entity* planeEntity;
Entity* quadStripEnt;
Entity* maleEntity;
Entity* teapotEntity;
Entity* monkeyEntity;
EntityPtr cubeEntity;
RenderTargetTexture* g_planeTextureRT;
PinholeCameraPtr g_camera;
ViewportPtr g_viewport;
SceneManagerPtr scene;
RenderablesRasterizer* g_rasterizer;
ILTextureManager* g_texMgr;
TTFontPtr g_font;
TextPtr g_text;
OrthographicCameraPtr g_cam2d;
LightPtr frontLight, backLight;
LightPtr pointLight;
LightPtr spotLight;
MaterialPtr billboardMat(new Material());
void displayFunc();
void reshapeFunc(int width, int height);
void keyboardFunc(unsigned char key, int x, int y);
void mouseFunc(int buton, int state, int x, int y);
void mouseMotionFunc(int x, int y);
void mousePassiveMotionFunc(int x, int y);
void specialKeyFunc(int key, int x, int y);
void idleFunc(void);
void closeFunc(void);
void createVertexBuffers(void);
void initialize();
void loadModels();
void loadAllTextures();
void rtt(RenderTargetTexture* rt);
void render(PinholeCameraPtr camera, ViewportPtr viewport);
int main(int argc, char** argv) {
try {
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
glutInitWindowPosition(10, 10);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_MULTISAMPLE | GLUT_ALPHA | GLUT_DEPTH);
glutInitContextVersion(3, 2);
glutInitContextProfile( GLUT_COMPATIBILITY_PROFILE);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG);
int mainWinID = glutCreateWindow("mainWin");
glutSetWindow(mainWinID);
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
std::cerr << "Error: " << glewGetErrorString(err) << std::endl;
return 1;
}
glutSetWindowTitle("OpenGL Tutor ver. 0.0.0.1");
// set callbacks
glutDisplayFunc(displayFunc);
glutReshapeFunc(reshapeFunc);
glutKeyboardFunc(keyboardFunc);
glutMotionFunc(mouseMotionFunc);
glutPassiveMotionFunc(mousePassiveMotionFunc);
glutSpecialFunc(specialKeyFunc);
glutIdleFunc(idleFunc);
glutCloseFunc(closeFunc);
initialize();
if (!GLEW_ARB_vertex_buffer_object) {
std::cerr << "GLEW_ARB_vertex_buffer_object not supported" << std::endl;
exit(1);
}
glutMainLoop();
glutDestroyWindow(mainWinID);
} catch (GLException& e) {
std::cerr << "Caught a GLException: " << e.what() << std::endl;
std::cerr << "Details: " << e.details() << std::endl;
std::cerr << "GL error: " << e.glError() << std::endl;
}
return 0;
}
void initialize() {
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
ilInit();
iluInit();
ilutInit();
ilutRenderer(ILUT_OPENGL);
ilEnable(IL_ORIGIN_SET);
ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
g_viewport = ViewportPtr(new Viewport());
g_viewport->m_width = 640;
g_viewport->m_height = 480;
g_viewport->m_clearColor.set(0.0f);
yaw = pitch = roll = 0.0f;
g_camera = PinholeCameraPtr(new PinholeCamera());
g_camera->setPos(Vec3f(0, 0, 5));
// g_camera->setLook(Vec3f(0, 0, -1));
g_camera->setNear(0.1f);
g_camera->setFar(1000.0f);
g_camera->setFov(60.0f);
g_camera->setAspectRatio(0.75f);
g_cam2d = OrthographicCameraPtr(new OrthographicCamera());
g_cam2d->setPos(Vec3f(0, 0, 0));
g_cam2d->setRotation(Vec3f(0.0f, 0.0f, 0.0f));
g_cam2d->setNear(0.1f);
g_cam2d->setFar(1000.0f);
g_cam2d->setWidth(640);
g_cam2d->setHeight(480);
g_texMgr = new ILTextureManager();
g_rasterizer = new RenderablesRasterizer(g_texMgr);
g_font.reset(new TTFont());
g_font->setFilename("bluebold.ttf");
g_font->addCodepointRange(CodepointRange(32, 166));
g_font->setPointSize(7);
g_font->setHres(300);
g_font->setVres(200);
if (!g_font->create()) {
std::cerr << "Error creating font\n";
}
frontLight = LightPtr(new Light());
frontLight->m_type = Light::LightsTypeDirectional;
frontLight->m_direction = Vec3f(1.0f, 0.0f, -1.0f);
frontLight->m_diffuse = Colour::WHITE;
frontLight->m_specular = Colour::WHITE;
backLight = LightPtr(new Light());
backLight->m_type = Light::LightsTypeDirectional;
backLight->m_direction = Vec3f::Z_Axis;
backLight->m_diffuse = Colour(1.0f, 0.0f, 0.0f); //Colour::WHITE;
backLight->m_specular = Colour::WHITE;
pointLight = LightPtr(new Light());
pointLight->m_type = Light::LightsTypeLamp;
pointLight->m_position = Vec3f(0.0f, 0.0f, 1.0f);
pointLight->m_diffuse = Colour(1.0f, 1.0f, 1.0f);
pointLight->m_specular = Colour::WHITE;
// pointLight->m_linearAttenuation = 1.0f;
spotLight = LightPtr(new Light());
spotLight->m_type = Light::LightsTypeSpot;
spotLight->m_position = Vec3f(0.0f, 0.0f, 1.0f);
spotLight->m_direction = Vec3f(0.0f, 0.0f, -1.0f);
spotLight->m_diffuse = Colour(1.0f, 1.0f, 1.0f);
spotLight->m_specular = Colour::WHITE;
spotLight->m_cosSpotCutOff = 0.9f;
spotLight->m_cosOuterConeSpotCutOff = 0.8f;
// spotLight->m_linearAttenuation = 1.0f;
g_rasterizer->addLight(frontLight);
// g_rasterizer->addLight(backLight);
// g_rasterizer->addLight(pointLight);
// g_rasterizer->addLight(spotLight);
loadModels();
scene = SceneManagerPtr(new SceneManager());
scene->setTextureManager(g_texMgr);
scene->initialize();
// scene->setActiveSkyMapType(Sky_SphereMap);
// scene->setSphereSkyMap("spheremap.png");
scene->setActiveSkyMapType(Sky_CubeMap);
scene->setCubeSkyMap("early_morning.jpg");
}
void loadModels() {
ShaderGenerator sg;
MeshFactory mf(g_texMgr);
///////////////////////////////////////////////////////////////////////
// create multi-material cube
// std::cout << "creating cube\n";
// std::list<Mesh*> multiMatMeshes = mf.createFromFile("multitex.obj");
// multiMat = new Entity();
// std::list<Mesh*>::iterator it = multiMatMeshes.begin();
// while (it != multiMatMeshes.end()) {
// MeshModel* model = new MeshModel(*it);
// multiMat->addRenderable(model);
// ++it;
// }
// Matrix4f& m2 = multiMat->getTransform();
// m2 = Matrix4f::Translation(2.0f, 5.0f, 5.0f) * m2;
// std::cout << "done cube\n";
///////////////////////////////////////////////////////////////////////
// // create a cube mesh
// {
// Mesh* cubeMesh = mf.createCube();
//
// MaterialPtr cubeMat(new Material("cubeMat"));
// cubeMat->m_twoSided = true;
// cubeMat->m_specular.set(0.0f);
// cubeMat->m_shadeless = true;
//
// Texture* tex = new Texture();
// g_texMgr->loadTexture("rockwall.bmp", tex);
//
// cubeMat->addTexture(TexturePtr(tex), TexMapTo_Diffuse, TexBlendOp_Multiply);
// cubeMesh->setMaterial(cubeMat);
//
// cubeEntity = EntityPtr(new Entity());
// MeshModel* cubeMeshModel = new MeshModel(cubeMesh);
// cubeMeshModel->getRenderState().setCulling(false);
// cubeEntity->addRenderable(cubeMeshModel);
// Matrix4f& cubeXform = cubeEntity->getTransform();
// cubeXform = Matrix4f::Translation(0.0f, 5.0f, 0.0f) * cubeXform;
// }
///////////////////////////////////////////////////////////////////////
// create Bob mesh
// std::list<Mesh*> meshes = mf.createFromFile("data/models/Bob.md5mesh");
// bobEntity = new Entity();
// it = meshes.begin();
// while (it != meshes.end()) {
// MeshModel* bobModel = new MeshModel(*it);
// bobEntity->addRenderable(bobModel);
// ++it;
// }
// Matrix4f& m = bobEntity->getTransform();
// m = Matrix4f::Scale(0.1f, 0.1f, 0.1f) * m;
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// create male figure mesh
/*
std::list<Mesh*> maleMeshes = mf.createFromFile("muscular_male_basemesh.obj");
maleEntity = new Entity();
it = maleMeshes.begin();
while (it != maleMeshes.end()) {
MeshModel* maleModel = new MeshModel(*it);
maleModel->getMaterial()->m_texStack->textures[0]->setMinFilter(TexFilter_Bilinear_Mipmap_Bilinear);
maleModel->getMaterial()->m_texStack->textures[0]->setAnisotropy(8);
maleEntity->addRenderable(maleModel);
++it;
}
Matrix4f& m1 = maleEntity->getTransform();
m1 = Matrix4f::Translation(0.0f, 0.0f, -3.0f) * Matrix4f::Scale(0.4f, 0.4f, 0.4f) * m1;
*/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// create teapot mesh
/*
{
std::cout << "CREATING TEAPOT->>>>>>>>.\n";
Texture* tex = new Texture();
tex->m_useMipmaps = false;
g_texMgr->loadTexture("rockwall_NH.tga", tex);
std::list<Mesh*> teapotMeshes = mf.createFromFile("teapot-tbn.obj", true, true);
teapotEntity = new Entity();
it = teapotMeshes.begin();
while (it != teapotMeshes.end()) {
MeshModel* teapotModel = new MeshModel(*it);
teapotModel->getRenderState().setCulling(false);
MaterialPtr mat = teapotModel->getMaterial();
mat->m_texStack->textures[0].reset(tex);
mat->m_texStack->texOutputs[0].mapTo = TexMapTo_Normal;
teapotEntity->addRenderable(teapotModel);
++it;
}
Matrix4f& m1 = teapotEntity->getTransform();
m1 = Matrix4f::Translation(4.0f, 0.4f, -2.0f) * m1;
}
*/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// create monkey mesh
{
Texture* tex = new Texture();
tex->m_useMipmaps = false;
g_texMgr->loadTexture("uvgrid.png", tex);
std::list<Mesh*> monkeMeshes = mf.createFromFile("unwrap.ply", true, true);
monkeyEntity = new Entity();
std::list<Mesh*>::iterator it = monkeMeshes.begin();
while (it != monkeMeshes.end()) {
MeshModel* monkeyModel = new MeshModel(*it);
MaterialPtr mat = monkeyModel->getMaterial();
mat->addTexture(TexturePtr(tex), TexMapTo_Diffuse, TexBlendOp_Multiply, TexMapInput_UV);
monkeyEntity->addRenderable(monkeyModel);
++it;
}
Matrix4f& m1 = monkeyEntity->getTransform();
m1 = Matrix4f::Translation(4.0f, 0.4f, -2.0f) * m1;
}
///////////////////////////////////////////////////////////////////////
// create billboard
{
billboardMat->m_name = "billboardMat";
billboardMat->m_twoSided = true;
billboardMat->m_diffuse.set(1.0f);
billboardMat->m_specular.set(1.0f);
billboardMat->m_shininess = 20.0f;
// billboardMat->m_shadeless = true;
// billboardMat->setCustomShaders(true);
// billboardMat->setFragmentShader("fs.glsl");
billboardMat->m_texStack = TextureStackPtr(new TextureStack());
Texture* tex = new Texture();
tex->m_useMipmaps = true;
tex->m_minFilter = TexFilter_Bilinear_Mipmap_Bilinear;
tex->m_magFilter = TexFilter_Bilinear_Mipmap_Bilinear;
g_texMgr->loadTexture(/*"fgrass1_v2_256.png" */"rockwall.bmp", tex);
billboardMat->m_texStack->textures[0].reset(tex);
billboardMat->m_texStack->texOutputs[0].blendOp = TexBlendOp_Multiply;
Texture* normalTex = new Texture();
normalTex->m_useMipmaps = false;
g_texMgr->loadTexture("rockwall_NormalMap.bmp", normalTex);
normalTex->configureGLState();
billboardMat->addTexture(TexturePtr(normalTex), TexMapTo_Normal);
normalTex->m_minFilter = TexFilter_Bilinear_Mipmap_Bilinear;
normalTex->m_magFilter = TexFilter_Bilinear;
normalTex->setWrapping(TexWrapMode_Repeat);
Texture* parallaxTex = new Texture();
parallaxTex->m_useMipmaps = true;
g_texMgr->loadTexture("rockwall_Parallax.bmp", parallaxTex);
parallaxTex->configureGLState();
billboardMat->addTexture(TexturePtr(parallaxTex), TexMapTo_Parallax);
parallaxTex->m_minFilter = TexFilter_Bilinear_Mipmap_Bilinear;
parallaxTex->m_magFilter = TexFilter_Bilinear;
parallaxTex->setWrapping(TexWrapMode_Repeat);
BillboardPtr bb = Billboard::create(Billboard_Spherical, 1.0f, 1.0f);
bb->setMaterial(billboardMat);
bb->getRenderState().setCulling(false);
billboardNMapEntity = new Entity();
billboardNMapEntity->addRenderable(bb);
Matrix4f& m1 = billboardNMapEntity->getTransform();
m1 = Matrix4f::Translation(-4.0f, 0.0f, 0.0f) * m1;
}
// create billboard
{
MaterialPtr billboardMat(new Material());
billboardMat->m_name = "billboardMat";
billboardMat->m_twoSided = true;
billboardMat->m_diffuse.set(1.0f);
billboardMat->m_specular.set(0.0f);
// billboardMat->m_shadeless = true;
billboardMat->m_texStack = TextureStackPtr(new TextureStack());
Texture* tex = new Texture();
tex->m_useMipmaps = true;
tex->m_minFilter = TexFilter_Bilinear_Mipmap_Bilinear;
tex->m_magFilter = TexFilter_Bilinear;
g_texMgr->loadTexture("rockwall.bmp", tex);
billboardMat->m_texStack->textures[0].reset(tex);
billboardMat->m_texStack->texOutputs[0].blendOp = TexBlendOp_Multiply;
BillboardPtr bb = Billboard::create(Billboard_Spherical, 1.0f, 1.0f);
bb->setMaterial(billboardMat);
bb->getRenderState().setCulling(false);
billboardEntity = new Entity();
billboardEntity->addRenderable(bb);
Matrix4f& m1 = billboardEntity->getTransform();
m1 = Matrix4f::Translation(2.0f, 0.0f, 0.0f) * m1;
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// QuadStrip
VertexFormat* vf = new VertexFormat();
vf->addAttribute(Vertex_Pos, VertexFormat_FLOAT3);
vf->addAttribute(Vertex_Normal, VertexFormat_FLOAT3);
vf->addAttribute(Vertex_Tangent, VertexFormat_FLOAT3);
vf->addAttribute(Vertex_BiNormal, VertexFormat_FLOAT3);
vf->addAttribute(Vertex_TexCoord0, VertexFormat_FLOAT2);
RenderPrimitive<QuadStripPrimitiveType>* qs = new RenderPrimitive<QuadStripPrimitiveType> ();
qs->setMaterial(billboardMat);
qs->specifyVertexFormat(VertexFormatPtr(vf));
qs->beginGeometry(3);
float quads_pos[] = { -1.0f, 1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
2.0f, 1.0f, 0.0f,
2.0f, -1.0f, 0.0f };
qs->vertexAttribArray(Vertex_Pos, quads_pos);
float quads_normals[] = { 0.0f, 0.0f, 1.0f };
for (int v = 0; v < 8; v++)
qs->vertexAttrib(Vertex_Normal, quads_normals);
float quads_tangents[] = { 1.0f, 0.0f, 0.0f };
for (int v = 0; v < 8; v++)
qs->vertexAttrib(Vertex_Tangent, quads_tangents);
float quads_binormals[] = { 0.0f, 1.0f, 0.0f };
for (int v = 0; v < 8; v++)
qs->vertexAttrib(Vertex_BiNormal, quads_binormals);
float quads_uvs[] = { 0.0f, 1.0f, 0.0f, 0.0f, 0.33f, 1.0f, 0.33f, 0.0f, 0.66f, 1.0f, 0.66f, 0.0f, 1.0f, 1.0f, 1.0f,
0.0f };
qs->vertexAttribArray(Vertex_TexCoord0, quads_uvs);
if (!qs->endGeometry()) {
std::cerr << "error while specifying quad strip geometry\n";
exit(0);
}
quadStripEnt = new Entity();
quadStripEnt->addRenderable(qs);
// Matrix4f& stripMat = quadStripEnt->getTransform();
// stripMat = Matrix4f::Translation(4.0f, 0.0f, 0.0f);
///////////////////////////////////////////////////////////////////////
g_text.reset(new Text(g_font));
// g_text->setPos(100 - g_viewport->m_width/2, 100 - g_viewport->m_height/2);
Matrix4f& mtxt = g_text->getTransform();
mtxt = Matrix4f::Translation(10.0f - g_viewport->m_width / 2.0f, 10.0f - g_viewport->m_height / 2.0f, 0.0f) * mtxt;
g_text->setText("hello");
///////////////////////////////////////////////////////////////////////
// create RTT quad
MaterialPtr quadMat(new Material());
quadMat->m_name = "quadMat";
quadMat->m_twoSided = true;
quadMat->m_diffuse.set(1.0f);
quadMat->m_texStack = TextureStackPtr(new TextureStack());
Texture* quadTex = new Texture();
quadTex->m_width = quadTex->m_sourceWidth = 512;
quadTex->m_height = quadTex->m_sourceHeight = 512;
quadTex->m_textureTarget = GL_TEXTURE_2D;
quadTex->m_useMipmaps = true;
quadTex->m_minFilter = TexFilter_Bilinear_Mipmap_Bilinear;
quadTex->m_magFilter = TexFilter_Bilinear;
quadTex->allocate();
quadTex->configureGLState();
quadMat->m_texStack->textures[0].reset(quadTex);
Mesh* quad = mf.createQuad();
quad->setMaterial(quadMat);
planeEntity = new Entity();
planeEntity->addRenderable(new MeshModel(quad));
Matrix4f& planeXform = planeEntity->getTransform();
planeXform = Matrix4f::Translation(-2.0f, 2.0f, 5.0f) * planeXform;
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// render target texture
g_planeTextureRT = new RenderTargetTexture(TexturePtr(quadTex), true, 0);
g_planeTextureRT->allocate();
///////////////////////////////////////////////////////////////////////
}
void displayFunc() {
// Note: necessary as the text's render state set the depth mask to false
GLUtil::setDefaultGLState();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
yaw = clamp(yaw, -360.0f, 360.0f);
pitch = clamp(pitch, -90.0f, 90.0f);
roll = clamp(roll, -360.0f, 360.0f);
g_camera->updateViewProj();
g_cam2d->updateViewProj();
// glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
long elapsed = timer.getMillis();
g_lastTime += elapsed;
if (g_lastTime > 1000) {
std::stringstream ss;
ss << "Frame time: " << elapsed << " ms";
g_text->setTransform(Matrix4f::Translation(10.0f - g_viewport->m_width / 2.0f, 10.0f - g_viewport->m_height / 2.0f, 0.0f));
g_text->setText(ss.str());
g_lastTime -= 1000;
}
// rtt(g_planeTextureRT);
render(g_camera, g_viewport);
// g_rasterizer->render(g_text.get(), g_cam2d, 1);
glutSwapBuffers();
}
void render(PinholeCameraPtr camera, ViewportPtr viewport) {
glViewport(viewport->m_x, viewport->m_y, viewport->m_width, viewport->m_height);
glClearColor(viewport->m_clearColor.r, viewport->m_clearColor.g, viewport->m_clearColor.b, viewport->m_clearColor.a);
// glPushMatrix();
// Vec3f& p = g_camera->getPos();
// glTranslatef(p.x, p.y, p.z);
// scene->renderSky(g_rasterizer);
// glPopMatrix();
// render Bob
// for (uint32_t i = 0; i < bobEntity->getNumRenderables(); i++) {
// Renderable* r = bobEntity->getRenderable(i);
// r->setTransform(bobEntity->getTransform());
// g_rasterizer->getRenderLayer(0).addRenderable(r);
// }
// render male figure
// for (uint32_t i = 0; i < maleEntity->getNumRenderables(); i++) {
// Renderable* r = maleEntity->getRenderable(i);
// r->setTransform(maleEntity->getTransform());
// g_rasterizer->getRenderLayer(0).addRenderable(r);
// }
// render teapot
/*
for (uint32_t i = 0; i < teapotEntity->getNumRenderables(); i++) {
Renderable* r = teapotEntity->getRenderable(i);
r->setTransform(teapotEntity->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(r);
}*/
for (uint32_t i = 0; i < monkeyEntity->getNumRenderables(); i++) {
Renderable* r = monkeyEntity->getRenderable(i);
r->setTransform(monkeyEntity->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(r);
}
// render cube
// Renderable* cube = cubeEntity->getRenderable(0);
// cube->setTransform(cubeEntity->getTransform());
// g_rasterizer->getRenderLayer(0).addRenderable(cube);
// render billboard
// Renderable* bb = billboardEntity->getRenderable(0);
// bb->setTransform(billboardEntity->getTransform());
// g_rasterizer->getRenderLayer(0).addRenderable(bb);
// render normal mapped billboard
// Renderable* bbNMap = billboardNMapEntity->getRenderable(0);
// bbNMap->setTransform(billboardNMapEntity->getTransform());
// g_rasterizer->getRenderLayer(0).addRenderable(bbNMap);
// render quad strip
// Renderable* qs = quadStripEnt->getRenderable(0);
// qs->setTransform(quadStripEnt->getTransform());
// g_rasterizer->getRenderLayer(0).addRenderable(qs);
/*
// render multi-material cube
for (uint32_t i = 0; i < multiMat->getNumRenderables(); i++) {
Renderable* r = multiMat->getRenderable(i);
r->setTransform(multiMat->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(r);
}
// render reflective plane
Renderable* pl = planeEntity->getRenderable(0);
pl->setTransform(planeEntity->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(pl);
*/
g_rasterizer->beginFrame(camera);
g_rasterizer->endFrame();
}
void rtt(RenderTargetTexture* rt) {
Viewport rttViewport;
rttViewport.m_width = rt->m_texture->m_width;
rttViewport.m_height = rt->m_texture->m_height;
rttViewport.m_clearColor.set(0.0f);
glViewport(0, 0, rttViewport.m_width, rttViewport.m_height);
glClearColor(rttViewport.m_clearColor.r, rttViewport.m_clearColor.g, rttViewport.m_clearColor.b,
rttViewport.m_clearColor.a);
PinholeCameraPtr rttCamera(new PinholeCamera());
rttCamera->setPos(Vec3f(0.0f, 0.0f, 20.0f)); //View(planeEntity->getTransform());
rttCamera->setFov(90.0f);
rttCamera->updateView();
rttCamera->updateProj();
g_planeTextureRT->bind();
// render Bob
for (uint32_t i = 0; i < bobEntity->getNumRenderables(); i++) {
Renderable* r = bobEntity->getRenderable(i);
r->setTransform(bobEntity->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(r);
}
// render billboard
Renderable* bb = billboardEntity->getRenderable(0);
bb->setTransform(billboardEntity->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(bb);
// render multi-material cube
for (uint32_t i = 0; i < multiMat->getNumRenderables(); i++) {
Renderable* r = multiMat->getRenderable(i);
r->setTransform(multiMat->getTransform());
g_rasterizer->getRenderLayer(0).addRenderable(r);
}
g_rasterizer->beginFrame(rttCamera);
g_rasterizer->endFrame();
g_planeTextureRT->unbind();
}
void reshapeFunc(int width, int height) {
float aspectRatio;
height = (height == 0) ? 1 : height;
g_viewport->m_width = width;
g_viewport->m_height = height;
g_cam2d->setWidth(width);
g_cam2d->setHeight(height);
aspectRatio = (float) height / (float) width;
g_camera->setAspectRatio(aspectRatio);
}
void keyboardFunc(unsigned char key, int x, int y) {
if (key == 's') {
g_shadeModel = GL_SMOOTH;
} else if (key == 'f') {
g_shadeModel = GL_FLAT;
} else if (key == 'a') {
camMoved = true;
g_camera->left(.5f);
} else if (key == 'd') {
camMoved = true;
g_camera->right(.5f);
} else if (key == 'r') {
camMoved = true;
g_camera->setPos(5.0f, 2.0f, 10.0f);
g_camera->setLook(Vec3f::Zero);
} else if (key == 'o') {
spotLight->m_cosSpotCutOff -= 0.1f;
spotLight->m_cosOuterConeSpotCutOff -= 0.1f;
std::cout << "spotligt cut off angle: " << spotLight->m_cosSpotCutOff << "\n";
} else if (key == 'p') {
spotLight->m_cosSpotCutOff += 0.1f;
spotLight->m_cosOuterConeSpotCutOff += 0.1f;
std::cout << "spotligt cut off angle: " << spotLight->m_cosSpotCutOff << "\n";
} else if (key == ',') {
billboardMat->m_parallaxScale -= 0.01f;
std::cout << "parallax scale: " << billboardMat->m_parallaxScale << "\n";
} else if (key == '.') {
billboardMat->m_parallaxScale += 0.01f;
std::cout << "parallax scale: " << billboardMat->m_parallaxScale << "\n";
} else if (key == '<') {
billboardMat->m_parallaxBias -= 0.01f;
std::cout << "parallax bias: " << billboardMat->m_parallaxBias << "\n";
} else if (key == '>') {
billboardMat->m_parallaxBias += 0.01f;
std::cout << "parallax bias: " << billboardMat->m_parallaxBias << "\n";
}
}
void mouseFunc(int buton, int state, int x, int y) {
}
void mouseMotionFunc(int x, int y) {
}
void mousePassiveMotionFunc(int x, int y) {
}
std::ostream& operator<<(std::ostream& os, Matrix4f mat) {
os << "\n[" << mat.m[0][0] << " , " << mat.m[0][1] << " , " << mat.m[0][2] << " , " << mat.m[0][3] << "]\n";
os << "[" << mat.m[1][0] << " , " << mat.m[1][1] << " , " << mat.m[1][2] << " , " << mat.m[1][3] << "]\n";
os << "[" << mat.m[2][0] << " , " << mat.m[2][1] << " , " << mat.m[2][2] << " , " << mat.m[2][3] << "]\n";
os << "[" << mat.m[3][0] << " , " << mat.m[3][1] << " , " << mat.m[3][2] << " , " << mat.m[3][3] << "]\n";
return os;
}
void specialKeyFunc(int key, int x, int y) {
camMoved = true;
if (key == GLUT_KEY_LEFT) {
g_camera->turnLeft(2.5f);
} else if (key == GLUT_KEY_RIGHT) {
g_camera->turnRight(2.5f);
} else if (key == GLUT_KEY_PAGE_UP) {
g_camera->lookUp(2.5f);
} else if (key == GLUT_KEY_PAGE_DOWN) {
g_camera->lookDown(2.5f);
} else if (key == GLUT_KEY_UP) {
g_camera->forward(0.2f);
} else if (key == GLUT_KEY_DOWN) {
g_camera->backward(0.2f);
} else if (key == GLUT_KEY_HOME) {
g_camera->up(.4f);
} else if (key == GLUT_KEY_END) {
g_camera->down(.4f);
} else if (key == GLUT_KEY_F1) {
std::cout << g_camera->getView();
} else {
camMoved = false;
}
}
void idleFunc(void) {
// rotZ += 0.05f;
if (camMoved) {
std::cout << "cam pos (x, y, z): " << g_camera->getPos().x << ", " << g_camera->getPos().y << ", "
<< g_camera->getPos().z << std::endl;
std::cout << "cam orientation (yaw, pitch, roll): " << g_camera->getRotation().y << ", "
<< g_camera->getRotation().x << ", " << g_camera->getRotation().z << std::endl;
std::cout << "cam look-at (x, y, z): " << g_camera->getLook().x << ", " << g_camera->getLook().y << ", "
<< g_camera->getLook().z << std::endl;
std::cout << "cam up (x, y, z): " << g_camera->getUp().x << ", " << g_camera->getUp().y << ", "
<< g_camera->getUp().z << std::endl;
std::cout << "cam right (x, y, z): " << g_camera->getRight().x << ", " << g_camera->getRight().y << ", "
<< g_camera->getRight().z << std::endl;
camMoved = false;
}
glutPostRedisplay();
}
void closeFunc() {
}
| [
"[email protected]",
"vardis.g@localhost",
"giorgos@localhost"
]
| [
[
[
1,
1
],
[
3,
12
],
[
14,
14
],
[
18,
24
],
[
26,
63
],
[
65,
65
],
[
67,
70
],
[
76,
78
],
[
80,
82
],
[
92,
92
],
[
94,
110
],
[
157,
179
],
[
182,
186
],
[
195,
195
],
[
197,
197
],
[
199,
200
],
[
204,
207
],
[
242,
242
],
[
252,
255
],
[
258,
260
],
[
273,
274
],
[
298,
299
],
[
310,
311
],
[
384,
384
],
[
464,
467
],
[
474,
476
],
[
478,
479
],
[
488,
493
],
[
502,
513
],
[
517,
518
],
[
523,
530
],
[
532,
541
],
[
543,
559
],
[
561,
561
],
[
565,
569
],
[
571,
571
],
[
573,
578
],
[
581,
584
],
[
589,
596
],
[
598,
598
],
[
604,
612
],
[
639,
639
],
[
648,
648
],
[
668,
697
],
[
701,
719
],
[
724,
738
],
[
763,
774
],
[
783,
800
],
[
803,
816
],
[
819,
826
],
[
828,
828
]
],
[
[
2,
2
],
[
13,
13
],
[
15,
17
],
[
66,
66
],
[
72,
74
],
[
79,
79
],
[
85,
91
],
[
93,
93
],
[
117,
119
],
[
122,
122
],
[
124,
124
],
[
156,
156
],
[
180,
181
],
[
187,
194
],
[
196,
196
],
[
201,
203
],
[
208,
241
],
[
243,
251
],
[
256,
257
],
[
261,
272
],
[
275,
297
],
[
300,
309
],
[
314,
328
],
[
330,
357
],
[
360,
383
],
[
385,
463
],
[
468,
473
],
[
477,
477
],
[
480,
487
],
[
494,
501
],
[
514,
516
],
[
520,
522
],
[
560,
560
],
[
562,
564
],
[
570,
570
],
[
572,
572
],
[
579,
580
],
[
585,
588
],
[
597,
597
],
[
599,
603
],
[
614,
618
],
[
620,
638
],
[
640,
647
],
[
649,
667
],
[
720,
723
],
[
739,
762
],
[
775,
782
],
[
801,
802
],
[
817,
818
],
[
827,
827
]
],
[
[
25,
25
],
[
64,
64
],
[
71,
71
],
[
75,
75
],
[
83,
84
],
[
111,
116
],
[
120,
121
],
[
123,
123
],
[
125,
155
],
[
198,
198
],
[
312,
313
],
[
329,
329
],
[
358,
359
],
[
519,
519
],
[
531,
531
],
[
542,
542
],
[
613,
613
],
[
619,
619
],
[
698,
700
],
[
829,
829
]
]
]
|
8fdac030b30082a3a66a3e4b073bf4b58ffd2177 | df4928511778393732aa2f1560f204826f05fe10 | /gamestate.cpp | e2f9d924b8051b70004acf1b0cb81f71637b1127 | []
| no_license | ViktorNordgren/sword-of-kings | ad88769671eb5a1134e3909bd25310d429fede81 | 4d16f69dca6f0d1f82aac393fa79d96632903f49 | refs/heads/master | 2018-01-08T10:26:29.012309 | 2007-11-29T06:57:45 | 2007-11-29T06:57:45 | 49,721,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | cpp | /*
* GameState.cpp
*/
#include "engine.h"
#include "gamestate.h"
/*
* Class GameState
*/
GameState::GameState(void* eng)
{
sword_found = false;
talked_to_geoffery = false;
engine = eng;
}
/*
* Will return true if the passed in condition has been met.
*/
bool GameState::isConditionTrue(string cond)
{
if(cond.compare(DEFAULT) == 0)
{
return true;
}
if(cond.compare(HAS_SWORD_OF_KINGS) == 0)
{
return sword_found;
}
if(cond.compare(TALKED_TO_GEOFFERY) == 0)
{
return talked_to_geoffery;
}
}
/*
* This will perform the action specified.
*/
void GameState::performAction(string action)
{
if(action.compare(NOTHING) == 0)
{
return;
}
if(action.compare(START_GAME) == 0)
{
((Engine*)engine)->displayDialog(GEOFFREY_DIALOG_1, CORNELIUS_DIALOG_1);
talked_to_geoffery = true;
}
if(action.compare(CORNELIUS_DIALOG_1) == 0)
{
((Engine*)engine)->displayDialog(CORNELIUS_DIALOG_1, GEOFFREY_DIALOG_2);
}
if(action.compare(GEOFFREY_DIALOG_2) == 0)
{
((Engine*)engine)->displayDialog(GEOFFREY_DIALOG_2, LANCE_DIALOG_1);
}
if(action.compare(LANCE_DIALOG_1) == 0)
{
((Engine*)engine)->displayDialog(LANCE_DIALOG_1, NOTHING);
}
if(action.compare(PICKED_UP_SWORD_OF_KINGS) == 0)
{
sword_found = true;
((Engine*)engine)->removeNPC(0);
((Engine*)engine)->addNPC("BOSS", 16, 1);
}
if(action.compare(FIGHT_BOSS) == 0)
{
((Engine*)engine)->startBossBattle();
}
if(action.compare(FIGHT_BEASTOR) == 0)
{
((Engine*)engine)->startBeastorBattle();
}
}
| [
"[email protected]",
"mhousser@5b9ac4b1-7c3f-0410-9070-89a53124ee38"
]
| [
[
[
1,
4
],
[
6,
11
],
[
13,
15
],
[
17,
23
],
[
29,
42
],
[
50,
50
],
[
65,
66
],
[
68,
78
]
],
[
[
5,
5
],
[
12,
12
],
[
16,
16
],
[
24,
28
],
[
43,
49
],
[
51,
64
],
[
67,
67
]
]
]
|
44e97b4b61820d9f663b11199ad16891ef2b7ebc | 0531b270535a46f315ead3524e60fb70fd6055da | /Source/libkwl/SendQueue.cpp | 0dc182d06589d9e96f3e089de849b7434d164d97 | []
| no_license | jannispl/kwlbot | e7588283d395ea6d54f6a82d45f2f0577f66fde1 | a5c1ea65c38067747893eeccdae726faeedec0d5 | refs/heads/master | 2021-01-01T19:10:16.324535 | 2010-12-12T22:58:24 | 2010-12-12T22:58:24 | 33,863,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,450 | cpp | #include "StdInc.h"
#include "SendQueue.h"
CSendQueue::CSendQueue()
{
}
CSendQueue::~CSendQueue()
{
}
// bRealloc: will copy memory from pPtr to some newly allocated memory
// bNeedFree: free the memory when it's no longer needed (sent)
// (automatically true when bRealloc)
void CSendQueue::Add(char *pPtr, size_t iSize, bool bRealloc, bool bNeedFree)
{
SendBuffer buf;
buf.pFileBuffer = NULL;
buf.iSize = iSize;
if (bRealloc)
{
buf.ucMode = 1;
char *pMemory = reinterpret_cast<char *>(malloc(iSize));
memcpy(pMemory, pPtr, iSize);
buf.pPtr = pMemory;
}
else
{
buf.pPtr = pPtr;
buf.ucMode = bNeedFree ? 1 : 0;
}
m_bufferQueue.push(buf);
}
void CSendQueue::AddFile(FILE *pFile, size_t iBufferSize, bool bNeedClose)
{
SendBuffer buf;
buf.iLastBufferSize = 0;
buf.pPtr = reinterpret_cast<char *>(pFile);
buf.iSize = iBufferSize;
buf.pFileBuffer = reinterpret_cast<char *>(malloc(iBufferSize));
buf.ucMode = bNeedClose ? 2 : 3;
m_bufferQueue.push(buf);
}
bool CSendQueue::IsEmpty() const
{
return m_bufferQueue.empty();
}
// return true: everything handled well
// return false: something not done yet
bool CSendQueue::Process(socket_t socket)
{
while (!IsEmpty())
{
SendBuffer &buf = m_bufferQueue.front();
if (buf.pFileBuffer != NULL)
{
if (!feof((FILE *)buf.pPtr) || buf.iLastBufferSize != 0)
{
if (buf.iLastBufferSize != 0)
{
if (send(socket, buf.pFileBuffer, buf.iLastBufferSize, 0) == -1)
{
return false;
}
else
{
buf.iLastBufferSize = 0;
}
}
else
{
size_t iRead = fread(buf.pFileBuffer, 1, buf.iSize, (FILE *)buf.pPtr);
if (iRead != 0)
{
if (send(socket, buf.pFileBuffer, iRead, 0) == -1)
{
buf.iLastBufferSize = iRead;
return false;
}
}
else
{
if (buf.ucMode == 2)
{
fclose((FILE *)buf.pPtr);
}
free(buf.pFileBuffer);
m_bufferQueue.pop();
}
}
}
else
{
if (buf.ucMode == 2)
{
fclose((FILE *)buf.pPtr);
}
free(buf.pFileBuffer);
m_bufferQueue.pop();
}
}
else
{
if (send(socket, buf.pPtr, buf.iSize, 0) == -1)
{
return false;
}
if (buf.ucMode == 1)
{
free(buf.pPtr);
}
m_bufferQueue.pop();
}
}
return true;
}
| [
"[email protected]@f9c66ffb-4930-c197-0f80-100fa691f586",
"mave1337@f9c66ffb-4930-c197-0f80-100fa691f586"
]
| [
[
[
1,
57
],
[
59,
126
]
],
[
[
58,
58
]
]
]
|
3a42aacb5e431c568a5d58b89eba8133dcde5071 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/ContentTools/Common/Filters/FilterScene/SceneTransform/hctSceneTransformFilter.h | 6e9d6b719efefb4784601c06a868d2dfa5ccf222 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,193 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HAVOK_FILTER_SCENE_TRANSFORM_COMPRESSION_H
#define HAVOK_FILTER_SCENE_TRANSFORM_COMPRESSION_H
#include <ContentTools/Common/Filters/FilterScene/SceneTransform/hctSceneTransformOptions.h>
#include <Common/SceneData/Scene/hkxSceneUtils.h>
class hctSceneTransformFilter : public hctFilterInterface
{
private:
struct ResourceDataTransformInfo : public hkxSceneUtils::TransformInfo
{
public:
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA, hctSceneTransformFilter::ResourceDataTransformInfo );
hkReal m_floatScale;
hkReal m_angleMultiplier;
};
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_EXPORT);
hctSceneTransformFilter(const hctFilterManagerInterface* owner);
/*virtual*/ ~hctSceneTransformFilter();
/*virtual*/ void setOptions(const void* optionData, int optionDataSize, unsigned int version);
/*virtual*/ HWND showOptions(HWND owner);
/*virtual*/ void process( class hkRootLevelContainer& data );
/// Option ptr only valid until the filter is deleted and/or the filter dll is unloaded
/*virtual*/ int getOptionsSize() const;
/*virtual*/ void getOptions(void* optionData) const;
/*virtual*/ void hideOptions();
private:
void transformResourceData(const hkxSceneUtils::SceneTransformOptions& options, class hkResourceContainer* resourceContainer);
void transformResourceMember(ResourceDataTransformInfo& resourceDataTransformInfo, const hkClassMember& member, void* object, hkPointerMap<void*, int>& processedObjects);
// Public for the dialog
public:
HWND m_optionsDialog;
hkBool m_fillingControls; // True when we are setting up the data in the controls; avoids recursion
hkBool m_doNotRefreshEdit; // To avoid the custom samples edit box being updated constantly and cursor being lost
hctSceneTransformOptions m_options;
// A buffer for storing the options in XML form.
mutable hkArray<char> m_optionsBuf;
// Dialog handling stuff
void setControlsFromData();
void setDataFromControls();
};
class hctSceneTransformFilterDesc : public hctFilterDescriptor
{
public:
/*virtual*/ unsigned int getID() const { return 0xaa786565; }
/*virtual*/ FilterCategory getCategory() const { return HK_CATEGORY_CORE; }
/*virtual*/ FilterBehaviour getFilterBehaviour() const { return HK_DATA_MUTATES_INPLACE; }
/*virtual*/ const char* getShortName() const { return "Transform Scene"; }
/*virtual*/ const char* getLongName() const { return "Scene Transformation Filter"; }
/*virtual*/ unsigned int getFilterVersion() const { return HCT_FILTER_VERSION(1,2,1); }
/*virtual*/ hctFilterInterface* createFilter(const class hctFilterManagerInterface* owner) const { return new hctSceneTransformFilter(owner); }
/*virtual*/ HavokComponentMask getRequiredHavokComponents () const { return HK_COMPONENT_COMMON; }
};
extern hctSceneTransformFilterDesc g_sceneTransformDesc;
#endif // HAVOK_FILTER_SCENE_TRANSFORM_COMPRESSION_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
102
]
]
]
|
1584b7dec39b111f6a946935dca2920a1936f17d | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/tool/BGHomography/BGHomography/BackGroundHomo.h | 3063a24a99b5c306129e780349b3852483447ed5 | []
| no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 952 | h | #ifndef _BGHOMO
#define _BGHOMO
#include "cv.h"
#include "highgui.h"
#include <cvaux.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
#define WIDTH 320
#define HEIGHT 240
class BackGroundHomo{
public:
BackGroundHomo();
~BackGroundHomo();
void findHomo();
void buildMappingTable();
void warpCaliImg(char* srcImgName,IplImage* dstImg);
void warpCaliCapture(IplImage*srcImg, IplImage* dstImg);
void loadHomo(char* homoName , char* mTableName);
int getMappingValue(float x, float y,int oriIntensity);
void convertImg(IplImage* inputImg);
void setBackground(IplImage* markBGImg);
void warpImg(IplImage* srcImg);
void changeBG(IplImage* BGImg);
public:
CvMat srcPoint;
CvMat dstPoint;
CvMat* MatHomography;
IplImage*gray0Image;
IplImage*gray255Image;
IplImage*mappingTable;
IplImage*backgroundImg;
IplImage*oribackgroundImg;
IplImage*resultImg;
};
#endif | [
"claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a"
]
| [
[
[
1,
44
]
]
]
|
a8cf665a141239a28f219c2ae5238ffdadc65bd4 | f64fcd89d88b8d58694ec3774f623e7bd77589df | /include/main.cpp | b36951233d226b83154dec34038ea1b4babcd13a | []
| no_license | raceimaztion/createSimulator | 4d75f4d5e47b5d4b9e816f83487e783d7d79caa1 | 15ae791dd85ccbba0145487c4ed7457280f90db0 | refs/heads/master | 2016-09-10T11:36:10.203186 | 2011-05-28T21:24:29 | 2011-05-28T21:24:29 | 1,658,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,951 | cpp | // main.cc
//#include "cm.h"
// For waiting in milliseconds
#ifdef MODE_LOCAL
#ifdef WINDOW
#include <Winbase.h>
#else
#include <unistd.h>
#endif
#endif
#ifdef MODE_EMBEDDED
volatile uint16_t __timer_count = 0;
volatile uint8_t __timer_running = 0;
#endif
void padCommand();
void endCommand();
/*
* This is the main library source file for the Create Simulator.
*/
// Turns the robot on.
void cm_power_on(void)
{
#ifdef MODE_EMBEDDED
if (!cm_robot_power_status())
{
while (!cm_robot_power_status())
{
RobotPwrToggleLow;
cm_wait_ms(500); // Delay in this state
RobotPwrToggleHigh; // Low to high transition to toggle power
cm_wait_ms(100); // Delay in this state
RobotPwrToggleLow;
}
}
#endif
#ifdef MODE_LOCAL
// Tell the repeater to power the robot on
printf("PowerOn\n");
#endif
}
// Turns the Create/Roomba off.
void cm_power_off(void)
{
#ifdef MODE_EMBEDDED
if (cm_robot_power_status())
{
while (cm_robot_power_status())
{
RobotPwrToggleLow;
cm_wait_ms(500); // Delay in this state
RobotPwrToggleHigh; // Low to high transition to toggle power
cm_wait_ms(100); // Delay in this state
RobotPwrToggleLow;
}
}
#endif
#ifdef MODE_LOCAL
// Tell the repeater to turn the robot off
printf("PowerOff\n");
#endif
}
// Grants full control of the robot (and all consequences) to your program.
void cm_full_mode(void)
{
sendByte(CmdFull);
}
/**
* Conditionally grants full control of the robot to your program.
* If the robot enters a danger condition, the robot returns to passive mode.
*/
void cm_safe_mode(void)
{
sendByte(CmdSafe);
}
/**
* Returns the robot to passive mode, where your program can query sensors,
* but not drive the robot.
* Note: This is the default mode.
*/
void cm_passive_mode(void)
{
cm_play_demo(255);
}
/**
* Tells the robot to play the specified demo.
* See the DEMO_* constants for more information.
*/
void cm_play_demo(const uint8_t &demo)
{
sendByte(CmdDemo);
padCommand();
sendByte(demo);
endCommand();
}
/**
* Set the rate of data transfer between the robot and the Command Module.
* Not important for the most part.
* See the Baud* codes in oi.h for more information.
*/
void cm_baud_rate(const uint8_t &baud)
{
if(baud <= 11)
{
sendByte(CmdBaud);
#ifdef MODE_EMBEDDED
UCSR0A |= _BV(TXC0);
#endif
sendByte(baud);
#ifdef MODE_EMBEDDED
// Wait until transmit is complete
while(!(UCSR0A & _BV(TXC0))) ;
cli();
// Switch the baud rate register
switch (baud)
{
case Baud115200:
UBRR0 = Ubrr115200;
break;
case Baud57600:
UBRR0 = Ubrr57600;
break;
case Baud38400:
UBRR0 = Ubrr38400;
break;
case Baud28800:
UBRR0 = Ubrr28800;
break;
case Baud19200:
UBRR0 = Ubrr19200;
break;
case Baud14400:
UBRR0 = Ubrr14400;
break;
case Baud9600:
UBRR0 = Ubrr9600;
break;
case Baud4800:
UBRR0 = Ubrr4800;
break;
case Baud2400:
UBRR0 = Ubrr2400;
break;
case Baud1200:
UBRR0 = Ubrr1200;
break;
case Baud600:
UBRR0 = Ubrr600;
break;
case Baud300:
UBRR0 = Ubrr300;
break;
}
sei();
cm_wait_ms(100);
#endif
}
} // end cm_baud_rate()
/**
* Tells the robot to run the "Cover" demo.
* Note: If the robot is a Roomba, it will clean the floor.
*/
void cm_demo_cover(void)
{
sendByte(CmdClean);
endCommand();
}
/**
* Tells the robot to run the "cover" demo and dock with its charging station
* when its battery gets low.
* Note: If the robot is a Roomba, it will clean the floor.
*/
void cm_demo_cover_and_dock(void)
{
sendByte(CmdDock);
endCommand();
}
/**
* Tells the robot to run the "spot clean" demo.
* Note: If the robot is a Roomba, it will clean the floor.
*/
void cm_demo_spot(void)
{
sendByte(CmdSpot);
endCommand();
}
/**
* Tells the robot to start driving at the specified speed, with the specified
* driving radius to the left. Note that MAX_INT16 and MIN_INT16 have it
* drive as straight as possible, but it's still not entirely straight.
*/
void cm_drive(const int16_t &speed, const int16_t &radius)
{
sendByte(CmdDrive);
padCommand();
sendWord(speed);
padCommand();
sendWord(radius);
endCommand();
}
/**
* Tells the robot to start driving by specifying the driving speed of each wheel.
*/
void cm_direct_drive(const int16_t &right_speed, const int16_t &left_speed)
{
sendByte(CmdDriveWheels);
padCommand();
sendWord(right_speed);
padCommand();
sendWord(left_speed);
endCommand();
}
/**
* Convenience function to tell the robot to stop driving.
*/
void cm_stop_driving(void)
{
cm_direct_drive(0, 0);
}
/**
* Controls the LEDs on top of the robot.
* @param play Turns the Play light on if non-zero.
* @param advance Turns the Advance light on if non-zero.
* @param power_color Sets the shade of the Power light between green (at 0) and orange (at 255).
* @param power_intensity Sets the brightness of the Power light from off (at 0) to full brightness (at 255).
*/
void cm_set_leds(const uint8_t &play, const uint8_t &advance, const uint8_t &power_color, const uint8_t &power_intensity)
{
uint8_t b = 0;
if (play) b |= LEDPlay;
if (advance) b |= LEDAdvance;
sendByte(CmdLeds);
padCommand();
sendByte(b);
padCommand();
sendByte(power_color);
padCommand();
sendByte(power_intensity);
endCommand();
}
/**
* Sets the digital outputs on the Create's cargo bay connector.
* @param pin*: Turns the pin on if non-zero.
* Note 1: Not used in simulations.
* Note 2: Only available on Create robots. Does nothing on Roomba or Scooba robots.
*/
void cm_digital_outputs(const uint8_t &pin0, const uint8_t &pin1, const uint8_t &pin2)
{
uint8_t b = 0;
if (pin0) b |= 0x01;
if (pin1) b |= 0x02;
if (pin2) b |= 0x04;
sendByte(CmdOutputs);
padCommand();
sendByte(b);
endCommand();
}
/**
* Sends the provided byte out over IR.
*/
void cm_send_ir(const uint8_t &data)
{
sendByte(CmdIRChar);
padCommand();
sendByte(data);
endCommand();
}
/**
* Stores a song under the given number for later playback.
*/
void cm_store_song(const uint8_t &song_number, const uint8_t &song_length, const uint8_t song_notes[], const uint8_t song_lengths[])
{
sendByte(CmdSong);
padCommand();
sendByte(song_number);
padCommand();
sendByte(song_length);
for (uint8_t i=0; i < song_length; i++)
{
padCommand();
sendByte(song_notes[i]);
padCommand();
sendByte(song_lengths[i]);
}
endCommand();
}
/**
* Plays the song stored under the given number.
*/
void cm_play_song(const uint8_t &song_number)
{
sendByte(CmdPlay);
padCommand();
sendByte(song_number);
endCommand();
}
/* ************************* *
* Sensor-reading functions: *
* ************************* */
/**
* Returns 1 if the left bumper is pressed.
*/
uint8_t cm_read_left_bumper(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_BUMP_DROP);
endCommand();
if (readByte() & 0x02)
return 1;
else
return 0;
}
/**
* Returns 1 if the right bumper is pressed.
*/
uint8_t cm_read_right_bumper(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_BUMP_DROP);
endCommand();
if (readByte() & 0x01)
return 1;
else
return 0;
}
/**
* Returns 1 if the left wheel is dropped.
*/
uint8_t cm_read_left_wheel_drop(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_BUMP_DROP);
endCommand();
if (readByte() & 0x08)
return 1;
else
return 0;
}
/**
* Returns 1 if the right wheel is dropped.
*/
uint8_t cm_read_right_wheel_drop(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_BUMP_DROP);
endCommand();
if (readByte() & 0x04)
return 1;
else
return 0;
}
/**
* Returns 1 if the caster wheel is dropped.
*/
uint8_t cm_read_caster_wheel_drop(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_BUMP_DROP);
endCommand();
if (readByte() & 0x10)
return 1;
else
return 0;
}
/**
* Returns 1 if the robot currently sees a wall on its right side.
* Note: There is only one wall sensor on all iRobot robots.
*/
uint8_t cm_read_wall(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_WALL);
endCommand();
return readByte();
}
/**
* Returns 1 if the robot sees a cliff on its far left cliff sensor.
*/
uint8_t cm_read_far_left_cliff(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FAR_LEFT_CLIFF);
endCommand();
return readByte();
}
/**
* Returns 1 if the robot sees a cliff on its front left cliff sensor.
*/
uint8_t cm_read_front_left_cliff(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FRONT_LEFT_CLIFF);
endCommand();
return readByte();
}
/**
* Returns 1 if the robot sees a cliff on its front right cliff sensor.
*/
uint8_t cm_read_front_right_cliff(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FRONT_RIGHT_CLIFF);
endCommand();
return readByte();
}
/**
* Returns 1 if the robot sees a cliff on its far right cliff sensor.
*/
uint8_t cm_read_far_right_cliff(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FAR_RIGHT_CLIFF);
endCommand();
return readByte();
}
/**
* Returns 1 if the robot currently sees a virtual wall.
*/
uint8_t cm_read_virtual_wall(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_VIRTUAL_WALL);
endCommand();
return readByte();
}
/*
TODO: Implement something to deal with the "Low Side Driver and Wheel Overcurrents"
sensor request. code #14.
*/
/**
* Reads the byte last received from the IR sensor.
* See the REMOTE_* codes in the cm.h header.
*/
uint8_t cm_read_ir(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_IR_CODE);
endCommand();
return readByte();
}
/*
TODO: Implement the "Buttons" sensor request. code #18.
*/
/**
* Reads the distance the robot has moved since the last time it was asked.
* Note: Units are in millimeters.
*/
int16_t cm_read_distance(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_DISTANCE);
endCommand();
return readWord();
}
/**
* Reads the angle the robot has turned since the last time it was asked.
* Note: Units are in degrees, with positive values to the right and negative
* values to the left.
*/
int16_t cm_read_angle(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_ANGLE);
endCommand();
return readWord();
}
/**
* Reads the battery's current charging state.
* See the BATTERY_* codes in the cm.h header.
*/
uint8_t cm_read_charging_state(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_CHARGE_STATE);
endCommand();
return readByte();
}
/**
* Reads the battery's current voltage in millivolts.
*/
uint16_t cm_read_battery_voltage(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_VOLTAGE);
endCommand();
return readWord();
}
/**
* Reads the amount of current running into (positive values) or out of (negative values)
* the robot's battery.
*/
int16_t cm_read_battery_current(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_CURRENT);
endCommand();
return readWord();
}
/**
* Reads the battery's current temperature in degrees Celsius.
*/
int8_t cm_read_battery_temperature(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_TEMPERATURE);
endCommand();
return readWord();
}
/**
* Reads the battery's current charge in milliamp-hours.
* Note: This value is not accurate if the robot is running off Alkaline batteries.
*/
uint16_t cm_read_battery_charge(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_CHARGE);
endCommand();
return readWord();
}
/**
* Reads the battery's estimated charge capacity in milliamp-hours.
* Note: This value is not accurate if the robot is running off Alkaline batteries.
*/
uint16_t cm_read_battery_capacity(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_CAPACITY);
endCommand();
return readWord();
}
/**
* Reads the strength of the wall sensor's signal.
* The range is 0 to 4095.
*/
uint16_t cm_read_wall_signal(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_WALL_SIGNAL);
endCommand();
return readWord();
}
/**
* Reads the strength of the far left cliff sensor's signal.
* The range is 0 to 4095.
*/
uint16_t cm_read_left_cliff_signal(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FAR_LEFT_CLIFF_SIGNAL);
endCommand();
return readWord();
}
/**
* Reads the strength of the front left cliff sensor's signal.
* The range is 0 to 4095.
*/
uint16_t cm_read_front_left_cliff_signal(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FRONT_LEFT_CLIFF_SIGNAL);
endCommand();
return readWord();
}
/**
* Reads the strength of the front right cliff sensor's signal.
* The range is 0 to 4095.
*/
uint16_t cm_read_front_right_cliff_signal(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FRONT_RIGHT_CLIFF_SIGNAL);
endCommand();
return readWord();
}
/**
* Reads the strength of the far right cliff sensor's signal.
* The range is 0 to 4095.
*/
uint16_t cm_read_right_cliff_signal(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_FAR_RIGHT_CLIFF_SIGNAL);
endCommand();
return readWord();
}
/*
TODO: Implement the "Cargo Bay Digital Inputs" sensor request. code #32, formatted byte.
TODO: Implement the "Cargo Bay Analog Signal" sensor request. code #33, unsigned 10-bit int.
TODO: Implement the "Charging Sources Available" sensor request. code #34, formatted byte.
*/
/**
* Reads the current Open Interface mode.
* See the OI_MODE_* codes in the cm.h header.
*/
uint8_t cm_read_oi_mode(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_OI_MODE);
endCommand();
return readByte();
}
/**
* Reads the number of the currently-playing song.
* Range is 0-15.
*/
uint8_t cm_read_current_song_number(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_SONG_NUMBER);
endCommand();
return readByte();
}
/**
* Returns 1 if there is a song currently playing.
*/
uint8_t cm_read_is_song_playing(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_SONG_PLAYING);
endCommand();
return readByte();
}
/**
* Returns the last-requested speed.
* Range is -500 to 500, units are in millimeters per second.
*/
uint16_t cm_read_requested_speed(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_SPEED);
endCommand();
return readWord();
}
/**
* Returns the last-requested radius.
* Range is -32768 to 32767, units are in millimeters.
*/
uint16_t cm_read_requested_radius(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_RADIUS);
endCommand();
return readWord();
}
/**
* Returns the last-requested speed for the right wheel.
* Range is -500 to 500, in millimeters per second.
*/
uint16_t cm_read_requested_right_speed(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_RIGHT_WHEEL_SPEED);
endCommand();
return readWord();
}
/**
* Returns the last-requested speed for the left wheel.
* Range is -500 to 500, in millimeters per second.
*/
uint16_t cm_read_requested_left_speed(void)
{
sendByte(CmdSensors);
padCommand();
sendByte(SEN_LEFT_WHEEL_SPEED);
endCommand();
return readWord();
}
/**
* Returns the robot's current power state. 1 for on, 0 for off.
*/
uint8_t cm_robot_power_status(void)
{
#ifdef MODE_EMBEDDED
if (RobotIsOn)
return 1;
else
return 0;
#endif
// TODO: Figure out how to ask for this.
#ifdef MODE_LOCAL
printf("RobotIsOn\n");
return readByte();
#endif
}
/**
* Waits for the specified length of time in milliseconds.
*/
void cm_wait_ms(const uint16_t &time)
{
#ifdef MODE_EMBEDDED
__timer_count = time;
__timer_running = 1;
while (__timer_running) ;
#endif
#ifdef MODE_LOCAL
// TODO: Figure out how to wait in a resolution of milliseconds
#ifdef WINDOWS
Sleep(time);
#else
usleep(time);
#endif
#endif
}
/*
* Generally-useful functions that the main library of code uses to communicate with the robot
*/
void sendByte(const uint8_t &value)
{
#ifdef MODE_EMBEDDED
while(!(UCSR0A & _BV(UDRE0))) ;
UDR0 = value;
#else // Typically, MODE_LOCAL is defined if MODE_EMBEDDED isn't
printf("0x%02X", value);
#endif
}
void sendWord(const uint16_t &value)
{
#ifdef MODE_EMBEDDED
sendByte(0xff & (value >> 8));
sendByte(0xff & value);
#else // Typically, MODE_LOCAL is defined if MODE_EMBEDDED isn't
printf("0x%04X", value);
#endif
}
uint8_t readByte(void)
{
#ifdef MODE_EMBEDDED
while(!(UCSR0A & _BV(RXC0))) ;
return UDR0;
#else // Typically, MODE_LOCAL is defined if MODE_EMBEDDED isn't
int value;
scanf("0x%x", &value);
return (uint8_t)(0xff & value);
#endif
}
uint16_t readWord(void)
{
#ifdef MODE_EMBEDDED
return TO_UINT16(readByte(), readByte());
#else // Typically, MODE_LOCAL is defined if MODE_EMBEDDED isn't
int value;
scanf("0x%x", &value);
return (uint16_t)(0xffff & value);
#endif
}
// Used in MODE_LOCAL execution only, adds a space between codes so the repeater can translate
// the codes effectively.
void padCommand(void)
{
#ifdef MODE_LOCAL
printf(" ");
#endif
}
// Used in MODE_LOCAL execution only, adds a newline to the end of a command.
void endCommand(void)
{
#ifdef MODE_LOCAL
printf("\n");
#endif
}
/*
* This is the main entry point for the embedded version:
*/
#ifdef MODE_EMBEDDED
int main(void)
{
// Do init stuff here
// Set I/O pins
DDRB = 0x10;
PORTB = 0xCF;
DDRC = 0x00;
PORTC = 0xFF;
DDRD = 0xE6;
PORTD = 0x7D;
// Set up the serial port
UBRR0 = 19;
UCSR0B = (_BV(RXCIE0) | _BV(TXEN0) | _BV(RXEN0));
UCSR0C = (_BV(UCSZ00) | _BV(UCSZ01));
// Set up timer 1 to generate an interrupt every 1 ms
TCCR1A = 0x00;
TCCR1B = (_BV(WGM12) | _BV(CS12));
OCR1A = 71;
TIMSK1 = _BV(OCIE1A);
// Start the OI:
sendByte(CmdStart);
}
// This is the timer callback
// Timer 1 interrupt times delays in ms
SIGNAL(SIG_OUTPUT_COMPARE1A)
{
if (__timer_count)
__timer_count --;
else
__timer_running = 0;
}
#endif
#ifdef MODE_LOCAL
int main(void)
{
// TODO: Configure a timer
// Start the OI:
sendByte(CmdStart);
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
962
]
]
]
|
a96d42e8c7b979391381fde106a1eb07f9eae4ac | c63c4fed502fd4cbf82acc7901ba0d72b0338bdb | /Create/Task/JoystickNavigationTask.cpp | 77f40bb6af1d19277b2a31efdd025ba2f2630821 | []
| no_license | seeyousystems/core | 7436a38fb09ea08f5d29cf8db2490c92f48d9267 | baddc89a366ad769a1a9c9a59c14f28291b81971 | refs/heads/master | 2020-05-17T19:11:57.814200 | 2011-05-06T04:00:59 | 2011-05-06T04:00:59 | 1,517,217 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,906 | cpp | /*
* JoystickNavigationTask.cpp
*
* ===========================================================================
*
* Copyright 2008-2009 Daniel Kruesi (Dan Krusi) and David Grob
*
* This file is part of the emms framework.
*
* The emms framework 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.
*
* The emms framework 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 software. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "JoystickNavigationTask.h"
#include "../Library/Math.h"
#include "../Library/Debug.h"
#include "../Navigation/Navigation.h"
#include "../Navigation/Weight/FullSpeedWeight.h"
#include "../Navigation/Weight/JoystickWeight.h"
#include "../Navigation/Weight/RightWallFollowerWeight.h"
//#include "../Navigation/Weight/RemoteControlWeight.h"
#include "../Navigation/Weight/CollisionAvoidanceWeight.h"
#include "../Navigation/Weight/AccelerationFilterWeight.h"
#include "../Navigation/Weight/ControllerSpeedWeight.h"
JoystickNavigationTask::JoystickNavigationTask(Create *create, TaskPriority priority) :
Task("JoystickNavigationTask", create, create->intSetting("Task_JoystickNavigationTask_Interval"), priority ){
}
JoystickNavigationTask::~JoystickNavigationTask(){
}
void JoystickNavigationTask::preProcess() {
if( create->navigation->name == "SystemOfWeightsNavigation"){
navigation = (SystemOfWeightsNavigation*) create->navigation;
navigation->deleteAllWeights();
navigation->addWeight(new JoystickWeight(create));
// navigation->addWeight(new RemoteControlWeight(create));
navigation->addWeight(new CollisionAvoidanceWeight(create, CollisionAvoidanceWeight::AvoidanceDirectionAuto));
navigation->addWeight(new AccelerationFilterWeight(create));
// navigation->addWeight(new RightWallFollowerWeight(create));
navigation->addWeight(new ControllerSpeedWeight(create));
} else {
navigation = NULL;
Debug::warning("[JoystickNavigationTask] This navigation module is not supported");
this->status = Interrupted;
}
}
void JoystickNavigationTask::process() {
if(!navigation) return;
Vector2D wheelSpeed = navigation->getWheelSpeed(0,0);
create->controller->setWheelSpeed((short)wheelSpeed.x(), (short)wheelSpeed.y());
}
void JoystickNavigationTask::postProcess() {
create->controller->setWheelSpeed(0, 0);
}
QString JoystickNavigationTask::description() {
return "";
}
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
bc25d4cb2d2363c60b67b3e3e811afae621a32f0 | 1724fb22a0b715c4597c5056ce571f0fbdb1cc46 | /opengta2/clientlist.cpp | b5bde7593751180d96a9f207f8c442ac39244638 | []
| no_license | basecq/OpenGTA2 | 71127e333b7b6c6a60388ad8b4fb5c4408aa5bdd | 2266c354a638397b84ca4766c69e3a50f4e367de | refs/heads/master | 2020-04-06T05:25:34.926813 | 2010-01-27T02:35:09 | 2010-01-27T02:35:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,914 | cpp | #include "opengta_sv.h"
Client_List Clients;
void netCallback_NEWCLIENT(Network_Connection* Connection, Network_Message* Msg) {
LockID lockID = Thread.EnterLock(MUTEX_CLIENTLIST);
if (Network.IsServer) { //This message tells server to register a new client
clientinfo_entry* newClient = 0;
int clientID = BAD_ID;
bool isNewClient = true;
//See if this client was already connected (if so - just change name)
clientID = Clients.getByConnection(Connection);
if (clientID != BAD_ID) {
newClient = Clients.List[clientID];
isNewClient = true;
}
//If he wasn't, try to find empty client slot
if (clientID == BAD_ID) {
for (uint i = 0; i < Clients.List.AllocCount; i++) {
if (Clients.List[i]->ClientName[0] == 0) {
newClient = Clients.List[i];
clientID = i;
break;
}
}
}
Network_Message* replyMsg = Connection->NewMessage();
if (newClient) {
//If it's a new client, spawn him a pedestrian
if (isNewClient) {
newClient->PlayerPed = Peds.Create(Vector3f(430.5f,447.5f,5.0f));
Peds[newClient->PlayerPed]->controlClient = clientID;
newClient->serverOwner = false;
newClient->Connection = Connection;
}
//Change his name
for (int i = 0; i < 32; i++) newClient->ClientName[i] = Msg->ReadByte();
//Reply client with his new client ID, player ped ID, and his name (if it was changed)
replyMsg->Start(NETMESSAGE_NEWCLIENT);
replyMsg->SendInt(clientID);
replyMsg->SendInt(newClient->PlayerPed);
for (int i = 0; i < 32; i++) replyMsg->SendByte(newClient->ClientName[i]);
replyMsg->End();
logWrite("Connected client (%s)",newClient->ClientName);
logWritem("ped id: %d, client id: %d",newClient->PlayerPed,clientID);
//Send all valid clients
Clients.networkUpdateClientList(clientID);
} else {
logWrite("Denied client (%s): max players",newClient->ClientName);
replyMsg->Start(NETMESSAGE_NEWCLIENT);
replyMsg->SendInt(BAD_ID);
replyMsg->End();
}
} else { //This message tells client he was succesfully registered by server
int clientID = Msg->ReadInt();
if (clientID == BAD_ID) {
logWrite("Server denied connection!");
Network.Disconnect();
} else {
logWrite("Server accepted connection, spawning...");
Clients.LocalClient = clientID;
Clients[clientID]->PlayerPed = Msg->ReadInt();
for (int i = 0; i < 32; i++) Clients[clientID]->ClientName[i] = Msg->ReadByte();
logWritem("assigned local client id %d, ped id %d, name: %s",
clientID,Clients[clientID]->PlayerPed,Clients[clientID]->ClientName);
//Request resynchronize all pedestrians
Peds.networkResync();
}
}
Thread.LeaveLock(lockID);
}
void netCallback_CLIENTLIST(Network_Connection* Connection, Network_Message* Msg) {
LockID lockID = Thread.EnterLock(MUTEX_CLIENTLIST);
if (!Network.IsServer) { //Receive list of clients from server
int numClients = Msg->ReadByte();
for (int i = 0; i < numClients; i++) {
int clientID = Msg->ReadInt();
Clients[clientID]->PlayerPed = Msg->ReadInt();
for (int j = 0; j < 32; j++) Clients[clientID]->ClientName[j] = Msg->ReadByte();
}
}
Thread.LeaveLock(lockID);
}
void netCallback_CLIENTINPUT(Network_Connection* Connection, Network_Message* Msg) {
LockID lockID = Thread.EnterLock(MUTEX_CLIENTLIST);
if (Network.IsServer) { //Receive client input, send it to all other clients
for (uint i = 0; i < Clients.List.AllocCount; i++) {
if (Clients[i]->Connection == Connection) {
int keys = Msg->ReadInt();
for (int j = 0; j < 8; j++) {
Clients[i]->PlayerKeys[j] = (keys & (1 << (j+1))) != 0;
}
float hdg = Msg->ReadFloat();
Ped* playerPed = Peds[Clients[i]->PlayerPed];
if (playerPed) playerPed->Heading = hdg;
//Send message to other clients
for (uint k = 0; k < Clients.List.AllocCount; k++) {
if ((k != i) &&
(Clients[k]->Connection) && (Clients[k]->ClientName[0]) &&
(Clients[k]->Connection->socketHandle >= 0)) {
Network_Message* msg = Clients[k]->Connection->NewMessage();
msg->Start(NETMESSAGE_CLIENTINPUT);
msg->SendByte(1); //Count
msg->SendInt(i); //ClientID
msg->SendInt(keys); //Keys
msg->SendFloat(hdg);
msg->End();
}
}
Thread.LeaveLock(lockID);
return;
}
}
} else { //Receive client input (clientside)
int numClients = Msg->ReadByte();
for (int i = 0; i < numClients; i++) {
int clientID = Msg->ReadInt();
int keys = Msg->ReadInt();
if (clientID != Clients.LocalClient) { //Do not apply keys to local client, to avoid visual lags
for (int j = 0; j < 8; j++) {
Clients[clientID]->PlayerKeys[j] = (keys & (1 << (j+1))) != 0;
}
}
}
}
Thread.LeaveLock(lockID);
}
void Client_List::networkUpdateClientList(ClientID client) {
// LockID lockID = Thread.EnterLock(MUTEX_CLIENTLIST);
if (client == BAD_ID) return;
if (!Clients[client]->ClientName[0]) return;
if (!Clients[client]->Connection) return;
//Count clients
int numClients = 0;
for (uint i = 0; i < Clients.List.AllocCount; i++)
if (Clients[i]->ClientName[0]) numClients++;
//Send all valid clients
Network_Message* clistMsg = Clients[client]->Connection->NewMessage();
clistMsg->Start(NETMESSAGE_CLIENTLIST);
clistMsg->SendByte(numClients);
for (uint i = 0; i < Clients.List.AllocCount; i++) {
if (Clients[i]->ClientName[0]) {
clistMsg->SendInt(i); //ClientID
clistMsg->SendInt(Clients[i]->PlayerPed);
for (int j = 0; j < 32; j++) clistMsg->SendByte(Clients[i]->ClientName[j]);
}
}
clistMsg->End();
//Thread.LeaveLock(lockID);
}
int cvMaxPlayers_Read(int numParams, int* paramType, int* params) {
CVAR_SET_INT(0,Clients.List.AllocCount);
return 1;
}
void cvMaxPlayers_Write(int numParams, int* paramType, int* params) {
Clients.SetMaxPlayers(CVAR_GET_INT(0));
}
void Client_List::Initialize() {
logWrite("Initializing client list");
cvMaxPlayers = Convar.Create("max_players",cvMaxPlayers_Read,cvMaxPlayers_Write);
//SetMaxPlayers(256);
List.Preallocate(256);
for (uint i = 0; i < List.AllocCount; i++) List[i]->Connection = 0;
Reinitialize();
Network.networkCallback[NETMESSAGE_NEWCLIENT] = netCallback_NEWCLIENT;
Network.networkCallback[NETMESSAGE_CLIENTLIST] = netCallback_CLIENTLIST;
Network.networkCallback[NETMESSAGE_CLIENTINPUT] = netCallback_CLIENTINPUT;
}
void Client_List::SetMaxPlayers(int numPlayers) {
List.Preallocate(numPlayers);
Reinitialize();
}
void Client_List::Reinitialize() {
LockID lockID = Thread.EnterLock(MUTEX_CLIENTLIST);
if (List.AllocCount > 0) {
//Close all client connections that might be still open
for (uint i = 0; i < List.AllocCount; i++) {
if (List[i]->Connection) List[i]->Connection->Close();
}
}
for (uint i = 0; i < List.AllocCount; i++) {
for (uint j = 0; j < 8; j++) List[i]->PlayerKeys[j] = 0;
List[i]->serverOwner = false;
List[i]->PlayerPed = BAD_ID;
List[i]->ClientName[0] = 0;
List[i]->Connection = 0;
}
if (Network.IsConnected) { //If we are connected, register ourselves in server list
//Local client will be given out by server later
LocalClient = BAD_ID;
char buf[32];
sprintf(buf,"Player %d",Random.Int(11111,99999));
Network_Message* Msg = Network[0]->NewMessage();
Msg->Start(NETMESSAGE_NEWCLIENT);
for (int i = 0; i < 32; i++) Msg->SendByte(buf[i]);
Msg->End();
} else {
if (!Game.IsDedicatedServer) {
//Add master client
strcpy(List[0]->ClientName,"LISTEN SERVER");
List[0]->serverOwner = true;
LocalClient = 0; //On listen server this specifies master clients ID
List[0]->PlayerPed = Peds.Create(Vector3f(430.5f,447.5f,5.0f));
Peds[List[0]->PlayerPed]->controlClient = 0;
} else {
//No master client on dedicated server
LocalClient = BAD_ID;
}
}
Thread.LeaveLock(lockID);
}
void Client_List::Deinitialize() {
List.Release();
}
ClientID Client_List::getByConnection(Network_Connection* Connection) {
for (uint i = 0; i < List.AllocCount; i++) {
if (List[i]->Connection == Connection) {
return i;
}
}
return BAD_ID;
}
void Client_List::Frame() {
if (Network.IsServer) {
for (uint i = 0; i < Clients.List.AllocCount; i++) {
if (Clients.LocalClient == i) continue;
if (Clients[i]->ClientName[0]) {
if ((Clients[i]->Connection) &&
(Clients[i]->Connection->socketHandle < 0)) {
Clients[i]->Connection = 0;
}
if ((!Clients[i]->Connection) && (!Clients[i]->serverOwner)) {
Clients[i]->ClientName[0] = 0;
Peds.Kill(Clients[i]->PlayerPed);
}
}
}
}
if (Clients.LocalClient == BAD_ID) return;
if (Network.IsConnected) {
//Update control clients FIXME
for (uint k = 0; k < Clients.List.AllocCount; k++) {
if (Clients[k]->ClientName[0]) {
Ped* ped = Peds[Clients[k]->PlayerPed];
if (ped) {
ped->controlClient = k;
}
}
}
}
if (Network.IsConnected || Network.IsServer) {
bool resendKeys = false;
for (int i = 0; i < 8; i++) {
if (Clients[Clients.LocalClient]->PlayerKeys[i] !=
Clients[Clients.LocalClient]->prevPlayerKeys[i]) {
Clients[Clients.LocalClient]->prevPlayerKeys[i] = Clients[Clients.LocalClient]->PlayerKeys[i];
resendKeys = true;
}
}
if (resendKeys) {
if (Network.IsServer) {
for (uint k = 0; k < Clients.List.AllocCount; k++) {
if ((k != Clients.LocalClient) &&
(Clients[k]->Connection) && (Clients[k]->ClientName[0]) &&
(Clients[k]->Connection->socketHandle >= 0)) {
Network_Message* msg = Clients[k]->Connection->NewMessage();
msg->Start(NETMESSAGE_CLIENTINPUT);
msg->SendByte(1);
msg->SendInt(Clients.LocalClient);
int keys = 0;
for (int i = 0; i < 8; i++) keys = keys | (Clients[Clients.LocalClient]->PlayerKeys[i] * (1 << (i+1)));
msg->SendInt(keys);
Ped* playerPed = Peds[Clients[Clients.LocalClient]->PlayerPed];
if (playerPed) msg->SendFloat(playerPed->Heading); else msg->SendFloat(0);
msg->End();
}
}
} else {
Network_Message* msg = Network.Connections[0]->NewMessage();
msg->Start(NETMESSAGE_CLIENTINPUT);
int keys = 0;
for (int i = 0; i < 8; i++) keys = keys | (Clients[Clients.LocalClient]->PlayerKeys[i] * (1 << (i+1)));
msg->SendInt(keys);
Ped* playerPed = Peds[Clients[Clients.LocalClient]->PlayerPed];
if (playerPed) msg->SendFloat(playerPed->Heading); else msg->SendFloat(0);
msg->End();
}
}
}
} | [
"[email protected]"
]
| [
[
[
1,
329
]
]
]
|
599c296416cb824ef1a44c553cfefe72e78370b0 | 7f30cb109e574560873a5eb8bb398c027f85eeee | /src/wxWiiManagerDialog.h | a305853cd80a273f8b8a4a352f8500775f4f28d3 | []
| no_license | svn2github/MITO | e8fd0e0b6eebf26f2382f62660c06726419a9043 | 71d1269d7666151df52d6b5a98765676d992349a | refs/heads/master | 2021-01-10T03:13:55.083371 | 2011-10-14T15:40:14 | 2011-10-14T15:40:14 | 47,415,786 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,627 | h | /**
* \file wxWiiManagerDialog.h
* \brief File per la creazione del dialog che permette di impostare i parametri dei Wiimote rilevabili
*/
#ifndef _wxWiiManagerDialog_h_
#define _wxWiiManagerDialog_h_
#include <wx/wx.h>
#include <wx/odcombo.h>
#include <wx/bmpcbox.h>
#define num_Colors 7
#define connectLabel "Connect"
#define selectAllLabel "Connect to all Wii"
#define pointerColorLabel "Pointer Color"
#define choiceColorLabel "Choice Pointer Color"
#define rilevaButtonLabel "Redetect"
#define rilevaPressed wxID_HIGHEST + 1
#define idRotationMode wxID_HIGHEST + 2
#define listOfColors {"Red","Yellow","Blue","Green","Violet","Orange","White"}
class wxWiiManagerDialog : public wxDialog
{
public:
wxWiiManagerDialog( wxWindow *parent, int Wii_num = 0, int* batteryLevel = NULL, wxWindowID id = wxID_ANY, const wxString & title = "Wiimote Manager", const wxPoint& position = wxDefaultPosition,
const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE);
~wxWiiManagerDialog() {}
bool isWiiSelected(int i);
int getColorChosen(int i);
wxChoice* getRotationModeChoice();
private:
DECLARE_EVENT_TABLE()
wxPanel* createAWiiBox(wxWindow * parent, int idWii, int batteryLevel);
wxWindow* getWiiPanel(int i);
wxChoice* getChoiceColor(wxWindow * win);
wxCheckBox* getCheckBox(wxWindow * win);
wxStaticText* getBatteryText(wxWindow * win);
wxCheckBox* getAllSelectBox();
wxButton* getStartButton();
void OnRileva(wxCommandEvent & event);
void OnCheckBox(wxCommandEvent & event);
int Wii_num;
};
#endif | [
"kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de"
]
| [
[
[
1,
59
]
]
]
|
e9e668f29cbb138d6f4c20c4da074b4a5219c55d | a1e5c0a674084927ef5b050ebe61a89cd0731bc6 | /OpenGL_SceneGraph_Stussman/Code/Aufgabe1/main.h | 22740681d86da84e4223adb4780ce67b0102fb4b | []
| no_license | danielkummer/scenegraph | 55d516dc512e1b707b6d75ec2741f48809d8797f | 6c67c41a38946ac413333a84c76340c91b87dc96 | refs/heads/master | 2016-09-01T17:36:02.995636 | 2008-06-05T09:45:24 | 2008-06-05T09:45:24 | 32,327,185 | 0 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 1,549 | h | /**************************************************/
/* */
/* Main Header Aufgabe 1 optional */
/* */
/**************************************************/
/* Authors: Reto Bollinger */
/* [email protected] */
/* */
/* Hanspeter Brühlmann */
/* [email protected] */
/* */
/**************************************************/
/* Date: 15. October 2004 */
/**************************************************/
#ifndef _MAIN_H
#define _MAIN_H
#ifdef WIN32
#include <windows.h>
#else
#include <GL/glx.h>
#include <stdarg.h>
#endif
#include <SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <SDL_syswm.h>
#include <SDL_byteorder.h>
using namespace std;
/**************************************************/
/* Function definition */
/**************************************************/
void quit_program( int code ); // Quit program
void process_events( ); // Process keyevents
bool init_OpenGL( ); // Init OpenGL
bool init_SDL(); // Init SDL Engine
int main( int argc, char* argv[] ); // Main
#endif
| [
"dr0iddr0id@fe886383-234b-0410-a1ab-e127868e2f45"
]
| [
[
[
1,
52
]
]
]
|
8b9b151a564beae56ba9fc9c3b18ded2ad5eedcd | 9df2486e5d0489f83cc7dcfb3ccc43374ab2500c | /src/objects/spinbox.h | d511abdac624fda21b3d56e0e7fac89bde0f29bd | []
| no_license | renardchien/Eta-Chronicles | 27ad4ffb68385ecaafae4f12b0db67c096f62ad1 | d77d54184ec916baeb1ab7cc00ac44005d4f5624 | refs/heads/master | 2021-01-10T19:28:28.394781 | 2011-09-05T14:40:38 | 2011-09-05T14:40:38 | 1,914,623 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,783 | h | /***************************************************************************
* spinbox.h - header for the corresponding cpp file
*
* Copyright (C) 2003 - 2009 Florian Richter
***************************************************************************/
/*
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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SMC_SPINBOX_H
#define SMC_SPINBOX_H
#include "../core/globals.h"
#include "../objects/box.h"
namespace SMC
{
/* *** *** *** *** *** *** *** *** cSpinBox *** *** *** *** *** *** *** *** *** */
class cSpinBox : public cBaseBox
{
public:
// constructor
cSpinBox( float x, float y );
// create from stream
cSpinBox( CEGUI::XMLAttributes &attributes );
// destructor
virtual ~cSpinBox( void );
// init defaults
void Init( void );
// copy
virtual cSpinBox *Copy( void );
// create from stream
virtual void Create_From_Stream( CEGUI::XMLAttributes &attributes );
// save to stream
virtual void Save_To_Stream( ofstream &file );
// Activate the Spinning
virtual void Activate( void );
// Stop the Spinning
void Stop( void );
// update
virtual void Update( void );
// if update is valid for the current state
virtual bool Is_Update_Valid( void );
// spin counter
float spin_counter;
// if spinning
bool spin;
};
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
#endif
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
7fd76cb18c917afec743f9cd9cc59a353c418ad4 | 1bbd5854d4a2efff9ee040e3febe3f846ed3ecef | /src/scrview/host.h | 2f910f5012d1a20a9b0a8310e679f94f8a0acdaf | []
| no_license | amanuelg3/screenviewer | 2b896452a05cb135eb7b9eb919424fe6c1ce8dd7 | 7fc4bb61060e785aa65922551f0e3ff8423eccb6 | refs/heads/master | 2021-01-01T18:54:06.167154 | 2011-12-21T02:19:10 | 2011-12-21T02:19:10 | 37,343,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | h | #ifndef HOST_H
#define HOST_H
#include <QThread>
#include <QMutex>
#include "server.h"
#include "scrmaker.h"
#include "mouse.h"
#include "mousedatacollector.h"
class Host : public QThread
{
private:
bool isClient;
QString format;
int w;
int h;
QMutex* scrMutex;
QMutex* mouseMutex;
ScrMaker* scrProcess;
MouseDataCollector* mouseProcess;
Server* serv;
public:
Host(int w, int h, QString format);
void run();
void takeClient() { isClient = false; }
bool hasClient() { return isClient; }
void setW(int w) { this->w = w; }
int getW() { return w; }
void setH(int h) { this->h = h; }
int getH() { return h; }
void setFormat(QString format) { this->format = format; }
QString getFormat() { return format; }
void takeMouseData(MouseData* data) { mouseProcess->newData(data); }
};
#endif // HOST_H
| [
"JuliusR@localhost"
]
| [
[
[
1,
38
]
]
]
|
e2a6579adfa189e27b5c69b457da2ee8ea9eedd4 | 59066f5944bffb953431bdae0482a2abfb75f49a | /trunk/ogreopcode/TerrainExample/src/main.cpp | b26bf2f5905f18185cd91b74c451e3ac65d20124 | []
| no_license | BackupTheBerlios/conglomerate-svn | 5b1afdea5fbcdd8b3cdcc189770b1ad0f8027c58 | bbecac90353dca2ae2114d40f5a6697b18c435e5 | refs/heads/master | 2021-01-01T18:37:56.730293 | 2006-05-21T03:12:39 | 2006-05-21T03:12:39 | 40,668,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,356 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
You may use this sample code for anything you like, it is not covered by the
LGPL like the rest of the engine.
-----------------------------------------------------------------------------
*/
#include "OgreOpcodeTerrainExample.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{
// Create application object
OgreOpcodeTerrainExampleApp app;
SET_TERM_HANDLER;
try {
app.go();
} catch( Ogre::Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " <<
e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif
| [
"jacmoe@4fa2dde5-35f3-0310-a95e-e112236e8438"
]
| [
[
[
1,
54
]
]
]
|
f7cd0c664cf28339a12f29fdf14e0cb382da8769 | 9310fd7bac6871c98b216a2e081b19e9232c14ed | /lib/agr/samples/prototype/src/WiimoteTestView.cpp | 00685b26b6672cf863b6438d5471fbd0a928a1cb | []
| no_license | baloo/wiidrums | 1345525c759a2325274ddbfe182a9549c6c4e325 | ed3832d4f91cd9932bfeb321b8aa57340a502d48 | refs/heads/master | 2016-09-09T18:19:06.403352 | 2009-05-21T02:04:09 | 2009-05-21T02:04:09 | 179,309 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,013 | cpp | // WiimoteTestView.cpp : implementation of the CWiimoteTestView class
//
#include "stdafx.h"
#include "WiimoteTest.h"
#include <vector>
#include "WiiAccelerometer.h"
#include "WiimoteTestDoc.h"
#include "WiimoteTestView.h"
#include ".\wiimotetestview.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CWiimoteTestView
IMPLEMENT_DYNCREATE(CWiimoteTestView, CScrollView)
BEGIN_MESSAGE_MAP(CWiimoteTestView, CScrollView)
ON_WM_TIMER()
ON_WM_LBUTTONDOWN()
ON_WM_KEYDOWN()
END_MESSAGE_MAP()
// CWiimoteTestView construction/destruction
CWiimoteTestView::CWiimoteTestView()
{
}
CWiimoteTestView::~CWiimoteTestView()
{
}
BOOL CWiimoteTestView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CScrollView::PreCreateWindow(cs);
}
// CWiimoteTestView drawing
void CWiimoteTestView::OnDraw(CDC* pDC)
{
CWiimoteTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// CScrollView::SetScrollSizes(
// TEST, hardcoded
// TODO : proper menus
// display curent value
CString text;
text.Format( "Wiimote 1 acc : x = %d, y = %d, z = %d, sqDist = %d",
pDoc->m_acc1_x_array[ pDoc->m_arrayLast1 ],
pDoc->m_acc1_y_array[ pDoc->m_arrayLast1 ],
pDoc->m_acc1_z_array[pDoc-> m_arrayLast1 ],
pDoc->m_wiimote1SquareDist
);
CRect rect = CRect( 10, 0, 1000, 100 );
pDC->DrawText( text, &rect, 0 );
#if USE_OLD_CODE
// View actual
pDC->Rectangle( 10, 20, 350, 70 );
rect = CRect( 15, 25, 1000, 100 );
if( pDoc->m_movementVocabulary.empty() )
{
text.Format( "Current move, size = %d", pDoc->m_lastMovement.size() );
pDC->DrawText( text, &rect, 0 );
}
else
{
text.Format( "Current move, size = %d, prob %f", pDoc->m_lastMovement.size(), pDoc->forward( &(pDoc->m_lastMovement) ) );
pDC->DrawText( text, &rect, 0 );
rect = CRect( 15, 45, 1000, 100 );
text.Format( "Clustered : " );
pDoc->m_lastMovementVocabulary.resize( pDoc->m_normalisedVectorSize );
pDoc->computeObservationCluster( &(pDoc->m_lastMovement), &(pDoc->m_lastMovementVocabulary) );
for( int i=0; i<pDoc->m_normalisedVectorSize; i++ )
{
text.Format( "%s %d", text, pDoc->m_lastMovementVocabulary[i] );
}
pDC->DrawText( text, &rect, 0 );
}
// Record actual
pDC->Rectangle( 10, 69, 350, 100 );
rect = CRect( 15, 72, 1000, 100 );
text.Format( "Add current to the list" );
pDC->DrawText( text, &rect, 0 );
for( unsigned int i=0; i<pDoc->m_movementVector.size(); i++ )
{
pDC->Rectangle( 10, i*60+130, 350, i*60+180 );
rect = CRect( 15, i*60+132, 1000, i*60+180 );
if( pDoc->m_movementVectorProb.size() > 0 )
{
text.Format( "Move %d, length %d, prob %f ", i+1, pDoc->m_movementVector[i].size(), pDoc->m_movementVectorProb[i] );
}
else
{
text.Format( "Move %d, length %d", i+1, pDoc->m_movementVector[i].size() );
}
pDC->DrawText( text, &rect, 0 );
if( !pDoc->m_movementVocabulary.empty() )
{
rect = CRect( 15, i*60+150, 1000, i*60+180 );
text.Format( "Clusterised : " );
for( int j=0; j<pDoc->m_normalisedVectorSize; j++ )
{
text.Format( "%s %d", text, pDoc->m_movementVocabulary[ i ][ j ] );
}
pDC->DrawText( text, &rect, 0 );
}
}
#else // New version using AGR
// View actual
pDC->Rectangle( 10, 20, 350, 70 );
rect = CRect( 15, 25, 1000, 100 );
if( pDoc->m_movementVocabulary.empty() )
{
text.Format( "Current move, size = %d", pDoc->m_GRcurrentMovement.getSize() );
pDC->DrawText( text, &rect, 0 );
}
else // not yet implemented
{
text.Format( "Current move, size = %d, prob %f",
pDoc->m_GRcurrentMovement.getSize(),
pDoc->m_gestureRecogniser.gestureLikelihood( 0, pDoc->m_GRcurrentMovement )
);
pDC->DrawText( text, &rect, 0 );
//rect = CRect( 15, 45, 1000, 100 );
//text.Format( "Clustered : " );
//pDoc->m_lastMovementVocabulary.resize( pDoc->m_normalisedVectorSize );
//pDoc->computeObservationCluster( &(pDoc->m_lastMovement), &(pDoc->m_lastMovementVocabulary) );
//for( int i=0; i<pDoc->m_normalisedVectorSize; i++ )
//{
// text.Format( "%s %d", text, pDoc->m_lastMovementVocabulary[i] );
//}
//pDC->DrawText( text, &rect, 0 );
}
// Record actual
pDC->Rectangle( 10, 69, 350, 100 );
rect = CRect( 15, 72, 1000, 100 );
text.Format( "Add current to the list" );
pDC->DrawText( text, &rect, 0 );
for( unsigned int i=0; i<pDoc->m_GRmovementVector.size(); i++ )
{
pDC->Rectangle( 10, i*60+130, 350, i*60+180 );
rect = CRect( 15, i*60+132, 1000, i*60+180 );
if( pDoc->m_movementVectorProb.size() > i )
{
text.Format( "Move %d, length %d, prob %f ", i+1, pDoc->m_GRmovementVector[i].getSize(), pDoc->m_movementVectorProb[i] );
}
else
{
text.Format( "Move %d, length %d", i+1, pDoc->m_GRmovementVector[i].getSize() );
}
pDC->DrawText( text, &rect, 0 );
if( !pDoc->m_movementVocabulary.empty() )
{
rect = CRect( 15, i*60+150, 1000, i*60+180 );
text.Format( "Clusterised : " );
for( int j=0; j<pDoc->m_movementVocabulary[ i ].size(); j++ )
{
text.Format( "%s %d", text, pDoc->m_movementVocabulary[ i ][ j ] );
}
pDC->DrawText( text, &rect, 0 );
}
}
#endif
//// Display graph
//// wiimote 1, x
//unsigned int startPoint = pDoc->m_arrayLast1+1;
//if( startPoint == SIZE_ACC_ARRAY )
// startPoint = 0;
//static const int posGraph1_x = 0;
//static const int posGraph1_y = 50;
//for( int x=0; x<SIZE_ACC_ARRAY; x++ )
//{
// int i = (startPoint+x) % SIZE_ACC_ARRAY;
// if( i == startPoint )
// pDC->MoveTo( x + posGraph1_x, pDoc->m_acc1_x_array[i] + posGraph1_y );
// else
// pDC->LineTo( x + posGraph1_x, pDoc->m_acc1_x_array[i] + posGraph1_y );
//}
//// wiimote 1, y
//static const int posGraph2_x = 0;
//static const int posGraph2_y = 250;
//for( int x=0; x<SIZE_ACC_ARRAY; x++ )
//{
// int i = (startPoint+x) % SIZE_ACC_ARRAY;
// if( i == startPoint )
// pDC->MoveTo( x + posGraph2_x, pDoc->m_acc1_y_array[i] + posGraph2_y );
// else
// pDC->LineTo( x + posGraph2_x, pDoc->m_acc1_y_array[i] + posGraph2_y );
//}
//// wiimote 1, z
//static const int posGraph3_x = 0;
//static const int posGraph3_y = 450;
//for( int x=0; x<SIZE_ACC_ARRAY; x++ )
//{
// int i = (startPoint+x) % SIZE_ACC_ARRAY;
// if( i == startPoint )
// pDC->MoveTo( x + posGraph3_x, pDoc->m_acc1_z_array[i] + posGraph3_y );
// else
// pDC->LineTo( x + posGraph3_x, pDoc->m_acc1_z_array[i] + posGraph3_y );
//}
}
void CWiimoteTestView::saveMoves()
{
CWiimoteTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
FILE* f = fopen( "movement.txt", "w" );
#if USE_OLD_CODE
int nbMove = pDoc->m_movementVector.size();
fprintf( f, "%d \n", nbMove );
for( int i=0; i<nbMove; i++ )
{
fprintf( f, "%d \n", pDoc->m_movementVector[i].size() );
std::vector<cVector3int>::iterator iter;
for( iter = pDoc->m_movementVector[i].begin(); iter != pDoc->m_movementVector[i].end(); iter++ )
{
fprintf( f, "%d %d %d ", iter->x, iter->y, iter->z );
}
fprintf( f, "\n" );
}
#else // use GR
unsigned int nbMove = pDoc->m_GRmovementVector.size();
fprintf( f, "%d \n", nbMove );
for( unsigned int i=0; i<nbMove; i++ )
{
cMovement* ptMov = &pDoc->m_GRmovementVector[i];
fprintf( f, "%d \n", ptMov->getSize() );
for( unsigned int i=0; i< ptMov->getSize(); i++ )
{
cVector3int vec = ptMov->getData( i );
fprintf( f, "%d %d %d ", vec.x, vec.y, vec.z );
}
fprintf( f, "\n" );
}
#endif
fclose( f );
MessageBox( "Saved" );
}
void CWiimoteTestView::loadMoves()
{
CWiimoteTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
FILE* f = fopen( "movement.txt", "r" );
#if USE_OLD_CODE
int nbMove = 0;
fscanf( f, "%d", &nbMove );
pDoc->m_movementVector.resize( nbMove );
for( int i=0; i<nbMove; i++ )
{
int nbPoint = 0;
fscanf( f, "%d", &nbPoint );
std::vector<cVector3int>::iterator iter;
for( int j=0; j<nbPoint; j++ )
{
cVector3int vec;
fscanf( f, "%d %d %d", &vec.x, &vec.y, &vec.z );
pDoc->m_movementVector[i].push_back( vec );
}
}
#else // use GR
int nbMove = 0;
fscanf( f, "%d", &nbMove );
pDoc->m_GRmovementVector.resize( nbMove );
for( int i=0; i<nbMove; i++ )
{
unsigned int nbPoint = 0;
fscanf( f, "%d", &nbPoint );
pDoc->m_GRmovementVector[i].initialise( nbPoint );
cVector3int* buffer = pDoc->m_GRmovementVector[i].modifyBuffer();
for( unsigned int j=0; j<nbPoint; j++ )
{
fscanf( f, "%d %d %d", &buffer[j].x, &buffer[j].y, &buffer[j].z );
}
}
#endif
fclose( f );
}
// CWiimoteTestView diagnostics
#ifdef _DEBUG
void CWiimoteTestView::AssertValid() const
{
CScrollView::AssertValid();
}
void CWiimoteTestView::Dump(CDumpContext& dc) const
{
CScrollView::Dump(dc);
}
CWiimoteTestDoc* CWiimoteTestView::GetDocument() const // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CWiimoteTestDoc)));
return (CWiimoteTestDoc*)m_pDocument;
}
#endif //_DEBUG
// TODO : remove or clean
// used for tests
float time()
{
static __int64 start = 0;
static __int64 frequency = 0;
if (start==0)
{
QueryPerformanceCounter((LARGE_INTEGER*)&start);
QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
return 0.0f;
}
__int64 counter = 0;
QueryPerformanceCounter((LARGE_INTEGER*)&counter);
return (float) ((counter - start) / double(frequency));
}
// CWiimoteTestView message handlers
void CWiimoteTestView::OnTimer(UINT nIDEvent)
{
CWiimoteTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
CSize sizeTotal;
sizeTotal.cx = 355;
sizeTotal.cy = pDoc->m_movementVector.size()*60+190;
SetScrollSizes(MM_TEXT, sizeTotal);
InvalidateRect( NULL );
SetTimer(1, 100, 0 );
CScrollView::OnTimer(nIDEvent);
}
void CWiimoteTestView::OnInitialUpdate()
{
CScrollView::OnInitialUpdate();
CSize sizeTotal;
sizeTotal.cx = 100;
sizeTotal.cy = 100;
SetScrollSizes(MM_TEXT, sizeTotal);
SetTimer( 1, 100, 0 );
}
void CWiimoteTestView::OnLButtonDown(UINT nFlags, CPoint inPoint)
{
CWiimoteTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
CPoint point = inPoint;
point.y += GetScrollPos( SB_VERT );
#if USE_OLD_CODE
CRect rect;
rect = CRect( 10, 20, 350, 70 );
if( rect.PtInRect( point ) )
{
pDoc->m_selectedMovement = &(pDoc->m_lastMovement);
pDoc->m_selectedId = -1;
}
rect = CRect( 10, 69, 350, 100 );
if( rect.PtInRect( point ) )
{
pDoc->m_movementVector.push_back( pDoc->m_lastMovement );
if( pDoc->m_selectedId >= 0 )
pDoc->m_selectedMovement = &(pDoc->m_movementVector[pDoc->m_selectedId]);
}
// tuch one of the recorded movement ?
for( unsigned int i=0; i<pDoc->m_movementVector.size(); i++ )
{
rect = CRect( 10, i*60+130, 350, i*60+180 );
if( rect.PtInRect( point ) )
{
pDoc->m_selectedMovement = &(pDoc->m_movementVector[i]);
pDoc->m_selectedId = i;
}
}
#else // using GR
CRect rect;
rect = CRect( 10, 20, 350, 70 );
if( rect.PtInRect( point ) )
{
pDoc->m_GRselectedMovement = &(pDoc->m_GRcurrentMovement);
pDoc->m_selectedId = -1;
}
rect = CRect( 10, 69, 350, 100 );
if( rect.PtInRect( point ) )
{
pDoc->m_GRmovementVector.push_back( pDoc->m_GRcurrentMovement );
if( pDoc->m_selectedId >= 0 )
pDoc->m_GRselectedMovement = &(pDoc->m_GRmovementVector[pDoc->m_selectedId]);
}
// tuch one of the recorded movement ?
for( unsigned int i=0; i<pDoc->m_GRmovementVector.size(); i++ )
{
rect = CRect( 10, i*60+130, 350, i*60+180 );
if( rect.PtInRect( point ) )
{
pDoc->m_GRselectedMovement = &(pDoc->m_GRmovementVector[i]);
pDoc->m_selectedId = i;
}
}
#endif
CScrollView::OnLButtonDown(nFlags, point);
}
void CWiimoteTestView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
CWiimoteTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
switch( nChar )
{
case 'T' :
#if USE_OLD_CODE
pDoc->testOld();
pDoc->calculateProba();
pDoc->calculateVoca();
#else // GR code
pDoc->test();
pDoc->calculateProba();
pDoc->calculateVoca();
#endif
break;
case 'E' :
#if USE_OLD_CODE
pDoc->exportHMM();
#else // GR code
pDoc->m_gestureRecogniser.save( "GR.txt" );
#endif
break;
case 'B' :
#if USE_OLD_CODE
pDoc->BaumWelchOptimisation();
pDoc->calculateProba();
#endif
break;
case 'W' :
saveMoves();
break;
case 'X' :
loadMoves();
break;
}
CScrollView::OnKeyDown(nChar, nRepCnt, nFlags);
}
| [
"[email protected]"
]
| [
[
[
1,
547
]
]
]
|
0b168a4fa196bf80642d4924071ddda619b05728 | 677f0ea3bcea23f622418669de6a5a54bb938e68 | /plot.cpp | 53d1f9daba6f442de0b9594c3335a8568c7ab460 | []
| no_license | joshuaeckroth/RBFNetworkSimulator | afe41ae2cba2bb90ba8c0ba2ba24c11f81794a74 | 43e2178455da924e9f83dafa5c0f107ca1400ffc | refs/heads/master | 2020-05-26T22:36:11.793164 | 2010-02-28T18:28:49 | 2010-02-28T18:28:49 | 538,607 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,550 | cpp | #include <cmath>
using namespace std;
#include <qwt_plot.h>
#include <qwt_plot_curve.h>
#include <qwt_series_data.h>
#include <qwt_legend.h>
#include <qwt_plot_marker.h>
#include <qwt_symbol.h>
#include <QWidget>
#include <QString>
#include <QDebug>
#include "plot.h"
#include "state.h"
Plot::Plot(QWidget *parent, State *_state)
: QwtPlot(parent), state(_state), samples(NULL), centers(NULL),
sampledFunction(NULL), estimatedCurve(NULL)
{
connect(state, SIGNAL(newSamples()), this, SLOT(newSamples()));
connect(state, SIGNAL(newCenters()), this, SLOT(newCenters()));
connect(state, SIGNAL(newBases()), this, SLOT(newBases()));
setCanvasBackground(QColor(255,255,255));
centerCurves.clear();
centerMemberCurves.clear();
basisCurves.clear();
basisColors.clear();
}
void Plot::newSamples()
{
samples = state->getSamples();
if(sampledFunction != NULL)
{
sampledFunction->detach();
delete sampledFunction;
}
sampledFunction = new QwtPlotCurve(QString("Sampled Function"));
sampledFunction->setSamples(*samples);
sampledFunction->setRenderHint(QwtPlotCurve::RenderAntialiased, true);
sampledFunction->setStyle(QwtPlotCurve::NoCurve);
sampledFunction->setSymbol(
QwtSymbol(QwtSymbol::Ellipse, QBrush(QColor("black")),
QPen(QColor("black")), QSizeF(3.0, 3.0)));
sampledFunction->attach(this);
replot();
}
void Plot::newCenters()
{
for(int i = 0; i < centerCurves.size(); i++)
{
if(centerCurves[i] != NULL)
{
centerCurves[i]->detach();
delete centerCurves[i];
}
}
for(int i = 0; i < centerMemberCurves.size(); i++)
{
if(centerMemberCurves[i] != NULL)
{
centerMemberCurves[i]->detach();
delete centerMemberCurves[i];
}
}
centerCurves.clear();
centers = state->getCenters();
basisColors.clear();
basisColors.resize(centers->size());
centerCurves.resize(centers->size());
centerMemberCurves.resize(centers->size());
QVector<QPointF> center(1);
int r, g, b;
for(int i = 0; i < centers->size(); i++)
{
center[0] = (*centers)[i].first;
r = qrand() % 256;
g = qrand() % 256;
b = qrand() % 256;
basisColors[i] = QColor(r, g, b);
centerCurves[i] = new QwtPlotCurve(QString("Centers"));
centerCurves[i]->setSamples(center);
centerCurves[i]->setRenderHint(QwtPlotCurve::RenderAntialiased, true);
centerCurves[i]->setStyle(QwtPlotCurve::NoCurve);
centerCurves[i]->setSymbol(
QwtSymbol(QwtSymbol::Ellipse, QBrush(),
QPen(basisColors[i], 2.0), QSizeF(15.0, 15.0)));
centerCurves[i]->attach(this);
centerMemberCurves[i] = new QwtPlotCurve(QString("Points in XYZ"));
centerMemberCurves[i]->setSamples((*centers)[i].second);
centerMemberCurves[i]->setRenderHint(QwtPlotCurve::RenderAntialiased, true);
centerMemberCurves[i]->setStyle(QwtPlotCurve::NoCurve);
centerMemberCurves[i]->setSymbol(
QwtSymbol(QwtSymbol::Ellipse, QBrush(),
QPen(basisColors[i]), QSizeF(8.0, 8.0)));
centerMemberCurves[i]->attach(this);
}
replot();
}
void Plot::newBases()
{
for(int i = 0; i < basisCurves.size(); i++)
{
if(basisCurves[i] != NULL)
{
basisCurves[i]->detach();
delete basisCurves[i];
}
}
bases = state->getBases();
basisCurves.resize(bases->size());
for(int i = 0; i < bases->size(); i++)
{
basisCurves[i] = new QwtPlotCurve(QString("Basis curve"));
basisCurves[i]->setSamples((*bases)[i]);
basisCurves[i]->setRenderHint(QwtPlotCurve::RenderAntialiased, true);
basisCurves[i]->setPen(QPen(basisColors[i]));
basisCurves[i]->attach(this);
}
estimated = state->getEstimated();
if(estimatedCurve != NULL)
{
estimatedCurve->detach();
delete estimatedCurve;
}
estimatedCurve = new QwtPlotCurve(QString("Estimated curve"));
estimatedCurve->setSamples(*estimated);
estimatedCurve->setRenderHint(QwtPlotCurve::RenderAntialiased, true);
estimatedCurve->setPen(QPen(QColor("black"), 2.0));
estimatedCurve->attach(this);
replot();
}
| [
"[email protected]"
]
| [
[
[
1,
148
]
]
]
|
eb8cbbd80364fd8a96f3b0312edc1ab8ee6372f3 | 6a98ab1a4800e6f169b75c17e01c2fa491989a79 | /Weapons/RapidLaserShot.h | c8b7dd2bf40ee71639b085b1eda90a4d65fdf7dd | []
| no_license | OpenEngineDK/branches-Prototype | 966eccfb9ddb0e4a3a68f8fb6a1c1a0d0314dd5c | 1364da5ca25a6eb00c829a63db8e083b2e03cc8b | refs/heads/master | 2021-01-01T05:18:26.599471 | 2008-08-13T09:52:42 | 2008-08-13T09:52:42 | 58,077,163 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,623 | h | // Rigid body rendering.
// -------------------------------------------------------------------
// Copyright (C) 2007 (See AUTHORS)
//
// This program is free software; It is covered by the GNU General
// Public License version 2 or any later version.
// See the GNU General Public License for more details (see LICENSE).
//--------------------------------------------------------------------
#ifndef _RAPID_LASER_SHOT_H_
#define _RAPID_LASER_SHOT_H_
#include "IShot.h"
#include <Renderers/IRenderNode.h>
#include <Renderers/IRenderingView.h>
#include <Scene/ISceneNode.h>
#include <Meta/OpenGL.h>
// forward declarations
namespace OpenEngine {
//namespace Geometry { class Box; }
namespace Scene { class TransformationNode; }
namespace Renderers { class IRenderNode; }
}
using namespace OpenEngine::Math;
using namespace OpenEngine::Geometry;
using namespace OpenEngine::Scene;
using namespace OpenEngine::Renderers;
using namespace std;
namespace OpenEngine {
namespace Prototype {
namespace Weapons {
class RapidLaserShot : public IShot {
private:
double lifeTime;
double decayTime;
float shotSpeed;
Vector<3,float> from;
Vector<3,float> to;
Vector<3,float> color;
public:
RapidLaserShot(Vector<3,float> from, Vector<3,float> to);
virtual ~RapidLaserShot();
virtual void Process(const float timeSinceLast);
void Apply(IRenderingView* view);
void Destroy();
};
}
} // NS Utils
} // NS OpenEngine
#endif // _DEFAULT_RIGID_BODY_RENDER_NODE_H_
| [
"[email protected]"
]
| [
[
[
1,
59
]
]
]
|
3a9801b7eb16916e3b147baf9988d2d990eceefe | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Messaging/Pop3Example/MAsyncWaiter.h | 4eaa226bf77808d72dd8690934d043722ba38e2d | []
| no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | // MAsyncWaiter.h
//
// Copyright (c) Symbian Software Ltd 2006. All rights reserved.
//
/**
@file
Contains the CMessAsyncWaiter class.
*/
#ifndef __MESS_ASYNCWAITER_H_
#define __MESS_ASYNCWAITER_H_
#include <e32base.h>
/**
CMessAsyncWaiter is a class that publicily inherits the class CActive.
CActive is core class of the active object abstraction.
It encapsulates both issuing a request to an asynchronous service provider
and handling the completed requests.
*/
class CMessAsyncWaiter : public CActive
{
public:
static CMessAsyncWaiter* NewL();
~CMessAsyncWaiter();
void StartAndWait();
TInt Result() const;
private:
CMessAsyncWaiter();
// CActive implementation
virtual void RunL();
virtual void DoCancel();
private:
TInt iError;
};
#endif // __MESS_ASYNCWAITER_H_
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
]
| [
[
[
1,
37
]
]
]
|
f52c43b9ba7b2f663140c44c085a403314b63acd | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziis/src/mod/resource/src/include/config.hh | 3b53d0fe75493425de02cc2194646626c425d495 | []
| no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,148 | hh | #ifndef ZIAFS_CONFIG_HH
# define ZIAFS_CONFIG_HH
#include <list>
#include <vector>
#include <config/tinyxml.hh>
#include "string_manager.hh"
namespace net
{
class config;
class config
{
public:
struct system
{
int nb_thread;
unsigned long poll_delay;
unsigned long expiration_delay;
std::string directory_listing;
};
struct module
{
std::string file;
std::string name;
};
struct server
{
std::list<int> id;
std::list<int> cgi_id;
int port;
unsigned int nr_bklog;
std::vector<std::string> directory_index;
std::list<std::string> modulename;
};
struct directory
{
int id;
std::string servername;
std::string docroot;
};
struct mime
{
std::string extension;
std::string type;
std::string image;
std::string cgi;
int is_cgi;
};
public:
config(const std::string &);
config();
~config();
config(char **);
bool reset();
// bool generate_config(server*, config&);
bool get_server(std::list<server*>::iterator&);
bool end_server(const std::list<server*>::iterator&);
bool get_directory(std::list<directory*>::iterator&);
bool end_directory(const std::list<directory*>::iterator&);
bool get_mimes(std::list<mime*>::iterator&);
bool end_mimes(const std::list<mime*>::iterator&);
bool get_modules(std::list<module*>::iterator&);
bool end_modules(const std::list<module*>::iterator&);
system* get_system() { return &m_system; };
private:
typedef bool (net::config::*pFunc)();
struct key
{
std::string keyword;
};
bool load_default();
bool parse();
bool parse_server();
bool parse_directory();
bool parse_mimes();
bool parse_modules();
bool parse_system();
TiXmlDocument m_xmldoc;
TiXmlNode* m_xmlnode;
std::list<server*> m_lserver;
std::list<directory*> m_ldirectory;
std::list<mime*> m_lmimes;
std::list<module*> m_lmodules;
system m_system;
};
}
#endif
| [
"zapoutix@754ce95b-6e01-0410-81d0-8774ba66fe44",
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
]
| [
[
[
1,
6
],
[
8,
90
]
],
[
[
7,
7
]
]
]
|
6b3304d34e6a3ac3aed689164761aad9ac299994 | 4ea18bdd6e29708401219df82fd2ea63fa3e3c59 | /source/Engine/CGUIStaticTTText.hpp | b303d1cdd1b3e76e8d60ecc406a036c467861218 | []
| no_license | sitc428/fyp3dgame | e4a11f027474f0eb52c711ab577034edcae86a17 | 6b06dc8a44d8e057336579c5e11c16b438720e63 | refs/heads/master | 2020-04-05T14:54:58.764314 | 2011-01-24T04:16:24 | 2011-01-24T04:16:24 | 32,114,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | hpp | #ifndef __C_GUI_STATIC_TRYETYPE_TEXT_HPP__
#define __C_GUI_STATIC_TRYETYPE_TEXT_HPP__
#include <irrlicht/irrlicht.h>
namespace irr
{
namespace gui
{
class CGUITTFont;
//class CGUIStaticTTText : public IGUIElement
class CGUIStaticTTText : public IGUIStaticText
{
public:
CGUIStaticTTText::CGUIStaticTTText(core::stringw text, CGUITTFont* font, core::rect<s32> pos, video::SColor color, IGUIEnvironment* env, IGUIElement* parent = 0, s32 id = -1);
virtual ~CGUIStaticTTText();
virtual void draw();
private:
CGUIStaticTTText();
core::stringw _text;
CGUITTFont* _font;
core::rect<s32> _pos;
video::SColor _color;
};
}
}
#endif //__C_GUI_STATIC_TRYETYPE_TEXT_HPP__ | [
"[email protected]@723dad30-d554-0410-9681-1d1d8597b35f"
]
| [
[
[
1,
31
]
]
]
|
8ce83d42f42369b5eeaab2bcb77a20ea34245933 | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /vaultscript/pawnc/include/default.inc | 4e885ef6fbd0a1444041add8366dae5c8d62589a | []
| no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 106 | inc | #include <core>
#include <console>
#include <float>
#include <string>
#include <file>
#include <time> | [
"[email protected]"
]
| [
[
[
1,
6
]
]
]
|
b4e8d59776abd7e479ff42c9ea2c50074f77008a | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/game/parent_entity.hh | f4052ec41e882dcb6b18117bf6214a0c9ba4861e | []
| no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,437 | hh | ////////////////////////////////////////////////////////////////////////////////
// Filename : parent_entity.hh
// Authors : Creteur Clement
// Last edit : 08/11/09 - 20h00
// Comment :
////////////////////////////////////////////////////////////////////////////////
#ifndef GAME_PARENT_ENTITY_HH
#define GAME_PARENT_ENTITY_HH
#include <string>
#include <list>
#include "entity.hh"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class EntParent : public Entity
{
public:
EntParent(EntityEnum parType, Entity* parParent, const std::string& parName);
~EntParent();
Entity* GetOneEntityByType(EntityEnum parType);
Entity* GetOneEntityByName(const std::string& parName);
void GetAllEntitiesByType(EntityEnum parType, std::vector<Entity*>& parAll);
void GetAllEntitiesByName(const std::string& parName, std::vector<Entity*>& parAll);
Entity* TestFirstCollision(Entity* parMover);
void TestAllCollisions(Entity* parMover, std::vector<Entity*>& parEntities);
void Update();
void PreDraw();
bool InsertInside(Entity* parEntity);
private:
std::list<Entity*> FChilds;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
]
| [
[
[
1,
43
]
]
]
|
51a3885ceae4d5dedce728f02d0300c06ac16227 | a2904986c09bd07e8c89359632e849534970c1be | /topcoder/BoxLoader.cpp | 977b9bc30a64019da86688e6c3bb7c62cc216cbc | []
| no_license | naturalself/topcoder_srms | 20bf84ac1fd959e9fbbf8b82a93113c858bf6134 | 7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5 | refs/heads/master | 2021-01-22T04:36:40.592620 | 2010-11-29T17:30:40 | 2010-11-29T17:30:40 | 444,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,010 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "BoxLoader.cpp"
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
using namespace std;
#define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i)
#define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i)
#define all(a) a.begin(), a.end()
class BoxLoader {
public:
int mostItems(int boxX, int boxY, int boxZ, int itemX, int itemY, int itemZ) {
vector<int> vi;
int mx=0;
vi.push_back(itemX);
vi.push_back(itemY);
vi.push_back(itemZ);
sort(all(vi));
do{
if(vi[0]>boxX || vi[1]>boxY || vi[2]>boxZ) continue;
mx = max(mx,(boxX/vi[0])*(boxY/vi[1])*(boxZ/vi[2]));
}while(next_permutation(all(vi)));
return mx;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 100; int Arg1 = 98; int Arg2 = 81; int Arg3 = 3; int Arg4 = 5; int Arg5 = 7; int Arg6 = 7560; verify_case(0, Arg6, mostItems(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5)); }
void test_case_1() { int Arg0 = 10; int Arg1 = 10; int Arg2 = 10; int Arg3 = 9; int Arg4 = 9; int Arg5 = 11; int Arg6 = 0; verify_case(1, Arg6, mostItems(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5)); }
void test_case_2() { int Arg0 = 201; int Arg1 = 101; int Arg2 = 301; int Arg3 = 100; int Arg4 = 30; int Arg5 = 20; int Arg6 = 100; verify_case(2, Arg6, mostItems(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5)); }
void test_case_3() { int Arg0 = 913; int Arg1 = 687; int Arg2 = 783; int Arg3 = 109; int Arg4 = 93; int Arg5 = 53; int Arg6 = 833; verify_case(3, Arg6, mostItems(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5)); }
void test_case_4() { int Arg0 = 6; int Arg1 = 5; int Arg2 = 4; int Arg3 = 3; int Arg4 = 2; int Arg5 = 1; int Arg6 = 20; verify_case(4, Arg6, mostItems(Arg0, Arg1, Arg2, Arg3, Arg4, Arg5)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
BoxLoader ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"shin@CF-7AUJ41TT52JO.(none)"
]
| [
[
[
1,
73
]
]
]
|
c16a0c14d5f516c9a1ad74a3981058504b1e8ea6 | 9ad9345e116ead00be7b3bd147a0f43144a2e402 | /SeedMinerIntegratedSolution/WAHArray/AlgoUtils.h | f432bb47b7c6fb1e6c11d86cbe484004f34fa959 | []
| no_license | asankaf/scalable-data-mining-framework | e46999670a2317ee8d7814a4bd21f62d8f9f5c8f | 811fddd97f52a203fdacd14c5753c3923d3a6498 | refs/heads/master | 2020-04-02T08:14:39.589079 | 2010-07-18T16:44:56 | 2010-07-18T16:44:56 | 33,870,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | h | #pragma once
#include "BitStreamHolder.h"
#include "boost\dynamic_bitset\dynamic_bitset.hpp"
#include <vector>
#include <map>
#include "EncodedAttributeInfo.h"
namespace Algorithm{
class AlgoUtils
{
public:
AlgoUtils(void);
~AlgoUtils(void);
BitStreamHolder * FindPattern(dynamic_bitset<> & _pattern,vector<BitStreamHolder *> & _container);
BitStreamInfo * FindPattern(dynamic_bitset<> & _pattern,vector<BitStreamInfo *> & _container);
dynamic_bitset<> FindPattern(dynamic_bitset<> & _pattern,vector<dynamic_bitset<>> & _container);
BitStreamHolder * WrapWithHolder(BitStreamInfo * _stream,int _attribute_id,int _bit_map_id);
map<int,dynamic_bitset<>> GetUniqueBitmaps(EncodedAttributeInfo * _attribute,vector<BitStreamHolder *> & _bitmaps,vector<dynamic_bitset<>> & _unique_patterns,map<int,vector<int>> & _index_bitmap_map);
};
} | [
"buddhi.1986@c7f6ba40-6498-11de-987a-95e5a5a5d5f1"
]
| [
[
[
1,
21
]
]
]
|
44cd6ee1d13aae64d6c86b3bf1cc7a7f00ec3fce | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/Include/md_method.h | 80bae8aac3b6f4101a3023e9f329b24c30d8076f | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58,126 | h | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#pragma once
#ifndef __MD_METHOD_H
#define __MD_METHOD_H
#include "md_vector.h"
#include "md_share2.h"
#include "md_share3.h"
#include "md_share4.h"
#include "md_data.h"
#ifdef __MD_METHOD_CPP
#define DllImportExport __declspec(dllexport)
#elif !defined(DEVLIB)
#define DllImportExport __declspec(dllimport)
#else
#define DllImportExport
#endif
//---------------------------------------------------------------------------
// local forward's
class MBaseMethodImpl;
class MSurgeUnitDefBase;
class MReactionBlk;
class MMethodUtility;
class MProbalPCtrl;
class MUnitDefBase;
class MTagIO;
// remote forward's
class MdlNode;
class PkDataUnion;
class DataDefnBlk;
class DataChangeBlk;
class ValidateDataBlk;
class CSetDatumsData;
class NodeDrawEntry;
class TagObjClass;
class CReactionBase;
class CFilesUsedArray;
class CClosureInfoArray;
class CPropagateNetInfoCtrl;
class SpModel;
class CEnvironHXBase;
class CVLEBase;
class CFT_Flash;
class CFT_Condenser;
class CFT_Mixer;
class CMacroMdl;
class CMacroMdlBase;
class CRqdPressCtrl;
class CNodeTagIOItem;
class CNodeTagIOList;
//---------------------------------------------------------------------------
/* Class MInOutDefStruct : Used to Setup definition of IO (input/output) ports to a model.
Defined as a static array of MInOutDefStruct. The last entry must be NULL to indicate end of array.
NOTE: The IO Port name must be unique and valid tag (no illegal characters or spaces in name).
Once used in projects, this name CAN NOT be changed as it forms part of tags for defining
model connections, otherwise projects will not load! (If desparate an edit in some of
the tables in the scd_mdls.mdb database can overcome the problem.)*/
//List of possible connection directions
const DWORD MIO_In = 0x00000001; // Input only
const DWORD MIO_Out = 0x00000002; // Output only
const DWORD MIO_InOut = MIO_In|MIO_Out; // Input or Output
//List of possible connection types
const DWORD MIO_Material = 0x00000010; // Pipe link
const DWORD MIO_Control = 0x00000020; // Control link
const DWORD MIO_Electrical = 0x00000040; // Electrical link
//List of other connection port options
const DWORD MIO_Transfer = 0x00000100; // Only allow pipes of type transfer link to be connected
const DWORD MIO_PipeEntry = 0x00000200; // Marks the IO point an an entry to or exit from a pipe (eg at a tank)
const DWORD MIO_PipeJoin = 0x00000400; // Marks the IO point an an entry to or exit from a 'join' (eg at a tee-piece)
const DWORD MIO_ApertureHoriz = 0x00000800; // Pipe is connected "horizontal" (eg base of tank)
const long MCN_Join = 0x00100000; // Pipe connected directly to others and balance is enforced (default)
const long MCN_Open = 0x00200000; // Pipe connected to a tank or similar which can accumulate material
const long MCN_Closed = 0x00400000; // No flow permitted to or from this IO pt
const long MCN_IOMask = 0x0000ffff; // Mask for container connection Ids
// Tear Type
enum MTearTypes { MTT_NoTear = 0, MTT_SystemTear = 1, MTT_ManualTear = 2, MTT_Break = 3 };
// Tear Priority
enum MTearPriorities { MTP_First = 0, MTP_Normal = 1, MTP_Last = 2 };
struct DllImportExport MInOutDefStruct
{
LPTSTR m_sDesc; //connection port description (eg "Steam Vent"). Can be changed
LPTSTR m_sName; //unique connection port Name. NOTE: This forms part of tag for pipe connections. (eg "Steam")
long m_lId; //unique port ID
long m_nRqd; //minimum number of connections required to this IO port
long m_nMax; //maximum number of connections allowed to this IO port
long m_lCnId; //used to group a number different port IDs (eg shell and tube sides of heatexchanger)
float m_dFracHgt; //default connection height as a fraction between 0.0f and 1.0f (only relevant in dynamic to models with surge)
DWORD m_dwOptions; //IO connection port options and type. MIO_xxx Multiple flags can be set using | (eg MIO_In|MIO_Material)
LPTSTR m_AltNames[5]; // an array of alternate names (Optional - for upgrade purposes)
};
//---------------------------------------------------------------------------
// Method Options
const DWORD MO_ShowIOs = 0x00000004;
const DWORD MO_ShowIOOpts = 0x00000008;
const DWORD MO_ShowContents = 0x00000010;
//---------------------------------------------------------------------------
enum MStatesToSet { MSS_ZeroFlows=1 , MSS_Empty=2, MSS_Preset=3, MSS_PBInitialise=5, MSS_DynStatsRunInit=6, MMS_EmptySpillTargets=7 };
class MUtilArray : public CArray <MMethodUtility*, MMethodUtility*> {};
//---------------------------------------------------------------------------
class DllImportExport MBaseMethodCommon : public MBaseDataCommon, public MSubConstructBase
{
public:
MBaseMethodCommon(MUnitDefBase *pUnitDef, TaggedObject * pNd);
public:
MUnitDefBase *m_pUnitDef;
MBaseMethodImpl *m_pImpl;
MdlNode *m_pNd;
MUtilArray m_Utils;
MInOutDefStruct *m_pIODefs;
long m_nJoins;
};
//---------------------------------------------------------------------------
class DllImportExport MBaseMethodCommonRef
{
public:
MBaseMethodCommonRef(MBaseMethodCommon *pCom) :
//m_pImpl(pCom->m_pImpl),
m_pCommon(pCom),
m_pNd(pCom->m_pNd)
//,
//m_pDDB(pCom->m_pDDB),
//m_pDCB(pCom->m_pDCB),
//m_pVDB(pCom->m_pVDB)
{
}
public:
MBaseMethodCommon * m_pCommon;
//MBaseMethodImpl * &m_pImpl;
MdlNode * &m_pNd;
//DataDefnBlk * &m_pDDB;
//DataChangeBlk * &m_pDCB;
//ValidateDataBlk * &m_pVDB;
};
//===========================================================================
/* Class MJoin: Helper class for managing a join. A join is a number of streams
from one or more port Id connections.*/
class DllImportExport MJoin
{
public:
MJoin (MdlNode*p, long iJoin) { m_pNd=p; m_iJoin=iJoin; };
MJoin (const MJoin & J) { m_pNd=J.m_pNd; m_iJoin=J.m_iJoin; };
// Properties
double getP();
void putP(double P);
__declspec(property(get=getP,put=putP)) double P;
// Operators
double GetProbalPIn(MProbalPCtrl *pPC=NULL);
void SetProbalP(MProbalPCtrl *pPC=NULL);
void SetProbalP(double P, bool DoInputs=false, bool DoOutputs=true);
void EvalProbalP(MProbalPCtrl *pPC=NULL, SpModel * pVec=NULL);
protected:
MdlNode * m_pNd;
long m_iJoin;
};
//---------------------------------------------------------------------------
/* Class MJoins: Array of Join classes.*/
class DllImportExport MJoins : public MBaseMethodCommonRef
{
public:
MJoins(MBaseMethodCommon *pCom) : MBaseMethodCommonRef(pCom) {};
// Properties
long getCount();
void putCount(long N);
__declspec(property(get=getCount,put=putCount)) long Count;
MJoin operator[](int iJoin) { return MJoin(m_pNd, iJoin); }
private:
};
//===========================================================================
class CPressBlk;
class DllImportExport MPressureBlk
{
public:
MPressureBlk(CPressBlk*p) { m_pPB=p; };
MPressureBlk(const MPressureBlk & PB) { m_pPB=PB.m_pPB; };
double getPEst();
__declspec(property(get=getPEst)) double PEst;
protected:
CPressBlk * m_pPB;
};
//---------------------------------------------------------------------------
class DllImportExport MFlowBlk
{
public:
MFlowBlk(MdlNode*p, long IONo) { m_pNd=p; m_iIONo=IONo; };
MFlowBlk(const MFlowBlk & FB) { m_pNd=FB.m_pNd; m_iIONo=FB.m_iIONo; };
double getQm();
double getQmEst();
double getDPb();
void putDPb(double DP);
void SetDPb(double DP, double dDP);
double getDPq();
void putDPq(double DP);
void SetDPq(double DP, double dDP);
double getDPz();
void putDPz(double DP);
void SetDPz(double DP, double dDP);
void SetQmFree();
void SetXferMode();
void SetXferCapacity(double QmCap);
void SetQmReqd(double QmReqd, bool IsDegFree=true, double MaxNode=dNAN, double MaxFlng=dNAN);
void SetDerivsBad(bool On=true);
void SetFunctOfPress(bool On=true);
double MeanPress();
double MeanFlngPress();
double MeanNodePress();
double MeanFBPress();
double getVelocity();
double getRegulation();
void putRegulation(double A);
int QmSign();
double QmMeas(double Scl=1.0);
double QvMeas(double Scl=1.0);
double VelMeas(double Scl=1.0);
double DQmMeas(double Scl=1.0);
static double RangeFlow(double Qm, double LoLimit);
double SetQmMeasRange(double Rho, double LoQm);
double SetQvMeasRange(double Rho, double LoVol);
double SetVelMeasRange(double Rho, double Area, double LoVel);
MPressureBlk getNodePBlk();
MPressureBlk getFlngPBlk();
__declspec(property(get=getQm)) double Qm;
__declspec(property(get=getQmEst)) double QmEst;
__declspec(property(get=getDPb,put=putDPb)) double DPb;
__declspec(property(get=getDPq,put=putDPq)) double DPq;
__declspec(property(get=getVelocity)) double Velocity;
__declspec(property(get=getRegulation,put=putRegulation)) double Regulation;
__declspec(property(get=getNodePB)) MPressureBlk NodePBlk;
__declspec(property(get=getFlngPB)) MPressureBlk FlngPBlk;
protected:
MdlNode *m_pNd;
long m_iIONo;
};
//---------------------------------------------------------------------------
class DllImportExport MFlow
{
public:
MFlow (MdlNode*p, long IONo) { m_pNd=p; m_iIONo=IONo; };
MFlow (const MFlow & F) { m_pNd=F.m_pNd; m_iIONo=F.m_iIONo; };
bool getValid() { return m_pNd && m_iIONo>=0; };
long getId();
long getIdRmt();
bool getIsFlwIn();
bool getIsFlwOut();
double getEstFlwIn();
double getEstFlwOut();
double getFlwIn();
double getFlwOut();
MStream getStream();
MFlowBlk getFlowBlk() { return MFlowBlk(m_pNd, m_iIONo); };
double getAbsHeight();
void putAbsHeight(double H);
double getRelHeight();
void putRelHeight(double H);
double getDatum();
double getIOPJoin();
double getIOPFlange();
bool getIsMakeUpReqd();
bool getIsMakeUpReqdLcl();
bool getIsMakeUpAvail();
double getMakeUpReqd();
void putMakeUpReqd(double Rqd);
double getMakeUpReqdLcl();
void putMakeUpReqdLcl(double Rqd);
double getMakeUpAvail();
void putMakeUpAvail(double Avl);
MTearTypes getTearTypeRequired();
void putTearTypeRequired(MTearTypes Type);
MTearPriorities getTearPriority();
void putTearPriority(MTearPriorities Priority);
__declspec(property(get=getValid)) bool Valid;
__declspec(property(get=getId)) long Id;
__declspec(property(get=getIdRmt)) long IdRmt;
__declspec(property(get=getIsFlwIn)) bool IsFlwIn;
__declspec(property(get=getIsFlwOut)) bool IsFlwOut;
__declspec(property(get=getEstFlwIn)) double EstFlwIn;
__declspec(property(get=getEstFlwOut)) double EstFlwOut;
__declspec(property(get=getFlwIn)) double FlwIn;
__declspec(property(get=getFlwOut)) double FlwOut;
__declspec(property(get=getFlowBlk)) MFlowBlk FlowBlk;
__declspec(property(get=getStream)) MStream Stream;
__declspec(property(get=getAbsHeight,put=putAbsHeight)) double AbsHeight;
__declspec(property(get=getRelHeight,put=putRelHeight)) double RelHeight;
__declspec(property(get=getDatum)) double Datum;
__declspec(property(get=getIOPJoin)) double IOPJoin;
__declspec(property(get=getIOPFlange)) double IOPFlange;
__declspec(property(get=getIsMakeUpReqd)) bool IsMakeUpReqd;
__declspec(property(get=getIsMakeUpReqdLcl)) bool IsMakeUpReqdLcl;
__declspec(property(get=getIsMakeUpAvail)) bool IsMakeUpAvail;
__declspec(property(get=getMakeUpReqd,put=putMakeUpReqd)) double MakeUpReqd;
__declspec(property(get=getMakeUpReqdLcl,put=putMakeUpReqdLcl)) double MakeUpReqdLcl;
__declspec(property(get=getMakeUpAvail,put=putMakeUpAvail)) double MakeUpAvail;
__declspec(property(get=getTearTypeRequired,put=putTearTypeRequired)) MTearTypes TearTypeRequired;
__declspec(property(get=getTearPriority,put=putTearPriority)) MTearPriorities TearPriority;
//// Methods
void SetOpen(long iJoinId, bool Damped=false);
void SetClosed(long iJoinId);
void SetJoin(long iJoinId);
void SetP(double P);
void SetP(double P, double SLDensity, double Head);
protected:
MdlNode *m_pNd;
long m_iIONo;
};
//---------------------------------------------------------------------------
//class DllImportExport MSurgeIF : public MBaseMethodCommonRef
// {
// friend class BlackBoxBase;
// friend class CBBBase;
// public:
// MSurgeIF (MBaseMethodCommon *pCom) : MBaseMethodCommonRef(pCom) { m_nSrg=0; m_pSDD=NULL; };
// long getCount();
// void putCount(long n);
// double getHeight(long iSurge);
// void putHeight(long iSurge, double H);
// double getAbsHeight(long iSurge, long iIO);
// void putAbsHeight(long iSurge, long iIO, double H);
// double getRelHeight(long iSurge, long iIO);
// void putRelHeight(long iSurge, long iIO, double H);
// __declspec(property(get=getCount,put=putCount)) long Count;
// __declspec(property(get=getHeight,put=putHeight)) double Height[/*iSurge*/];
// __declspec(property(get=getAbsHeight,put=putAbsHeight)) double AbsHeight[/*iSurge*/][/*iIO*/];
// __declspec(property(get=getRelHeight,put=putRelHeight)) double RelHeight[/*iSurge*/][/*iIO*/];
// private:
// CSetDatumsData * m_pSDD;
// long m_nSrg;
// } Surge;
//---------------------------------------------------------------------------
/* Class MFlowIOs: Helper class for accessing streams connected to input and output connections (ie ports).
There may be zero, one or more streams connected to a given port Id. A stream connected to a port Id may
be an input or output (different streams for the same port Id could be input or output).
*/
class DllImportExport MFlowIOs : public MBaseMethodCommonRef
{
public:
MFlowIOs (MBaseMethodCommon *pCom) : MBaseMethodCommonRef(pCom) {};
// Return number of connected streams for the specified Port Id (-1 for all)
long getCount(long Id=-1);
// Return index of first connected stream for the specified Port Id (-1 for all)
long getFirst(long Id=-1);
// Return index of next connected stream after the specified index for the specified Port Id (-1 for all)
long getNext(long CurIndex, long Id=-1);
// Return index of first input connected stream for the specified Port Id (-1 for all)
long getFirst_In(long Id=-1);
// Return index of next input connected stream after the specified index for the specified Port Id (-1 for all)
long getNext_In(long CurIndex, long Id=-1);
// Return index of first output connected stream for the specified Port Id (-1 for all)
long getFirst_Out(long Id=-1);
// Return index of next output connected stream after the specified index for the specified Port Id (-1 for all)
long getNext_Out(long CurIndex, long Id=-1);
// Return total mass flow for the stream of the specified index
MFlow operator[](int Index) { return MFlow(m_pNd, Index); }
// Sum of all connected streams, filtered by the specified phases, to the specified Port Id (-1 for all) into Cd.
// MStream will be at min P of all streams. Return total mass flow.
double AddMixtureIn_Id(MStream & Cd, long Id=-1, DWORD PhaseM=MP_All);
public:
__declspec(property(get=getCount)) long Count[/*Id*/];
__declspec(property(get=getFirst)) long First[/*Id*/];
__declspec(property(get=getFirst_In)) long First_In[/*Id*/];
__declspec(property(get=getNext_In)) long Next_In[/*CurIndex*/][/*Id*/];
__declspec(property(get=getFirst_Out)) long First_Out[/*Id*/];
__declspec(property(get=getNext_Out)) long Next_Out[/*CurIndex*/][/*Id*/];
private:
//void CheckMIOStreams();
};
//===========================================================================
// Control IO Interface
class DllImportExport MCtrlIOs : public MBaseMethodCommonRef
{
public:
MCtrlIOs(MBaseMethodCommon *pCom) : MBaseMethodCommonRef(pCom) {};
long getNoCtrlIOs();
__declspec(property(get=getNoCtrlIOs)) long NoCtrlIOs;
};
//===========================================================================
/* Class MTagIO: Helper class for geting or setting external tags.
This can be with once off get and set commands; or through a subscription
list where tags are continuously updated.
*/
class DllImportExport MTagIOItem
{
protected:
MTagIOItem(MTagIO & TagIO, bool DoAllocate);// cannot instantiate standalone
public:
virtual ~MTagIOItem();
public:
MTagIOResult CheckTag();
long getSubsIndex();
LPCSTR getTag();
void putTag(LPCSTR Tag);
bool getNumDataType();
bool getIntDataType();
bool getFloatDataType();
bool getStrngDataType();
short getDataType();
MD_Flags getIOFlags();
MCnv getCnv();
//return true if tag is valid (Tag Exists & CnvTxt is acceptable)
bool getIsValid();
//return value IO tag
long getLong();
//set value of IO tag
void putLong(long Value);
//return value in SI units of IO tag
double getDoubleSI();
//set value SI units of IO tag
void putDoubleSI(double Value);
//return value in SI units of IO tag
double getDoubleCnv(LPCSTR Cnv=NULL);
//set value SI units of IO tag
void putDoubleCnv(double Value, LPCSTR Cnv=NULL);
//return value IO tag
LPCSTR getString();
//set value of IO tag
void putString(LPCSTR Value);
//return conversion index of IO tag
short getCnvIndex();
//return conversion text of IO tag
LPCSTR getCnvText();
//return conversion index of IO tag
long getUserHandle();
//return conversion text of IO tag
void putUserHandle(long Handle);
// return the previous result;
MTagIOResult getResult();
__declspec(property(get=getSubsIndex)) long SubsIndex;
__declspec(property(get=getNumDataType)) bool NumDataType;
__declspec(property(get=getIntDataType)) bool IntDataType;
__declspec(property(get=getFloatDataType)) bool FloatDataType;
__declspec(property(get=getStrngDataType)) bool StrngDataType;
__declspec(property(get=getIsParam)) bool IsParam;
__declspec(property(get=getDataType)) short DataType;
__declspec(property(get=getFlags)) MD_Flags Flags;
__declspec(property(get=getCnv)) MCnv Cnv;
__declspec(property(get=getTag,put=putTag)) LPCSTR Tag;
__declspec(property(get=getLong,put=putLong)) long Long;
__declspec(property(get=getDoubleSI,put=putDoubleSI)) double DoubleSI;
__declspec(property(get=getDoubleCnv,put=putDoubleCnv)) double DoubleCnv[];
__declspec(property(get=getString,put=putString)) LPCSTR String;
__declspec(property(get=getCnvIndex)) short CnvIndex;
__declspec(property(get=getCnvText)) LPCSTR CnvText;
__declspec(property(get=getUserHandle,put=putUserHandle)) long UserHandle;
__declspec(property(get=getIOFlags)) MD_Flags IOFlags;
__declspec(property(get=getResult)) MTagIOResult Result;
// convert a ResultCode into a String
static LPCSTR ResultString(MTagIOResult Res);
public:
MTagIO * m_pTagIO;
CNodeTagIOItem * m_pItem;
bool m_bOwnsItem;
MTagIOResult m_PrevResult;
};
//===========================================================================
class DllImportExport MTagIODirect : public MTagIOItem
{
public:
MTagIODirect(MTagIO & TagIO, LPCTSTR ReqdTag=NULL);
virtual ~MTagIODirect();
MTagIOResult ReadValue(bool LogTheError=true);
MTagIOResult WriteValue(bool LogTheError=true);
};
//===========================================================================
class DllImportExport MTagIOSubscription : public MTagIOItem
{
friend class MTagIO;
public:
MTagIOSubscription(MTagIO & TagIO);
virtual ~MTagIOSubscription();
public:
long Configure(long UserHandle, LPCSTR ItemTag, LPCSTR Name, long Options);
//return true if tag is valid and active
bool getIsActive();
__declspec(property(get=getIsActive)) bool IsActive;
//return true IO tag is a Get
bool getIsGet();
//return true IO tag is a Set
bool getIsSet();
//return true IO tag is a Parameter
bool getIsParm();
__declspec(property(get=getIsGet)) bool IsGet;
__declspec(property(get=getIsSet)) bool IsSet;
__declspec(property(get=getIsParm)) bool IsParm;
};
class DllImportExport MTagIO : public MBaseMethodCommonRef
{
friend class MTagIOItem;
friend class MTagIOSubscription;
public:
MTagIO(MBaseMethodCommon *pCom) : MBaseMethodCommonRef(pCom) {};
static CString FormatAsTagOnly(const CString & Tag);
static CString FormatAsTagAndCnv(const CString & Tag);
static LPCSTR ResultString(MTagIOResult Res);
//Enable and activate TagIO subscription
void Open();
//Disable and stop TagIO subscription
void Close();
//return count of IO tags
long getCount();
//sets/return Active state of IO tags
bool getActive();
//return count of IO tags
void putActive(bool On);
// must used in ValidateDataFields - returns false when TagIOValidation must NOT occur
bool ValidateReqd();
// must used to bracket Config's etc
bool StartValidateDataFields();
bool EndValidateDataFields();
__declspec(property(get=getCount)) long Count;
__declspec(property(get=getActive,put=putActive)) bool Active;
protected:
void Add(MTagIOSubscription * pItem);
void Remove(MTagIOSubscription * pItem);
void RemoveAll();
};
//===========================================================================
class DllImportExport MClosureInfo
{
public:
MClosureInfo(CClosureInfoArray & CIA, MVector & RefMdl);
bool DoFlows();
bool DoContent();
//int JoinID();
void AddHeatFlwIn(int Join, double HfFlow, double HsFlow);
void AddHeatFlwOut(int Join, double HfFlow, double HsFlow);
void AddPowerIn(int Join, double PowerIn);
void AddMassFlwIn(int Join, MVector & MassFlow);
void AddMassFlwOut(int Join, MVector & MassFlow);
void AddContentHeat(int Join, double Heat);
void AddContentMass(int Join, MVector & Mass);
protected:
CClosureInfoArray & m_CIA;
};
//===========================================================================
/* Class MBaseMethod: Base method class from which custom user unit models are derived.*/
class DllImportExport MBaseMethod : public MBaseMethodCommon
{
friend class BlackBoxBase;
friend class CBBBase;
public:
MBaseMethod(MUnitDefBase * pUnitDef, TaggedObject * pNd); //constructor
virtual ~MBaseMethod(); //destructor
void Init(MdlNode * pNd); //Basic initialisation
virtual void Init() {}; //initialisation, used to setup UnitDef
virtual void BuildDataFields() = 0; // pure virtual method for defining data fields
virtual bool ExchangeDataFields() { return false; }; // virtual method for manipulating data
virtual bool ValidateDataFields() { return true; }; // virtual method for validating data
//interface (used by Init):
void SetIODefinition(MInOutDefStruct * pDefs);
void RegisterFlashTrainNode(int IOId, bool fModel, const type_info * pNdVarTypeId);
//interface (used by all):
public://data members and helper classes
CString m_sErrorMsg;
MLog Log;
MDebug Dbg;
MDataDefn DD;
MDataChange DX;
MDataValidate DV;
MJoins Joins;
MFlowIOs FlwIOs;
MCtrlIOs CtrlIOs;
MTagIO TagIO;
private:
long m_lJoinMask;
public://--- Properties ---------
//Model tag
LPCTSTR getTag();
//Model class ID
LPCTSTR getClassId();
//Network solver modes
bool getIsNetProbal();
bool getIsNetDynamic();
//EvalProduct solve Methods
bool getIsSolveDirect();
bool getIsSolveInline();
bool getIsSolveBuffered();
//Solver time in seconds from 1970
double getTime();
//Iteration time increment in seconds
double getDeltaTime();
//Joinmask Used in EvalProducts
long getJoinMask();
//Pause solver (go to Idle mode) at end of iteration
void SetIdleRequired(char* pNote = NULL);
//Stop solver at end of iteration
void SetStopRequired(char* pNote = NULL);
public://--- Runtime Virtual methods ---------
virtual bool PreStartCheck() { m_sErrorMsg = ""; return true; }; // to check immediatly before a solve or run
virtual void PostConnect(long IONo) {};
virtual void PreDisConnect(long IONo) {};
virtual void SetDatums() {};
virtual void SetSizes() {};
virtual void InitialiseSolution() {}; // each
virtual bool PropagateNetInfo(CPropagateNetInfoCtrl & Ctrl, long IONo);
virtual void StartSolution() {}; // each Start of run
virtual void StartStep() {}; // each Iteration - At Start of Step
virtual bool ConfigureJoins(); // each Iteration - Configure IO Connections
virtual void EvalMakeUpReqd() {};
virtual void EvalMakeUpAvail() {};
virtual bool EvalJoinPressures() { return false; }; // each Dyn Iteration - Setup Pressures at input to FlwIO's
virtual bool EvalJoinFlows(long JoinNo) { return false; }; // each Dyn Iteration - Set up Flow relationships
virtual bool EvalFlowEquations(eScdFlwEqnTasks Task, long IONo, long FE, long LnkNo) { return false; }; // iterations with each Dyn Iteration - Converge Pressure-Flow relationships
virtual void EvalProducts() {}; // each Iteration
virtual void EvalIntegral(double StepSize) {}; // each Dyn Iteration - Advance the model StepSize
virtual void EvalDiscrete() {}; // each Dyn Iteration -
virtual void EvalCtrlInitialise(eScdCtrlTasks Tasks=CO_All) {}; // each Start of Run
virtual void EvalCtrlActions(eScdCtrlTasks Tasks=CO_All) {}; // each Iteration - To apply result of control
virtual void EvalCtrlStrategy(eScdCtrlTasks Tasks=CO_All) {}; // each Iteration - To calculate required control actions
virtual void EvalCtrlTerminate(eScdCtrlTasks Tasks=CO_All) {}; // each End of Run
virtual void EvalStatistics(eScdCtrlTasks Tasks=CO_All) {}; // each Iteration End to calculate Stats relevant to model
virtual void EvalPowerAvailable() {};
virtual void EvalPowerRequired() {};
virtual void EvalState() {}; // each Dyn Iteration - Finalise the state of the model
virtual void ClosureInfo(MClosureInfo & CI) {};
virtual void SetState(MStatesToSet SS) {}; // on demand to initialise the state
virtual bool GetModelAction(CMdlActionArray & Acts) { return false; };
virtual bool SetModelAction(CMdlAction & Act) { return false; };
virtual bool GetModelGraphic(CMdlGraphicArray & Grfs) { return false; };
virtual bool OperateModelGraphic(CMdlGraphicWnd & Wnd, CMdlGraphic & Grf) { return false; };
public:// MacroModels (eg Flash Train)
virtual void MacroMdlEvaluate(eScdMacroMdlEvals Eval) {};
virtual bool MacroMdlValidNd(int iIONo) { return true; };
virtual void MacroMdlAddNd(int iIONo) {};
virtual void MacroMdlRemoveNd(int iIONo) {};
virtual CMacroMdlBase* MacroMdlActivate() { return NULL; };
virtual void MacroMdlDeactivate() {};
public:// Utilities
void MakeUpNodeTransferAvail(int JoinId); // Transfers Makeup Availabilities to Destinations
void MakeUpNodeTransferReqd(int JoinId); // Transfers Makeup Requirements to Source
bool getDbgBrk();
//Model tag
__declspec(property(get=getTag)) LPCTSTR Tag;
//Model class ID
__declspec(property(get=getClassId)) LPCTSTR ClassId;
//Network solver modes
__declspec(property(get=getIsNetProbal)) bool IsNetProbal;
__declspec(property(get=getIsNetDynamic)) bool IsNetDynamic;
//EvalProduct solve Methods
__declspec(property(get=getIsSolveDirect)) bool IsSolveDirect;
__declspec(property(get=getIsSolveInline)) bool IsSolveInline;
__declspec(property(get=getIsSolveBuffered)) bool IsSolveBuffered;
//Solver time in seconds from 1970
__declspec(property(get=getTime)) double Time;
//Iteration time increment in seconds
__declspec(property(get=getDeltaTime)) double DeltaTime;
__declspec(property(get=getDbgBrk)) bool DbgBrk;
__declspec(property(get=getJoinMask)) long JoinMask;
};
//---------------------------------------------------------------------------
/*class DllImportExport MBaseMethodEx : public MBaseMethod
{
// This class is designed to be an 'Extended' vesion of MBaseMethod which would
// 'open up' more complex capabilities'
};*/
//===========================================================================
//
//===========================================================================
//Model solve mode options... (any combination; but at least ONE of the following)
const DWORD MSolveMode_Probal = 0x00000001; //is probal model
const DWORD MSolveMode_DynamicFlow = 0x00000002; //is dynamic model (flow / material transfer)
const DWORD MSolveMode_DynamicFull = 0x00000004; //is dynamic model (pressure / full hydrolic)
//const DWORD MSolveMode_Electrical = 0x00000008; //is dynamic model (electrical)
const DWORD MSolveMode_All = MSolveMode_Probal|MSolveMode_DynamicFlow|MSolveMode_DynamicFull;
//Model group option... (should use ONE of the following)
const DWORD MGroup_General = 0x00000001; //general group
const DWORD MGroup_Energy = 0x00000002; //energy transfer group
const DWORD MGroup_Separation = 0x00000004; //mass separation group
const DWORD MGroup_PSD = 0x00000008; //size distribution group
const DWORD MGroup_Transfer = 0x00000010; //mass transfer group
const DWORD MGroup_Alumina = 0x00000020; //alumina group
const DWORD MGroup_Electrical = 0x00000040; //Power Reticulation/Elect/Pneumatic
//Model Licensing add-on options... (any combination; none or any number of the following)
const DWORD MLicense_Standard = 0x00000001; //Part of standard models (eg tank, tie, etc)
const DWORD MLicense_BlackBox = 0x00000002; //"BlackBox" models developed using SMDK
const DWORD MLicense_HeatExchange = 0x00000004; //Heat Exchange models (eg flash-tank, shell&tube, etc)
const DWORD MLicense_PowerPlant = 0x00000008; //Power Plant models (eg turbine, boiler, etc)
const DWORD MLicense_PSD = 0x00000010; //Particle size-distribution/communition models (eg screen, crusher, etc)
const DWORD MLicense_Alumina = 0x00000020; //Alumina models (eg Precipitator, etc)
const DWORD MLicense_Electrical = 0x00000040; //Electrical/Power Distribution models (eg transformer, switch, etc)
const DWORD MLicense_User = 0x00000080; //custom/client models
//---------------------------------------------------------------------------
/*Class MUnitDefBase: Helper class for class definition for the unit "class factory".
DEFINE_TRANSFER_UNIT(Object, Class, DLL) or DEFINE_SURGE_UNIT(Object, Class, DLL) are
used to add your SMDK unit class to the system. This definition class requires that you
provide the override for the virtual function GetOptions(). This is used to set options
by overriding defaults. Defaults are:
DefaultTag: "X" or "S" (Transfer or Surge)
Drawing: a box
TreeDescription: "User:Class"
Description: ""
ModelSolveMode: MSolveMode_Probal
ModelGroup: MGroup_General
ModelLicense: MLicense_Standard
*/
class DllImportExport MUnitDefBase : public MSubConstructBaseDef
{
friend class CBBBase;
friend class CBBSurge;
friend class CBBTransfer;
friend class MUnitDefBaseEx;
public:
MUnitDefBase(bool WithDevelopementChecks);
virtual ~MUnitDefBase();
virtual MSubConstructBase * Construct(TaggedObject * pNd) = 0;
public:
// Model Definition Construct. Use this to set the model options
virtual void GetOptions() = 0;
//return the full class name, DLL*Class (eg "Demo*Reactor")
LPCSTR ClassName() { return (LPCSTR)m_sClassName; };
public:
// The default prefix characters when a tag is generated eg "TG" will produce TG_1, TG_2, TG_3
// AddUsrPrefix defines whether all fields are prefixed by 'Usr.' or not
void SetDefaultTag(LPCTSTR DefTag, bool AddUsrPrefix=false);
// Set graphics group of symbols (eg "Tank", "HeatTransfer") and provide a default drawing symbol
void SetDrawing(LPCTSTR DrwGroup, double Drawing[]);
// A Description in the form of TreeNode:[TreeNode:...]UnitDescription eg. "Process:Unit:Tank"
void SetTreeDescription(LPCTSTR TreeDesc);
// A Long Description
void SetDescription(LPCTSTR Desc);
// Set Model Solve Mode that this Unit model supports (One or more of the MSolveMode_xxx flags)
void SetModelSolveMode(DWORD Mode);
// Set Model Groups (One of the MGroup_xxx flags)
void SetModelGroup(DWORD Group);
// Set License Options... (should use ONE of the following)
void SetModelLicense(DWORD License);
protected:
CString m_sClassName; // Class name
TagObjClass * m_pClassDef;
NodeDrawEntry * m_pDrawEntry;
CString m_sDllName;
private:
bool m_WithDevelopementChecks;
bool m_AddUsrPrefix;
//void DevelopementChecksOn();
//void DevelopementChecksOff();
};
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
//Class MTransferUnitDefBase: Unit Definition base class for Transfer unit models.
class DllImportExport MTransferUnitDefBase : public MUnitDefBase
{
public:
MTransferUnitDefBase(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR ShortDesc, LPCTSTR DLL, bool WithDevelopementChecks);
virtual ~MTransferUnitDefBase() {};
};
//---------------------------------------------------------------------------
#ifdef SMDK_Debug
#define DEVCHECKSON 1
#else
#define DEVCHECKSON 0
#endif
//---------------------------------------------------------------------------
/*Macro for adding a SMDK transfer unit to the system. Chose the 'Class' and 'DLL'
names carefully as once these are released and used in projects they cannot easily
be changed, if they are changed old projects will not load (unless the scd_models.mdb
is carefully edited to make the equivalent changes!)
The parameters are:
Obj : The C++ class object name (ie your class as declared in the source code)
(eg SimpleReactor)
Class : A short string name for your class. Must follow valid tag naming rules
(ie no spaces, etc) (eg "Reactor")
DLL : A short string name for the group this belongs to. This is usually the DLL group and is
as a #define DLL_GroupName in a shared header file such as stdafx.h
(eg #define DLL_GroupName "DemoUsr")
*/
#define DEFINE_TRANSFER_UNIT(Obj, Class, DLL) \
class Obj##_UnitDef : public MTransferUnitDefBase \
{ \
public: \
Obj##_UnitDef(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR pShortDesc, LPCTSTR pDLL); \
~Obj##_UnitDef(); \
virtual MSubConstructBase* Construct(TaggedObject * pNd); \
virtual void GetOptions(); /* to be supplied by the user*/ \
}; \
extern Obj##_UnitDef Obj##_UnitD; \
Obj##_UnitDef::Obj##_UnitDef(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR pShortDesc, LPCTSTR pDLL) : \
MTransferUnitDefBase(pClass, pSubClass, pShortDesc, pDLL, DEVCHECKSON) { GetOptions(); }; \
Obj##_UnitDef::~Obj##_UnitDef() { }; \
MSubConstructBase* Obj##_UnitDef::Construct(TaggedObject * pNd) { return new Obj(this, pNd); }; \
Obj##_UnitDef Obj##_UnitD(DLL##"*"##Class, NULL, "User:"##Class, DLL);
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
//Class MSurgeUnitDefBase: Unit Definition base class for unit models with surge (contents).
class DllImportExport MSurgeUnitDefBase : public MUnitDefBase
{
public:
MSurgeUnitDefBase(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR ShortDesc, LPCTSTR DLL, bool WithDevelopementChecks);
virtual ~MSurgeUnitDefBase() {};
};
//---------------------------------------------------------------------------
/*Macro for adding a SMDK surge unit to the system. See description for DEFINE_TRANSFER_UNIT.*/
#define DEFINE_SURGE_UNIT(Obj, Class, DLL) \
class Obj##_UnitDef : public MSurgeUnitDefBase \
{ \
public: \
Obj##_UnitDef(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR pShortDesc, LPCTSTR pDLL); \
~Obj##_UnitDef(); \
virtual MSubConstructBase* Construct(TaggedObject * pNd); \
virtual void GetOptions(); /* to be supplied by the user*/ \
}; \
extern Obj##_UnitDef Obj##_UnitD; \
Obj##_UnitDef::Obj##_UnitDef(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR pShortDesc, LPCTSTR pDLL) : \
MSurgeUnitDefBase(pClass, pSubClass, pShortDesc, pDLL, DEVCHECKSON) { GetOptions(); }; \
Obj##_UnitDef::~Obj##_UnitDef() { }; \
MSubConstructBase* Obj##_UnitDef::Construct(TaggedObject * pNd) { return new Obj(this, pNd); }; \
Obj##_UnitDef Obj##_UnitD(DLL##"*"##Class, NULL, "User:"##Class, DLL);
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
//Class MControlUnitDefBase: Unit Definition base class for unit models with surge (contents).
class DllImportExport MControlUnitDefBase : public MUnitDefBase
{
public:
MControlUnitDefBase(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR ShortDesc, LPCTSTR DLL, bool WithDevelopementChecks);
virtual ~MControlUnitDefBase() {};
};
//---------------------------------------------------------------------------
/*Macro for adding a SMDK surge unit to the system. See description for DEFINE_TRANSFER_UNIT.*/
#define DEFINE_CONTROL_UNIT(Obj, Class, DLL) \
class Obj##_UnitDef : public MControlUnitDefBase \
{ \
public: \
Obj##_UnitDef(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR pShortDesc, LPCTSTR pDLL); \
~Obj##_UnitDef(); \
virtual MSubConstructBase* Construct(TaggedObject * pNd); \
virtual void GetOptions(); /* to be supplied by the user*/ \
}; \
extern Obj##_UnitDef Obj##_UnitD; \
Obj##_UnitDef::Obj##_UnitDef(LPCTSTR pClass, LPCTSTR pSubClass, LPCTSTR pShortDesc, LPCTSTR pDLL) : \
MControlUnitDefBase(pClass, pSubClass, pShortDesc, pDLL, DEVCHECKSON) { GetOptions(); }; \
Obj##_UnitDef::~Obj##_UnitDef() { }; \
MSubConstructBase* Obj##_UnitDef::Construct(TaggedObject * pNd) { return new Obj(this, pNd); }; \
Obj##_UnitDef Obj##_UnitD(DLL##"*"##Class, NULL, "User:"##Class, DLL);
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
/*Class MMethodUtility: Base class for "Utility Helper" classes to provide
access to "utility" classes in SysCAD (eg reaction block, VLE, etc)*/
class DllImportExport MMethodUtility : public MBaseMethodCommonRef
{
public:
MMethodUtility(MBaseMethodCommon *pCom, LPCTSTR Tag);
virtual ~MMethodUtility();
virtual void BuildDataFields() { };
virtual bool ExchangeDataFields() { return false; };
virtual bool ValidateDataFields() { return true; };
virtual void OnAppActivate(bool bActive) {};
virtual int FilesUsed(CFilesUsedArray & Files) { return 0; }
virtual void SetTag(LPCTSTR Tag) { m_sTag=Tag; };
virtual LPCTSTR Tag() { return m_sTag; };
protected:
CString m_sTag;
};
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
/*Class MProbalPCtrl: Helper class for managing input or outpu stream pressures.*/
class DllImportExport MProbalPCtrl : public MMethodUtility
{
friend class MJoin;
public:
MProbalPCtrl(MBaseMethodCommon *pCom, LPCTSTR Tag="PCtrl", long Method=PC_SatP, double PRqd=StdP+100, bool MdlAvail=true);
~MProbalPCtrl();
void BuildDataFields(long Options);
void CalculateResult();
long getMethod();
void putMethod(long Method);
double getPRqd();
void putPRqd(double PRqd);
double getTRqd();
void putTRqd(double TRqd);
double getPMeas();
void putPMeas(double PMeas);
double getP2Set();
void putP2Set(double P2Set);
_declspec(property(get=getMethod,put=putMethod)) long Method;
_declspec(property(get=getPRqd, put=putPRqd)) double PRqd;
_declspec(property(get=getTRqd, put=putTRqd)) double TRqd;
_declspec(property(get=getPMeas, put=putPMeas)) double PMeas;
_declspec(property(get=getP2Set, put=putP2Set)) double P2Set;
void SetP2Set(double P2Set, bool DoInputs, bool DoOutputs);
protected:
CRqdPressCtrl * m_pPCtrl;
};
//---------------------------------------------------------------------------
/* Class MReactionBlk: Helper class to provide access to the SysCAD reaction block functionality.*/
class DllImportExport MReactionBlk : public MMethodUtility
{
public:
MReactionBlk(MBaseMethodCommon *pCom, bool IsSurgeType, LPCTSTR Tag="RB");
~MReactionBlk();
public:
void OnOffCheckBox(DWORD Flags=MF_PARAM_STOPPED);
void BuildDataFields();
void EvalProducts(MStream & S, double EstFinalT=dNAN);
public:
double HfSumTot(bool RefToProd=false);
double HfSumSrc(bool RefToProd=false);
double HfSumSnk(bool RefToProd=false);
double HfSumRct(bool RefToProd=false);
double HfErr(bool RefToProd=false);
double HsSumHX();
double HsSumPwr();
double EstFinalT();
public:
void Enable();
void Disable();
bool Enabled();
bool OnAndOK();
protected:
bool ExchangeDataFields();
bool ValidateDataFields();
private:
bool Open();
bool Load(LPCTSTR pRCTFn);
void Close();
void OnAppActivate(bool bActive);
int FilesUsed(CFilesUsedArray & Files);
protected:
CReactionBase * m_pRB;
};
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
/* Class MEnvironHXBlk: Helper class to provide access to the SysCAD EHX block functionality.*/
class DllImportExport MEnvironHXBlk : public MMethodUtility
{
public:
MEnvironHXBlk(MBaseMethodCommon *pCom, DWORD Options, LPCTSTR Tag="EHX");
~MEnvironHXBlk();
public:
void OnOffCheckBox(DWORD Flags=MF_PARAM_STOPPED);
void BuildDataFields();
void EvalProducts(MStream & S, double FinalTEst=dNAN);
void EvalProducts(MStream & S, double Len, double Diam, double FinalTEst=dNAN);
double HeatFlow();
public:
void Enable();
void Disable();
bool Enabled();
protected:
bool ExchangeDataFields();
bool ValidateDataFields();
protected:
CEnvironHXBase * m_pEHX;
};
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
/* Class MVLEBlk: Helper class to provide access to the SysCAD VLE block functionality.*/
class DllImportExport MVLEBlk : public MMethodUtility
{
public:
MVLEBlk(MBaseMethodCommon *pCom, DWORD SelectMask, LPCTSTR Tag="VLE");
~MVLEBlk();
public:
void OnOffCheckBox(DWORD Flags=MF_PARAM_STOPPED);
void BuildDataFields();
public:
// Flash the contents
double SatPVapFrac(MVector &Mdl);
// Flash the contents such that the mass fraction of vapour is VapFrac
void SetSatPVapFrac(MVector &Mdl, double Temp, double Press, double VapFrac, DWORD Flags);
// Flash the contents such that the mass fraction of vapour is VapFrac
void SetSatPVapFrac(MVector &Mdl, double VapFrac, DWORD Flags);
// Flash the contents such that the mass fraction of vapour is VapFrac
void SetSatPVapFrac(MStream &Q, double Temp, double Press, double VapFrac, DWORD Flags);
// Flash the contents such that the mass fraction of vapour is VapFrac
void SetSatPVapFrac(MStream &Q, double VapFrac, DWORD Flags);
// Flash the contents given Temperature & Pressure (adjust VapMassFrac)
void TPFlash(MVector &Mdl, double Temp, double Press, DWORD Flags);
// Flash the contents given Duty & Pressure (adjust VapMassFrac & T)
// ie T will be the Saturation Temp at the final conditions
// InjectedDuty is that added due to mechanical inefficiencies is machinery like pumps
void PFlash(MStream &Q, double Press, double InjectedDuty=0.0, DWORD Flags=0);
// Flash the contents given Duty & Pressure (adjust VapMassFrac & T)
// ie T will be the Saturation Temp at the final conditions
// InjectedDuty is that added due to mechanical inefficiencies is machinery like pumps
void PFlash(MStream &Ql, MStream &Qv, double Press, double InjectedDuty=0.0, DWORD Flags=0);
// Flash the contents to equilibrium within the Fixed Container Volume
void VFlash(MContainer &Cn, double InjectedDuty=0.0, DWORD Flags=0);
// Flash the contents Such that mass of Vapour is VapMass (adjust T & P)
void MVapFlash(MStream &Q, double VapMass, double InjectedDuty=0.0, DWORD Flags=0);
// Flash the contents Such that mass of Vapour is VapMass (adjust T & P)
void MVapFlash(MStream &Ql, MStream &Qv, double VapMass, double InjectedDuty=0.0, DWORD Flags=0);
// returns the Saturation Pressure At T igonres the Partial pressure of other gasses
double SaturationP(MVector & V, double T);
// returns the Total Pressure At T ie SaturationP + Partial Pressure of other gasses
double SaturationTotalP(MVector & V, double T);
public:
void Enable();
void Disable();
bool Enabled();
protected:
bool ExchangeDataFields();
bool ValidateDataFields();
protected:
CVLEBase * m_pVLE;
};
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
/* Class MFT_Flash: Helper class for managing a steam source in a flash train macro model.*/
class DllImportExport MFT_Flash : public MMethodUtility
{
public:
MFT_Flash(MBaseMethodCommon *pCom, LPCTSTR Tag="FSrc");
~MFT_Flash();
operator CMacroMdlBase *();
const type_info * TypeInfo();
void BuildDataFields();
bool ExchangeDataFields();
bool ValidateDataFields();
void SetState(eScdMdlStateActs RqdState);
bool getActive();
double getFeedP();
void putFeedP(double FeedP);
double getFeedSaturationP();
void putFeedSaturationP(double FeedSaturationP);
double getFlashP();
void putFlashP(double FlashP);
double getFlashT();
void putFlashT(double FlashT);
double getEstFlashP();
void putEstFlashP(double EstFlashP);
double getVapourFlow();
void putVapourFlow(double VapourFlow);
double getMinFlshTrainP();
double getSuctionP();
double getPEval();
void putPEval(double PEval);
double getVapourFlowEval();
void putVapourFlowEval(double VapourFlowEval);
double getVapourFlowSensEval();
void putVapourFlowSensEval(double VapourFlowSensEval);
bool getVapourFlowSensGood();
void putVapourFlowSensGood(bool VapourFlowSensGood);
public:
_declspec(property(get=getActive)) bool Active;
_declspec(property(get=getFeedP,put=putFeedP)) double FeedP;
_declspec(property(get=getFeedSaturationP,put=putFeedSaturationP)) double FeedSaturationP;
_declspec(property(get=getFlashP,put=putFlashP)) double FlashP;
_declspec(property(get=getFlashT,put=putFlashT)) double FlashT;
_declspec(property(get=getEstFlashP,put=putEstFlashP)) double EstFlashP;
_declspec(property(get=getVapourFlow,put=putVapourFlow)) double VapourFlow;
_declspec(property(get=getMinFlshTrainP)) double MinFlshTrainP;
_declspec(property(get=getSuctionP)) double SuctionP;
_declspec(property(get=getPEval,put=putPEval)) double PEval;
_declspec(property(get=getVapourFlowEval,put=putVapourFlowEval)) double VapourFlowEval;
_declspec(property(get=getVapourFlowSensEval,put=putVapourFlowSensEval)) double VapourFlowSensEval;
_declspec(property(get=getVapourFlowSensGood,put=putVapourFlowSensGood)) bool VapourFlowSensGood;
protected:
CFT_Flash * m_pFlash;
};
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
/* Class MFT_Condenser: Helper class for managing a steam sink in a flash train macro model.*/
class DllImportExport MFT_Condenser : public MMethodUtility
{
public:
MFT_Condenser(MBaseMethodCommon *pCom, LPCTSTR Tag="FSnk");
~MFT_Condenser();
operator CMacroMdlBase *();
const type_info * TypeInfo();
void BuildDataFields();
bool ExchangeDataFields();
bool ValidateDataFields();
void SetState(eScdMdlStateActs RqdState);
bool getActive();
double getSuctionP();
void putSuctionP(double SuctionP);
double getVapourFlow();
void putVapourFlow(double VapourFlow);
double getVapourFlowReqd();
void putVapourFlowReqd(double VapourFlowReqd);
double getMinSaturationP();
void putMinSaturationP(double MinSaturationP);
public:
_declspec(property(get=getActive)) bool Active;
_declspec(property(get=getSuctionP,put=putSuctionP)) double SuctionP;
_declspec(property(get=getVapourFlow,put=putVapourFlow)) double VapourFlow;
_declspec(property(get=getVapourFlowReqd,put=putVapourFlowReqd)) double VapourFlowReqd;
_declspec(property(get=getMinSaturationP,put=putMinSaturationP)) double MinSaturationP;
protected:
CFT_Condenser * m_pCondenser;
};
// --------------------------------------------------------------------------
//class DllImportExport MFT_Mixer : public MMethodUtility
// {
// public:
//
// MFT_Mixer(MBaseMethodCommon *pCom, LPCTSTR Tag="FMix");
// ~MFT_Mixer();
// void BuildDataFields();
// bool ExchangeDataFields();
// bool ValidateDataFields();
// void Activate(CMacroMdl * pMMNd, pFlwNode pNd);
// void Deactivate();
//
// protected:
// CFT_Mixer * m_pMix;
//
// };
//---------------------------------------------------------------------------
//
//
//
//---------------------------------------------------------------------------
#undef DllImportExport
#endif
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
11
],
[
14,
16
],
[
18,
30
],
[
33,
35
],
[
37,
45
],
[
47,
48
],
[
50,
55
],
[
57,
57
],
[
61,
68
],
[
74,
74
],
[
90,
90
],
[
96,
105
],
[
107,
122
],
[
126,
129
],
[
131,
146
],
[
152,
158
],
[
162,
164
],
[
167,
190
],
[
192,
246
],
[
248,
250
],
[
256,
257
],
[
259,
267
],
[
269,
327
],
[
359,
403
],
[
408,
410
],
[
412,
412
],
[
414,
414
],
[
417,
417
],
[
419,
419
],
[
421,
421
],
[
423,
423
],
[
425,
425
],
[
427,
428
],
[
431,
431
],
[
437,
461
],
[
639,
672
],
[
676,
688
],
[
690,
692
],
[
694,
703
],
[
712,
734
],
[
736,
751
],
[
757,
765
],
[
772,
789
],
[
798,
837
],
[
839,
847
],
[
849,
862
],
[
865,
912
],
[
914,
929
],
[
931,
935
],
[
937,
938
],
[
940,
964
],
[
966,
990
],
[
1024,
1053
],
[
1055,
1059
],
[
1061,
1085
],
[
1088,
1112
],
[
1114,
1138
],
[
1173,
1183
],
[
1186,
1186
],
[
1188,
1188
],
[
1190,
1190
],
[
1192,
1192
],
[
1195,
1196
],
[
1210,
1210
],
[
1212,
1212
],
[
1219,
1235
],
[
1237,
1277
],
[
1279,
1287
],
[
1289,
1297
],
[
1304,
1329
],
[
1331,
1334
],
[
1336,
1368
]
],
[
[
12,
13
],
[
17,
17
],
[
31,
32
],
[
36,
36
],
[
46,
46
],
[
49,
49
],
[
56,
56
],
[
58,
60
],
[
69,
73
],
[
75,
89
],
[
91,
95
],
[
106,
106
],
[
123,
125
],
[
130,
130
],
[
147,
151
],
[
159,
161
],
[
247,
247
],
[
251,
255
],
[
258,
258
],
[
268,
268
],
[
328,
358
],
[
462,
462
],
[
468,
468
],
[
470,
472
],
[
474,
490
],
[
493,
509
],
[
511,
552
],
[
555,
610
],
[
613,
613
],
[
615,
638
],
[
673,
675
],
[
689,
689
],
[
693,
693
],
[
704,
711
],
[
735,
735
],
[
752,
756
],
[
766,
771
],
[
790,
797
],
[
848,
848
],
[
863,
864
],
[
913,
913
],
[
930,
930
],
[
936,
936
],
[
939,
939
],
[
965,
965
],
[
991,
1023
],
[
1060,
1060
],
[
1086,
1087
],
[
1140,
1148
],
[
1153,
1171
],
[
1185,
1185
],
[
1187,
1187
],
[
1189,
1189
],
[
1191,
1191
],
[
1193,
1193
],
[
1197,
1209
],
[
1211,
1211
],
[
1213,
1217
],
[
1288,
1288
]
],
[
[
165,
166
],
[
191,
191
],
[
404,
407
],
[
411,
411
],
[
413,
413
],
[
415,
416
],
[
418,
418
],
[
420,
420
],
[
422,
422
],
[
424,
424
],
[
426,
426
],
[
429,
430
],
[
432,
436
],
[
463,
467
],
[
469,
469
],
[
473,
473
],
[
491,
492
],
[
510,
510
],
[
553,
554
],
[
611,
612
],
[
614,
614
],
[
838,
838
],
[
1054,
1054
],
[
1113,
1113
],
[
1139,
1139
],
[
1149,
1152
],
[
1172,
1172
],
[
1184,
1184
],
[
1194,
1194
],
[
1218,
1218
],
[
1236,
1236
],
[
1278,
1278
],
[
1298,
1303
],
[
1330,
1330
],
[
1335,
1335
]
]
]
|
8e02de3539d04b181e81379c9d572c0774d9100a | 3f6437b0deb731e795642e71ea219b911e6af3cc | /MaterialDlg.cpp | 52e014a34b1658c814c60ceb25b615ffd467de83 | []
| no_license | tzafrir/graphics1 | b910f554108235f595b7d3db1407c284afc5a66f | 0bde27d56ad4b36c5b5b355d919e18e0367a4e0d | refs/heads/master | 2016-09-10T21:37:58.249424 | 2011-01-03T19:35:18 | 2011-01-03T19:35:18 | 1,098,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 959 | cpp | // MaterialDlg.cpp : implementation file
//
#include "stdafx.h"
#include "OpenGL.h"
#include "MaterialDlg.h"
// CMaterialDlg dialog
IMPLEMENT_DYNAMIC(CMaterialDlg, CDialog)
CMaterialDlg::CMaterialDlg(CWnd* pParent /*=NULL*/)
: CDialog(CMaterialDlg::IDD, pParent)
, m_ambient(0)
, m_diffuse(0)
, m_shininess(0)
, m_specular(0)
{
}
CMaterialDlg::~CMaterialDlg()
{
}
void CMaterialDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_MATERIAL_AMBIENT, m_ambient);
DDV_MinMaxDouble(pDX, m_ambient, 0, 1);
DDX_Text(pDX, IDC_MATERIAL_DIFFUSE, m_diffuse);
DDV_MinMaxDouble(pDX, m_diffuse, 0, 1);
DDX_Text(pDX, IDC_MATERIAL_SHININESS, m_shininess);
DDV_MinMaxDouble(pDX, m_shininess, 0, 128);
DDX_Text(pDX, IDC_MATERIAL_SPECULAR, m_specular);
}
BEGIN_MESSAGE_MAP(CMaterialDlg, CDialog)
END_MESSAGE_MAP()
// CMaterialDlg message handlers
| [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
6f6fb156f349f4072b48fba8804c50e1e06932c4 | 3a8f285d73216552b351cf471a08bcc2ad929c7f | /ghost/bnet.cpp | 811e39f0c999f324fd200a617c6afae2663c104d | [
"Apache-2.0"
]
| permissive | LAPIZTOLITA/Ghost-C-- | 614adf84aaa908b61e0f00085e41718d5c54391f | ea5ab65de6d60ed4a95038e09657cf331520c077 | refs/heads/master | 2021-01-25T05:28:06.178821 | 2011-05-09T13:53:32 | 2011-05-09T13:53:32 | 1,884,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88,486 | cpp | /*
Copyright [2008] [Trevor Hogan]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
CODE PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/
*/
#include "ghost.h"
#include "util.h"
#include "config.h"
#include "language.h"
#include "socket.h"
#include "commandpacket.h"
#include "ghostdb.h"
#include "bncsutilinterface.h"
#include "bnlsclient.h"
#include "bnetprotocol.h"
#include "bnet.h"
#include "map.h"
#include "packed.h"
#include "savegame.h"
#include "replay.h"
#include "gameprotocol.h"
#include "game_base.h"
#include <boost/filesystem.hpp>
using namespace boost :: filesystem;
//
// CBNET
//
CBNET :: CBNET( CGHost *nGHost, string nServer, string nServerAlias, string nBNLSServer, uint16_t nBNLSPort, uint32_t nBNLSWardenCookie, string nCDKeyROC, string nCDKeyTFT, string nCountryAbbrev, string nCountry, uint32_t nLocaleID, string nUserName, string nUserPassword, string nFirstChannel, string nRootAdmin, char nCommandTrigger, bool nHoldFriends, bool nHoldClan, bool nPublicCommands, unsigned char nWar3Version, BYTEARRAY nEXEVersion, BYTEARRAY nEXEVersionHash, string nPasswordHashType, string nPVPGNRealmName, uint32_t nMaxMessageLength, uint32_t nHostCounterID )
{
// todotodo: append path seperator to Warcraft3Path if needed
m_GHost = nGHost;
m_Socket = new CTCPClient( );
m_Protocol = new CBNETProtocol( );
m_BNLSClient = NULL;
m_BNCSUtil = new CBNCSUtilInterface( nUserName, nUserPassword );
m_CallableAdminList = m_GHost->m_DB->ThreadedAdminList( nServer );
m_CallableBanList = m_GHost->m_DB->ThreadedBanList( nServer );
m_Exiting = false;
m_Server = nServer;
string LowerServer = m_Server;
transform( LowerServer.begin( ), LowerServer.end( ), LowerServer.begin( ), (int(*)(int))tolower );
if( !nServerAlias.empty( ) )
m_ServerAlias = nServerAlias;
else if( LowerServer == "useast.battle.net" )
m_ServerAlias = "USEast";
else if( LowerServer == "uswest.battle.net" )
m_ServerAlias = "USWest";
else if( LowerServer == "asia.battle.net" )
m_ServerAlias = "Asia";
else if( LowerServer == "europe.battle.net" )
m_ServerAlias = "Europe";
else
m_ServerAlias = m_Server;
if( nPasswordHashType == "pvpgn" && !nBNLSServer.empty( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] pvpgn connection found with a configured BNLS server, ignoring BNLS server" );
nBNLSServer.clear( );
nBNLSPort = 0;
nBNLSWardenCookie = 0;
}
m_BNLSServer = nBNLSServer;
m_BNLSPort = nBNLSPort;
m_BNLSWardenCookie = nBNLSWardenCookie;
m_CDKeyROC = nCDKeyROC;
m_CDKeyTFT = nCDKeyTFT;
// remove dashes and spaces from CD keys and convert to uppercase
m_CDKeyROC.erase( remove( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), '-' ), m_CDKeyROC.end( ) );
m_CDKeyTFT.erase( remove( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), '-' ), m_CDKeyTFT.end( ) );
m_CDKeyROC.erase( remove( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), ' ' ), m_CDKeyROC.end( ) );
m_CDKeyTFT.erase( remove( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), ' ' ), m_CDKeyTFT.end( ) );
transform( m_CDKeyROC.begin( ), m_CDKeyROC.end( ), m_CDKeyROC.begin( ), (int(*)(int))toupper );
transform( m_CDKeyTFT.begin( ), m_CDKeyTFT.end( ), m_CDKeyTFT.begin( ), (int(*)(int))toupper );
if( m_CDKeyROC.size( ) != 26 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - your ROC CD key is not 26 characters long and is probably invalid" );
if( m_GHost->m_TFT && m_CDKeyTFT.size( ) != 26 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - your TFT CD key is not 26 characters long and is probably invalid" );
m_CountryAbbrev = nCountryAbbrev;
m_Country = nCountry;
m_LocaleID = nLocaleID;
m_UserName = nUserName;
m_UserPassword = nUserPassword;
m_FirstChannel = nFirstChannel;
m_RootAdmin = nRootAdmin;
transform( m_RootAdmin.begin( ), m_RootAdmin.end( ), m_RootAdmin.begin( ), (int(*)(int))tolower );
m_CommandTrigger = nCommandTrigger;
m_War3Version = nWar3Version;
m_EXEVersion = nEXEVersion;
m_EXEVersionHash = nEXEVersionHash;
m_PasswordHashType = nPasswordHashType;
m_PVPGNRealmName = nPVPGNRealmName;
m_MaxMessageLength = nMaxMessageLength;
m_HostCounterID = nHostCounterID;
m_LastDisconnectedTime = 0;
m_LastConnectionAttemptTime = 0;
m_LastNullTime = 0;
m_LastOutPacketTicks = 0;
m_LastOutPacketSize = 0;
m_LastAdminRefreshTime = GetTime( );
m_LastBanRefreshTime = GetTime( );
m_FirstConnect = true;
m_WaitingToConnect = true;
m_LoggedIn = false;
m_InChat = false;
m_HoldFriends = nHoldFriends;
m_HoldClan = nHoldClan;
m_PublicCommands = nPublicCommands;
}
CBNET :: ~CBNET( )
{
delete m_Socket;
delete m_Protocol;
delete m_BNLSClient;
while( !m_Packets.empty( ) )
{
delete m_Packets.front( );
m_Packets.pop( );
}
delete m_BNCSUtil;
for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); ++i )
delete *i;
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); ++i )
delete *i;
for( vector<PairedAdminCount> :: iterator i = m_PairedAdminCounts.begin( ); i != m_PairedAdminCounts.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedAdminAdd> :: iterator i = m_PairedAdminAdds.begin( ); i != m_PairedAdminAdds.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedAdminRemove> :: iterator i = m_PairedAdminRemoves.begin( ); i != m_PairedAdminRemoves.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedBanCount> :: iterator i = m_PairedBanCounts.begin( ); i != m_PairedBanCounts.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedBanAdd> :: iterator i = m_PairedBanAdds.begin( ); i != m_PairedBanAdds.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedBanRemove> :: iterator i = m_PairedBanRemoves.begin( ); i != m_PairedBanRemoves.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedGPSCheck> :: iterator i = m_PairedGPSChecks.begin( ); i != m_PairedGPSChecks.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
for( vector<PairedDPSCheck> :: iterator i = m_PairedDPSChecks.begin( ); i != m_PairedDPSChecks.end( ); ++i )
m_GHost->m_Callables.push_back( i->second );
if( m_CallableAdminList )
m_GHost->m_Callables.push_back( m_CallableAdminList );
if( m_CallableBanList )
m_GHost->m_Callables.push_back( m_CallableBanList );
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); ++i )
delete *i;
}
BYTEARRAY CBNET :: GetUniqueName( )
{
return m_Protocol->GetUniqueName( );
}
unsigned int CBNET :: SetFD( void *fd, void *send_fd, int *nfds )
{
unsigned int NumFDs = 0;
if( !m_Socket->HasError( ) && m_Socket->GetConnected( ) )
{
m_Socket->SetFD( (fd_set *)fd, (fd_set *)send_fd, nfds );
++NumFDs;
if( m_BNLSClient )
NumFDs += m_BNLSClient->SetFD( fd, send_fd, nfds );
}
return NumFDs;
}
bool CBNET :: Update( void *fd, void *send_fd )
{
//
// update callables
//
for( vector<PairedAdminCount> :: iterator i = m_PairedAdminCounts.begin( ); i != m_PairedAdminCounts.end( ); )
{
if( i->second->GetReady( ) )
{
uint32_t Count = i->second->GetResult( );
if( Count == 0 )
QueueChatCommand( m_GHost->m_Language->ThereAreNoAdmins( m_Server ), i->first, !i->first.empty( ) );
else if( Count == 1 )
QueueChatCommand( m_GHost->m_Language->ThereIsAdmin( m_Server ), i->first, !i->first.empty( ) );
else
QueueChatCommand( m_GHost->m_Language->ThereAreAdmins( m_Server, UTIL_ToString( Count ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedAdminCounts.erase( i );
}
else
++i;
}
for( vector<PairedAdminAdd> :: iterator i = m_PairedAdminAdds.begin( ); i != m_PairedAdminAdds.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
AddAdmin( i->second->GetUser( ) );
QueueChatCommand( m_GHost->m_Language->AddedUserToAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorAddingUserToAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedAdminAdds.erase( i );
}
else
++i;
}
for( vector<PairedAdminRemove> :: iterator i = m_PairedAdminRemoves.begin( ); i != m_PairedAdminRemoves.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
RemoveAdmin( i->second->GetUser( ) );
QueueChatCommand( m_GHost->m_Language->DeletedUserFromAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorDeletingUserFromAdminDatabase( m_Server, i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedAdminRemoves.erase( i );
}
else
++i;
}
for( vector<PairedBanCount> :: iterator i = m_PairedBanCounts.begin( ); i != m_PairedBanCounts.end( ); )
{
if( i->second->GetReady( ) )
{
uint32_t Count = i->second->GetResult( );
if( Count == 0 )
QueueChatCommand( m_GHost->m_Language->ThereAreNoBannedUsers( m_Server ), i->first, !i->first.empty( ) );
else if( Count == 1 )
QueueChatCommand( m_GHost->m_Language->ThereIsBannedUser( m_Server ), i->first, !i->first.empty( ) );
else
QueueChatCommand( m_GHost->m_Language->ThereAreBannedUsers( m_Server, UTIL_ToString( Count ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedBanCounts.erase( i );
}
else
++i;
}
for( vector<PairedBanAdd> :: iterator i = m_PairedBanAdds.begin( ); i != m_PairedBanAdds.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
AddBan( i->second->GetUser( ), i->second->GetIP( ), i->second->GetGameName( ), i->second->GetAdmin( ), i->second->GetReason( ) );
QueueChatCommand( m_GHost->m_Language->BannedUser( i->second->GetServer( ), i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorBanningUser( i->second->GetServer( ), i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedBanAdds.erase( i );
}
else
++i;
}
for( vector<PairedBanRemove> :: iterator i = m_PairedBanRemoves.begin( ); i != m_PairedBanRemoves.end( ); )
{
if( i->second->GetReady( ) )
{
if( i->second->GetResult( ) )
{
RemoveBan( i->second->GetUser( ) );
QueueChatCommand( m_GHost->m_Language->UnbannedUser( i->second->GetUser( ) ), i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->ErrorUnbanningUser( i->second->GetUser( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedBanRemoves.erase( i );
}
else
++i;
}
for( vector<PairedGPSCheck> :: iterator i = m_PairedGPSChecks.begin( ); i != m_PairedGPSChecks.end( ); )
{
if( i->second->GetReady( ) )
{
CDBGamePlayerSummary *GamePlayerSummary = i->second->GetResult( );
if( GamePlayerSummary )
QueueChatCommand( m_GHost->m_Language->HasPlayedGamesWithThisBot( i->second->GetName( ), GamePlayerSummary->GetFirstGameDateTime( ), GamePlayerSummary->GetLastGameDateTime( ), UTIL_ToString( GamePlayerSummary->GetTotalGames( ) ), UTIL_ToString( (float)GamePlayerSummary->GetAvgLoadingTime( ) / 1000, 2 ), UTIL_ToString( GamePlayerSummary->GetAvgLeftPercent( ) ) ), i->first, !i->first.empty( ) );
else
QueueChatCommand( m_GHost->m_Language->HasntPlayedGamesWithThisBot( i->second->GetName( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedGPSChecks.erase( i );
}
else
++i;
}
for( vector<PairedDPSCheck> :: iterator i = m_PairedDPSChecks.begin( ); i != m_PairedDPSChecks.end( ); )
{
if( i->second->GetReady( ) )
{
CDBDotAPlayerSummary *DotAPlayerSummary = i->second->GetResult( );
if( DotAPlayerSummary )
{
string Summary = m_GHost->m_Language->HasPlayedDotAGamesWithThisBot( i->second->GetName( ),
UTIL_ToString( DotAPlayerSummary->GetTotalGames( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalWins( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalLosses( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalDeaths( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalCreepKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalCreepDenies( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalAssists( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalNeutralKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalTowerKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalRaxKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetTotalCourierKills( ) ),
UTIL_ToString( DotAPlayerSummary->GetAvgKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgDeaths( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgCreepKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgCreepDenies( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgAssists( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgNeutralKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgTowerKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgRaxKills( ), 2 ),
UTIL_ToString( DotAPlayerSummary->GetAvgCourierKills( ), 2 ) );
QueueChatCommand( Summary, i->first, !i->first.empty( ) );
}
else
QueueChatCommand( m_GHost->m_Language->HasntPlayedDotAGamesWithThisBot( i->second->GetName( ) ), i->first, !i->first.empty( ) );
m_GHost->m_DB->RecoverCallable( i->second );
delete i->second;
i = m_PairedDPSChecks.erase( i );
}
else
++i;
}
// refresh the admin list every 5 minutes
if( !m_CallableAdminList && GetTime( ) - m_LastAdminRefreshTime >= 300 )
m_CallableAdminList = m_GHost->m_DB->ThreadedAdminList( m_Server );
if( m_CallableAdminList && m_CallableAdminList->GetReady( ) )
{
// CONSOLE_Print( "[BNET: " + m_ServerAlias + "] refreshed admin list (" + UTIL_ToString( m_Admins.size( ) ) + " -> " + UTIL_ToString( m_CallableAdminList->GetResult( ).size( ) ) + " admins)" );
m_Admins = m_CallableAdminList->GetResult( );
m_GHost->m_DB->RecoverCallable( m_CallableAdminList );
delete m_CallableAdminList;
m_CallableAdminList = NULL;
m_LastAdminRefreshTime = GetTime( );
}
// refresh the ban list every 60 minutes
if( !m_CallableBanList && GetTime( ) - m_LastBanRefreshTime >= 3600 )
m_CallableBanList = m_GHost->m_DB->ThreadedBanList( m_Server );
if( m_CallableBanList && m_CallableBanList->GetReady( ) )
{
// CONSOLE_Print( "[BNET: " + m_ServerAlias + "] refreshed ban list (" + UTIL_ToString( m_Bans.size( ) ) + " -> " + UTIL_ToString( m_CallableBanList->GetResult( ).size( ) ) + " bans)" );
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); ++i )
delete *i;
m_Bans = m_CallableBanList->GetResult( );
m_GHost->m_DB->RecoverCallable( m_CallableBanList );
delete m_CallableBanList;
m_CallableBanList = NULL;
m_LastBanRefreshTime = GetTime( );
}
// we return at the end of each if statement so we don't have to deal with errors related to the order of the if statements
// that means it might take a few ms longer to complete a task involving multiple steps (in this case, reconnecting) due to blocking or sleeping
// but it's not a big deal at all, maybe 100ms in the worst possible case (based on a 50ms blocking time)
if( m_Socket->HasError( ) )
{
// the socket has an error
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] disconnected from battle.net due to socket error" );
if( m_Socket->GetError( ) == ECONNRESET && GetTime( ) - m_LastConnectionAttemptTime <= 15 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - you are probably temporarily IP banned from battle.net" );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" );
m_GHost->EventBNETDisconnected( this );
delete m_BNLSClient;
m_BNLSClient = NULL;
m_BNCSUtil->Reset( m_UserName, m_UserPassword );
m_Socket->Reset( );
m_LastDisconnectedTime = GetTime( );
m_LoggedIn = false;
m_InChat = false;
m_WaitingToConnect = true;
return m_Exiting;
}
if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && !m_WaitingToConnect )
{
// the socket was disconnected
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] disconnected from battle.net" );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" );
m_GHost->EventBNETDisconnected( this );
delete m_BNLSClient;
m_BNLSClient = NULL;
m_BNCSUtil->Reset( m_UserName, m_UserPassword );
m_Socket->Reset( );
m_LastDisconnectedTime = GetTime( );
m_LoggedIn = false;
m_InChat = false;
m_WaitingToConnect = true;
return m_Exiting;
}
if( m_Socket->GetConnected( ) )
{
// the socket is connected and everything appears to be working properly
m_Socket->DoRecv( (fd_set *)fd );
ExtractPackets( );
ProcessPackets( );
// update the BNLS client
if( m_BNLSClient )
{
if( m_BNLSClient->Update( fd, send_fd ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] deleting BNLS client" );
delete m_BNLSClient;
m_BNLSClient = NULL;
}
else
{
BYTEARRAY WardenResponse = m_BNLSClient->GetWardenResponse( );
if( !WardenResponse.empty( ) )
m_Socket->PutBytes( m_Protocol->SEND_SID_WARDEN( WardenResponse ) );
}
}
// check if at least one packet is waiting to be sent and if we've waited long enough to prevent flooding
// this formula has changed many times but currently we wait 1 second if the last packet was "small", 3.5 seconds if it was "medium", and 4 seconds if it was "big"
uint32_t WaitTicks = 0;
if( m_LastOutPacketSize < 10 )
WaitTicks = 1000;
else if( m_LastOutPacketSize < 100 )
WaitTicks = 3500;
else
WaitTicks = 4000;
if( !m_OutPackets.empty( ) && GetTicks( ) - m_LastOutPacketTicks >= WaitTicks )
{
if( m_OutPackets.size( ) > 7 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] packet queue warning - there are " + UTIL_ToString( m_OutPackets.size( ) ) + " packets waiting to be sent" );
m_Socket->PutBytes( m_OutPackets.front( ) );
m_LastOutPacketSize = m_OutPackets.front( ).size( );
m_OutPackets.pop( );
m_LastOutPacketTicks = GetTicks( );
}
// send a null packet every 60 seconds to detect disconnects
if( GetTime( ) - m_LastNullTime >= 60 && GetTicks( ) - m_LastOutPacketTicks >= 60000 )
{
m_Socket->PutBytes( m_Protocol->SEND_SID_NULL( ) );
m_LastNullTime = GetTime( );
}
m_Socket->DoSend( (fd_set *)send_fd );
return m_Exiting;
}
if( m_Socket->GetConnecting( ) )
{
// we are currently attempting to connect to battle.net
if( m_Socket->CheckConnect( ) )
{
// the connection attempt completed
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connected" );
m_GHost->EventBNETConnected( this );
m_Socket->PutBytes( m_Protocol->SEND_PROTOCOL_INITIALIZE_SELECTOR( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_INFO( m_War3Version, m_GHost->m_TFT, m_LocaleID, m_CountryAbbrev, m_Country ) );
m_Socket->DoSend( (fd_set *)send_fd );
m_LastNullTime = GetTime( );
m_LastOutPacketTicks = GetTicks( );
while( !m_OutPackets.empty( ) )
m_OutPackets.pop( );
return m_Exiting;
}
else if( GetTime( ) - m_LastConnectionAttemptTime >= 15 )
{
// the connection attempt timed out (15 seconds)
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connect timed out" );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] waiting 90 seconds to reconnect" );
m_GHost->EventBNETConnectTimedOut( this );
m_Socket->Reset( );
m_LastDisconnectedTime = GetTime( );
m_WaitingToConnect = true;
return m_Exiting;
}
}
if( !m_Socket->GetConnecting( ) && !m_Socket->GetConnected( ) && ( m_FirstConnect || GetTime( ) - m_LastDisconnectedTime >= 90 ) )
{
// attempt to connect to battle.net
m_FirstConnect = false;
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] connecting to server [" + m_Server + "] on port 6112" );
m_GHost->EventBNETConnecting( this );
if( !m_GHost->m_BindAddress.empty( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to bind to address [" + m_GHost->m_BindAddress + "]" );
if( m_ServerIP.empty( ) )
{
m_Socket->Connect( m_GHost->m_BindAddress, m_Server, 6112 );
if( !m_Socket->HasError( ) )
{
m_ServerIP = m_Socket->GetIPString( );
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] resolved and cached server IP address " + m_ServerIP );
}
}
else
{
// use cached server IP address since resolving takes time and is blocking
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using cached server IP address " + m_ServerIP );
m_Socket->Connect( m_GHost->m_BindAddress, m_ServerIP, 6112 );
}
m_WaitingToConnect = false;
m_LastConnectionAttemptTime = GetTime( );
return m_Exiting;
}
return m_Exiting;
}
void CBNET :: ExtractPackets( )
{
// extract as many packets as possible from the socket's receive buffer and put them in the m_Packets queue
string *RecvBuffer = m_Socket->GetBytes( );
BYTEARRAY Bytes = UTIL_CreateByteArray( (unsigned char *)RecvBuffer->c_str( ), RecvBuffer->size( ) );
// a packet is at least 4 bytes so loop as long as the buffer contains 4 bytes
while( Bytes.size( ) >= 4 )
{
// byte 0 is always 255
if( Bytes[0] == BNET_HEADER_CONSTANT )
{
// bytes 2 and 3 contain the length of the packet
uint16_t Length = UTIL_ByteArrayToUInt16( Bytes, false, 2 );
if( Length >= 4 )
{
if( Bytes.size( ) >= Length )
{
m_Packets.push( new CCommandPacket( BNET_HEADER_CONSTANT, Bytes[1], BYTEARRAY( Bytes.begin( ), Bytes.begin( ) + Length ) ) );
*RecvBuffer = RecvBuffer->substr( Length );
Bytes = BYTEARRAY( Bytes.begin( ) + Length, Bytes.end( ) );
}
else
return;
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error - received invalid packet from battle.net (bad length), disconnecting" );
m_Socket->Disconnect( );
return;
}
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error - received invalid packet from battle.net (bad header constant), disconnecting" );
m_Socket->Disconnect( );
return;
}
}
}
void CBNET :: ProcessPackets( )
{
CIncomingGameHost *GameHost = NULL;
CIncomingChatEvent *ChatEvent = NULL;
BYTEARRAY WardenData;
vector<CIncomingFriendList *> Friends;
vector<CIncomingClanList *> Clans;
// process all the received packets in the m_Packets queue
// this normally means sending some kind of response
while( !m_Packets.empty( ) )
{
CCommandPacket *Packet = m_Packets.front( );
m_Packets.pop( );
if( Packet->GetPacketType( ) == BNET_HEADER_CONSTANT )
{
switch( Packet->GetID( ) )
{
case CBNETProtocol :: SID_NULL:
// warning: we do not respond to NULL packets with a NULL packet of our own
// this is because PVPGN servers are programmed to respond to NULL packets so it will create a vicious cycle of useless traffic
// official battle.net servers do not respond to NULL packets
m_Protocol->RECEIVE_SID_NULL( Packet->GetData( ) );
break;
case CBNETProtocol :: SID_GETADVLISTEX:
GameHost = m_Protocol->RECEIVE_SID_GETADVLISTEX( Packet->GetData( ) );
if( GameHost )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joining game [" + GameHost->GetGameName( ) + "]" );
delete GameHost;
GameHost = NULL;
break;
case CBNETProtocol :: SID_ENTERCHAT:
if( m_Protocol->RECEIVE_SID_ENTERCHAT( Packet->GetData( ) ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joining channel [" + m_FirstChannel + "]" );
m_InChat = true;
m_Socket->PutBytes( m_Protocol->SEND_SID_JOINCHANNEL( m_FirstChannel ) );
}
break;
case CBNETProtocol :: SID_CHATEVENT:
ChatEvent = m_Protocol->RECEIVE_SID_CHATEVENT( Packet->GetData( ) );
if( ChatEvent )
ProcessChatEvent( ChatEvent );
delete ChatEvent;
ChatEvent = NULL;
break;
case CBNETProtocol :: SID_CHECKAD:
m_Protocol->RECEIVE_SID_CHECKAD( Packet->GetData( ) );
break;
case CBNETProtocol :: SID_STARTADVEX3:
if( m_Protocol->RECEIVE_SID_STARTADVEX3( Packet->GetData( ) ) )
{
m_InChat = false;
m_GHost->EventBNETGameRefreshed( this );
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] startadvex3 failed" );
m_GHost->EventBNETGameRefreshFailed( this );
}
break;
case CBNETProtocol :: SID_PING:
m_Socket->PutBytes( m_Protocol->SEND_SID_PING( m_Protocol->RECEIVE_SID_PING( Packet->GetData( ) ) ) );
break;
case CBNETProtocol :: SID_AUTH_INFO:
if( m_Protocol->RECEIVE_SID_AUTH_INFO( Packet->GetData( ) ) )
{
if( m_BNCSUtil->HELP_SID_AUTH_CHECK( m_GHost->m_TFT, m_GHost->m_Warcraft3Path, m_CDKeyROC, m_CDKeyTFT, m_Protocol->GetValueStringFormulaString( ), m_Protocol->GetIX86VerFileNameString( ), m_Protocol->GetClientToken( ), m_Protocol->GetServerToken( ) ) )
{
// override the exe information generated by bncsutil if specified in the config file
// apparently this is useful for pvpgn users
if( m_EXEVersion.size( ) == 4 )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using custom exe version bnet_custom_exeversion = " + UTIL_ToString( m_EXEVersion[0] ) + " " + UTIL_ToString( m_EXEVersion[1] ) + " " + UTIL_ToString( m_EXEVersion[2] ) + " " + UTIL_ToString( m_EXEVersion[3] ) );
m_BNCSUtil->SetEXEVersion( m_EXEVersion );
}
if( m_EXEVersionHash.size( ) == 4 )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using custom exe version hash bnet_custom_exeversionhash = " + UTIL_ToString( m_EXEVersionHash[0] ) + " " + UTIL_ToString( m_EXEVersionHash[1] ) + " " + UTIL_ToString( m_EXEVersionHash[2] ) + " " + UTIL_ToString( m_EXEVersionHash[3] ) );
m_BNCSUtil->SetEXEVersionHash( m_EXEVersionHash );
}
if( m_GHost->m_TFT )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to auth as Warcraft III: The Frozen Throne" );
else
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempting to auth as Warcraft III: Reign of Chaos" );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_CHECK( m_GHost->m_TFT, m_Protocol->GetClientToken( ), m_BNCSUtil->GetEXEVersion( ), m_BNCSUtil->GetEXEVersionHash( ), m_BNCSUtil->GetKeyInfoROC( ), m_BNCSUtil->GetKeyInfoTFT( ), m_BNCSUtil->GetEXEInfo( ), "GHost" ) );
// the Warden seed is the first 4 bytes of the ROC key hash
// initialize the Warden handler
if( !m_BNLSServer.empty( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] creating BNLS client" );
delete m_BNLSClient;
m_BNLSClient = new CBNLSClient( m_BNLSServer, m_BNLSPort, m_BNLSWardenCookie );
m_BNLSClient->QueueWardenSeed( UTIL_ByteArrayToUInt32( m_BNCSUtil->GetKeyInfoROC( ), false, 16 ) );
}
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - bncsutil key hash failed (check your Warcraft 3 path and cd keys), disconnecting" );
m_Socket->Disconnect( );
delete Packet;
return;
}
}
break;
case CBNETProtocol :: SID_AUTH_CHECK:
if( m_Protocol->RECEIVE_SID_AUTH_CHECK( Packet->GetData( ) ) )
{
// cd keys accepted
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] cd keys accepted" );
m_BNCSUtil->HELP_SID_AUTH_ACCOUNTLOGON( );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGON( m_BNCSUtil->GetClientKey( ), m_UserName ) );
}
else
{
// cd keys not accepted
switch( UTIL_ByteArrayToUInt32( m_Protocol->GetKeyState( ), false ) )
{
case CBNETProtocol :: KR_ROC_KEY_IN_USE:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - ROC CD key in use by user [" + m_Protocol->GetKeyStateDescription( ) + "], disconnecting" );
break;
case CBNETProtocol :: KR_TFT_KEY_IN_USE:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - TFT CD key in use by user [" + m_Protocol->GetKeyStateDescription( ) + "], disconnecting" );
break;
case CBNETProtocol :: KR_OLD_GAME_VERSION:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - game version is too old, disconnecting" );
break;
case CBNETProtocol :: KR_INVALID_VERSION:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - game version is invalid, disconnecting" );
break;
default:
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - cd keys not accepted, disconnecting" );
break;
}
m_Socket->Disconnect( );
delete Packet;
return;
}
break;
case CBNETProtocol :: SID_AUTH_ACCOUNTLOGON:
if( m_Protocol->RECEIVE_SID_AUTH_ACCOUNTLOGON( Packet->GetData( ) ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] username [" + m_UserName + "] accepted" );
if( m_PasswordHashType == "pvpgn" )
{
// pvpgn logon
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using pvpgn logon type (for pvpgn servers only)" );
m_BNCSUtil->HELP_PvPGNPasswordHash( m_UserPassword );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGONPROOF( m_BNCSUtil->GetPvPGNPasswordHash( ) ) );
}
else
{
// battle.net logon
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] using battle.net logon type (for official battle.net servers only)" );
m_BNCSUtil->HELP_SID_AUTH_ACCOUNTLOGONPROOF( m_Protocol->GetSalt( ), m_Protocol->GetServerPublicKey( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_AUTH_ACCOUNTLOGONPROOF( m_BNCSUtil->GetM1( ) ) );
}
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - invalid username, disconnecting" );
m_Socket->Disconnect( );
delete Packet;
return;
}
break;
case CBNETProtocol :: SID_AUTH_ACCOUNTLOGONPROOF:
if( m_Protocol->RECEIVE_SID_AUTH_ACCOUNTLOGONPROOF( Packet->GetData( ) ) )
{
// logon successful
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon successful" );
m_LoggedIn = true;
m_GHost->EventBNETLoggedIn( this );
m_Socket->PutBytes( m_Protocol->SEND_SID_NETGAMEPORT( m_GHost->m_HostPort ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_ENTERCHAT( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_FRIENDSLIST( ) );
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMEMBERLIST( ) );
}
else
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] logon failed - invalid password, disconnecting" );
// try to figure out if the user might be using the wrong logon type since too many people are confused by this
string Server = m_Server;
transform( Server.begin( ), Server.end( ), Server.begin( ), (int(*)(int))tolower );
if( m_PasswordHashType == "pvpgn" && ( Server == "useast.battle.net" || Server == "uswest.battle.net" || Server == "asia.battle.net" || Server == "europe.battle.net" ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] it looks like you're trying to connect to a battle.net server using a pvpgn logon type, check your config file's \"battle.net custom data\" section" );
else if( m_PasswordHashType != "pvpgn" && ( Server != "useast.battle.net" && Server != "uswest.battle.net" && Server != "asia.battle.net" && Server != "europe.battle.net" ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] it looks like you're trying to connect to a pvpgn server using a battle.net logon type, check your config file's \"battle.net custom data\" section" );
m_Socket->Disconnect( );
delete Packet;
return;
}
break;
case CBNETProtocol :: SID_WARDEN:
WardenData = m_Protocol->RECEIVE_SID_WARDEN( Packet->GetData( ) );
if( m_BNLSClient )
m_BNLSClient->QueueWardenRaw( WardenData );
else
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] warning - received warden packet but no BNLS server is available, you will be kicked from battle.net soon" );
break;
case CBNETProtocol :: SID_FRIENDSLIST:
Friends = m_Protocol->RECEIVE_SID_FRIENDSLIST( Packet->GetData( ) );
for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); ++i )
delete *i;
m_Friends = Friends;
break;
case CBNETProtocol :: SID_CLANMEMBERLIST:
vector<CIncomingClanList *> Clans = m_Protocol->RECEIVE_SID_CLANMEMBERLIST( Packet->GetData( ) );
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); ++i )
delete *i;
m_Clans = Clans;
break;
}
}
delete Packet;
}
}
void CBNET :: ProcessChatEvent( CIncomingChatEvent *chatEvent )
{
CBNETProtocol :: IncomingChatEvent Event = chatEvent->GetChatEvent( );
bool Whisper = ( Event == CBNETProtocol :: EID_WHISPER );
string User = chatEvent->GetUser( );
string Message = chatEvent->GetMessage( );
if( Event == CBNETProtocol :: EID_WHISPER || Event == CBNETProtocol :: EID_TALK )
{
if( Event == CBNETProtocol :: EID_WHISPER )
{
CONSOLE_Print( "[WHISPER: " + m_ServerAlias + "] [" + User + "] " + Message );
m_GHost->EventBNETWhisper( this, User, Message );
}
else
{
CONSOLE_Print( "[LOCAL: " + m_ServerAlias + "] [" + User + "] " + Message );
m_GHost->EventBNETChat( this, User, Message );
}
// handle spoof checking for current game
// this case covers whispers - we assume that anyone who sends a whisper to the bot with message "spoofcheck" should be considered spoof checked
// note that this means you can whisper "spoofcheck" even in a public game to manually spoofcheck if the /whois fails
if( Event == CBNETProtocol :: EID_WHISPER && m_GHost->m_CurrentGame )
{
if( Message == "s" || Message == "sc" || Message == "spoof" || Message == "check" || Message == "spoofcheck" )
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, User, true );
else if( Message.find( m_GHost->m_CurrentGame->GetGameName( ) ) != string :: npos )
{
// look for messages like "entered a Warcraft III The Frozen Throne game called XYZ"
// we don't look for the English part of the text anymore because we want this to work with multiple languages
// it's a pretty safe bet that anyone whispering the bot with a message containing the game name is a valid spoofcheck
if( m_PasswordHashType == "pvpgn" && User == m_PVPGNRealmName )
{
// the equivalent pvpgn message is: [PvPGN Realm] Your friend abc has entered a Warcraft III Frozen Throne game named "xyz".
vector<string> Tokens = UTIL_Tokenize( Message, ' ' );
if( Tokens.size( ) >= 3 )
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, Tokens[2], false );
}
else
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, User, false );
}
}
// handle bot commands
if( Message == "?trigger" && ( IsAdmin( User ) || IsRootAdmin( User ) || ( m_PublicCommands && m_OutPackets.size( ) <= 3 ) ) )
QueueChatCommand( m_GHost->m_Language->CommandTrigger( string( 1, m_CommandTrigger ) ), User, Whisper );
else if( !Message.empty( ) && Message[0] == m_CommandTrigger )
{
// extract the command trigger, the command, and the payload
// e.g. "!say hello world" -> command: "say", payload: "hello world"
string Command;
string Payload;
string :: size_type PayloadStart = Message.find( " " );
if( PayloadStart != string :: npos )
{
Command = Message.substr( 1, PayloadStart - 1 );
Payload = Message.substr( PayloadStart + 1 );
}
else
Command = Message.substr( 1 );
transform( Command.begin( ), Command.end( ), Command.begin( ), (int(*)(int))tolower );
if( IsAdmin( User ) || IsRootAdmin( User ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] admin [" + User + "] sent command [" + Message + "]" );
/*****************
* ADMIN COMMANDS *
******************/
//
// !ADDADMIN
//
if( Command == "addadmin" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( IsAdmin( Payload ) )
QueueChatCommand( m_GHost->m_Language->UserIsAlreadyAnAdmin( m_Server, Payload ), User, Whisper );
else
m_PairedAdminAdds.push_back( PairedAdminAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminAdd( m_Server, Payload ) ) );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !ADDBAN
// !BAN
//
else if( ( Command == "addban" || Command == "ban" ) && !Payload.empty( ) )
{
// extract the victim and the reason
// e.g. "Varlock leaver after dying" -> victim: "Varlock", reason: "leaver after dying"
string Victim;
string Reason;
stringstream SS;
SS << Payload;
SS >> Victim;
if( !SS.eof( ) )
{
getline( SS, Reason );
string :: size_type Start = Reason.find_first_not_of( " " );
if( Start != string :: npos )
Reason = Reason.substr( Start );
}
if( IsBannedName( Victim ) )
QueueChatCommand( m_GHost->m_Language->UserIsAlreadyBanned( m_Server, Victim ), User, Whisper );
else
m_PairedBanAdds.push_back( PairedBanAdd( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanAdd( m_Server, Victim, string( ), string( ), User, Reason ) ) );
}
//
// !ANNOUNCE
//
else if( Command == "announce" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AnnounceMessageDisabled( ), User, Whisper );
m_GHost->m_CurrentGame->SetAnnounce( 0, string( ) );
}
else
{
// extract the interval and the message
// e.g. "30 hello everyone" -> interval: "30", message: "hello everyone"
uint32_t Interval;
string Message;
stringstream SS;
SS << Payload;
SS >> Interval;
if( SS.fail( ) || Interval == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to announce command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to announce command" );
else
{
getline( SS, Message );
string :: size_type Start = Message.find_first_not_of( " " );
if( Start != string :: npos )
Message = Message.substr( Start );
QueueChatCommand( m_GHost->m_Language->AnnounceMessageEnabled( ), User, Whisper );
m_GHost->m_CurrentGame->SetAnnounce( Interval, Message );
}
}
}
}
//
// !AUTOHOST
//
else if( Command == "autohost" )
{
if( IsRootAdmin( User ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AutoHostDisabled( ), User, Whisper );
m_GHost->m_AutoHostGameName.clear( );
m_GHost->m_AutoHostOwner.clear( );
m_GHost->m_AutoHostServer.clear( );
m_GHost->m_AutoHostMaximumGames = 0;
m_GHost->m_AutoHostAutoStartPlayers = 0;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = false;
m_GHost->m_AutoHostMinimumScore = 0.0;
m_GHost->m_AutoHostMaximumScore = 0.0;
}
else
{
// extract the maximum games, auto start players, and the game name
// e.g. "5 10 BattleShips Pro" -> maximum games: "5", auto start players: "10", game name: "BattleShips Pro"
uint32_t MaximumGames;
uint32_t AutoStartPlayers;
string GameName;
stringstream SS;
SS << Payload;
SS >> MaximumGames;
if( SS.fail( ) || MaximumGames == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to autohost command" );
else
{
SS >> AutoStartPlayers;
if( SS.fail( ) || AutoStartPlayers == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to autohost command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #3 to autohost command" );
else
{
getline( SS, GameName );
string :: size_type Start = GameName.find_first_not_of( " " );
if( Start != string :: npos )
GameName = GameName.substr( Start );
QueueChatCommand( m_GHost->m_Language->AutoHostEnabled( ), User, Whisper );
delete m_GHost->m_AutoHostMap;
m_GHost->m_AutoHostMap = new CMap( *m_GHost->m_Map );
m_GHost->m_AutoHostGameName = GameName;
m_GHost->m_AutoHostOwner = User;
m_GHost->m_AutoHostServer = m_Server;
m_GHost->m_AutoHostMaximumGames = MaximumGames;
m_GHost->m_AutoHostAutoStartPlayers = AutoStartPlayers;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = false;
m_GHost->m_AutoHostMinimumScore = 0.0;
m_GHost->m_AutoHostMaximumScore = 0.0;
}
}
}
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !AUTOHOSTMM
//
else if( Command == "autohostmm" )
{
if( IsRootAdmin( User ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AutoHostDisabled( ), User, Whisper );
m_GHost->m_AutoHostGameName.clear( );
m_GHost->m_AutoHostOwner.clear( );
m_GHost->m_AutoHostServer.clear( );
m_GHost->m_AutoHostMaximumGames = 0;
m_GHost->m_AutoHostAutoStartPlayers = 0;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = false;
m_GHost->m_AutoHostMinimumScore = 0.0;
m_GHost->m_AutoHostMaximumScore = 0.0;
}
else
{
// extract the maximum games, auto start players, minimum score, maximum score, and the game name
// e.g. "5 10 800 1200 BattleShips Pro" -> maximum games: "5", auto start players: "10", minimum score: "800", maximum score: "1200", game name: "BattleShips Pro"
uint32_t MaximumGames;
uint32_t AutoStartPlayers;
double MinimumScore;
double MaximumScore;
string GameName;
stringstream SS;
SS << Payload;
SS >> MaximumGames;
if( SS.fail( ) || MaximumGames == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to autohostmm command" );
else
{
SS >> AutoStartPlayers;
if( SS.fail( ) || AutoStartPlayers == 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to autohostmm command" );
else
{
SS >> MinimumScore;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #3 to autohostmm command" );
else
{
SS >> MaximumScore;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #4 to autohostmm command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #5 to autohostmm command" );
else
{
getline( SS, GameName );
string :: size_type Start = GameName.find_first_not_of( " " );
if( Start != string :: npos )
GameName = GameName.substr( Start );
QueueChatCommand( m_GHost->m_Language->AutoHostEnabled( ), User, Whisper );
delete m_GHost->m_AutoHostMap;
m_GHost->m_AutoHostMap = new CMap( *m_GHost->m_Map );
m_GHost->m_AutoHostGameName = GameName;
m_GHost->m_AutoHostOwner = User;
m_GHost->m_AutoHostServer = m_Server;
m_GHost->m_AutoHostMaximumGames = MaximumGames;
m_GHost->m_AutoHostAutoStartPlayers = AutoStartPlayers;
m_GHost->m_LastAutoHostTime = GetTime( );
m_GHost->m_AutoHostMatchMaking = true;
m_GHost->m_AutoHostMinimumScore = MinimumScore;
m_GHost->m_AutoHostMaximumScore = MaximumScore;
}
}
}
}
}
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !AUTOSTART
//
else if( Command == "autostart" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) )
{
if( Payload.empty( ) || Payload == "off" )
{
QueueChatCommand( m_GHost->m_Language->AutoStartDisabled( ), User, Whisper );
m_GHost->m_CurrentGame->SetAutoStartPlayers( 0 );
}
else
{
uint32_t AutoStartPlayers = UTIL_ToUInt32( Payload );
if( AutoStartPlayers != 0 )
{
QueueChatCommand( m_GHost->m_Language->AutoStartEnabled( UTIL_ToString( AutoStartPlayers ) ), User, Whisper );
m_GHost->m_CurrentGame->SetAutoStartPlayers( AutoStartPlayers );
}
}
}
//
// !CHANNEL (change channel)
//
else if( Command == "channel" && !Payload.empty( ) )
QueueChatCommand( "/join " + Payload );
//
// !CHECKADMIN
//
else if( Command == "checkadmin" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( IsAdmin( Payload ) )
QueueChatCommand( m_GHost->m_Language->UserIsAnAdmin( m_Server, Payload ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->UserIsNotAnAdmin( m_Server, Payload ), User, Whisper );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !CHECKBAN
//
else if( Command == "checkban" && !Payload.empty( ) )
{
CDBBan *Ban = IsBannedName( Payload );
if( Ban )
QueueChatCommand( m_GHost->m_Language->UserWasBannedOnByBecause( m_Server, Payload, Ban->GetDate( ), Ban->GetAdmin( ), Ban->GetReason( ) ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->UserIsNotBanned( m_Server, Payload ), User, Whisper );
}
//
// !CLOSE (close slot)
//
else if( Command == "close" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
// close as many slots as specified, e.g. "5 10" closes slots 5 and 10
stringstream SS;
SS << Payload;
while( !SS.eof( ) )
{
uint32_t SID;
SS >> SID;
if( SS.fail( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to close command" );
break;
}
else
m_GHost->m_CurrentGame->CloseSlot( (unsigned char)( SID - 1 ), true );
}
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !CLOSEALL
//
else if( Command == "closeall" && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
m_GHost->m_CurrentGame->CloseAllSlots( );
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !COUNTADMINS
//
else if( Command == "countadmins" )
{
if( IsRootAdmin( User ) )
m_PairedAdminCounts.push_back( PairedAdminCount( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminCount( m_Server ) ) );
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !COUNTBANS
//
else if( Command == "countbans" )
m_PairedBanCounts.push_back( PairedBanCount( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanCount( m_Server ) ) );
//
// !DBSTATUS
//
else if( Command == "dbstatus" )
QueueChatCommand( m_GHost->m_DB->GetStatus( ), User, Whisper );
//
// !DELADMIN
//
else if( Command == "deladmin" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( !IsAdmin( Payload ) )
QueueChatCommand( m_GHost->m_Language->UserIsNotAnAdmin( m_Server, Payload ), User, Whisper );
else
m_PairedAdminRemoves.push_back( PairedAdminRemove( Whisper ? User : string( ), m_GHost->m_DB->ThreadedAdminRemove( m_Server, Payload ) ) );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !DELBAN
// !UNBAN
//
else if( ( Command == "delban" || Command == "unban" ) && !Payload.empty( ) )
m_PairedBanRemoves.push_back( PairedBanRemove( Whisper ? User : string( ), m_GHost->m_DB->ThreadedBanRemove( Payload ) ) );
//
// !DISABLE
//
else if( Command == "disable" )
{
if( IsRootAdmin( User ) )
{
QueueChatCommand( m_GHost->m_Language->BotDisabled( ), User, Whisper );
m_GHost->m_Enabled = false;
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !DOWNLOADS
//
else if( Command == "downloads" && !Payload.empty( ) )
{
uint32_t Downloads = UTIL_ToUInt32( Payload );
if( Downloads == 0 )
{
QueueChatCommand( m_GHost->m_Language->MapDownloadsDisabled( ), User, Whisper );
m_GHost->m_AllowDownloads = 0;
}
else if( Downloads == 1 )
{
QueueChatCommand( m_GHost->m_Language->MapDownloadsEnabled( ), User, Whisper );
m_GHost->m_AllowDownloads = 1;
}
else if( Downloads == 2 )
{
QueueChatCommand( m_GHost->m_Language->MapDownloadsConditional( ), User, Whisper );
m_GHost->m_AllowDownloads = 2;
}
}
//
// !ENABLE
//
else if( Command == "enable" )
{
if( IsRootAdmin( User ) )
{
QueueChatCommand( m_GHost->m_Language->BotEnabled( ), User, Whisper );
m_GHost->m_Enabled = true;
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !END
//
else if( Command == "end" && !Payload.empty( ) )
{
// todotodo: what if a game ends just as you're typing this command and the numbering changes?
uint32_t GameNumber = UTIL_ToUInt32( Payload ) - 1;
if( GameNumber < m_GHost->m_Games.size( ) )
{
// if the game owner is still in the game only allow the root admin to end the game
if( m_GHost->m_Games[GameNumber]->GetPlayerFromName( m_GHost->m_Games[GameNumber]->GetOwnerName( ), false ) && !IsRootAdmin( User ) )
QueueChatCommand( m_GHost->m_Language->CantEndGameOwnerIsStillPlaying( m_GHost->m_Games[GameNumber]->GetOwnerName( ) ), User, Whisper );
else
{
QueueChatCommand( m_GHost->m_Language->EndingGame( m_GHost->m_Games[GameNumber]->GetDescription( ) ), User, Whisper );
CONSOLE_Print( "[GAME: " + m_GHost->m_Games[GameNumber]->GetGameName( ) + "] is over (admin ended game)" );
m_GHost->m_Games[GameNumber]->StopPlayers( "was disconnected (admin ended game)" );
}
}
else
QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( Payload ), User, Whisper );
}
//
// !ENFORCESG
//
else if( Command == "enforcesg" && !Payload.empty( ) )
{
// only load files in the current directory just to be safe
if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos )
QueueChatCommand( m_GHost->m_Language->UnableToLoadReplaysOutside( ), User, Whisper );
else
{
string File = m_GHost->m_ReplayPath + Payload + ".w3g";
if( UTIL_FileExists( File ) )
{
QueueChatCommand( m_GHost->m_Language->LoadingReplay( File ), User, Whisper );
CReplay *Replay = new CReplay( );
Replay->Load( File, false );
Replay->ParseReplay( false );
m_GHost->m_EnforcePlayers = Replay->GetPlayers( );
delete Replay;
}
else
QueueChatCommand( m_GHost->m_Language->UnableToLoadReplayDoesntExist( File ), User, Whisper );
}
}
//
// !EXIT
// !QUIT
//
else if( Command == "exit" || Command == "quit" )
{
if( IsRootAdmin( User ) )
{
if( Payload == "nice" )
m_GHost->m_ExitingNice = true;
else if( Payload == "force" )
m_Exiting = true;
else
{
if( m_GHost->m_CurrentGame || !m_GHost->m_Games.empty( ) )
QueueChatCommand( m_GHost->m_Language->AtLeastOneGameActiveUseForceToShutdown( ), User, Whisper );
else
m_Exiting = true;
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !GETCLAN
//
else if( Command == "getclan" )
{
SendGetClanList( );
QueueChatCommand( m_GHost->m_Language->UpdatingClanList( ), User, Whisper );
}
//
// !GETFRIENDS
//
else if( Command == "getfriends" )
{
SendGetFriendsList( );
QueueChatCommand( m_GHost->m_Language->UpdatingFriendsList( ), User, Whisper );
}
//
// !GETGAME
//
else if( Command == "getgame" && !Payload.empty( ) )
{
uint32_t GameNumber = UTIL_ToUInt32( Payload ) - 1;
if( GameNumber < m_GHost->m_Games.size( ) )
QueueChatCommand( m_GHost->m_Language->GameNumberIs( Payload, m_GHost->m_Games[GameNumber]->GetDescription( ) ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( Payload ), User, Whisper );
}
//
// !GETGAMES
//
else if( Command == "getgames" )
{
if( m_GHost->m_CurrentGame )
QueueChatCommand( m_GHost->m_Language->GameIsInTheLobby( m_GHost->m_CurrentGame->GetDescription( ), UTIL_ToString( m_GHost->m_Games.size( ) ), UTIL_ToString( m_GHost->m_MaxGames ) ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->ThereIsNoGameInTheLobby( UTIL_ToString( m_GHost->m_Games.size( ) ), UTIL_ToString( m_GHost->m_MaxGames ) ), User, Whisper );
}
//
// !HOLD (hold a slot for someone)
//
else if( Command == "hold" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
// hold as many players as specified, e.g. "Varlock Kilranin" holds players "Varlock" and "Kilranin"
stringstream SS;
SS << Payload;
while( !SS.eof( ) )
{
string HoldName;
SS >> HoldName;
if( SS.fail( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to hold command" );
break;
}
else
{
QueueChatCommand( m_GHost->m_Language->AddedPlayerToTheHoldList( HoldName ), User, Whisper );
m_GHost->m_CurrentGame->AddToReserved( HoldName );
}
}
}
//
// !HOSTSG
//
else if( Command == "hostsg" && !Payload.empty( ) )
m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, true, Payload, User, User, m_Server, Whisper );
//
// !LOAD (load config file)
//
else if( Command == "load" )
{
if( Payload.empty( ) )
QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper );
else
{
string FoundMapConfigs;
try
{
path MapCFGPath( m_GHost->m_MapCFGPath );
string Pattern = Payload;
transform( Pattern.begin( ), Pattern.end( ), Pattern.begin( ), (int(*)(int))tolower );
if( !exists( MapCFGPath ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing map configs - map config path doesn't exist" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMapConfigs( ), User, Whisper );
}
else
{
directory_iterator EndIterator;
path LastMatch;
uint32_t Matches = 0;
for( directory_iterator i( MapCFGPath ); i != EndIterator; ++i )
{
string FileName = i->path( ).filename( ).string( );
string Stem = i->path( ).stem( ).string( );
transform( FileName.begin( ), FileName.end( ), FileName.begin( ), (int(*)(int))tolower );
transform( Stem.begin( ), Stem.end( ), Stem.begin( ), (int(*)(int))tolower );
if( !is_directory( i->status( ) ) && i->path( ).extension( ) == ".cfg" && FileName.find( Pattern ) != string :: npos )
{
LastMatch = i->path( );
++Matches;
if( FoundMapConfigs.empty( ) )
FoundMapConfigs = i->path( ).filename( ).string( );
else
FoundMapConfigs += ", " + i->path( ).filename( ).string( );
// if the pattern matches the filename exactly, with or without extension, stop any further matching
if( FileName == Pattern || Stem == Pattern )
{
Matches = 1;
break;
}
}
}
if( Matches == 0 )
QueueChatCommand( m_GHost->m_Language->NoMapConfigsFound( ), User, Whisper );
else if( Matches == 1 )
{
string File = LastMatch.filename( ).string( );
QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( m_GHost->m_MapCFGPath + File ), User, Whisper );
CConfig MapCFG;
MapCFG.Read( LastMatch.string( ) );
m_GHost->m_Map->Load( &MapCFG, m_GHost->m_MapCFGPath + File );
}
else
QueueChatCommand( m_GHost->m_Language->FoundMapConfigs( FoundMapConfigs ), User, Whisper );
}
}
catch( const exception &ex )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing map configs - caught exception [" + ex.what( ) + "]" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMapConfigs( ), User, Whisper );
}
}
}
//
// !LOADSG
//
else if( Command == "loadsg" && !Payload.empty( ) )
{
// only load files in the current directory just to be safe
if( Payload.find( "/" ) != string :: npos || Payload.find( "\\" ) != string :: npos )
QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGamesOutside( ), User, Whisper );
else
{
string File = m_GHost->m_SaveGamePath + Payload + ".w3z";
string FileNoPath = Payload + ".w3z";
if( UTIL_FileExists( File ) )
{
if( m_GHost->m_CurrentGame )
QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGameGameInLobby( ), User, Whisper );
else
{
QueueChatCommand( m_GHost->m_Language->LoadingSaveGame( File ), User, Whisper );
m_GHost->m_SaveGame->Load( File, false );
m_GHost->m_SaveGame->ParseSaveGame( );
m_GHost->m_SaveGame->SetFileName( File );
m_GHost->m_SaveGame->SetFileNameNoPath( FileNoPath );
}
}
else
QueueChatCommand( m_GHost->m_Language->UnableToLoadSaveGameDoesntExist( File ), User, Whisper );
}
}
//
// !MAP (load map file)
//
else if( Command == "map" )
{
if( Payload.empty( ) )
QueueChatCommand( m_GHost->m_Language->CurrentlyLoadedMapCFGIs( m_GHost->m_Map->GetCFGFile( ) ), User, Whisper );
else
{
string FoundMaps;
try
{
path MapPath( m_GHost->m_MapPath );
string Pattern = Payload;
transform( Pattern.begin( ), Pattern.end( ), Pattern.begin( ), (int(*)(int))tolower );
if( !exists( MapPath ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing maps - map path doesn't exist" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMaps( ), User, Whisper );
}
else
{
directory_iterator EndIterator;
path LastMatch;
uint32_t Matches = 0;
for( directory_iterator i( MapPath ); i != EndIterator; ++i )
{
string FileName = i->path( ).filename( ).string( );
string Stem = i->path( ).stem( ).string( );
transform( FileName.begin( ), FileName.end( ), FileName.begin( ), (int(*)(int))tolower );
transform( Stem.begin( ), Stem.end( ), Stem.begin( ), (int(*)(int))tolower );
if( !is_directory( i->status( ) ) && FileName.find( Pattern ) != string :: npos )
{
LastMatch = i->path( );
++Matches;
if( FoundMaps.empty( ) )
FoundMaps = i->path( ).filename( ).string( );
else
FoundMaps += ", " + i->path( ).filename( ).string( );
// if the pattern matches the filename exactly, with or without extension, stop any further matching
if( FileName == Pattern || Stem == Pattern )
{
Matches = 1;
break;
}
}
}
if( Matches == 0 )
QueueChatCommand( m_GHost->m_Language->NoMapsFound( ), User, Whisper );
else if( Matches == 1 )
{
string File = LastMatch.filename( ).string( );
QueueChatCommand( m_GHost->m_Language->LoadingConfigFile( File ), User, Whisper );
// hackhack: create a config file in memory with the required information to load the map
CConfig MapCFG;
MapCFG.Set( "map_path", "Maps\\Download\\" + File );
MapCFG.Set( "map_localpath", File );
m_GHost->m_Map->Load( &MapCFG, File );
}
else
QueueChatCommand( m_GHost->m_Language->FoundMaps( FoundMaps ), User, Whisper );
}
}
catch( const exception &ex )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] error listing maps - caught exception [" + ex.what( ) + "]" );
QueueChatCommand( m_GHost->m_Language->ErrorListingMaps( ), User, Whisper );
}
}
}
//
// !OPEN (open slot)
//
else if( Command == "open" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
// open as many slots as specified, e.g. "5 10" opens slots 5 and 10
stringstream SS;
SS << Payload;
while( !SS.eof( ) )
{
uint32_t SID;
SS >> SID;
if( SS.fail( ) )
{
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input to open command" );
break;
}
else
m_GHost->m_CurrentGame->OpenSlot( (unsigned char)( SID - 1 ), true );
}
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !OPENALL
//
else if( Command == "openall" && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
m_GHost->m_CurrentGame->OpenAllSlots( );
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !PRIV (host private game)
//
else if( Command == "priv" && !Payload.empty( ) )
m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, Payload, User, User, m_Server, Whisper );
//
// !PRIVBY (host private game by other player)
//
else if( Command == "privby" && !Payload.empty( ) )
{
// extract the owner and the game name
// e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~"
string Owner;
string GameName;
string :: size_type GameNameStart = Payload.find( " " );
if( GameNameStart != string :: npos )
{
Owner = Payload.substr( 0, GameNameStart );
GameName = Payload.substr( GameNameStart + 1 );
m_GHost->CreateGame( m_GHost->m_Map, GAME_PRIVATE, false, GameName, Owner, User, m_Server, Whisper );
}
}
//
// !PUB (host public game)
//
else if( Command == "pub" && !Payload.empty( ) )
m_GHost->CreateGame( m_GHost->m_Map, GAME_PUBLIC, false, Payload, User, User, m_Server, Whisper );
//
// !PUBBY (host public game by other player)
//
else if( Command == "pubby" && !Payload.empty( ) )
{
// extract the owner and the game name
// e.g. "Varlock dota 6.54b arem ~~~" -> owner: "Varlock", game name: "dota 6.54b arem ~~~"
string Owner;
string GameName;
string :: size_type GameNameStart = Payload.find( " " );
if( GameNameStart != string :: npos )
{
Owner = Payload.substr( 0, GameNameStart );
GameName = Payload.substr( GameNameStart + 1 );
m_GHost->CreateGame( m_GHost->m_Map, GAME_PUBLIC, false, GameName, Owner, User, m_Server, Whisper );
}
}
//
// !RELOAD
//
else if( Command == "reload" )
{
if( IsRootAdmin( User ) )
{
QueueChatCommand( m_GHost->m_Language->ReloadingConfigurationFiles( ), User, Whisper );
m_GHost->ReloadConfigs( );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SAY
//
else if( Command == "say" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) ) {
QueueChatCommand( Payload );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SAYGAME
//
else if( Command == "saygame" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
// extract the game number and the message
// e.g. "3 hello everyone" -> game number: "3", message: "hello everyone"
uint32_t GameNumber;
string Message;
stringstream SS;
SS << Payload;
SS >> GameNumber;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to saygame command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to saygame command" );
else
{
getline( SS, Message );
string :: size_type Start = Message.find_first_not_of( " " );
if( Start != string :: npos )
Message = Message.substr( Start );
if( GameNumber - 1 < m_GHost->m_Games.size( ) )
m_GHost->m_Games[GameNumber - 1]->SendAllChat( "ADMIN: " + Message );
else
QueueChatCommand( m_GHost->m_Language->GameNumberDoesntExist( UTIL_ToString( GameNumber ) ), User, Whisper );
}
}
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SAYGAMES
//
else if( Command == "saygames" && !Payload.empty( ) )
{
if( IsRootAdmin( User ) )
{
if( m_GHost->m_CurrentGame )
m_GHost->m_CurrentGame->SendAllChat( Payload );
for( vector<CBaseGame *> :: iterator i = m_GHost->m_Games.begin( ); i != m_GHost->m_Games.end( ); ++i )
(*i)->SendAllChat( "ADMIN: " + Payload );
}
else
QueueChatCommand( m_GHost->m_Language->YouDontHaveAccessToThatCommand( ), User, Whisper );
}
//
// !SP
//
else if( Command == "sp" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->ShufflingPlayers( ) );
m_GHost->m_CurrentGame->ShuffleSlots( );
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !START
//
else if( Command == "start" && m_GHost->m_CurrentGame && !m_GHost->m_CurrentGame->GetCountDownStarted( ) && m_GHost->m_CurrentGame->GetNumHumanPlayers( ) > 0 )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
// if the player sent "!start force" skip the checks and start the countdown
// otherwise check that the game is ready to start
if( Payload == "force" )
m_GHost->m_CurrentGame->StartCountDown( true );
else
m_GHost->m_CurrentGame->StartCountDown( false );
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !SWAP (swap slots)
//
else if( Command == "swap" && !Payload.empty( ) && m_GHost->m_CurrentGame )
{
if( !m_GHost->m_CurrentGame->GetLocked( ) )
{
uint32_t SID1;
uint32_t SID2;
stringstream SS;
SS << Payload;
SS >> SID1;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #1 to swap command" );
else
{
if( SS.eof( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] missing input #2 to swap command" );
else
{
SS >> SID2;
if( SS.fail( ) )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] bad input #2 to swap command" );
else
m_GHost->m_CurrentGame->SwapSlots( (unsigned char)( SID1 - 1 ), (unsigned char)( SID2 - 1 ) );
}
}
}
else
QueueChatCommand( m_GHost->m_Language->TheGameIsLockedBNET( ), User, Whisper );
}
//
// !UNHOST
//
else if( Command == "unhost" )
{
if( m_GHost->m_CurrentGame )
{
if( m_GHost->m_CurrentGame->GetCountDownStarted( ) )
QueueChatCommand( m_GHost->m_Language->UnableToUnhostGameCountdownStarted( m_GHost->m_CurrentGame->GetDescription( ) ), User, Whisper );
// if the game owner is still in the game only allow the root admin to unhost the game
else if( m_GHost->m_CurrentGame->GetPlayerFromName( m_GHost->m_CurrentGame->GetOwnerName( ), false ) && !IsRootAdmin( User ) )
QueueChatCommand( m_GHost->m_Language->CantUnhostGameOwnerIsPresent( m_GHost->m_CurrentGame->GetOwnerName( ) ), User, Whisper );
else
{
QueueChatCommand( m_GHost->m_Language->UnhostingGame( m_GHost->m_CurrentGame->GetDescription( ) ), User, Whisper );
m_GHost->m_CurrentGame->SetExiting( true );
}
}
else
QueueChatCommand( m_GHost->m_Language->UnableToUnhostGameNoGameInLobby( ), User, Whisper );
}
//
// !WARDENSTATUS
//
else if( Command == "wardenstatus" )
{
if( m_BNLSClient )
QueueChatCommand( "WARDEN STATUS --- " + UTIL_ToString( m_BNLSClient->GetTotalWardenIn( ) ) + " requests received, " + UTIL_ToString( m_BNLSClient->GetTotalWardenOut( ) ) + " responses sent.", User, Whisper );
else
QueueChatCommand( "WARDEN STATUS --- Not connected to BNLS server.", User, Whisper );
}
}
else
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] non-admin [" + User + "] sent command [" + Message + "]" );
/*********************
* NON ADMIN COMMANDS *
*********************/
// don't respond to non admins if there are more than 3 messages already in the queue
// this prevents malicious users from filling up the bot's chat queue and crippling the bot
// in some cases the queue may be full of legitimate messages but we don't really care if the bot ignores one of these commands once in awhile
// e.g. when several users join a game at the same time and cause multiple /whois messages to be queued at once
if( IsAdmin( User ) || IsRootAdmin( User ) || ( m_PublicCommands && m_OutPackets.size( ) <= 3 ) )
{
//
// !STATS
//
if( Command == "stats" )
{
string StatsUser = User;
if( !Payload.empty( ) )
StatsUser = Payload;
// check for potential abuse
if( !StatsUser.empty( ) && StatsUser.size( ) < 16 && StatsUser[0] != '/' )
m_PairedGPSChecks.push_back( PairedGPSCheck( Whisper ? User : string( ), m_GHost->m_DB->ThreadedGamePlayerSummaryCheck( StatsUser ) ) );
}
//
// !STATSDOTA
// !SD
//
else if( Command == "statsdota" || Command == "sd" )
{
string StatsUser = User;
if( !Payload.empty( ) )
StatsUser = Payload;
// check for potential abuse
if( !StatsUser.empty( ) && StatsUser.size( ) < 16 && StatsUser[0] != '/' )
m_PairedDPSChecks.push_back( PairedDPSCheck( Whisper ? User : string( ), m_GHost->m_DB->ThreadedDotAPlayerSummaryCheck( StatsUser ) ) );
}
//
// !VERSION
//
else if( Command == "version" )
{
if( IsAdmin( User ) || IsRootAdmin( User ) )
QueueChatCommand( m_GHost->m_Language->VersionAdmin( m_GHost->m_Version ), User, Whisper );
else
QueueChatCommand( m_GHost->m_Language->VersionNotAdmin( m_GHost->m_Version ), User, Whisper );
}
}
}
}
else if( Event == CBNETProtocol :: EID_CHANNEL )
{
// keep track of current channel so we can rejoin it after hosting a game
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] joined channel [" + Message + "]" );
m_CurrentChannel = Message;
}
else if( Event == CBNETProtocol :: EID_INFO )
{
CONSOLE_Print( "[INFO: " + m_ServerAlias + "] " + Message );
// extract the first word which we hope is the username
// this is not necessarily true though since info messages also include channel MOTD's and such
string UserName;
string :: size_type Split = Message.find( " " );
if( Split != string :: npos )
UserName = Message.substr( 0, Split );
else
UserName = Message.substr( 0 );
// handle spoof checking for current game
// this case covers whois results which are used when hosting a public game (we send out a "/whois [player]" for each player)
// at all times you can still /w the bot with "spoofcheck" to manually spoof check
if( m_GHost->m_CurrentGame && m_GHost->m_CurrentGame->GetPlayerFromName( UserName, true ) )
{
if( Message.find( "is away" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsAway( UserName ) );
else if( Message.find( "is unavailable" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsUnavailable( UserName ) );
else if( Message.find( "is refusing messages" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofPossibleIsRefusingMessages( UserName ) );
else if( Message.find( "is using Warcraft III The Frozen Throne in the channel" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsNotInGame( UserName ) );
else if( Message.find( "is using Warcraft III The Frozen Throne in channel" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsNotInGame( UserName ) );
else if( Message.find( "is using Warcraft III The Frozen Throne in a private channel" ) != string :: npos )
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsInPrivateChannel( UserName ) );
if( Message.find( "is using Warcraft III The Frozen Throne in game" ) != string :: npos || Message.find( "is using Warcraft III Frozen Throne and is currently in game" ) != string :: npos )
{
// check both the current game name and the last game name against the /whois response
// this is because when the game is rehosted, players who joined recently will be in the previous game according to battle.net
// note: if the game is rehosted more than once it is possible (but unlikely) for a false positive because only two game names are checked
if( Message.find( m_GHost->m_CurrentGame->GetGameName( ) ) != string :: npos || Message.find( m_GHost->m_CurrentGame->GetLastGameName( ) ) != string :: npos )
m_GHost->m_CurrentGame->AddToSpoofed( m_Server, UserName, false );
else
m_GHost->m_CurrentGame->SendAllChat( m_GHost->m_Language->SpoofDetectedIsInAnotherGame( UserName ) );
}
}
}
else if( Event == CBNETProtocol :: EID_ERROR )
CONSOLE_Print( "[ERROR: " + m_ServerAlias + "] " + Message );
else if( Event == CBNETProtocol :: EID_EMOTE )
{
CONSOLE_Print( "[EMOTE: " + m_ServerAlias + "] [" + User + "] " + Message );
m_GHost->EventBNETEmote( this, User, Message );
}
}
void CBNET :: SendJoinChannel( string channel )
{
if( m_LoggedIn && m_InChat )
m_Socket->PutBytes( m_Protocol->SEND_SID_JOINCHANNEL( channel ) );
}
void CBNET :: SendGetFriendsList( )
{
if( m_LoggedIn )
m_Socket->PutBytes( m_Protocol->SEND_SID_FRIENDSLIST( ) );
}
void CBNET :: SendGetClanList( )
{
if( m_LoggedIn )
m_Socket->PutBytes( m_Protocol->SEND_SID_CLANMEMBERLIST( ) );
}
void CBNET :: QueueEnterChat( )
{
if( m_LoggedIn )
m_OutPackets.push( m_Protocol->SEND_SID_ENTERCHAT( ) );
}
void CBNET :: QueueChatCommand( string chatCommand )
{
if( chatCommand.empty( ) )
return;
if( m_LoggedIn )
{
if( m_PasswordHashType == "pvpgn" && chatCommand.size( ) > m_MaxMessageLength )
chatCommand = chatCommand.substr( 0, m_MaxMessageLength );
if( chatCommand.size( ) > 255 )
chatCommand = chatCommand.substr( 0, 255 );
if( m_OutPackets.size( ) > 10 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] attempted to queue chat command [" + chatCommand + "] but there are too many (" + UTIL_ToString( m_OutPackets.size( ) ) + ") packets queued, discarding" );
else
{
CONSOLE_Print( "[QUEUED: " + m_ServerAlias + "] " + chatCommand );
m_OutPackets.push( m_Protocol->SEND_SID_CHATCOMMAND( chatCommand ) );
}
}
}
void CBNET :: QueueChatCommand( string chatCommand, string user, bool whisper )
{
if( chatCommand.empty( ) )
return;
// if whisper is true send the chat command as a whisper to user, otherwise just queue the chat command
if( whisper )
QueueChatCommand( "/w " + user + " " + chatCommand );
else
QueueChatCommand( chatCommand );
}
void CBNET :: QueueGameCreate( unsigned char state, string gameName, string hostName, CMap *map, CSaveGame *savegame, uint32_t hostCounter )
{
if( m_LoggedIn && map )
{
if( !m_CurrentChannel.empty( ) )
m_FirstChannel = m_CurrentChannel;
m_InChat = false;
// a game creation message is just a game refresh message with upTime = 0
QueueGameRefresh( state, gameName, hostName, map, savegame, 0, hostCounter );
}
}
void CBNET :: QueueGameRefresh( unsigned char state, string gameName, string hostName, CMap *map, CSaveGame *saveGame, uint32_t upTime, uint32_t hostCounter )
{
if( hostName.empty( ) )
{
BYTEARRAY UniqueName = m_Protocol->GetUniqueName( );
hostName = string( UniqueName.begin( ), UniqueName.end( ) );
}
if( m_LoggedIn && map )
{
// construct a fixed host counter which will be used to identify players from this realm
// the fixed host counter's 4 most significant bits will contain a 4 bit ID (0-15)
// the rest of the fixed host counter will contain the 28 least significant bits of the actual host counter
// since we're destroying 4 bits of information here the actual host counter should not be greater than 2^28 which is a reasonable assumption
// when a player joins a game we can obtain the ID from the received host counter
// note: LAN broadcasts use an ID of 0, battle.net refreshes use an ID of 1-10, the rest are unused
uint32_t FixedHostCounter = ( hostCounter & 0x0FFFFFFF ) | ( m_HostCounterID << 28 );
if( saveGame )
{
uint32_t MapGameType = MAPGAMETYPE_SAVEDGAME;
// the state should always be private when creating a saved game
if( state == GAME_PRIVATE )
MapGameType |= MAPGAMETYPE_PRIVATEGAME;
// use an invalid map width/height to indicate reconnectable games
BYTEARRAY MapWidth;
MapWidth.push_back( 192 );
MapWidth.push_back( 7 );
BYTEARRAY MapHeight;
MapHeight.push_back( 192 );
MapHeight.push_back( 7 );
if( m_GHost->m_Reconnect )
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), MapWidth, MapHeight, gameName, hostName, upTime, "Save\\Multiplayer\\" + saveGame->GetFileNameNoPath( ), saveGame->GetMagicNumber( ), map->GetMapSHA1( ), FixedHostCounter ) );
else
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), UTIL_CreateByteArray( (uint16_t)0, false ), UTIL_CreateByteArray( (uint16_t)0, false ), gameName, hostName, upTime, "Save\\Multiplayer\\" + saveGame->GetFileNameNoPath( ), saveGame->GetMagicNumber( ), map->GetMapSHA1( ), FixedHostCounter ) );
}
else
{
uint32_t MapGameType = map->GetMapGameType( );
MapGameType |= MAPGAMETYPE_UNKNOWN0;
if( state == GAME_PRIVATE )
MapGameType |= MAPGAMETYPE_PRIVATEGAME;
// use an invalid map width/height to indicate reconnectable games
BYTEARRAY MapWidth;
MapWidth.push_back( 192 );
MapWidth.push_back( 7 );
BYTEARRAY MapHeight;
MapHeight.push_back( 192 );
MapHeight.push_back( 7 );
if( m_GHost->m_Reconnect )
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), MapWidth, MapHeight, gameName, hostName, upTime, map->GetMapPath( ), map->GetMapCRC( ), map->GetMapSHA1( ), FixedHostCounter ) );
else
m_OutPackets.push( m_Protocol->SEND_SID_STARTADVEX3( state, UTIL_CreateByteArray( MapGameType, false ), map->GetMapGameFlags( ), map->GetMapWidth( ), map->GetMapHeight( ), gameName, hostName, upTime, map->GetMapPath( ), map->GetMapCRC( ), map->GetMapSHA1( ), FixedHostCounter ) );
}
}
}
void CBNET :: QueueGameUncreate( )
{
if( m_LoggedIn )
m_OutPackets.push( m_Protocol->SEND_SID_STOPADV( ) );
}
void CBNET :: UnqueuePackets( unsigned char type )
{
queue<BYTEARRAY> Packets;
uint32_t Unqueued = 0;
while( !m_OutPackets.empty( ) )
{
// todotodo: it's very inefficient to have to copy all these packets while searching the queue
BYTEARRAY Packet = m_OutPackets.front( );
m_OutPackets.pop( );
if( Packet.size( ) >= 2 && Packet[1] == type )
++Unqueued;
else
Packets.push( Packet );
}
m_OutPackets = Packets;
if( Unqueued > 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] unqueued " + UTIL_ToString( Unqueued ) + " packets of type " + UTIL_ToString( type ) );
}
void CBNET :: UnqueueChatCommand( string chatCommand )
{
// hackhack: this is ugly code
// generate the packet that would be sent for this chat command
// then search the queue for that exact packet
BYTEARRAY PacketToUnqueue = m_Protocol->SEND_SID_CHATCOMMAND( chatCommand );
queue<BYTEARRAY> Packets;
uint32_t Unqueued = 0;
while( !m_OutPackets.empty( ) )
{
// todotodo: it's very inefficient to have to copy all these packets while searching the queue
BYTEARRAY Packet = m_OutPackets.front( );
m_OutPackets.pop( );
if( Packet == PacketToUnqueue )
++Unqueued;
else
Packets.push( Packet );
}
m_OutPackets = Packets;
if( Unqueued > 0 )
CONSOLE_Print( "[BNET: " + m_ServerAlias + "] unqueued " + UTIL_ToString( Unqueued ) + " chat command packets" );
}
void CBNET :: UnqueueGameRefreshes( )
{
UnqueuePackets( CBNETProtocol :: SID_STARTADVEX3 );
}
bool CBNET :: IsAdmin( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
for( vector<string> :: iterator i = m_Admins.begin( ); i != m_Admins.end( ); ++i )
{
if( *i == name )
return true;
}
return false;
}
bool CBNET :: IsRootAdmin( string name )
{
// m_RootAdmin was already transformed to lower case in the constructor
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
// updated to permit multiple root admins seperated by a space, e.g. "Varlock Kilranin Instinct121"
// note: this function gets called frequently so it would be better to parse the root admins just once and store them in a list somewhere
// however, it's hardly worth optimizing at this point since the code's already written
stringstream SS;
string s;
SS << m_RootAdmin;
while( !SS.eof( ) )
{
SS >> s;
if( name == s )
return true;
}
return false;
}
CDBBan *CBNET :: IsBannedName( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
// todotodo: optimize this - maybe use a map?
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); ++i )
{
if( (*i)->GetName( ) == name )
return *i;
}
return NULL;
}
CDBBan *CBNET :: IsBannedIP( string ip )
{
// todotodo: optimize this - maybe use a map?
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); ++i )
{
if( (*i)->GetIP( ) == ip )
return *i;
}
return NULL;
}
void CBNET :: AddAdmin( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
m_Admins.push_back( name );
}
void CBNET :: AddBan( string name, string ip, string gamename, string admin, string reason )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
m_Bans.push_back( new CDBBan( m_Server, name, ip, "N/A", gamename, admin, reason ) );
}
void CBNET :: RemoveAdmin( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
for( vector<string> :: iterator i = m_Admins.begin( ); i != m_Admins.end( ); )
{
if( *i == name )
i = m_Admins.erase( i );
else
++i;
}
}
void CBNET :: RemoveBan( string name )
{
transform( name.begin( ), name.end( ), name.begin( ), (int(*)(int))tolower );
for( vector<CDBBan *> :: iterator i = m_Bans.begin( ); i != m_Bans.end( ); )
{
if( (*i)->GetName( ) == name )
i = m_Bans.erase( i );
else
++i;
}
}
void CBNET :: HoldFriends( CBaseGame *game )
{
if( game )
{
for( vector<CIncomingFriendList *> :: iterator i = m_Friends.begin( ); i != m_Friends.end( ); ++i )
game->AddToReserved( (*i)->GetAccount( ) );
}
}
void CBNET :: HoldClan( CBaseGame *game )
{
if( game )
{
for( vector<CIncomingClanList *> :: iterator i = m_Clans.begin( ); i != m_Clans.end( ); ++i )
game->AddToReserved( (*i)->GetName( ) );
}
}
| [
"hogantp@a7494f72-a4b0-11dd-a887-7ffe1a420f8d",
"[email protected]@a7494f72-a4b0-11dd-a887-7ffe1a420f8d",
"[email protected]@a7494f72-a4b0-11dd-a887-7ffe1a420f8d",
"[email protected]@a7494f72-a4b0-11dd-a887-7ffe1a420f8d"
]
| [
[
[
1,
2
],
[
4,
4
],
[
8,
8
],
[
10,
10
],
[
16,
16
],
[
18,
89
],
[
91,
93
],
[
96,
150
],
[
152,
153
],
[
155,
156
],
[
158,
159
],
[
161,
162
],
[
164,
165
],
[
167,
168
],
[
170,
171
],
[
173,
174
],
[
176,
177
],
[
179,
186
],
[
188,
202
],
[
204,
235
],
[
237,
255
],
[
257,
275
],
[
277,
296
],
[
298,
316
],
[
318,
336
],
[
338,
355
],
[
357,
367
],
[
389,
399
],
[
401,
426
],
[
428,
907
],
[
909,
916
],
[
918,
1029
],
[
1031,
1059
],
[
1061,
1102
],
[
1104,
1176
],
[
1178,
1266
],
[
1268,
1289
],
[
1291,
1296
],
[
1298,
1313
],
[
1315,
1327
],
[
1329,
1358
],
[
1360,
1370
],
[
1372,
1382
],
[
1384,
1389
],
[
1391,
1396
],
[
1398,
1414
],
[
1416,
1421
],
[
1423,
1436
],
[
1438,
1461
],
[
1463,
1476
],
[
1478,
1503
],
[
1505,
1532
],
[
1534,
1556
],
[
1558,
1566
],
[
1568,
1576
],
[
1578,
1590
],
[
1592,
1602
],
[
1604,
1631
],
[
1633,
1638
],
[
1640,
1663
],
[
1665,
1665
],
[
1668,
1673
],
[
1675,
1676
],
[
1678,
1678
],
[
1680,
1694
],
[
1696,
1716
],
[
1718,
1749
],
[
1751,
1774
],
[
1776,
1776
],
[
1779,
1784
],
[
1786,
1787
],
[
1789,
1789
],
[
1791,
1805
],
[
1807,
1831
],
[
1833,
1862
],
[
1864,
1874
],
[
1876,
1881
],
[
1883,
1902
],
[
1904,
1909
],
[
1911,
1930
],
[
1932,
1945
],
[
1954,
1958
],
[
1960,
2000
],
[
2002,
2007
],
[
2009,
2018
],
[
2020,
2033
],
[
2035,
2053
],
[
2055,
2088
],
[
2090,
2113
],
[
2115,
2154
],
[
2156,
2157
],
[
2159,
2174
],
[
2176,
2408
],
[
2410,
2437
],
[
2439,
2457
],
[
2459,
2497
],
[
2499,
2510
],
[
2512,
2540
],
[
2542,
2553
],
[
2555,
2561
],
[
2563,
2570
],
[
2572,
2574
]
],
[
[
3,
3
],
[
5,
7
],
[
9,
9
],
[
11,
15
],
[
17,
17
],
[
151,
151
],
[
154,
154
],
[
157,
157
],
[
160,
160
],
[
163,
163
],
[
166,
166
],
[
169,
169
],
[
172,
172
],
[
175,
175
],
[
178,
178
],
[
187,
187
],
[
203,
203
],
[
236,
236
],
[
256,
256
],
[
276,
276
],
[
297,
297
],
[
317,
317
],
[
337,
337
],
[
356,
356
],
[
368,
388
],
[
400,
400
],
[
427,
427
],
[
908,
908
],
[
917,
917
],
[
1030,
1030
],
[
1060,
1060
],
[
1103,
1103
],
[
1177,
1177
],
[
1267,
1267
],
[
1290,
1290
],
[
1297,
1297
],
[
1314,
1314
],
[
1328,
1328
],
[
1359,
1359
],
[
1371,
1371
],
[
1383,
1383
],
[
1390,
1390
],
[
1397,
1397
],
[
1415,
1415
],
[
1422,
1422
],
[
1437,
1437
],
[
1462,
1462
],
[
1477,
1477
],
[
1504,
1504
],
[
1533,
1533
],
[
1557,
1557
],
[
1567,
1567
],
[
1577,
1577
],
[
1591,
1591
],
[
1603,
1603
],
[
1632,
1632
],
[
1639,
1639
],
[
1664,
1664
],
[
1674,
1674
],
[
1717,
1717
],
[
1750,
1750
],
[
1775,
1775
],
[
1785,
1785
],
[
1832,
1832
],
[
1863,
1863
],
[
1875,
1875
],
[
1882,
1882
],
[
1903,
1903
],
[
1910,
1910
],
[
1931,
1931
],
[
1946,
1953
],
[
1959,
1959
],
[
2001,
2001
],
[
2008,
2008
],
[
2019,
2019
],
[
2034,
2034
],
[
2054,
2054
],
[
2089,
2089
],
[
2114,
2114
],
[
2155,
2155
],
[
2158,
2158
],
[
2175,
2175
],
[
2409,
2409
],
[
2438,
2438
],
[
2458,
2458
],
[
2498,
2498
],
[
2511,
2511
],
[
2541,
2541
],
[
2554,
2554
],
[
2562,
2562
],
[
2571,
2571
]
],
[
[
90,
90
],
[
94,
95
]
],
[
[
1666,
1667
],
[
1677,
1677
],
[
1679,
1679
],
[
1695,
1695
],
[
1777,
1778
],
[
1788,
1788
],
[
1790,
1790
],
[
1806,
1806
]
]
]
|
d9fc9bb8860581125e087a9adeb91c4ef0cbb9e0 | cc946ca4fb4831693af2c6f252100b9a83cfc7d0 | /uCash.Cybos/uCash.Cybos.FutureHogaMonitor.cpp | 852a39d57c7e6aa7bfe8191406c57697360b7e4f | []
| no_license | primespace/ucash-cybos | 18b8b324689516e08cf6d0124d8ad19c0f316d68 | 1ccece53844fad0ef8f3abc8bbb51dadafc75ab7 | refs/heads/master | 2021-01-10T04:42:53.966915 | 2011-10-14T07:15:33 | 2011-10-14T07:15:33 | 52,243,596 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,733 | cpp | /*
* uCash.Cybos Copyright (c) 2011 Taeyoung Park ([email protected])
*
* 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 "stdafx.h"
#include "uCash.Cybos.Export.h"
#include "uCash.Cybos.Define.h"
#include "uCash.Cybos.FutureHogaData.h"
#include "uCash.Cybos.CpObject.h"
#include "uCash.Cybos.CpFutureJpBid.h"
#include "uCash.Cybos.FutureHogaMonitor.h"
namespace uCash { namespace Cybos {
_ATL_FUNC_INFO FutureHogaMonitor::ReceivedInfo = { CC_STDCALL, VT_EMPTY, 0, { VT_EMPTY } };
FutureHogaMonitor::FutureHogaMonitor()
: m_callback(NULL)
{
}
FutureHogaMonitor::~FutureHogaMonitor()
{
if(m_obj.IsCreated()) {
Destroy();
}
}
bool FutureHogaMonitor::Create()
{
if(m_obj.IsCreated()) return true;
if(!m_obj.CreateInstance()) return false;
HRESULT hr = BaseClass::DispEventAdvise((IUnknownPtr)m_obj);
if(FAILED(hr)) {
m_obj.Release();
return false;
}
return true;
}
void FutureHogaMonitor::Destroy()
{
m_obj.Unsubscribe();
BaseClass::DispEventUnadvise((IUnknownPtr)m_obj);
m_obj.Release();
}
bool FutureHogaMonitor::Subscribe(LPCTSTR code)
{
if(m_obj.IsSubscribed()) return true;
m_obj.SetInputValue(0, code);
return (m_obj.Subscribe() == true);
}
void FutureHogaMonitor::Unsubscribe()
{
m_obj.Unsubscribe();
}
void __stdcall FutureHogaMonitor::OnReceivedData()
{
m_obj.GetHeaderValue<std::string>(0, m_data.Code);
m_obj.GetHeaderValue<long>(1, m_data.Time);
m_obj.GetHeaderValue<float>(2, m_data.SelPoint[0]);
m_obj.GetHeaderValue<float>(3, m_data.SelPoint[1]);
m_obj.GetHeaderValue<float>(4, m_data.SelPoint[2]);
m_obj.GetHeaderValue<float>(5, m_data.SelPoint[3]);
m_obj.GetHeaderValue<float>(6, m_data.SelPoint[4]);
m_obj.GetHeaderValue<long>(7, m_data.SelVolumn[0]);
m_obj.GetHeaderValue<long>(8, m_data.SelVolumn[1]);
m_obj.GetHeaderValue<long>(9, m_data.SelVolumn[2]);
m_obj.GetHeaderValue<long>(10, m_data.SelVolumn[3]);
m_obj.GetHeaderValue<long>(11, m_data.SelVolumn[4]);
m_obj.GetHeaderValue<long>(12, m_data.TotalSelVolumn);
m_obj.GetHeaderValue<long>(13, m_data.SelCount[0]);
m_obj.GetHeaderValue<long>(14, m_data.SelCount[1]);
m_obj.GetHeaderValue<long>(15, m_data.SelCount[2]);
m_obj.GetHeaderValue<long>(16, m_data.SelCount[3]);
m_obj.GetHeaderValue<long>(17, m_data.SelCount[4]);
m_obj.GetHeaderValue<long>(18, m_data.TotalSelCount);
m_obj.GetHeaderValue<float>(19, m_data.BuyPoint[0]);
m_obj.GetHeaderValue<float>(20, m_data.BuyPoint[1]);
m_obj.GetHeaderValue<float>(21, m_data.BuyPoint[2]);
m_obj.GetHeaderValue<float>(22, m_data.BuyPoint[3]);
m_obj.GetHeaderValue<float>(23, m_data.BuyPoint[4]);
m_obj.GetHeaderValue<long>(24, m_data.BuyVolumn[0]);
m_obj.GetHeaderValue<long>(25, m_data.BuyVolumn[1]);
m_obj.GetHeaderValue<long>(26, m_data.BuyVolumn[2]);
m_obj.GetHeaderValue<long>(27, m_data.BuyVolumn[3]);
m_obj.GetHeaderValue<long>(28, m_data.BuyVolumn[4]);
m_obj.GetHeaderValue<long>(29, m_data.TotalBuyVolumn);
m_obj.GetHeaderValue<long>(30, m_data.BuyCount[0]);
m_obj.GetHeaderValue<long>(31, m_data.BuyCount[1]);
m_obj.GetHeaderValue<long>(32, m_data.BuyCount[2]);
m_obj.GetHeaderValue<long>(33, m_data.BuyCount[3]);
m_obj.GetHeaderValue<long>(34, m_data.BuyCount[4]);
m_obj.GetHeaderValue<long>(35, m_data.TotalBuyCount);
m_obj.GetHeaderValue<short>(36, m_data.State);
if(m_callback) {
m_callback(m_data);
}
}
void FutureHogaMonitor::SetCallback(FutureHogaMonitorCallback callback)
{
m_callback = callback;
}
}} // namespace uCash::Cybos | [
"[email protected]"
]
| [
[
[
1,
149
]
]
]
|
e112e6cd37a5b120eef8a329f2b7d9beb7e8ba48 | cd61c8405fae2fa91760ef796a5f7963fa7dbd37 | /MobileRobots/ARNL/examples/combinedJustLocalization.cpp | 3a0e97231873e800ee44be97f4912517e388c304 | []
| no_license | rafaelhdr/tccsauron | b61ec89bc9266601140114a37d024376a0366d38 | 027ecc2ab3579db1214d8a404d7d5fa6b1a64439 | refs/heads/master | 2016-09-05T23:05:57.117805 | 2009-12-14T09:41:58 | 2009-12-14T09:41:58 | 32,693,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,335 | cpp | /*
MobileRobots Advanced Robotics Navigation and Localization (ARNL)
Version 1.7.1
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
All Rights Reserved.
MobileRobots Inc does not make any representations about the
suitability of this software for any purpose. It is provided "as is"
without express or implied warranty.
The license for this software is distributed as LICENSE.txt in the top
level directory.
[email protected]
MobileRobots
10 Columbia Drive
Amherst, NH 03031
800-639-9481
*/
#ifdef _GPP_OMIT_
/* proprietaryJustLocalizationTempl.cpp
* Combined example of just localization, used as template to generate users' examples.
*
* This program can be used as the input to the "gpp" preprocessor to
* generate versions for ARNL, SONARNL, MOGS
* but it is also by itself a usable program, which uses MCL if ARNL
* is defined, sonar localization if SONARNL is defined but ARNL is not defined,
* and GPS localization if either is defined and MOGS is enabled.
*
* TODO:
* Only include localization manager object if ARNL_MULTILOC is
* defined (when more than one localization technique is selected.)
*
*/
#endif
#if defined(ARNL)
/** @example arnlJustLocalization.cpp Example which does localization only,
but provides servers for remote operation with MobileEyes. */
#elif defined(SONARNL)
/** @example sonarnlJustLocalization.cpp Example which does localization only,
but provides servers for remote operation with MobileEyes. */
#elif defined (MOGS)
/** @example mogsJustLocalization.cpp Example which does localization only,
but provides servers for remote operation with MobileEyes. */
#endif
#ifdef ARNL
#warning Arnl selected. Enabling laser localization, docking, multirobot, mapping. Skipping SonArnl.
#define ARNL_LASERLOC
#elif defined(SONARNL)
#warning Sonarnl selected. Enabling sonar localization.
#define ARNL_SONARLOC
#endif
#ifdef MOGS
#warning Mogs selected. Enabling GPS localization.
#define ARNL_GPSLOC
#if defined(ARNL) || defined(SONARNL)
#define ARNL_MULTILOC
#endif
#endif
#if defined(MOGS) || defined(ARNL)
#define ARNL_SICK
#endif
#if !defined(MOGS) && !defined(ARNL) && !defined(SONARNL)
#error Must have at least one of MOGS, ARNL, SONARNL defined!
#endif
/**
This example server only does localization and not path planning.
To test this you can start up MobileEyes and connect to the robot
then just drive the robot around with teleoperation commands.
Use this example as a starting point for adding your own control behavior,
but using ARNL for localization.
Note, to make your own custom planning/navigation information and controls
available in MobileEyes you can look at ArServerClasses.cpp and make your own class
that adds the same server commands as ArServerInfoPath and
ArServerModeGoto.
*/
#include "Aria.h"
#include "ArNetworking.h"
#include "Arnl.h"
#ifdef ARNL_LASERLOC
#include "ArLocalizationTask.h"
#endif
#ifdef ARNL_DOCKING
#include "ArDocking.h"
#endif
#ifdef ARNL_SONARLOC
#include "ArSonarLocalizationTask.h"
#endif
int main(int argc, char *argv[])
{
Aria::init();
Arnl::init();
ArRobot robot;
ArServerBase server;
ArArgumentParser parser(&argc, argv);
parser.loadDefaultArguments();
ArSimpleConnector simpleConnector(&parser);
ArServerSimpleOpener simpleOpener (&parser);
#ifdef ARNL_GPSLOC
ArGPSConnector gpsConnector(&parser);
#endif
ArAnalogGyro gyro (&robot);
parser.loadDefaultArguments();
if (!Aria::parseArgs () || !parser.checkHelpAndWarnUnparsed())
{
Aria::logOptions ();
Aria::exit (1);
}
#ifdef ARNL_SICK
ArSick sick;
robot.addRangeDevice (&sick);
#endif
ArSonarDevice sonarDev;
robot.addRangeDevice (&sonarDev);
ArBumpers bumpers;
robot.addRangeDevice (&bumpers);
// Use the "examples" directory as a place to keep map files
char fileDir[1024];
ArUtil::addDirectories (fileDir, sizeof (fileDir), Aria::getDirectory (),
"examples");
// Set up the map, this will look for files in the examples
// directory (unless the file name starts with a / \ or .
// You can take out the argument to look in the current directory
ArMap arMap (fileDir);
// set it up to ignore empty file names (otherwise the parseFile
// on the config will fail)
arMap.setIgnoreEmptyFileName (true);
ArLocalizationManager locManager(&robot, &arMap);
#ifdef ARNL_LASERLOC
ArLog::log(ArLog::Normal, "Creating laser localization task");
ArLocalizationTask locTask (&robot, &sick, &arMap);
locManager.addLocalizationTask(&locTask);
#endif
#ifdef ARNL_SONARLOC
ArLog::log(ArLog::Normal, "Creating sonar localization task");
ArSonarLocalizationTask locTask (&robot, &sonarDev, &arMap);
locManager.addLocalizationTask(&locTask);
#endif
#ifdef ARNL_GPSLOC
ArLog::log(ArLog::Normal, "Connecting to GPS...");
ArGPS *gps = gpsConnector.createGPS(&robot);
if(!gps || !gps->connect())
{
ArLog::log(ArLog::Terse, "Error connecting to GPS device."
"Try -gpsType, -gpsPort, and/or -gpsBaud command-line arguments."
"Use -help for help. Exiting.");
Aria::exit(5);
}
ArLog::log(ArLog::Normal, "Creating GPS localization task");
ArGPSLocalizationTask gpsLocTask(&robot, gps, &arMap);
#endif
// Add log controls to configuration
ArLog::addToConfig (Aria::getConfig ());
// Open the server port
if (!simpleOpener.open (&server, fileDir, 240))
{
ArLog::log (ArLog::Normal, "Could not open server port");
exit (2);
}
// Connect to the robot
if (!simpleConnector.connectRobot (&robot))
{
ArLog::log (ArLog::Normal, "Could not connect to robot... exiting");
Aria::exit (3);
}
robot.enableMotors ();
robot.clearDirectMotion ();
// reset the simulator to its start position
robot.com(ArCommands::SIM_RESET);
#ifdef ARNL_SICK
simpleConnector.setupLaser (&sick);
#endif
// run robot task cycle
robot.runAsync (true);
#ifdef ARNL_SICK
// Run SICK thread and try to connect
sick.runAsync ();
if (!sick.blockingConnect ())
{
ArLog::log (ArLog::Normal, "Couldn't connect to laser, exiting");
Aria::exit (4);
}
#endif
ArUtil::sleep (300);
// Forbidden regions from the map.
ArForbiddenRangeDevice forbidden (&arMap);
robot.addRangeDevice (&forbidden);
// Objects that provide network services:
ArServerInfoRobot serverInfoRobot (&server, &robot);
ArServerInfoSensor serverInfoSensor (&server, &robot);
ArServerInfoLocalization serverInfoLocalization (&server, &robot, &locManager);
ArServerHandlerLocalization serverLocHandler (&server, &robot, &locManager);
ArServerHandlerMap serverMap (&server, &arMap);
// Drawing services in the map display:
ArServerInfoDrawings drawings (&server);
drawings.addRobotsRangeDevices (&robot);
// Misc. "custom " commands:
ArServerHandlerCommands commands (&server);
ArServerSimpleComUC uCCommands (&commands, &robot);
ArServerSimpleComMovementLogging loggingCommands (&commands, &robot);
ArServerSimpleComGyro gyroCommands (&commands, &robot, &gyro);
ArServerSimpleComLogRobotConfig configCommands (&commands, &robot);
// Set up the possible modes for remote control from a client such as
// MobileEyes:
// To stop and remain stopped:
ArServerModeStop modeStop (&server, &robot);
modeStop.addAsDefaultMode ();
#ifndef ARNL_SONARLOC
// Disable the sonar automatically if stopped and enable when we
// move
ArSonarAutoDisabler sonarAutoDisabler (&robot);
#endif
// Teleoperate by keyboard, joystick, etc:
ArServerModeRatioDrive modeRatioDrive (&server, &robot);
// Teloperation mode's configuration and special commands:
modeRatioDrive.addControlCommands (&commands);
modeRatioDrive.addToConfig (Aria::getConfig (), "Teleop settings");
// Wander mode:
ArServerModeWander
modeWander (&server, &robot);
// Prevent driving if localization is lost:
ArActionLost actionLostRatioDrive (&locManager, NULL, &modeRatioDrive);
modeRatioDrive.getActionGroup ()->addAction (&actionLostRatioDrive, 110);
// Prevent wandering if lost:
ArActionLost
actionLostWander (&locManager, NULL, &modeWander);
modeWander.getActionGroup ()->addAction (&actionLostWander, 110);
// This provides a small table of interesting information for the client
// to display to the operator:
ArServerInfoStrings
stringInfo (&server);
Aria::getInfoGroup ()->addAddStringCallback (stringInfo.
getAddStringFunctor ());
// Display localization score and more
#ifdef ARNL_SONARLOC
Aria::getInfoGroup ()->addStringDouble ("Localization Score", 8,
new ArRetFunctorC < double, ArSonarLocalizationTask > (&locTask,
&ArSonarLocalizationTask::
getLocalizationScore),
"%.03f");
#elif defined(ARNL_LASERLOC)
Aria::getInfoGroup ()->addStringDouble ("Localization Score", 8,
new ArRetFunctorC < double,
ArLocalizationTask > (&locTask,
&ArLocalizationTask::
getLocalizationScore),
"%.03f");
#endif
#ifdef ARNL_SICK
Aria::getInfoGroup ()->addStringInt ("Laser Packet Count", 10,
new ArRetFunctorC < int, ArSick > (&sick,
&ArSick::
getSickPacCount));
#endif
#ifdef ARNL_GPSLOC
// TODO
#endif
Aria::getInfoGroup ()->addStringInt ("Motor Packet Count", 10,
new ArConstRetFunctorC < int,
ArRobot > (&robot,
&ArRobot::getMotorPacCount));
// Create service that allows client to change configuration parameters in ArConfig
ArServerHandlerConfig handlerConfig (&server, Aria::getConfig (),
Arnl::getTypicalDefaultParamFileName (),
Aria::getDirectory ());
// Read in parameter files.
Aria::getConfig ()->useArgumentParser (&parser);
if (!Aria::getConfig ()->parseFile (Arnl::getTypicalParamFileName ()))
{
ArLog::log (ArLog::Normal, "Trouble loading configuration file, exiting");
Aria::exit (5);
}
// Error if there is no map
if (arMap.getFileName () == NULL || strlen (arMap.getFileName ()) <= 0)
{
ArLog::log(ArLog::Terse, "Warning, no map given. Use the -map command-line argument or modify the config using MobileEyes or by editing the parameter file.");
ArLog::log(ArLog::Terse, "See the ARNL documentation, including MAPPING.txt or SONAR_MAPPING.txt.");
}
ArLog::log (ArLog::Normal, "Directory for maps and file serving: %s", fileDir);
ArLog::log (ArLog::Normal, "See the ARNL README.txt for more information");
robot.unlock();
// Localize robot at home.
#ifdef ARNL_GPSLOC
gpsLocTask.setIdleFlag(true);
#endif
#if defined(ARNL_LASERLOC) || defined(ARNL_SONARLOC)
locTask.localizeRobotAtHomeBlocking();
#endif
server.runAsync();
ArLog::log(ArLog::Normal, "Server now running on port %d. Press Control-C to exit.", server.getTcpPort());
robot.waitForRunExit();
Aria::exit(0);
}
| [
"budsbd@8373e73c-ebb0-11dd-9ba5-89a75009fd5d"
]
| [
[
[
1,
362
]
]
]
|
f662128c3c6642e66c7bb9d4ad756fe294e69973 | 502efe97b985c69d6378d9c428c715641719ee03 | /src/moaicore/MOAILayoutFrame.cpp | 89047c4cc3a12b62e7b4967cab437559d597f869 | []
| no_license | neojjang/moai-beta | c3933bca2625bca4f4da26341de6b855e41b9beb | 6bc96412d35192246e35bff91df101bd7c7e41e1 | refs/heads/master | 2021-01-16T20:33:59.443558 | 2011-09-19T23:45:06 | 2011-09-19T23:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,484 | cpp | // Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <moaicore/MOAIDebugLines.h>
#include <moaicore/MOAIGfxDevice.h>
#include <moaicore/MOAILayoutFrame.h>
#include <moaicore/MOAILogMessages.h>
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name layout
@text Perform the layout algorithm to layout hierarchy.
@in MOAILayoutFrame self
@out nil
*/
int MOAILayoutFrame::_layout ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayoutFrame, "U" )
self->Layout ();
return 0;
}
//----------------------------------------------------------------//
/** @name setFit
@text Sets the fitting mode for each axis.
@in MOAILayoutFrame self
@in enum xFit The fitting mode for the X axis; can be FIT_EXPAND, FIT_CONTENT or FIT_ABSOLUTE.
@in enum yFit The fitting mode for the Y axis; can be FIT_EXPAND, FIT_CONTENT or FIT_ABSOLUTE.
@out nil
*/
int MOAILayoutFrame::_setFit ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayoutFrame, "U" )
self->mFit [ X_AXIS ] = state.GetValue < u32 >( 2, self->mFit [ X_AXIS ]);
self->mFit [ Y_AXIS ] = state.GetValue < u32 >( 3, self->mFit [ Y_AXIS ]);
return 0;
}
//----------------------------------------------------------------//
/** @name setIdealSize
@text Sets the size hint used for fitting.
@in MOAILayoutFrame self
@in enum xSize The size hinting for the X axis.
@in enum ySize The size hinting for the Y axis.
@out nil
*/
int MOAILayoutFrame::_setIdealSize ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayoutFrame, "U" )
self->mIdealSize [ X_AXIS ] = state.GetValue < float >( 2, self->mIdealSize [ X_AXIS ]);
self->mIdealSize [ Y_AXIS ] = state.GetValue < float >( 3, self->mIdealSize [ Y_AXIS ]);
return 0;
}
//----------------------------------------------------------------//
/** @name setLayout
@text Sets the layout mode for each axis. Each argument can be one of LAYOUT_ALIGN_{MIN,CENTER,MAX} combined with LAYOUT_JUSTIFY_{MIN,CENTER,MAX}. In this case, MIN, CENTER and MAX refer to the border along each axis; for the X axis MIN would be left and MAX would be right.
@in MOAILayoutFrame self
@in enum xLayout The alignment and justification mode for the X axis.
@in enum yLayout The alignment and justification mode for the Y axis.
@out nil
*/
int MOAILayoutFrame::_setLayout ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayoutFrame, "U" )
self->mLayout [ X_AXIS ] = state.GetValue < u32 >( 2, self->mLayout [ X_AXIS ]);
self->mLayout [ Y_AXIS ] = state.GetValue < u32 >( 3, self->mLayout [ Y_AXIS ]);
return 0;
}
//----------------------------------------------------------------//
/** @name setMargin
@text Sets the interior margins of the layout. This is the space between the edge of the layout and the content.
@in MOAILayoutFrame self
@in number left The margin between the left edge of the layout and the content.
@in number top The margin between the top edge of the layout and the content.
@in number right The margin between the right edge of the layout and the content.
@in number bottom The margin between the bottom edge of the layout and the content.
@out nil
*/
int MOAILayoutFrame::_setMargin ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayoutFrame, "U" )
self->mMargin [ X_AXIS ][ MIN ] = state.GetValue < float >( 2, self->mMargin [ X_AXIS ][ MIN ]);
self->mMargin [ Y_AXIS ][ MIN ] = state.GetValue < float >( 3, self->mMargin [ Y_AXIS ][ MIN ]);
self->mMargin [ X_AXIS ][ MAX ] = state.GetValue < float >( 4, self->mMargin [ X_AXIS ][ MAX ]);
self->mMargin [ Y_AXIS ][ MAX ] = state.GetValue < float >( 5, self->mMargin [ Y_AXIS ][ MAX ]);
return 0;
}
//----------------------------------------------------------------//
/** @name setWeight
@text Sets the stretch weighting for stretchable layouts (i.e. FIT_EXPAND). This is the proportional stretch relative to each other, so any number space can be used; 1, 2, 5 is the same as 0.5, 1, 2.5.
@in MOAILayoutFrame self
@in number xWeight The weighting for the X axis.
@in number yWeight The weighting for the Y axis.
@out nil
*/
int MOAILayoutFrame::_setWeight ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAILayoutFrame, "U" )
self->mWeight [ X_AXIS ] = state.GetValue < float >( 2, self->mWeight [ X_AXIS ]);
self->mWeight [ Y_AXIS ] = state.GetValue < float >( 3, self->mWeight [ Y_AXIS ]);
return 0;
}
//================================================================//
// MOAILayoutFrame
//================================================================//
//----------------------------------------------------------------//
void MOAILayoutFrame::ComputeContentSize ( u32 axis ) {
// local copy of fitting mode
u32 fit = this->mFit [ axis ];
// grab the parent and its fitting mode
MOAILayoutFrame* parent = this->GetParentWidget ();
float parentSize = 0.0f;
if ( parent ) {
if (( fit == FIT_EXPAND ) && ( parent->mFit [ axis ] == FIT_CONTENT )) {
fit = FIT_CONTENT;
}
else {
parentSize = parent->GetInnerSize ( axis );
}
}
// clear out the size
this->mSize [ axis ] = 0;
// if absolute, use ideal size
if ( fit == FIT_ABSOLUTE ) {
this->mSize [ axis ] = this->mIdealSize [ axis ];
}
// resolve parent fitting before computing size of children
if ( fit == FIT_EXPAND ) {
this->mSize [ axis ] = parentSize;
}
bool justified = (( this->mLayout [ axis ] & LAYOUT_JUSTIFY ) != 0 );
float contentSize = 0.0f;
// tally the size of the children
ChildLink* childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
child->ComputeContentSize ( axis );
float childSize = child->mSize [ axis ];
if ( justified ) {
contentSize += childSize;
}
else if ( childSize > contentSize ) {
contentSize = childSize;
}
}
this->mContentSize [ axis ] = contentSize;
if ( fit == FIT_CONTENT ) {
if ( this->mChildren.Count ()) {
this->mSize [ axis ] = contentSize;
}
else {
this->mSize [ axis ] = this->mIdealSize [ axis ];
}
}
}
//----------------------------------------------------------------//
void MOAILayoutFrame::Fit ( u32 axis ) {
float size = this->GetInnerSize ( axis );
float contentSize = this->mContentSize [ axis ];
if ( size == contentSize ) return;
contentSize = 0.0f;
ChildLink* childIt;
float fixSize = 0.0f;
float flexCount = 0.0f;
float totalWeight = 0.0f;
childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
float idealSize = child->mIdealSize [ axis ];
if ( child->mFit [ axis ] == FIT_EXPAND ) {
flexCount += 1.0f;
totalWeight += child->mWeight [ axis ];
}
else {
fixSize += idealSize;
}
}
float grow = size - fixSize;
if ( grow >= 0.0f ) {
// expand!
childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
if ( child->mFit [ axis ] == FIT_EXPAND ) {
float weight = child->mWeight [ axis ] / totalWeight;
child->mSize [ axis ] = grow * weight;
}
contentSize += child->mSize [ axis ];
}
}
else {
// shrink!
float scale = size / fixSize;
childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
if ( child->mFit [ axis ] == FIT_EXPAND ) {
child->mSize [ axis ] = 0.0f;
}
else {
child->mSize [ axis ] = child->mSize [ axis ] * scale;
}
contentSize += child->mSize [ axis ];
}
}
this->mContentSize [ axis ] = contentSize;
}
//----------------------------------------------------------------//
USRect MOAILayoutFrame::GetFrame () {
USRect frame;
frame.mXMin = this->mMargin [ X_AXIS ][ MIN ];
frame.mYMin = this->mMargin [ Y_AXIS ][ MIN ];
frame.mXMax = this->mSize [ X_AXIS ] - this->mMargin [ X_AXIS ][ MAX ];
frame.mYMax = this->mSize [ Y_AXIS ] - this->mMargin [ Y_AXIS ][ MAX ];
return frame;
}
//----------------------------------------------------------------//
float MOAILayoutFrame::GetInnerSize ( u32 axis ) {
float innerSize = this->mSize [ axis ] - ( this->mMargin [ axis ][ MIN ] + this->mMargin [ axis ][ MAX ]);
return innerSize < 0.0f ? 0.0f : innerSize;
}
//----------------------------------------------------------------//
MOAILayoutFrame* MOAILayoutFrame::GetParentWidget () {
if ( this->mTraitSource ) {
return this->mTraitSource->AsType < MOAILayoutFrame >();
}
return 0;
}
//----------------------------------------------------------------//
u32 MOAILayoutFrame::GetPerpAxis ( u32 axis ) {
return (( axis + 1 ) & 0x00000001 );
}
//----------------------------------------------------------------//
USRect MOAILayoutFrame::GetScissorRect () {
USRect scissorRect = this->GetFrame ();
USMatrix4x4 mtx;
mtx.Init ( this->mLocalToWorldMtx );
mtx.Append ( MOAIGfxDevice::Get ().GetWorldToWndMtx ( 1.0f, 1.0f ));
mtx.Transform ( scissorRect );
return scissorRect;
}
//----------------------------------------------------------------//
float MOAILayoutFrame::GetSize ( u32 axis ) {
return this->mSize [ axis ];
}
//----------------------------------------------------------------//
void MOAILayoutFrame::Layout () {
// compute current width
this->ComputeContentSize ( X_AXIS );
this->ComputeContentSize ( Y_AXIS );
this->Layout ( X_AXIS );
this->Layout ( Y_AXIS );
}
//----------------------------------------------------------------//
void MOAILayoutFrame::Layout ( u32 axis ) {
float size = this->GetInnerSize ( axis );
float minMargin = this->mMargin [ axis ][ MIN ];
float maxMargin = this->mMargin [ axis ][ MAX ];
if ( size == 0.0f ) {
float margin = minMargin + maxMargin;
float loc = 0;
if ( margin > 0.0f ) {
loc = minMargin * ( this->mSize [ axis ] / margin );
}
ChildLink* childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
child->SetLocByAxis ( axis, loc );
child->mSize [ axis ] = 0.0f;
child->Layout ( axis );
}
}
else if ( this->mLayout [ axis ] & LAYOUT_ALIGN ) {
float offset = 0.0f;
float scale = 0.0f;
switch ( this->mLayout [ axis ]) {
case LAYOUT_ALIGN_MIN: {
offset = minMargin;
scale = 0.0f;
break;
}
case LAYOUT_ALIGN_MAX: {
offset = minMargin + size;
scale = 1.0f;
break;
}
case LAYOUT_ALIGN_CENTER: {
offset = minMargin + ( size * 0.5f );
scale = 0.5f;
break;
}
}
ChildLink* childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
if ( child->mSize [ axis ] > size ) {
child->mSize [ axis ] = size;
}
child->SetLocByAxis ( axis, offset - ( child->mSize [ axis ] * scale ));
child->Layout ( axis );
}
}
else if ( this->mLayout [ axis ] & LAYOUT_JUSTIFY ) {
this->Fit ( axis );
float cursor = 0.0f;
float empty = size - this->mContentSize [ axis ];
switch ( this->mLayout [ axis ]) {
case LAYOUT_JUSTIFY_MIN: {
cursor = minMargin;
break;
}
case LAYOUT_JUSTIFY_MAX: {
cursor = minMargin + empty;
break;
}
case LAYOUT_JUSTIFY_CENTER: {
cursor = minMargin + ( empty * 0.5f );
break;
}
}
ChildLink* childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
child->SetLocByAxis ( axis, cursor );
cursor += child->mSize [ axis ];
child->Layout ( axis );
}
}
}
//----------------------------------------------------------------//
MOAILayoutFrame::MOAILayoutFrame () {
RTTI_BEGIN
RTTI_EXTEND ( MOAITransform )
RTTI_END
this->mMargin [ X_AXIS ][ MIN ] = 0.0f;
this->mMargin [ Y_AXIS ][ MIN ] = 0.0f;
this->mMargin [ X_AXIS ][ MAX ] = 0.0f;
this->mMargin [ Y_AXIS ][ MAX ] = 0.0f;
this->mLayout [ X_AXIS ] = LAYOUT_ALIGN_MIN;
this->mLayout [ Y_AXIS ] = LAYOUT_ALIGN_MIN;
this->mFit [ X_AXIS ] = FIT_ABSOLUTE;
this->mFit [ Y_AXIS ] = FIT_ABSOLUTE;
this->mWeight [ X_AXIS ] = 1.0f;
this->mWeight [ Y_AXIS ] = 1.0f;
this->mIdealSize [ X_AXIS ] = 0.0f;
this->mIdealSize [ Y_AXIS ] = 0.0f;
this->mLinkInChildren.Data ( this );
}
//----------------------------------------------------------------//
MOAILayoutFrame::~MOAILayoutFrame () {
this->RemoveChildren ();
}
//----------------------------------------------------------------//
void MOAILayoutFrame::RegisterLuaClass ( USLuaState& state ) {
MOAITransform::RegisterLuaClass ( state );
state.SetField ( -1, "LAYOUT_ALIGN_MIN", ( u32 )LAYOUT_ALIGN_MIN );
state.SetField ( -1, "LAYOUT_ALIGN_MAX", ( u32 )LAYOUT_ALIGN_MAX );
state.SetField ( -1, "LAYOUT_ALIGN_CENTER", ( u32 )LAYOUT_ALIGN_CENTER );
state.SetField ( -1, "LAYOUT_JUSTIFY_MIN", ( u32 )LAYOUT_JUSTIFY_MIN );
state.SetField ( -1, "LAYOUT_JUSTIFY_MAX", ( u32 )LAYOUT_JUSTIFY_MAX );
state.SetField ( -1, "LAYOUT_JUSTIFY_CENTER", ( u32 )LAYOUT_JUSTIFY_CENTER );
state.SetField ( -1, "FIT_EXPAND", ( u32 )FIT_EXPAND );
state.SetField ( -1, "FIT_ABSOLUTE", ( u32 )FIT_ABSOLUTE );
state.SetField ( -1, "FIT_CONTENT", ( u32 )FIT_CONTENT );
}
//----------------------------------------------------------------//
void MOAILayoutFrame::RegisterLuaFuncs ( USLuaState& state ) {
MOAITransform::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "layout", _layout },
{ "setFit", _setFit },
{ "setIdealSize", _setIdealSize },
{ "setLayout", _setLayout },
{ "setMargin", _setMargin },
{ "setWeight", _setWeight },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
void MOAILayoutFrame::RemoveChildren () {
ChildLink* childIt = this->mChildren.Head ();
for ( ; childIt; childIt = childIt->Next ()) {
MOAILayoutFrame* child = childIt->Data ();
child->SetParent ( 0 );
}
}
//----------------------------------------------------------------//
void MOAILayoutFrame::SetLocByAxis ( u32 axis, float loc ) {
if ( axis == Y_AXIS ) {
this->mLoc.mY = loc;
}
else {
this->mLoc.mX = loc;
}
}
//----------------------------------------------------------------//
void MOAILayoutFrame::SetParent ( MOAITransformBase* parent ) {
this->mLinkInChildren.Remove ();
this->MOAITransform::SetParent ( parent );
if ( parent ) {
MOAILayoutFrame* parentWidget = parent->AsType < MOAILayoutFrame >();
if ( parentWidget ) {
parentWidget->mChildren.PushBack ( this->mLinkInChildren );
}
}
}
//----------------------------------------------------------------//
STLString MOAILayoutFrame::ToString () {
STLString repr ( MOAITransform::ToString ());
return repr;
}
| [
"[email protected]",
"[email protected]",
"Patrick@agile.(none)",
"[email protected]"
]
| [
[
[
1,
5
],
[
7,
281
],
[
284,
298
],
[
300,
300
],
[
303,
533
]
],
[
[
6,
6
]
],
[
[
282,
283
]
],
[
[
299,
299
],
[
301,
302
]
]
]
|
f22bcc2822498e441b62d5256c1989a9faff9c2c | c60f02a60d94fb5ca4d8a185e055df4addca519c | /src/Shape.cpp | 300530aa24ce2305f00d28e6cbea1861d80769f6 | []
| no_license | kbeyerlein/kDFA | 9b4f48afba43bd2fc730b8d5889b23c247051ff2 | c075b85629ff53dfe1e2f51f61c656fe7d032429 | refs/heads/master | 2020-03-29T12:29:01.244581 | 2011-08-22T23:28:14 | 2011-08-22T23:28:14 | 2,067,600 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 38,720 | cpp | #include "Shape.h"
//#define DEBUG
Shape::Shape()
{
name="";
type="";
firstDist=0;
surfRelaxDist=0;
firstPos=0;
nextShape=0;
maxShell=0;
diffPatt=0;
/*
try{
diffPatt=new Pattern* [Pattern::nLambda];
for (int i=0;i<Pattern::nLambda;i++){
diffPatt[i]=new Pattern(shape);
}
}
catch (exception& e){
printf("\nException found in Shape diffPatt initialization: %s\n", e.what());
}*/
element="";
a=0;
nParams_a=0;
a_D=0;
wShape=0;
mu=0;
sigma=0;
alpha=0;
beta=0;
f=0;
kappa=0;
n_R=0;
wShell=0;
nRelaxShells=0;
derivSRD_mu=0;
derivSRD_sig=0;
distribution="";
deltaSize=0;
p=0;
dW_mu=0;
dW_sig=0;
endSize=0;
posPath="";
distPath="";
D=0;
nA_D=0;
nAtoms=0;
preCalcPatts=0;
nPreCalcPatts=0;
}
Shape::~Shape(void)
{
delete surfRelaxDist;
if (diffPatt){
for (int i=0;i<Pattern::nLambda; i++){
delete diffPatt[i];
}
delete [] diffPatt;
}
delete [] wShell;
delete [] p;
delete [] dW_mu;
delete [] dW_sig;
if (a){
if (!(a[0]->global)){
for (int i=0;i<nParams_a; i++){
delete a[i];
}
delete [] a;
}
}
delete wShape;
//NOTE: when adding a global parameter deallocate it in ~Compare()
if (mu){
if (!mu->global){
delete mu;
}
}
if (sigma){
if (!sigma->global){
delete sigma;
}
}
if (alpha){
if (!alpha->global){
delete alpha;
}
}
if (beta){
if (!beta->global){
delete beta;
}
}
if (f){
if (!f->global){
delete f;
}
}
if (kappa){
if (!kappa->global){
delete kappa;
}
}
if (n_R){
if (!n_R->global){
delete n_R;
}
}
if (deltaSize){
if (!deltaSize->global){
delete deltaSize;
}
}
delete [] D;
delete [] a_D;
delete [] nA_D;
if (preCalcPatts){
for (int i=0;i<nPreCalcPatts;i++){
if (preCalcPatts[i]){
//for (int j=0;j<Pattern::nLambda;j++){
// delete preCalcPatts[i][j];
//}
delete [] preCalcPatts[i];
}
}
delete [] preCalcPatts;
}
}
int Shape::LoadPositions()
{
//TODO Change so that function kills program in the case of errors
int err=0;
Position *curPos, *prevPos=0;
ifstream posfiles;
string temp=posPath+"positionFiles.txt";
posfiles.open(temp.c_str());
if(posfiles.is_open()){
printf("Reading position files for shape %s ...\n", name.c_str());
int count=1;
while(!posfiles.eof()){
posfiles >> temp;
if (!posfiles.eof()){
curPos = new Position(const_cast<char *>(temp.c_str()));
if (firstPos==0){
firstPos=curPos;
prevPos=curPos;
}
else{
if (prevPos){
prevPos->nextPos=curPos;
prevPos=curPos;
}
}
err=curPos->ReadPosFile();
curPos->shell=count;
maxShell=getmax(maxShell,curPos->shell);
if (err!=0) {
printf("Could not open position file: %s", temp.c_str());
return -1;
}
count++;
}
}
posfiles.close();
}
else{
printf("Error: Cannot find list of position files %s\n", temp.c_str());
return -1;
}
printf("MaxShell: %i\n",maxShell);
//Check to max sure pos files of all shells are found and sort linked list
/*
//TODO Below is pointless because pos->shell is given counter above in loop
int shell, place, missing=0;
Position *orderPos;
orderPos=firstPos;
for (shell=1;shell<=maxShell;shell++){
curPos=orderPos;
prevPos=orderPos;
if (orderPos==firstPos)
place=1+missing;
else
place=orderPos->shell+missing;
flag=false;
while(curPos!=0&&!flag)
{
if (curPos->shell==shell){
flag=true;
if(place!=shell){
prevPos->nextPos=curPos->nextPos;
if (shell==1){
curPos->nextPos=firstPos;
firstPos=curPos;
}
else{
curPos->nextPos=orderPos->nextPos;
orderPos->nextPos=curPos;
}
}
orderPos=curPos;
}
prevPos=curPos;
curPos=curPos->nextPos;
place++;
}
if (!flag){
printf("Position file for shell %i is missing", shell);
err=-1;
missing++;
}
}
*/
return err;
}
void Shape::LoadDistances()
{
int nDist=0;
Distance *curDist, *prevDist=0;
ifstream distfiles;
string temp=distPath+"distanceFiles.txt";
distfiles.open(temp.c_str());
if(distfiles.is_open()){
printf("Reading distance files for shape %s ...\n", name.c_str());
while(!distfiles.eof()){
distfiles >> temp;
if (!distfiles.eof()){
curDist = new Distance(const_cast<char *>(temp.c_str()));
if (firstDist==0){
firstDist=curDist;
}
else{
if (prevDist){
prevDist->nextDist=curDist;
}
}
prevDist=curDist;
curDist->ReadDistFile();
nDist++;
}
}
distfiles.close();
}
else{
printf("Could not find list of distance files: %s\n", temp.c_str());
exit(1);
}
curDist=firstDist;
int maxDistShell=0;
for (int i=0;i<nDist;i++){
maxDistShell=getmax(curDist->shell,maxDistShell);
curDist=curDist->nextDist;
}
if (maxDistShell>maxShell){
cout<<"Error: maximum distance shell is larger than maximum position shell for shape: "<< name<<endl;
}
else{
maxDistShell=getmax(maxDistShell,maxShell);
}
//Init ordered list
Distance **orderedDistList=new Distance * [maxDistShell];
for (int i=0; i<maxDistShell; i++){
orderedDistList[i]=0;
}
//Fill in already existing distances
curDist=firstDist;
for (int i=0; i<nDist; i++){
orderedDistList[curDist->shell-1]=curDist;
curDist=curDist->nextDist;
}
//Find missing distances, calculate and output them
string prefix="distances."+type+"Shell", suffix=".debye";
for (int i=0;i<maxDistShell;i++){
if (orderedDistList[i]==0){
int shell=i+1;
printf("Distance file for shell %i is missing\n", shell);
ostringstream num;
num<<shell;
string filename=prefix+num.str()+suffix;
orderedDistList[i]= new Distance();
orderedDistList[i]->fileName=filename;
orderedDistList[i]->shell=shell;
CalcDistForShell(orderedDistList[i]);
#define OUTDIST
#ifdef OUTDIST
orderedDistList[i]->OutputDistToFile(distPath, type);
printf("Distance file calculated for shell %i\n",shell);
#endif
}
}
//Rebuild Linked List
firstDist=orderedDistList[0];
curDist=firstDist;
for (int i=1;i<maxDistShell;i++){
curDist->nextDist=orderedDistList[i];
curDist=curDist->nextDist;
}
curDist->nextDist=0;
delete [] orderedDistList;
}
/*
int Shape::InitParamBounds()
{
int err=0;
if (wShape->val==-1) err=-1;
wShape->name=name+"Weight";
wShape->min=0;
wShape->max=1;
wShape->global=false;
if (a[0]->val==-1) err=-1;
if (a[0]->min==-1) a[0]->min=0;
if (a[0]->max==-1) a[0]->max=10;
// Want to rewrite this to calc min and max given the range of shell sizes
if (distribution=="LogNorm"){
if (mu->val==-1) err=-1;
if (mu->min==-1) mu->min=-1000;
if (mu->max==-1) mu->max=1000;
if (sigma->val==-1) err=-1;
if (sigma->min==-1) sigma->min=0;
if (sigma->max==-1) sigma->max=1000;
}
// Not sure that kappa has no real bounds, need to look into it some more.
if (f->val==-1) err=-1;
if (f->min==-1) f->min=0;
if (f->max==-1) f->max=1;
if (kappa->val==-1) err=-1;
if (kappa->min==-1) kappa->min=0;
if (kappa->max==-1) kappa->max=1000;
if (err==-1)
printf("Parameter not initalized for shape %s\n",name.c_str());
return err;
}
*/
/*
int Shape::SurfaceRelaxation(double *derivfSize_mu, double *derivfSize_sig)
{
Currently not used and needs some work before use!!
int i,j, k,err=0;
printf("Calculating surface relaxation for %s\n", shape.c_str());
//Initialize temp surface relax position files
Position **surfRelaxPos=0;
Distance *tempSRDist=0;
surfRelaxPos=(Position**) malloc(nRelaxShells*sizeof(Position*));
if (surfRelaxPos==0) err=-1;
//for (i=0;i<nRelaxShells&&!err;i++){
surfRelaxPos[i] = new Position();
if (surfRelaxPos[i]!=0){
surfRelaxPos[i]->f=f->val;
surfRelaxPos[i]->kappa=kappa->val;
}
else err=-1;
}
//Initlaize surface relax distance files
if (!err){
tempSRDist = new Distance ();
if (tempSRDist==0) err=-1;
}
if (!err){
if (surfRelaxDist==0) surfRelaxDist= new Distance();
if (surfRelaxDist==0) err=-1;
}
if (!err) InitSRDistance(*tempSRDist);
if (!err) InitSRDistance(*surfRelaxDist);
if (derivSRD_mu==0&&!err) derivSRD_mu=new Distance();
if (derivSRD_sig==0&&!err) derivSRD_sig=new Distance();
if (derivSRD_mu==0||derivSRD_sig==0) err=-1;
if (!err) err=InitSRDistance(*derivSRD_mu);
if (!err) err=InitSRDistance(*derivSRD_sig);
int startSize=1;
if (!err){
if (distribution=="LogNorm"){
//
if (startSize<1||endSize>maxShell){
printf("Needed range of Prob function is not possible with given distances\n");
err=-1;
}
}
else if (distribution=="Delta"){
startSize=size;
endSize=startSize;
}
}
//calculate SR and distances for this shape
Position **posPlaceHold=(Position **) malloc(nRelaxShells*sizeof(Position*));
for (i=0;i<nRelaxShells&&!err;i++){
if (posPlaceHold)
posPlaceHold[i]=firstPos;
else {printf("Error in memory allocation in Surface Relaxation function\n"); err=-1;}
surfRelaxPos[i]= new Position();
}
for (i=startSize; i<=endSize&&!err; i++){
if (distribution=="LogNorm"){
for (j=0;j<nRelaxShells && j<i && !err;j++){
//if (surfRelaxPos[j]->nAtoms==0) err=CopyPosition(surfRelaxPos[j], firstPos);
//else err=CopyPosition(surfRelaxPos[j], surfRelaxPos[j]->nextPos);
if (surfRelaxPos[j]!=0){
err=CopyPosition(*surfRelaxPos[j],posPlaceHold[j]);
}
else err=-1;
if (!err) surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i);
else{
printf("Error in Surface Relaxation position memory allocation\n");
err=-1;
}
}
}
else if (distribution=="Delta"){
Position *tempPos=firstPos;
for (j=0;j<size-nRelaxShells; j++) tempPos=tempPos->nextPos;
for (j=nRelaxShells-1; j>=0&&!err; j--){
err=CopyPosition(*surfRelaxPos[j], tempPos);
if (!err){
surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i);
tempPos=tempPos->nextPos;
}
else{
printf("Error in Surface Relaxation position memory allocation\n");
err=-1;
}
}
}
if (!err){
Position *curPos;
for (j=0;j<nRelaxShells && j<i;j++){
curPos=firstPos;
// for each relaxed shell calc distances between other relaxed shells
for (k=j;k<nRelaxShells&&k<i;k++){
//Need to check that this produces correct results
tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, surfRelaxPos[k]->x, surfRelaxPos[k]->y, surfRelaxPos[k]->z, surfRelaxPos[k]->nAtoms, tempSRDist->mult, SRPREC, tempSRDist->nDist, j==k, 0);
}
// for each relaxed shell calc distances between core shells
for (k=0;k<i-nRelaxShells;k++){
tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, curPos->x, curPos->y, curPos->z, curPos->nAtoms, tempSRDist->mult, SRPREC, tempSRDist->nDist, false, 0);
curPos=curPos->nextPos;
}
}
// For each size weight the mult by the size distribution
int startind=0;
if (surfRelaxDist->dist[0]==0){
surfRelaxDist->mult[0]+=p[i-1]*tempSRDist->mult[0];
derivSRD_mu->mult[0]+=derivfSize_mu[i-1]*tempSRDist->mult[0];
derivSRD_sig->mult[0]+=derivfSize_sig[i-1]*tempSRDist->mult[0];
tempSRDist->mult[0]=0;
startind++;
}
for (j=startind;j<tempSRDist->nDist;j++){
surfRelaxDist->mult[j]+=2*p[i-1]*tempSRDist->mult[j];
derivSRD_mu->mult[j]+=2*derivfSize_mu[i-1]*tempSRDist->mult[j];
derivSRD_sig->mult[j]+=2*derivfSize_sig[i-1]*tempSRDist->mult[j];
tempSRDist->mult[j]=0;
}
//memset(tempSRDist->mult, 0, tempSRDist->nDist*sizeof(double));
}
for (j=0; j<nRelaxShells&&j<i;j++){
posPlaceHold[j]=posPlaceHold[j]->nextPos;
}
}
// Consolidate the relaxation distances
if (!err){
surfRelaxDist->ConsolidateDistance();
derivSRD_mu->ConsolidateDistance();
derivSRD_sig->ConsolidateDistance();
}
return err;
}
*/
// Working on this function
//TODO Debug SurfaceRelaxation
int Shape::SurfaceRelaxation(Distance *totSRDist)
{
int err=0, startSize=1, startind=0;
Position *curPos;
Position **surfRelaxPos, **posPlaceHold;
Distance *tempSRDist;
#ifdef DEBUG
cout<<"Entering SurfaceRelaxation\n";
#endif
//Initialize temp surface relax position files
try{
surfRelaxPos=new Position* [nRelaxShells];
for (int i=0;i<nRelaxShells;i++)
surfRelaxPos[i]=new Position();
posPlaceHold = new Position* [nRelaxShells];
tempSRDist = new Distance();
}
catch (exception& e){
printf("\nException found in SurfaceRelaxation alloc: %s\n", e.what());
exit(1);
}
//Initialize surface relax distance files
InitSRDistance(tempSRDist);
InitSRDistance(totSRDist);
//Change startSize
if (distribution=="LogNorm"||distribution=="Gamma"){
/*
//startSize=floor(exp(mu->val-3*sig->val)/GetShapeScaleFactor());
startSize=1;
if (startSize<1||endSize>maxShell){
printf("Needed range of Prob function is not possible with given distances\n");
err=-1;
}
*/
}
else if (distribution=="Delta"){
int shell= CalcDeltaShellSize();
if (shell==-1){
//Do not calculate SR in this case
cout<<"Not Calculating SurfaceRelaxation, Delta size not supported.\n";
startSize=1;
endSize=startSize-1;
}
else{
startSize=shell;
}
}
else{
cout<< "Size Distribution: "<<distribution<<" is not supported in Surface Relaxation.\n";
err=-1;
}
//calculate SR and distances for this shape
printf("Calculating surface relaxation for %s\n", name.c_str());
//Initialize place holder
for (int i=0;i<nRelaxShells;i++)
posPlaceHold[i]=firstPos;
//Copy positions and Apply surface relax
for (int i=startSize; i<=endSize&&!err; i++){
startind=0;
if (distribution=="LogNorm"||distribution=="Gamma"){
for (int j=0;j<nRelaxShells && j<i && !err;j++){
CopyPosition(surfRelaxPos[j],posPlaceHold[j]);
if (type=="sphere"||type=="sphere_Cerv"){
// surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i, f->val, kappa->val);//surfRelaxPos[j]->ApplyRadialSurfaceRelax(i, GetShapeScaleFactor()/(2.0*a->val));
if (n_R==0){
surfRelaxPos[j]->ApplyNormExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), GetShapeShellD()*10.0/2.0);
}
else{
surfRelaxPos[j]->ApplyNormOscExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), n_R->GetVal(), GetShapeShellD()*10.0/2.0);
}
}
else
surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i, f->GetVal(), kappa->GetVal());
surfRelaxPos[j]->ScalePos(a_D[i-1]);
}
}
//Not Tested yet!!
else if (distribution=="Delta"){
Position *tempPos=firstPos;
int shell= CalcDeltaShellSize();
for (int j=0;j<shell-nRelaxShells; j++) tempPos=tempPos->nextPos;
//for (int j=nRelaxShells-1; j>=0&&!err; j--){
for (int j=0;j<nRelaxShells&&!err;j++){
CopyPosition(surfRelaxPos[j], tempPos);
if (type=="sphere"||type=="sphere_Cerv"){
if (n_R==0){
surfRelaxPos[j]->ApplyNormExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), GetShapeShellD()*10.0/2.0);
}
else{
surfRelaxPos[j]->ApplyNormOscExpRadialSurfRelax(i, f->GetVal(), kappa->GetVal(), n_R->GetVal(), GetShapeShellD()*10.0/2.0);
}
}
else
surfRelaxPos[j]->ApplyPlanarSurfaceRelax(i, f->GetVal(), kappa->GetVal());
surfRelaxPos[j]->ScalePos(a_D[i-1]);
tempPos=tempPos->nextPos;
}
}
else{
cout<<"\nERROR in SurfaceRelaxation()\n";
err=-1;
}
//Calculate distances including surface relax shells
if (!err){
for (int j=0;j<nRelaxShells && j<i;j++){
curPos=firstPos;
// for each relaxed shell calc distances between other relaxed shells
for (int k=j;k<nRelaxShells&&k<i;k++){
tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, surfRelaxPos[k]->x, surfRelaxPos[k]->y, surfRelaxPos[k]->z, surfRelaxPos[k]->nAtoms, tempSRDist->mult, float(SRPREC), tempSRDist->nDist, j==k, 0);
}
// for each relaxed shell calc distances between core shells
for (int k=0;k<i-nRelaxShells;k++){
Position tempPos;
CopyPosition(&tempPos, curPos);
//Scale position so can use a(D) and surface relax at same time.
tempPos.ScalePos(a_D[i-1]);
tempSRDist->DebbyCalcSums(surfRelaxPos[j]->x,surfRelaxPos[j]->y,surfRelaxPos[j]->z, surfRelaxPos[j]->nAtoms, tempPos.x, tempPos.y, tempPos.z, tempPos.nAtoms, tempSRDist->mult, float(SRPREC), tempSRDist->nDist, false, 0);
curPos=curPos->nextPos;
}
}
// For each size weight the mult by the size distribution
if (totSRDist->dist[0]==0){
totSRDist->mult[0]+=p[i-1]*tempSRDist->mult[0];
tempSRDist->mult[0]=0;
startind=1;
}
for (int j=startind;j<tempSRDist->nDist;j++){
totSRDist->mult[j]+=2*p[i-1]*tempSRDist->mult[j];
tempSRDist->mult[j]=0;
}
}
//Increase placeholder will not increase more holders than there are shells for the given size
for (int j=0; j<nRelaxShells&& j<i;j++){
posPlaceHold[j]=posPlaceHold[j]->nextPos;
}
}
// Consolidate the relaxation distances
if (!err){
totSRDist->ConsolidateDistance();
}
delete tempSRDist;
for (int i=0;i<nRelaxShells;i++)
delete surfRelaxPos[i];
delete [] surfRelaxPos;
delete [] posPlaceHold;
return err;
}
//Problem in release mode!!
void Shape::CopyPosition(Position* to, Position* from)
{
to->nAtoms=from->nAtoms;
to->shell= from->shell;
to->nextPos=from->nextPos;
if (to->x!=0)
_mm_free (to->x);
to->x= (float *) _mm_malloc (to->nAtoms*sizeof(float),16);
if (to->y!=0)
_mm_free (to->y);
to->y= (float *) _mm_malloc (to->nAtoms*sizeof(float),16);
if (to->z!=0)
_mm_free (to->z);
to->z= (float *) _mm_malloc (to->nAtoms*sizeof(float),16);
if (to->x==0||to->y==0||to->z==0){
printf("\nException found in CopyPosition alloc: error in aligned memory alloc\n");
exit(1);
}
for (int i=0;i<to->nAtoms;i++){
to->x[i]=from->x[i];
to->y[i]=from->y[i];
to->z[i]=from->z[i];
}
}
void Shape::CopyDistance(Distance * to, Distance *from)
{
to->f=from->f;
to->kappa=from->kappa;
to->fileName=from->fileName;
to->shell=from->shell;
to->nDist=from->nDist;
try{
if (to->dist){
delete [] to->dist;
}
if (to->mult){
delete [] to->mult;
}
to->dist=new double [to->nDist];
to->mult=new double [to->nDist];
}
catch(exception &e){
cout<<"Error in CopyDistance: "<<e.what()<<endl;
exit(-1);
}
for (int i=0;i<to->nDist;i++){
to->dist[i]=from->dist[i];
to->mult[i]=from->mult[i];
}
}
void Shape::InitSRDistance(Distance *currSRDist)
{
double maxDistSq, maxDist;
double delD=GetShapeShellD()*10/2.0;
Distance *currDist=firstDist;
for (int i=0;i<endSize-1;i++) currDist=currDist->nextDist;
if (currDist->shell==endSize){
maxDist=currDist->dist[currDist->nDist-1];
maxDist/=2.0;
maxDist=2*sqrt(maxDist*maxDist+2*f->GetVal()*delD*maxDist+f->GetVal()*f->GetVal()*delD*delD);
//Scale by lattice parameter so can use a_D with SR.
maxDist*=a_D[endSize-1];
}
else {
printf("Error in finding maxDist for InitSRDistance\n");
exit(0);
}
maxDistSq=(maxDist+2)*(maxDist+2);
currSRDist->InitDistance((int)(ceil(maxDistSq/SRPREC)));
}
// TODO make recalculation of diffraction pattern slightly more efficient by using preloaded intensities
// As long as lattice param has not changed.
int Shape::CalcPattern()
{
int err=0;
if (!diffPatt){
try{
diffPatt=new Pattern* [Pattern::nLambda];
for (int i=0;i<Pattern::nLambda;i++){
diffPatt[i]=new Pattern(name);
}
}
catch (exception& e){
printf("\nException found in Shape diffPatt initialization: %s\n", e.what());
return -1;
}
}
// Initialize lattice parameter for different size particles
InitLatticeParam();
// Initialize the size distribution
CalcSizeDistribution();
// Load any pre-calculated intensities from file
if (nPreCalcPatts>0){
LoadPatterns();
}
// Calculated then number of SurfaceRelaxation shells and the wieghts of each shell
nRelaxShells=GetNumSRShells();
CalcShellWeights();
cout<<"maxShell: " <<maxShell<<" nRelaxShells: "<<nRelaxShells<<endl;
// Calculate the SurfaceRelaxation distances
if (nRelaxShells>0){
if (surfRelaxDist==0){
try{
surfRelaxDist=new Distance();
}
catch (exception& e){
printf("\nException found in Shape->CalcPattern: %s\n", e.what());
exit(1);
}
}
err=SurfaceRelaxation(surfRelaxDist);
}
else {
if (surfRelaxDist!=0){
delete surfRelaxDist;
surfRelaxDist=0;
}
}
if (!err){
//Calc pattern for each lambda
for (int j=0;j<Pattern::nLambda&&!err;j++){
if(preCalcPatts==0){
//Routines to use when preCalculated patterns are NOT loaded.
if (nParams_a>1){
//Calculates for each size separately, scaling by a(D)
diffPatt[j]->CalcPattern(firstDist,endSize, p, a_D, nRelaxShells, surfRelaxDist, j);
}
else{
//Faster when only using constant lattice parameter because using wShell
diffPatt[j]->CalcPattern(firstDist, endSize, wShell, a[0]->GetVal(), surfRelaxDist, j);
}
}
else{
//Routine to use when precalculated patterns are loaded.
diffPatt[j]->CalcPattern(firstDist,endSize, p, a_D, nRelaxShells, surfRelaxDist, j, preCalcPatts);
}
}
}
return err;
}
//"Diameters" of shapes
double Shape::GetShapeShellD()
{
//Returns the maximum distance stepping for a given shape.
//Currently unitless.
//when multiplied by the lattice parameter in Ang,=>D(nm)
if (type=="tetrahedron") return (2*sqrt(2.0)/10.0);
else if (type=="octahedron") return (2/10.0);
else if (type=="cuboctahedron") return (sqrt(2.0)/10.0);
else if (type=="cube") return (sqrt(3.0)/10.0);
else if (type=="sphere") return (sqrt(2.0)/10.0);//NN Def
else if (type=="sphere_Cerv") return (.7815926418);//Cerv Def
else if (type=="sphereDefFaultAtCenter") return (sqrt(2.0)/10.0);
else if (type=="sphereTwinAtCenter") return (sqrt(2.0)/10.0);
else if (type=="cuboid1x1_1x1_21") return (sqrt(3.31)/10.0);
else if (type=="cuboid1x1_2x1_44") return (sqrt(3.64)/10.0);
else if (type=="icosahedron") return (sqrt(2.0)*(0.95105)*(1.05146)/10.0);
else if (type=="decahedron") return (sqrt(2.0)*(0.8506508)/10.0);
else if (type=="centroDecahedron") return (2*sqrt(2.0)*(0.8506508)/10.0);
else return 0;
}
//"Edge Lengths" of shapes
double Shape::GetShapeShellL()
{
//Returns the maximum distance stepping for a given shape.
//Currently unitless.
//when multiplied by the lattice parameter =>D(units of a)
if (type=="tetrahedron") return (2*sqrt(2.0));
else if (type=="octahedron") return ((sqrt(2.0)));
else if (type=="cuboctahedron") return (1.0/(sqrt(2.0)));
else if (type=="cube") return (1.0);
else if (type=="sphere") return (sqrt(2.0));//NN Def
else if (type=="sphereDefFaultAtCenter") return (sqrt(2.0));
else if (type=="sphereTwinAtCenter") return (sqrt(2.0));
else if (type=="cuboid1x1_1x1_21") return (1.0);
else if (type=="cuboid1x1_2x1_44") return (1.0);
else if (type=="icosahedron") return (1.05146/(sqrt(2.0)));
else if (type=="decahedron") return (1.0/(sqrt(2.0)));
else if (type=="centroDecahedron") return (sqrt(2.0));
//else if (type=="sphere_Cerv") return (.7815926418);//Cerv Def
else return 0;
}
double Shape::CalcTotVol()
{
double vTot=0;
int i;
for (i=1;i<=maxShell; i++)
{
vTot+=p[i-1]*GetUnitlessVolume(i)*a_D[i-1]*a_D[i-1]*a_D[i-1];
}
return vTot;
}
double Shape::GetUnitlessVolume(int n)
{
//Assume Lattice Parameter is unity
//Actual volume is then (Unitless volume) * a^3 (units of a^3)
double vol=0, sideLength=n*GetShapeShellL();
if (type=="tetrahedron"){
vol=sqrt(2.0)*sideLength*sideLength*sideLength/12.0;
}
else if (type =="octahedron"){
vol=sqrt(2.0)*sideLength*sideLength*sideLength/3.0;
}
else if (type=="cuboctahedron"){
vol=5*sqrt(2.0)*sideLength*sideLength*sideLength/3.0;
}
else if (type=="sphere"||type=="sphere_Cerv"||type=="sphereDefFaultAtCenter"||type=="sphereTwinAtCenter"){
vol=PI*sideLength*sideLength*sideLength/6.0;
}
else if (type=="cube"){
vol=sideLength*sideLength*sideLength;
}
else if (type=="cuboid1x1_1x1_21"){
vol=sideLength*1.1*sideLength*1.21*sideLength;
}
else if (type=="cuboid1x1_2x1_44"){
vol=sideLength*1.2*sideLength*1.44*sideLength;
}
else if (type=="icosahedron"){
vol=5*(3+sqrt(5.0))*sideLength*sideLength*sideLength/12.0;
}
else if (type=="decahedron"){
vol=(5+sqrt(5.0))*sideLength*sideLength*sideLength/12.0;
}
else if (type=="centroDecahedron"){
vol=(5+sqrt(5.0))*sideLength*sideLength*sideLength/12.0;
}
return vol;
}
void Shape::CalcNumAtoms()
{
Position *curPos=firstPos;
if (!nA_D){
try{
nA_D=new int [maxShell];
}
catch(exception &e){
cout<<"Exception found in Shape::GetNumAtoms: "<<e.what()<<endl;
}
for (int i=0;i<maxShell;i++){
nA_D[i]=0;
}
int total=0;
for (int i=0;i<maxShell;i++){
total+=curPos->nAtoms;
nA_D[i]=total;
curPos=curPos->nextPos;
}
}
nAtoms=0;
for (int i=0;i<maxShell;i++){
nAtoms+=nA_D[i]*p[i];
}
printf("Number of atoms: %f\n", nAtoms);
}
void Shape::CalcSizeDistribution()
{
if (!a_D){
cout<<"Error in CalcWeights: Lattice Parameter array is not initialized\n";
exit(0);
}
//Use lattice parameter in nanometers
double *a_nm;
try{
if (p){
delete [] p;
}
p = new double [maxShell];
a_nm = new double [maxShell];
}
catch (exception &e){
cout<<"\nException found in CalcWeights: "<<e.what()<<endl;
exit(1);
}
//Initialize arrays
for (int i=0;i<maxShell;i++){
p[i]=0;
a_nm[i]=a_D[i]/10.0;
}
//Check for Diameter Array
if (!D) {
InitDiameterArray();
}
CheckShellThickness();
//Calculate probabilty distribution function (p[i])
if (distribution=="Delta") DeltaDist(&p[0]);
else if(distribution=="LogNorm") LogNormalDist(&D[0], &p[0], &a_nm[0]);
else if (distribution=="Gamma") GammaDist(&D[0], &p[0], &a_nm[0]);
else {
cout<<endl<<"Error: Unsupported Size distribution: "<<distribution<<endl;
exit(0);
}
NormalizeSizeDistribution();
// Get endsize by looking at volume*weights
CalcEndSize();
//Check Number of Surf Relax Shells.
cout<<"Max size cutoff implied: "<<endSize<<endl;
cout<<"Calculating shell weights for "<< name<<endl;
try{
delete [] a_nm;
}
catch(exception &e){
cout<<"Error in CalcSizeDistributions: "<<e.what()<<"\n";
exit(1);
}
}
void Shape::CalcShellWeights()
{
try{
if (wShell){
delete [] wShell;
}
wShell = new double [maxShell];
}
catch (exception &e){
cout<<"\nException found in CalcWeights: "<<e.what()<<endl;
exit(1);
}
for (int i=0;i<maxShell;i++){
wShell[i]=0;
//Weights for shells without SR
for (int j=i+nRelaxShells;j<endSize;j++){
wShell[i]+=p[j];
}
}
}
void Shape::NormalizeSizeDistribution()
{
double tot=0;
for (int i=0;i<maxShell; i++){
tot+=p[i];
}
for (int i=0;i<maxShell; i++){
p[i]/=tot;
}
}
int Shape::WriteIntFileHeader(string _fPath, string _fName)
{
int err=0;
string filename=_fPath+_fName;
ifstream infile;
infile.open(filename.c_str());
if (infile.is_open()) printf("Intensity file %s exists.. Appending Header\n", _fName.c_str());
else printf("Creating Intensity file %s and writing header\n", _fName.c_str());
infile.close();
fstream file(filename.c_str(), ios_base::out|ios_base::app); //|ios_base::trunc);
file.setf(ios::fixed, ios::floatfield);
if (file.is_open()){
if (element!="") file<<"ELEM ";
file<<"SHAPE A DISTRIBUTION ";
if (distribution=="Delta") file<<"SHELLS ";
else if (distribution=="LogNorm") file<<"MU SIGMA ";
if (f!=0&&kappa!=0){
if (f->GetVal()!=0) file<<"SR_F SR_KAPPA ";
}
file<<"WEIGHT";
file<<endl;
if(element!="") file<<element<<" ";
file<<type<<" "<<a_D[maxShell-1]<<" "<<distribution<<" ";
if (distribution=="Delta") file<<deltaSize->GetVal()<<" ";
else if (distribution=="LogNorm") file<<mu->GetVal()<<" "<<sigma->GetVal()<<" ";
if (f!=0&&kappa!=0){
if (f->GetVal()!=0) file<<f->GetVal()<<" "<<kappa->GetVal()<<" ";
}
file<<wShape->GetVal();
file<<endl;
}
else{
printf ("Error writing to file %s\n", filename.c_str());
err=-1;
}
file.close();
return err;
}
void Shape::CalcEndSize()
{
bool stop=false;
int n=0;
double *volWeightSizeDist, maxVal=0;
Position *curPos=firstPos;
try{
volWeightSizeDist=new double [maxShell];
}
catch (exception& e){
printf("\nException found in CalcEndSize: %s\n", e.what());
exit(1);
}
for (int i=0;i<maxShell;i++){
n+=curPos->nAtoms;
volWeightSizeDist[i]=p[i]*n;
maxVal=getmax(maxVal, volWeightSizeDist[i]);
curPos=curPos->nextPos;
}
endSize=maxShell;
for (int i=(maxShell-1);i>=0&&!stop; i--)
{
if (volWeightSizeDist[i]<(.001*maxVal)){
endSize--;
}
else{
stop=true;
}
}
delete [] volWeightSizeDist;
}
double Shape::GammLn(const double xx)
{
// Returns the value ln(Gamma(xx)) for xx>0
//Taken from Numerical Recipes 3rd Edition pg. 257
int j;
double x, tmp, y, ser;
static const double cof[14]={57.1562356658629235, -59.5979603554754912,
14.1360979747417471, -0.491913816097620199, .339946499848118887e-4,
.465236289270485756e-4,-.983744753048795646e-4, .158088703224912494e-3,
-.210264441724104883e-3, .217439618115212643e-3, -.164318106536763890e-3,
.844182239838527433e-4, -.261908384015814087e-4, .368991826595316234e-5};
if (xx<0) throw("bad arg in GammLn");
y=x=xx;
tmp = x+5.2421875000;
tmp = (x+0.5)*log(tmp)-tmp;
ser=0.999999999999997092;
for (j=0;j<14;j++) ser+=cof[j]/++y;
return tmp+log(2.5066282746310005*ser/x);
}
void Shape::GammaDist(double *d, double *P, double *scale)
{
//Param *alpha=0, *beta=0;
if (!alpha||!beta){
cout<<"Uninitialized alpha and beta, cannot calculate Gamma distribution"<<endl;
exit(0);
}
double delD=(d[1]-d[0]);
if (delD==0){
cout<<"Error: shell diameter array in GammaDist"<<endl;
exit(0);
}
double c1=alpha->GetVal()*log(beta->GetVal()), c2=GammLn(alpha->GetVal());
for(int i=0;i<maxShell; i++){
P[i]=c1-c2+(alpha->GetVal()-1)*log(d[i]*scale[i])-(beta->GetVal()*d[i]*scale[i]);
P[i]=exp(P[i]);
if (i==0){
delD=d[i]*scale[i];
}
else{
delD=d[i]*scale[i]-d[i-1]*scale[i-1];
}
P[i]*=delD;
}
}
void Shape::LogNormalDist(double *d, double *P, double *scale)
{
if (!mu||!sigma){
cout<<"Uninitialized mu and sigma, cannot calculate Lognormal distribution"<<endl;
exit(0);
}
double delD=(d[1]-d[0]);
if (delD==0){
cout<<"Error: shell diameter array in LogNormalDist"<<endl;
exit(0);
}
//For other shapes other than spheres Diameter is replaced by the characteristic size parameter (L) in the shape before any strain is applied.
for (int i=0;i<maxShell;i++){
P[i]=exp(-(log(d[i]*scale[i])-mu->GetVal())*(log(d[i]*scale[i])-mu->GetVal())/(2*sigma->GetVal()*sigma->GetVal()))/(d[i]*scale[i]*sigma->GetVal()*sqrt(2*PI));
if (i==0){
delD=d[i]*scale[i];
}
else{
delD=d[i]*scale[i]-d[i-1]*scale[i-1];
}
P[i]*=delD;
}
}
void Shape::DeltaDist(double *P)
{
int shell=CalcDeltaShellSize();
for (int i=0;i<maxShell;i++){
P[i]=0.0;
}
if (shell==-1){
cout<<"\nWARNING: Particle size "<<deltaSize->GetVal()<<" is not supported by Delta Distribution, setting all size probabilities to 0.\n";
}
else{
//Adjust the particle size to a multiple of the shell thickness for clarity.
deltaSize->ChangeVal(shell*a[0]->GetVal()*GetShapeShellL());
cout<<"Delta Size Set to: "<<deltaSize->GetVal()<<endl;
P[shell-1]=1.0;
}
}
void Shape::InitLatticeParam()
{
if (!a_D){
try{
a_D=new double [maxShell];
}
catch(exception &e){
cout<<"Exception in InitLatticeParameter: "<<e.what()<<endl;
exit(1);
}
}
if (a[0]->name.find("Poly")!=string::npos){
PolynomialLatticeParam();
}
else{
ConstantLatticeParam();
}
}
// Generates array of lattice parameter following polynomial a+bx+cx^2
// Diameter of sphere with equivalent volume is used a size parameter
// This is so same lattice parmeter array can be applied to multiple shapes
void Shape::PolynomialLatticeParam()
{
for (int i=0;i<maxShell;i++){
double d=exp(log(GetUnitlessVolume(i+1)*6/PI)/3.0);
a_D[i]=a[0]->GetVal();
double temp=d;
for (int j=1; j<nParams_a;j++){
a_D[i]+=a[j]->GetVal()*temp;
temp*=d;
}
}
}
void Shape::ConstantLatticeParam()
{
for (int i=0;i<maxShell;i++){
a_D[i]=a[0]->GetVal();
}
}
//
void Shape::InitDiameterArray()
{
try{
D=new double [maxShell];
}
catch(exception &e){
cout<<"Exception found in InitDiameterArray: "<<e.what()<<endl;
exit(0);
}
//double deltaD=GetShapeShellD();
double deltaD=GetShapeShellL();
if (!deltaD){
cout<<"Unrecognized shape name in GetShapeShellD: "<<name<<endl;
exit(0);
}
for (int i=0;i<maxShell;i++){
D[i]=(i+1)*deltaD;
}
}
void Shape::CalcDistForShell(Distance *curDist)
{
float minx=0, miny=0, minz=0, maxx=0, maxy=0, maxz=0;
Position *outsideShell=firstPos;
for (int i=1;i<curDist->shell;i++){
outsideShell=outsideShell->nextPos;
}
minx=outsideShell->x[0];
maxx=minx;
miny=outsideShell->y[0];
maxy=miny;
minz=outsideShell->z[0];
maxz=minz;
for (int i=1;i<outsideShell->nAtoms;i++){
maxx=getmax(maxx,outsideShell->x[i]);
minx=getmin(minx,outsideShell->x[i]);
maxy=getmax(maxy,outsideShell->y[i]);
miny=getmin(miny,outsideShell->y[i]);
maxz=getmax(maxz,outsideShell->z[i]);
minz=getmin(minz,outsideShell->z[i]);
}
if (type=="decahedron"){
Position *tempShell=firstPos;
for (int j=1;j<curDist->shell-1;j++){
for (int i=1;i<tempShell->nAtoms;i++){
maxx=getmax(maxx,outsideShell->x[i]);
minx=getmin(minx,outsideShell->x[i]);
maxy=getmax(maxy,outsideShell->y[i]);
miny=getmin(miny,outsideShell->y[i]);
maxz=getmax(maxz,outsideShell->z[i]);
minz=getmin(minz,outsideShell->z[i]);
}
tempShell=tempShell->nextPos;
}
}
curDist->nDist=(int) ceil(((maxx-minx)*(maxx-minx)+(maxy-miny)*(maxy-miny)+(maxz-minz)*(maxz-minz))/DISTPREC)+1;
try{
curDist->dist= new double [curDist->nDist];
curDist->mult=new double [curDist->nDist];
}
catch (exception &e){
cout<<"Error in distance array memory allocation.\n";
exit(1);
}
for (int i=0;i<curDist->nDist;i++){
curDist->dist[i]=sqrt(i*DISTPREC);
curDist->mult[i]=0;
}
Position *curPos=firstPos;
for (int i=1;i<curDist->shell;i++){
curDist->DebbyCalcSums(curPos->x, curPos->y, curPos->z, curPos->nAtoms, outsideShell->x, outsideShell->y, outsideShell->z, outsideShell->nAtoms, curDist->mult, DISTPREC, curDist->nDist, false, 0);
curPos=curPos->nextPos;
}
curDist->DebbyCalcSums(curPos->x, curPos->y, curPos->z, curPos->nAtoms, outsideShell->x, outsideShell->y, outsideShell->z, outsideShell->nAtoms, curDist->mult, DISTPREC, curDist->nDist, true, 0);
curDist->ConsolidateDistance();
for (int i=1; i<curDist->nDist;i++ ){
curDist->mult[i]*=2.0;
}
}
int Shape::GetNumSRShells()
{
// Determine if there is surface relaxation
// Only apply to a shell if the amplitude is as large as the distance precision
if (f!=0&&kappa!=0){
if (f->GetVal()!=0){
//TODO Check that this SR function is correct..
double shellT=GetShapeShellD()*10.0*a_D[maxShell-1]/2.0;
if (shellT==0){
cout<<"Warning: Shape not supported in GetNumSRShells routine, using lattice parameter as shell thickness...\n";
shellT=a_D[maxShell-1];
}
//int nSR=(int)ceil(kappa->GetVal()*log(shellT*abs(f->GetVal())/SRPREC));
//For now just calculate all shells
int nSR=endSize;
if (nSR>maxShell){
cout<<"Warning: surface relaxation extends throughout particle and does not go to zero at center. \n";
nSR=maxShell;
}
if (nRelaxShells>endSize){
nRelaxShells=endSize;
cout<<"Number of Surf. Relax Shells is larger than largest considered particle..\n";
cout<<"Setting Number of Surf. Relax Shells to: "<<nRelaxShells<<endl;
}
else if (nSR<2){
cout<<"Warning: number of surface relaxation shells <2 !!!!"<<endl;
cout<<"Setting number of surface relaxation shells = 2\n";
nSR=2;
}
else{
cout<<"Number of Surface Relaxed Shells = "<<nSR<<endl;
}
return nSR;
//return (int)ceil(-kappa->GetVal()*log(SRPREC));
}
else {
cout<<"No Surface Relaxation applied (f=0)\n";
return 0;
}
}
else{
cout<<"No Surface Relaxation applied (f and/or kappa are uninitialized).\n";
return 0;
}
}
void Shape::CheckSupportedShapes()
{
if (type=="tetrahedron")
;
else if (type=="cuboctahedron")
;
else if (type=="octahedron")
;
else if (type=="sphere")
;
else if (type=="sphere_Cerv")
;
else if (type=="cube")
;
else if (type=="sphereDefFaultAtCenter")
;
else if (type=="sphereTwinAtCenter")
;
else if (type=="cuboid1x1_1x1_21")
;
else if (type=="cuboid1x1_2x1_44")
;
else if (type=="icosahedron")
;
else if (type=="decahedron")
;
else if (type=="centroDecahedron")
;
else {
cout<<"Unsupported Shape Type: "<<type<<endl;
exit(0);
}
}
void Shape::CheckShellThickness()
{
for (int i=1;i<maxShell;i++){
if ((D[i]*a_D[i])<(D[i-1]*a_D[i-1])){
cout<<"Error in Shape::CheckShellThickness(), lattice parameter results in negative shell thickness. "<<i<<endl;
exit(0);
}
}
}
int Shape::CalcDeltaShellSize()
{
//Assuming that lattice parameter is independent of size.
double N=deltaSize->GetVal()/(a[0]->GetVal()*GetShapeShellL());
//Consider +/- 0.5
int shell=getmax((int)N, (int)(N+0.5));
if (shell<1||shell>maxShell){
return -1;
}
else{
return shell;
}
}
int Shape::GetNumSizes()
{
int nSizes=0;
Position *curPos=firstPos;
while(curPos!=0){
nSizes++;
curPos=curPos->nextPos;
}
return nSizes;
}
int Shape::GetIndexOfShell(int shell)
{
int index=0;
Position *curPos=firstPos;
while(curPos!=0){
if (curPos->shell==shell){
return index;
}
else{
index++;
curPos=curPos->nextPos;
}
}
return -1;
}
| [
"[email protected]"
]
| [
[
[
1,
1393
]
]
]
|
04352a99d59ddc1345fd6b4add66dd6ed09b3e88 | 7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b | /vacp/pipeline.h | 7590af4b658d5ce2044f82cb39b9ed7348a44088 | []
| no_license | wangscript/maelstrom-editor | c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31 | 5bfab31bf444f44b9f8209f4deaed8715c305426 | refs/heads/master | 2021-01-10T01:37:00.619456 | 2011-11-21T23:17:08 | 2011-11-21T23:17:08 | 50,160,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 963 | h | #ifndef PIPELINE_H
#define PIPELINE_H
#include <QMap>
#include <content.h>
#include <build.h>
#include <QList>
#define NO_PLUGIN_HEADER
#include <plugin_header/vacp_plugin_common.h>
class BuildContext;
class Package;
class PluginManager;
class QString;
class Pipeline
{
private:
QMap<QString*, ContentExporter*> texture_exporters;
QMap<QString*, ContentCompiler*> texture_compilers;
PluginManager *plugin_manager;
std::list<BuildContext*> ctxs;
QList<BuildContext*> *build_package_internal(Package&, QString&);
public:
Pipeline(QString&);
void build_actor(QString&, QString&);
void build_package(QString&, QString&);
void context_finished(BuildContext *ctx);
void destroy();
void link_package(QString&, QString&);
ContentExporter *get_texture_exporter(QString &exporter_name);
ContentCompiler *get_texture_compiler(QString &compiler_name);
};
#endif // PIPELINE_H
| [
"[email protected]"
]
| [
[
[
1,
39
]
]
]
|
7c4fcc2c8699ce296c4c728872a93bd6d3d7077b | 638c9b075ac3bfdf3b2d96f1dd786684d7989dcd | /visualizer/source/Color.h | 6524df584c4b5b7c85af009da58c283aa98aaaec | []
| no_license | cycle-zz/archives | 4682d6143b9057b21af9845ecbd42d7131750b1b | f92b677342e75e5cb7743a0d1550105058aff8f5 | refs/heads/master | 2021-05-27T21:07:16.240438 | 2010-03-18T08:01:46 | 2010-03-18T08:01:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,747 | h | // start file: Color.h
// #############################################################################
// #
// # Derek Gerstmann
// # [email protected]
// #
// #############################################################################
#ifndef DG_COLOR_H
#define DG_COLOR_H
// headers
#include "DataTypes.h"
// -----------------------------------------------------------------------------
namespace dg
{
// -----------------------------------------------------------------------------
// #############################################################################
// Color - floating point color class with red, green, blue, and alpha components
// #############################################################################
// -----------------------------------------------------------------------------
class Color
{
public:
Color();
Color(Real dR, Real dG, Real dB, Real dA=1.0);
Color(const Color & rkColor);
Real r() const;
Real g() const;
Real b() const;
Real a() const;
Real& r();
Real& g();
Real& b();
Real& a();
Real operator()(UInt uiC) const;
Real operator[](UInt uiC) const;
Real& operator()(UInt uiC);
Real& operator[](UInt uiC);
Real getComponent(UInt uiC) const;
const Color& value();
Real* values();
void set(const Color& v);
void set(Real r, Real g, Real b, Real a=1.0);
void setRed(Real r);
void setGreen(Real g);
void setBlue(Real b);
void setAlpha(Real a);
void setComponent(Real n, UInt c);
void operator=(const Color & rkColor);
Bool operator==(const Color & rkColor) const;
Bool operator!=(const Color & rkColor) const;
Color operator+ (const Color & rkColor) const;
void operator++ (void);
void operator+= (const Color & rkColor);
Color operator- () const;
Color operator- (const Color & rkColor) const;
void operator-- (void);
void operator-= (const Color & rkColor);
Color operator* (const Color & rkColor) const;
void operator*= (const Color & rkColor);
Color operator* (const Int scalar) const;
void operator*= (const Int scalar);
Color operator* (const Real scalar) const;
void operator*= (const Real scalar);
void zero();
void negate();
static const Color BLACK;
static const Color GRAY;
static const Color WHITE;
private:
Real m_adC[4]; // RGBA
}; // end class: Color
//******************************************************************************
Color operator* (Real fScalar, const Color& rkV);
Color Clamp(const Color& rkV, Real fMin, Real fMax);
#include "Color.inc"
//******************************************************************************
} // end namespace: dg
#endif // endif: DG_COLOR_H
// end file: Color.h
| [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
06cb269a91e16857ce219b64dadef5a47d17010b | 999b44927f28a5d5924bd7e552d27d48f66222c0 | /include/Logger.h | 9728b281577d97a900d8ecc2329650542be6fae7 | []
| no_license | zakharov/KDLCollada | 4a9c7e8f6467fa0b8a2458690015b7cc5c22fe4b | 87ef1db551be1727e3608df60d411287085faadc | refs/heads/master | 2021-01-23T05:30:22.283377 | 2011-09-13T11:36:30 | 2011-09-13T11:36:30 | 2,076,603 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,301 | h | /*
Copyright (c) 2011 Alexey Zakharov
email alexey.zakharov at gmail.com
This file is part of KDLColladaParser.
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 LOGGER_H_
#define LOGGER_H_
#include <iosfwd>
#include <sstream>
#include <string>
//! Various defines for logging
#define LOG(level) LOG_BRICS_ ## level
#define LOG_BRICS_DEBUG Logger(Logger::LOGDEBUG).write(__FILE__, __LINE__)
#define LOG_BRICS_INFO Logger(Logger::INFO).write(__FILE__, __LINE__)
#define LOG_BRICS_WARNING Logger(Logger::WARNING).write(__FILE__, __LINE__)
#define LOG_BRICS_ERROR Logger(Logger::LOGERROR).write(__FILE__, __LINE__)
#define LOG_BRICS_FATAL Logger(Logger::FATAL).write(__FILE__, __LINE__)
//! A logging service based on streams.
//!
//! Any class may use LOG() macros to send log output to a
//! predefined source, usually console or a file. Usage is as follows:
//!
//! LOG(INFO) << "some text";
//!
//! The possible log levels are: INFO, WARNING, ERROR and FATAL.
//! One of those levels must always be provided.
//! FATAL will exit the whole application.
//! The logging here is inspired by the Google Logging Library "glog",
//! but in a very simplified form.
//!
//! The Logger class works by creating a new Logger object every time when
//! LOG() is called. When the object is deleted, the actual writing takes place.
class Logger {
public:
//! Enum for possible log levels. Order is important here
enum Loglevel {
LOGDEBUG = 0,
INFO = 1,
WARNING = 2,
LOGERROR = 3, // because windows redefines ERROR
FATAL = 4
};
//! Simple observer class to handle log messages in custom way
class Listener {
public:
virtual void write(Loglevel level, std::string message) = 0;
};
//! Constructor. Logger will only log if level if >= minLoglevel
Logger(Loglevel level);
//! Destructor. Calls flush() if required.
virtual ~Logger();
//! Sets minimum log level. Below \a minLoglevel, nothing will be logged.
static void setMinLoglevel(Loglevel minLoglevel);
//! Returns ths minimum log level. Below \a minLoglevel, nothing is logged.
static Loglevel getMinLoglevel();
//! Writes log output to the file with given \a filename.
static void setLogfile(std::string filename, bool append = false);
//! Sets wether log messages shall include the filename and line of where LOG() was called
static void setUseFilename(bool useFilename);
//! Sets a new listener for log messages.
static void setListener(Listener* listener);
//! Initiates writing log output. The actual writing occurs
//! when the Logger object is deleted.
std::ostream& write(std::string filename, int line);
protected:
//! Writes the logging text to its destination.
void flush();
//! Converts \a loglevel into a string.
std::string& levelToString(Loglevel loglevel);
static Loglevel minLoglevel;
static bool useFilename;
static bool useLogfile;
static std::string logfilename;
static std::ofstream logfile;
static Listener* listener;
std::ostringstream stream;
Loglevel level;
bool isAboveLoglevel;
bool needNewline;
};
#endif // LOGGER_H_
| [
"[email protected]"
]
| [
[
[
1,
107
]
]
]
|
3c61e3c4dde92956f080de4effc72cfa9de37513 | cfc9acc69752245f30ad3994cce0741120e54eac | /bikini/private/source/flash/machine.cpp | 244887136dcf183e3f14194e8ce9fb4d3aabcfdd | []
| no_license | Heartbroken/bikini-iii | 3b7852d1af722b380864ac87df57c37862eb759b | 93ffa5d43d9179b7c5e7f7c2df9df7dafd79a739 | refs/heads/master | 2020-03-28T00:41:36.281253 | 2009-04-30T14:58:10 | 2009-04-30T14:58:10 | 37,190,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,601 | cpp | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008 Viktor Reutzky
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#include "header.hpp"
namespace bk { /*--------------------------------------------------------------------------------*/
namespace flash { /*-----------------------------------------------------------------------------*/
namespace as { /*--------------------------------------------------------------------------------*/
//
static inline uint U8(const byte* &_d) {
u8 l_v = *(u8*)_d; _d += sizeof(u8);
return uint(l_v);
}
static inline uint U16(const byte* &_d) {
u16 l_v = *(u16*)_d; _d += sizeof(u16);
return uint(l_v);
}
static inline sint S16(const byte* &_d) {
byte l_b0 = *(_d++), l_b1 = *(_d++), l_b2 = *(_d++);
return sint(l_b0) | sint(l_b1 << 8) | sint(l_b2 << 16) | ((l_b2 & 0x80) ? sint(0xff << 24) : sint(0x00 << 24));
}
static inline uint U30(const byte* &_d) {
uint l_v = 0; byte l_b = *(_d++); uint l_c = 5;
while(l_c--) {
uint l_s = (4 - l_c) * 7;
l_v |= (l_b & 0x7f) << l_s;
if((l_b & 0x80) == 0) return l_v;
}
return l_v;
}
static inline uint U32(const byte* &_d) {
uint l_v = 0; byte l_b = *(_d++); uint l_c = 5;
while(l_c--) {
uint l_s = (4 - l_c) * 7;
l_v |= (l_b & 0x7f) << l_s;
if((l_b & 0x80) == 0) return l_v;
}
return l_v;
}
static inline uint S32(const byte* &_d) {
sint l_v = 0; byte l_b = *(_d++); uint l_c = 5;
while(l_c--) {
uint l_s = (4 - l_c) * 7;
l_v |= (l_b & 0x7f) << l_s;
if((l_b & 0x80) == 0) {
if((l_b & 0x40) != 0) l_v |= 0xffffff80 << l_s;
return l_v;
}
}
return l_v;
}
static inline rbig F64(const byte* &_d) {
f64 l_v = *(f64*)_d; _d += sizeof(f64);
return rbig(l_v);
}
static inline wstring STRING(const byte* &_d) {
uint l_s0 = U30(_d);
uint l_s1 = MultiByteToWideChar(CP_UTF8, 0, (achar*)_d, (int)l_s0, 0, 0);
wchar* l_w = (wchar*)calloc(l_s1, sizeof(wchar*));
MultiByteToWideChar(CP_UTF8, 0, (achar*)_d, (int)l_s0, l_w, (int)l_s1); _d += l_s0;
return wstring(l_w, l_s1);
}
static inline machine::ns NAMESPACE(const byte* &_d) {
machine::ns l_ns;
l_ns.kind = (machine::ns::nsk::namespace_kind)U8(_d);
l_ns.string = U30(_d);
return l_ns;
}
static inline machine::ns_set NSSET(const byte* &_d) {
machine::ns_set l_ns_set;
uint l_count = U30(_d); l_ns_set.nss.resize(l_count);
for(uint i = 0; i < l_count; ++i) l_ns_set.nss[i] = U32(_d);
return l_ns_set;
}
static inline machine::multiname MULTINAME(const byte* &_d) {
machine::multiname l_multiname;
l_multiname.kind = (machine::multiname::mnk::multiname_kind)U8(_d);
l_multiname.ns = l_multiname.name = l_multiname.ns_set = 0;
switch(l_multiname.kind) {
case machine::multiname::mnk::QName :
case machine::multiname::mnk::QNameA :
l_multiname.ns = U30(_d); l_multiname.name = U30(_d);
break;
case machine::multiname::mnk::RTQName :
case machine::multiname::mnk::RTQNameA :
l_multiname.name = U30(_d);
break;
case machine::multiname::mnk::RTQNameL :
case machine::multiname::mnk::RTQNameLA :
break;
case machine::multiname::mnk::Multiname :
case machine::multiname::mnk::MultinameA :
l_multiname.name = U30(_d); l_multiname.ns_set = U30(_d);
break;
case machine::multiname::mnk::MultinameL :
case machine::multiname::mnk::MultinameLA :
l_multiname.ns_set = U30(_d);
break;
};
return l_multiname;
}
static inline machine::method METHOD(const byte* &_d) {
machine::method l_method;
uint l_param_count = U30(_d);
l_method.return_type = U30(_d);
l_method.param_types.resize(l_param_count);
for(uint i = 0; i < l_param_count; ++i) l_method.param_types[i] = U30(_d);
l_method.name = U30(_d);
l_method.flags = U8(_d);
if(l_method.flags & machine::method::mf::HAS_OPTIONAL) {
uint l_option_count = U30(_d); l_method.options.resize(l_option_count);
for(uint i = 0; i < l_option_count; ++i) {
l_method.options[i].val = U30(_d);
l_method.options[i].kind = (machine::method::option::mok::kind)U8(_d);
}
}
if(l_method.flags & machine::method::mf::HAS_PARAM_NAMES) {
l_method.param_names.resize(l_param_count);
for(uint i = 0; i < l_param_count; ++i) l_method.param_names[i] = U30(_d);
}
l_method.body = bad_ID;
return l_method;
}
static inline machine::metadata METADATA(const byte* &_d) {
machine::metadata l_metadata;
l_metadata.name = U30(_d);
uint l_item_count = U30(_d); l_metadata.items.resize(l_item_count);
for(uint i = 0; i < l_item_count; ++i) {
l_metadata.items[i].key = U30(_d);
l_metadata.items[i].value = U30(_d);
}
return l_metadata;
}
static inline machine::trait TRAIT(const byte* &_d) {
machine::trait l_trait;
l_trait.name = U30(_d);
l_trait.kind = U8(_d);
switch(l_trait.kind & 0xf) {
case machine::trait::itt::Slot :
case machine::trait::itt::Const :
l_trait.slot_id = U30(_d);
l_trait.type_name = U30(_d);
l_trait.vindex = U30(_d);
if(l_trait.vindex != 0) l_trait.vkind = U8(_d);
break;
case machine::trait::itt::Class :
l_trait.slot_id = U30(_d);
l_trait.classi = U30(_d);
break;
case machine::trait::itt::Function :
l_trait.slot_id = U30(_d);
l_trait.function = U30(_d);
break;
case machine::trait::itt::Method :
case machine::trait::itt::Getter :
case machine::trait::itt::Setter :
l_trait.disp_id = l_trait.slot_id = U30(_d);
l_trait.method = U30(_d);
break;
}
if((l_trait.kind >> 4) & machine::trait::ita::Metadata) {
uint l_metadata_count = U30(_d); machine::metadatas l_metadatas; l_metadatas.resize(l_metadata_count);
for(uint i = 0; i < l_metadata_count; ++i) l_metadatas[i] = METADATA(_d);
}
return l_trait;
}
static inline machine::instance INSTANCE(const byte* &_d) {
machine::instance l_instance;
l_instance.name = U30(_d);
l_instance.super_name = U30(_d);
l_instance.flags = U8(_d);
l_instance.protected_ns = (l_instance.flags & machine::instance::oif::ClassProtectedNs) ? U30(_d) : 0;
uint l_intrf_count = U30(_d); l_instance.interfaces.resize(l_intrf_count);
for(uint i = 0; i < l_intrf_count; ++i) l_instance.interfaces[i] = U30(_d);
l_instance.iinit = U30(_d);
uint l_trait_count = U30(_d); l_instance.traits.resize(l_trait_count);
for(uint i = 0; i < l_trait_count; ++i) l_instance.traits[i] = TRAIT(_d);
return l_instance;
}
static inline machine::classinfo CLASS(const byte* &_d) {
machine::classinfo l_classinfo;
l_classinfo.cinit = U30(_d);
uint l_trait_count = U30(_d); l_classinfo.traits.resize(l_trait_count);
for(uint i = 0; i < l_trait_count; ++i) l_classinfo.traits[i] = TRAIT(_d);
return l_classinfo;
}
static inline machine::script SCRIPT(const byte* &_d) {
machine::script l_script;
l_script.init = U30(_d);
uint l_trait_count = U30(_d); l_script.traits.resize(l_trait_count);
for(uint i = 0; i < l_trait_count; ++i) l_script.traits[i] = TRAIT(_d);
return l_script;
}
static inline machine::methodbody METHODBODY(const byte* &_d) {
machine::methodbody l_methodbody;
l_methodbody.method = U30(_d);
l_methodbody.max_stack = U30(_d);
l_methodbody.local_count = U30(_d);
l_methodbody.init_scope_depth = U30(_d);
l_methodbody.max_scope_depth = U30(_d);
uint l_code_length = U30(_d); l_methodbody.code.resize(l_code_length);
for(uint i = 0; i < l_code_length; ++i) l_methodbody.code[i] = (byte)U8(_d);
uint l_exception_count = U30(_d); l_methodbody.exceptions.resize(l_exception_count);
for(uint i = 0; i < l_exception_count; ++i) {
machine::methodbody::exception &l_exception = l_methodbody.exceptions[i];
l_exception.from = U30(_d);
l_exception.to = U30(_d);
l_exception.target = U30(_d);
l_exception.exc_type = U30(_d);
l_exception.var_name = U30(_d);
}
uint l_trait_count = U30(_d); l_methodbody.traits.resize(l_trait_count);
for(uint i = 0; i < l_trait_count; ++i) l_methodbody.traits[i] = TRAIT(_d);
return l_methodbody;
}
//
// machine
machine::machine() {
// @@@
new_object();
set_object_prop(0, L"", 0, 10);
object_ref l_object;
l_object.ID = new_object();
set_object_prop(0, L"Object", l_object);
l_object.ID = new_object();
set_object_prop(0, L"EventDispatcher", l_object);
l_object.ID = new_object();
set_object_prop(0, L"DisplayObject", l_object);
l_object.ID = new_object();
set_object_prop(0, L"InteractiveObject", l_object);
l_object.ID = new_object();
set_object_prop(0, L"DisplayObjectContainer", l_object);
l_object.ID = new_object();
set_object_prop(0, L"Sprite", l_object);
l_object.ID = new_object();
set_object_prop(0, L"MovieClip", l_object);
}
machine::~machine() {
while(!m_segments.empty()) {
delete m_segments.back();
m_segments.pop_back();
}
}
bool machine::do_ABC(pointer _data, uint _size, bool _run/* = true*/) {
segment &l_segment = * new segment(*this, _data, _size);
m_segments.push_back(&l_segment);
if(_run) {
l_segment.run_script();
//assert(0);
}
return true;
}
uint machine::new_object() {
m_objects.push_back(object());
m_objects.back().set_ID(m_objects.size() - 1);
return m_objects.back().ID();
}
void machine::set_object_prop(uint _ID, const wstring &_name, const value &_value, uint _slot) {
m_objects[_ID].set(_name, _value, _slot);
}
const machine::value& machine::get_object_prop(uint _ID, uint _slot) {
return m_objects[_ID].get(_slot);
}
const machine::value& machine::get_object_prop(uint _ID, const wstring &_name) {
return m_objects[_ID].get(_name);
}
// machine::object
void machine::object::set(const wstring &_name, const value &_value, uint _slot) {
if(_slot != bad_ID) {
if(_slot >= m_props.size()) m_props.resize(_slot + 1);
prop &l_p = m_props[_slot];
l_p.n = _name; l_p.v = _value;
return;
}
for(uint i = 0, s = m_props.size(); i < s; ++i) {
prop &l_p = m_props[i];
if(l_p.n == _name) {
l_p.v = _value;
return;
}
}
prop l_p; l_p.n = _name; l_p.v = _value;
m_props.push_back(l_p);
}
const machine::value& machine::object::get(uint _slot) {
if(_slot < m_props.size()) {
return m_props[_slot].v;
}
static value sl_bad_value;
return sl_bad_value;
}
const machine::value& machine::object::get(const wstring &_name) {
for(uint i = 0, s = m_props.size(); i < s; ++i) {
if(m_props[i].n == _name) return m_props[i].v;
}
static value sl_bad_value;
return sl_bad_value;
}
// machine::segment
machine::segment::segment(machine &_machine, pointer _data, uint _size) : m_machine(_machine) {
const byte* l_data = (byte*)_data;
uint l_minor = U16(l_data);
uint l_major = U16(l_data);
if(l_major > 46) {
std::cerr << "ERROR: Wrong ActionScript 3.0 Byte Code version. Version 46.16 is expected\n";
return;
}
// int constants
uint l_int_count = U30(l_data); m_ints.resize(l_int_count);
for(uint i = 1; i < l_int_count; ++i) m_ints[i] = S32(l_data);
// uint constants
uint l_uint_count = U30(l_data); m_uints.resize(l_uint_count);
for(uint i = 1; i < l_uint_count; ++i) m_uints[i] = U32(l_data);
// double constants
uint l_double_count = U30(l_data); m_doubles.resize(l_double_count);
for(uint i = 1; i < l_double_count; ++i) m_doubles[i] = F64(l_data);
// string constants
uint l_string_count = U30(l_data); m_strings.resize(l_string_count);
for(uint i = 1; i < l_string_count; ++i) m_strings[i] = STRING(l_data);
// namespace constants
uint l_namespace_count = U30(l_data); m_namespaces.resize(l_namespace_count);
for(uint i = 1; i < l_namespace_count; ++i) m_namespaces[i] = NAMESPACE(l_data);
// ns_set constants
uint l_ns_set_count = U30(l_data); m_ns_sets.resize(l_ns_set_count);
for(uint i = 1; i < l_ns_set_count; ++i) m_ns_sets[i] = NSSET(l_data);
// multiname constants
uint l_multiname_count = U30(l_data); m_multinames.resize(l_multiname_count);
for(uint i = 1; i < l_multiname_count; ++i) m_multinames[i] = MULTINAME(l_data);
// methods
uint l_method_count = U30(l_data); m_methods.resize(l_method_count);
for(uint i = 0; i < l_method_count; ++i) m_methods[i] = METHOD(l_data);
// metadata
uint l_metadata_count = U30(l_data); metadatas l_metadatas; l_metadatas.resize(l_metadata_count);
for(uint i = 0; i < l_metadata_count; ++i) l_metadatas[i] = METADATA(l_data);
// classes
uint l_class_count = U30(l_data);
m_instances.resize(l_class_count); m_classinfos.resize(l_class_count);
for(uint i = 0; i < l_class_count; ++i) m_instances[i] = INSTANCE(l_data);
for(uint i = 0; i < l_class_count; ++i) m_classinfos[i] = CLASS(l_data);
// scripts
uint l_script_count = U30(l_data); m_scripts.resize(l_script_count);
for(uint i = 0; i < l_script_count; ++i) m_scripts[i] = SCRIPT(l_data);
// methods bodies
uint l_methodbody_count = U30(l_data); m_methodbodys.resize(l_methodbody_count);
for(uint i = 0; i < l_methodbody_count; ++i) {
methodbody &l_methodbody = m_methodbodys[i]; l_methodbody = METHODBODY(l_data);
m_methods[l_methodbody.method].body = i;
}
//
int a=0;
}
void machine::segment::run_script(uint _index) const {
assert(!m_scripts.empty());
uint l_index = _index < m_scripts.size() ? _index : m_scripts.size() - 1;
const script &l_script = m_scripts[l_index];
for(uint i = 0, s = l_script.traits.size(); i < s; ++i) {
const trait &l_t = l_script.traits[i];
if(l_t.slot_id > 0) {
value l_v = m_machine.get_object_prop(0, l_t.slot_id);
if(l_v.type() == bad_ID) {
const multiname &l_mn = m_multinames[l_t.name];
const wstring &l_name = m_strings[l_mn.name];
const ns &l_ns = m_namespaces[l_mn.ns];
const wstring &l_namespace = m_strings[l_ns.string];
m_machine.set_object_prop(0, l_name, 0, l_t.slot_id);
}
}
}
const method &l_method = m_methods[l_script.init];
env l_env;
object_ref l_global; l_global.ID = 0;
l_env.locals.push_back(l_global);
run(l_method.body, l_env);
}
void machine::segment::run(uint _methodbody, env &_env) const {
const byte* l_code = &m_methodbodys[_methodbody].code[0];
value l_result;
bool l_run = true;
while(l_run) {
opcode::opcodes l_op = (opcode::opcodes)U8(l_code);
switch(l_op) {
case opcode::add : {
} continue;
case opcode::add_i : {
} continue;
case opcode::astype : {
} continue;
case opcode::astypelate : {
} continue;
case opcode::bitand : {
} continue;
case opcode::bitnot : {
} continue;
case opcode::bitor : {
} continue;
case opcode::bitxor : {
} continue;
case opcode::call : {
} continue;
case opcode::callmethod : {
} continue;
case opcode::callproperty : {
} continue;
case opcode::callproplex : {
} continue;
case opcode::callpropvoid : {
} continue;
case opcode::callstatic : {
} continue;
case opcode::callsuper : {
} continue;
case opcode::callsupervoid : {
} continue;
case opcode::checkfilter : {
} continue;
case opcode::coerce : {
} continue;
case opcode::coerce_a : {
} continue;
case opcode::coerce_s : {
} continue;
case opcode::construct : {
} continue;
case opcode::constructprop : {
} continue;
case opcode::constructsuper : {
} continue;
case opcode::convert_b : {
} continue;
case opcode::convert_i : {
} continue;
case opcode::convert_d : {
} continue;
case opcode::convert_o : {
} continue;
case opcode::convert_u : {
} continue;
case opcode::convert_s : {
} continue;
case opcode::debug : {
} continue;
case opcode::debugfile : {
} continue;
case opcode::debugline : {
} continue;
case opcode::declocal : {
} continue;
case opcode::declocal_i : {
} continue;
case opcode::decrement : {
} continue;
case opcode::decrement_i : {
} continue;
case opcode::deleteproperty : {
} continue;
case opcode::divide : {
} continue;
case opcode::dup : {
_env.stack.push_back(_env.stack.back());
} continue;
case opcode::dxns : {
} continue;
case opcode::dxnslate : {
} continue;
case opcode::equals : {
} continue;
case opcode::esc_xattr : {
} continue;
case opcode::esc_xelem : {
} continue;
case opcode::findproperty : {
uint l_index = U30(l_code);
const multiname &l_mn = m_multinames[l_index];
const wstring &l_name = m_strings[l_mn.name];
const ns &l_ns = m_namespaces[l_mn.ns];
const wstring &l_namespace = m_strings[l_ns.string];
value l_v;
} continue;
case opcode::findpropstrict : {
} continue;
case opcode::getdescendants : {
} continue;
case opcode::getglobalscope : {
_env.stack.push_back(_env.scope[0]);
} continue;
case opcode::getglobalslot : {
} continue;
case opcode::getlex : {
uint l_index = U30(l_code);
const multiname &l_mn = m_multinames[l_index];
const wstring &l_name = m_strings[l_mn.name];
const ns &l_ns = m_namespaces[l_mn.ns];
const wstring &l_namespace = m_strings[l_ns.string];
value l_v;
for(uint i = _env.scope.size(); i-- > 0;) {
assert(_env.scope[i].type() == types::type_<object_ref>::index);
l_v = m_machine.get_object_prop(_env.scope[i].get<object_ref>().ID, l_name);
if(l_v.type() != bad_ID) break;
}
_env.stack.push_back(l_v);
int a=0;
} continue;
case opcode::getlocal : {
} continue;
case opcode::getlocal_0 : {
_env.stack.push_back(_env.locals[0]);
} continue;
case opcode::getlocal_1 : {
_env.stack.push_back(_env.locals[1]);
} continue;
case opcode::getlocal_2 : {
_env.stack.push_back(_env.locals[2]);
} continue;
case opcode::getlocal_3 : {
_env.stack.push_back(_env.locals[3]);
} continue;
case opcode::getproperty : {
} continue;
case opcode::getscopeobject : {
uint l_index = U8(l_code);
_env.stack.push_back(_env.scope[l_index]);
} continue;
case opcode::getslot : {
uint l_index = U8(l_code);
value l_o = _env.stack.back(); _env.stack.pop_back();
assert(l_o.type() == types::type_<object_ref>::index);
value l_v = m_machine.get_object_prop(l_o.get<object_ref>().ID, l_index);
_env.stack.push_back(l_v);
int a=0;
} continue;
case opcode::getsuper : {
} continue;
case opcode::greaterequals : {
} continue;
case opcode::greaterthan : {
} continue;
case opcode::hasnext : {
} continue;
case opcode::hasnext2 : {
} continue;
case opcode::ifeq : {
} continue;
case opcode::iffalse : {
} continue;
case opcode::ifge : {
} continue;
case opcode::ifgt : {
} continue;
case opcode::ifle : {
} continue;
case opcode::iflt : {
} continue;
case opcode::ifnge : {
} continue;
case opcode::ifngt : {
} continue;
case opcode::ifnle : {
} continue;
case opcode::ifnlt : {
} continue;
case opcode::ifne : {
} continue;
case opcode::ifstricteq : {
} continue;
case opcode::ifstrictne : {
} continue;
case opcode::iftrue : {
} continue;
case opcode::in : {
} continue;
case opcode::inclocal : {
} continue;
case opcode::inclocal_i : {
} continue;
case opcode::increment : {
} continue;
case opcode::increment_i : {
} continue;
case opcode::initproperty : {
uint l_index = U30(l_code);
const multiname &l_mn = m_multinames[l_index];
const wstring &l_name = m_strings[l_mn.name];
const ns &l_ns = m_namespaces[l_mn.ns];
const wstring &l_namespace = m_strings[l_ns.string];
value l_v = _env.stack.back(); _env.stack.pop_back();
value l_o = _env.stack.back(); _env.stack.pop_back();
assert(l_o.type() == types::type_<object_ref>::index);
m_machine.set_object_prop(l_o.get<object_ref>().ID, l_name, l_v);
int a=0;
} continue;
case opcode::instanceof : {
} continue;
case opcode::istype : {
} continue;
case opcode::istypelate : {
} continue;
case opcode::jump : {
} continue;
case opcode::kill : {
uint l_index = U30(l_code);
_env.locals[l_index] = value();
} continue;
case opcode::label : {
} continue;
case opcode::lessequals : {
} continue;
case opcode::lessthan : {
} continue;
case opcode::lookupswitch : {
} continue;
case opcode::lshift : {
} continue;
case opcode::modulo : {
} continue;
case opcode::multiply : {
} continue;
case opcode::multiply_i : {
} continue;
case opcode::negate : {
} continue;
case opcode::negate_i : {
} continue;
case opcode::newactivation : {
} continue;
case opcode::newarray : {
} continue;
case opcode::newcatch : {
} continue;
case opcode::newclass : {
uint l_index = U30(l_code);
const classinfo& l_ci = m_classinfos[l_index];
value l_base = _env.stack.back(); _env.stack.pop_back();
object_ref l_class; l_class.ID = m_machine.new_object();
for(uint i = 0, s = l_ci.traits.size(); i < s; ++i) {
const trait &l_t = l_ci.traits[i];
if(l_t.slot_id > 0) {
value l_v = m_machine.get_object_prop(l_class.ID, l_t.slot_id);
if(l_v.type() == bad_ID) {
const multiname &l_mn = m_multinames[l_t.name];
const wstring &l_name = m_strings[l_mn.name];
const ns &l_ns = m_namespaces[l_mn.ns];
const wstring &l_namespace = m_strings[l_ns.string];
m_machine.set_object_prop(l_class.ID, l_name, 0, l_t.slot_id);
}
}
}
_env.stack.push_back(l_class);
//
const method &l_method = m_methods[l_ci.cinit];
env l_env;
l_env.locals.push_back(l_class);
run(l_method.body, l_env);
//
int a=0;
} continue;
case opcode::newfunction : {
} continue;
case opcode::newobject : {
} continue;
case opcode::nextname : {
} continue;
case opcode::nextvalue : {
} continue;
case opcode::nop : {
} continue;
case opcode::not : {
} continue;
case opcode::pop : {
} continue;
case opcode::popscope : {
_env.scope.pop_back();
} continue;
case opcode::pushbyte : {
uint l_byte = U8(l_code);
_env.stack.push_back(l_byte);
} continue;
case opcode::pushdouble : {
} continue;
case opcode::pushfalse : {
} continue;
case opcode::pushint : {
} continue;
case opcode::pushnamespace : {
} continue;
case opcode::pushnan : {
} continue;
case opcode::pushnull : {
} continue;
case opcode::pushscope : {
_env.scope.push_back(_env.stack.back());
_env.stack.pop_back();
} continue;
case opcode::pushshort : {
} continue;
case opcode::pushstring : {
} continue;
case opcode::pushtrue : {
} continue;
case opcode::pushuint : {
} continue;
case opcode::pushundefined : {
} continue;
case opcode::pushwith : {
} continue;
case opcode::returnvalue : {
l_result = _env.stack.back(); _env.stack.pop_back();
l_run = false;
} continue;
case opcode::returnvoid : {
l_run = false;
} continue;
case opcode::rshift : {
} continue;
case opcode::setlocal : {
} continue;
case opcode::setlocal_0 : {
if(_env.locals.size() <= 0) _env.locals.resize(0 + 1);
_env.locals[0] = _env.stack.back(); _env.stack.pop_back();
} continue;
case opcode::setlocal_1 : {
if(_env.locals.size() <= 1) _env.locals.resize(1 + 1);
_env.locals[1] = _env.stack.back(); _env.stack.pop_back();
} continue;
case opcode::setlocal_2 : {
if(_env.locals.size() <= 2) _env.locals.resize(2 + 1);
_env.locals[2] = _env.stack.back(); _env.stack.pop_back();
} continue;
case opcode::setlocal_3 : {
if(_env.locals.size() <= 3) _env.locals.resize(3 + 1);
_env.locals[3] = _env.stack.back(); _env.stack.pop_back();
} continue;
case opcode::setglobalslot : {
} continue;
case opcode::setproperty : {
uint l_index = U30(l_code);
const multiname &l_mn = m_multinames[l_index];
const wstring &l_name = m_strings[l_mn.name];
const ns &l_ns = m_namespaces[l_mn.ns];
const wstring &l_namespace = m_strings[l_ns.string];
value l_v = _env.stack.back(); _env.stack.pop_back();
value l_o = _env.stack.back(); _env.stack.pop_back();
assert(l_o.type() == types::type_<object_ref>::index);
m_machine.set_object_prop(l_o.get<object_ref>().ID, l_name, l_v);
int a=0;
} continue;
case opcode::setslot : {
} continue;
case opcode::setsuper : {
} continue;
case opcode::strictequals : {
} continue;
case opcode::subtract : {
} continue;
case opcode::subtract_i : {
} continue;
case opcode::swap : {
} continue;
case opcode::throw_ : {
} continue;
case opcode::typeof : {
} continue;
case opcode::urshift : {
} continue;
default : {
assert(0);
l_run = false;
}
}
}
}
} /* namespace as -------------------------------------------------------------------------------*/
} /* namespace flash ----------------------------------------------------------------------------*/
} /* namespace bk -------------------------------------------------------------------------------*/
| [
"my.mass.storage@f4697e32-284f-0410-9ba2-936c71724aef"
]
| [
[
[
1,
790
]
]
]
|
566dd6549ab38027bae4cf3f50e90809033d57d2 | 8bb0a1d6c74f3a17d90c64d9ee40ae5153d15acb | / cs191-nds-project/splash_screen/CS191_Project/include/Projects/CSpriteRotations.h | de50e25c008b35ae3726b83f54b514fd0b50db3a | []
| no_license | btuduri/cs191-nds-project | 9b12382316c0a59d4e48acd7f40ed55c5c4cde41 | 146b2218cc53f960a034d053238a4cf111726279 | refs/heads/master | 2020-03-30T19:13:10.122474 | 2008-05-19T02:26:19 | 2008-05-19T02:26:19 | 32,271,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | #ifndef CSPRITEROTATIONS_H_
#define CSPRITEROTATIONS_H_
#pragma once
#include "ProjectLib.h"
#include "CMovableSprite.h"
#include "../graphics/projects/sprite_rotation.h"
class CSpriteRotations : public CMovableSprite
{
public:
virtual ~CSpriteRotations();
void initSprite();
void update();
private:
bool locked;
};
#endif /*CSPRITEROTATIONS_H_*/
| [
"kingofcode@67d8362a-e844-0410-8493-f333cf7aaa27"
]
| [
[
[
1,
21
]
]
]
|
8a3be539ff641b50cb544c29bada22c6105d602c | e354a51eef332858855eac4c369024a7af5ff804 | /routingtag.cpp | 5a68858fd35acf5b81a5069a44288141daa98739 | []
| no_license | cjus/msgCourierLite | 0f9c1e05b71abf820c55f74a913555eec2267bb4 | 9efc1d54737ba47620a03686707b31b1eeb61586 | refs/heads/master | 2020-04-05T22:41:39.141740 | 2010-09-05T18:43:12 | 2010-09-05T18:43:12 | 887,172 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | cpp | /* routingtag.cpp
Copyright (C) 2006 Carlos Justiniano
[email protected], [email protected], [email protected]
routingtag.cpp 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.
routingtag.cpp was developed by Carlos Justiniano for use on the
msgCourier project and the ChessBrain Project and is now 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 routingtag.cpp; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/**
@file routingtag.cpp
@brief Routing Tag
@author Carlos Justiniano
@attention Copyright (C) 2006 Carlos Justiniano, GNU GPL Licence (see source file header)
*/
#include "exception.h"
#include "log.h"
#include "routingtag.h"
using namespace std;
cRoutingTag::cRoutingTag()
{
}
cRoutingTag::~cRoutingTag()
{
}
const char* cRoutingTag::GetTag()
{
return m_sFullTag.c_str();
}
const char* cRoutingTag::GetTagName()
{
return m_sTagName.c_str();
}
const char* cRoutingTag::GetTagIPAddr()
{
return m_sTagIPAddr.c_str();
}
const char* cRoutingTag::GetTagPort()
{
return m_sTagPort.c_str();
}
void cRoutingTag::SetTag(const char *pTag)
{
string tag = pTag;
string::size_type at_idx = tag.find("@");
string::size_type colon_idx = tag.find(":");
// handle tag name
if (at_idx != string::npos && at_idx > 0)
m_sTagName = tag.substr(0, at_idx);
else
{
if (at_idx == string::npos && colon_idx == string::npos)
{
m_sTagName = pTag;
m_sFullTag = m_sTagName;
return;
}
else
{
m_sTagName = "unknown";
}
}
// handle port address
if (colon_idx != string::npos && colon_idx > 0)
m_sTagPort = tag.substr(colon_idx+1);
else
m_sTagPort = "0000";
// handle IP address
int iplen = colon_idx - at_idx - 1;
if (iplen > 0)
{
m_sTagIPAddr = tag.substr(at_idx+1, iplen);
}
else
{
string::size_type dot_idx = tag.find(".");
if (dot_idx != string::npos)
{
m_sTagIPAddr = tag;
}
else
{
m_sTagIPAddr = "0.0.0.0";
}
}
BuildFullTag();
}
void cRoutingTag::SetTagName(const char *pTagName)
{
m_sTagName = pTagName;
BuildFullTag();
}
void cRoutingTag::SetTagIPAddr(const char *pIPAddr)
{
m_sTagIPAddr = pIPAddr;
BuildFullTag();
}
void cRoutingTag::SetTagPort(const char *pPort)
{
m_sTagPort = pPort;
BuildFullTag();
}
void cRoutingTag::BuildFullTag()
{
stringstream sstag (stringstream::in | stringstream::out);
sstag << m_sTagName << "@" << m_sTagIPAddr << ":" << m_sTagPort;
m_sFullTag = sstag.str();
}
| [
"[email protected]"
]
| [
[
[
1,
138
]
]
]
|
9f72e7c43333621bccd8ac8b89bc0db6ea15907d | 975e3cacad2b513dff73ddd5ce3d449ad40c293b | /babel-2014-minett_a/trunk/portaudio/AudioCallback.cpp | 12e0de27fb0a9ab20568a683fccb86a2194d8ce0 | []
| no_license | alex-min/babelroxor | 08a2babfbd1cf51dcfcba589d9acc7afcebee6e3 | 53cbdedd7d4b68943fe99d74dbb5443b799cca05 | refs/heads/master | 2021-01-10T14:24:12.257931 | 2011-12-13T10:57:30 | 2011-12-13T10:57:30 | 46,981,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,083 | cpp | #include "AudioHandler.h"
#include "AudioCallback.h"
#include "audiothread.h"
using namespace Audio2;
int PortaudioWrapper::SendEncode(const void *inputBuffer,
void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData)
{
SpeexBuffer *s = (SpeexBuffer *)userData;
short *tmp = new short[framesPerBuffer];
short *ib = (short *)inputBuffer;
if (s->state == ENCODING)
{
for (unsigned int i = 0; i < framesPerBuffer; i++, ib++)
{
tmp[i] = *ib;
}
//s->buf = new char[s->encoder->FrameSize() + 1];
s->size_encoded = s->encoder->Encode(tmp, s->buf);
delete tmp;
std::list<std::string> const & loglist = AudioThreadSingleton::getInstance()->getLoginList();
if (loglist.size() != 0)
{
for (std::list<std::string>::const_iterator it = loglist.begin(); it != loglist.end(); ++it)
{
Protocol::getInstance()->send((*it), Protocol::AUDIO, (void *)s->buf, s->size_encoded);
}
}
AudioThreadSingleton::getInstance()->freeLoginList();
}
return (0);
}
int PortaudioWrapper::ReceiveDecode(const void *inputBuffer,
void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo*,
PaStreamCallbackFlags,
void *userData)
{
SpeexBuffer *s = (SpeexBuffer *)userData;
short *tmp;
short *ob = (short *)outputBuffer;
if (s->state == DECODING)
{
tmp = s->decoder->Decode(s->buf, s->size_encoded);
for (unsigned int i = 0; i < framesPerBuffer; i++, ob++)
{
*ob = tmp[i];
}
//delete s->buf;
s->state = ENCODING;
}
return (0);
}
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
7
],
[
9,
18
],
[
21,
21
],
[
23,
27
],
[
29,
37
],
[
39,
41
],
[
43,
44
],
[
47,
55
],
[
57,
60
],
[
62,
63
],
[
65,
66
]
],
[
[
3,
3
],
[
8,
8
],
[
19,
20
],
[
22,
22
],
[
28,
28
],
[
38,
38
],
[
42,
42
],
[
56,
56
],
[
61,
61
],
[
64,
64
]
],
[
[
45,
46
]
]
]
|
a31236796459f0dc66ee99149ce9f0345f866e2a | 5dfa2f8acf81eb653df4a35a76d6be973b10a62c | /trunk/Community_Core_Vision/addons/ofxCameraBase/inc/ofxCameraBaseSettings.h | 1531413e609db2e76827a476404aef313db3f747 | []
| no_license | guozanhua/ccv-multicam | d69534ff8592f7984a5eadc83ed8b20b9d3df949 | 31206f0de7f73b3d43f2a910fdcdffb7ed1bf2c2 | refs/heads/master | 2021-01-22T14:24:52.321877 | 2011-08-31T14:18:44 | 2011-08-31T14:18:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | h | /*
* ofxCameraBaseSettings.h
*
*
* Created on 12/03/11.
* Copyright 2011 NUI Group. All rights reserved.
* Author: Anatoly Churikov
*
*/
#ifndef OFX_CAMERABASE_SETTINGS_H
#define OFX_CAMERABASE_SETTINGS_H
#include <vector>
#include "vector2d.h"
#include <windows.h>
typedef enum
{
BASE_BRIGHTNESS,
BASE_EXPOSURE,
BASE_SHARPNESS,
BASE_WHITE_BALANCE,
BASE_HUE,
BASE_SATURATION,
BASE_GAMMA,
BASE_SHUTTER,
BASE_GAIN,
BASE_IRIS,
BASE_FOCUS,
BASE_ZOOM,
BASE_PAN,
BASE_FRAMERATE
} CAMERA_BASE_FEATURE;
typedef struct ofxCameraBaseSettings
{
GUID cameraGuid;
unsigned char cameraDepth;
int cameraWidth,cameraHeight,cameraLeft,cameraTop,cameraIndex;
bool videoPlayerOn,videoRecorderOn;
std::vector<bool> isPropertyOn;
std::vector<bool> isPropertyAuto;
std::vector<int> propertyFirstValue;
std::vector<int> propertySecondValue;
std::vector<CAMERA_BASE_FEATURE> propertyType;
std::vector<vector2df > calibrationPoints;
} ofxCameraBaseSettings;
#endif // OFX_CAMERABASE_SETTINGS_H | [
"[email protected]@da66ed7f-4d6a-8cb4-a557-1474cfe16edc"
]
| [
[
[
1,
50
]
]
]
|
e220d73c4a8e061e87b958d0594c24e61366389c | 6fa6532d530904ba3704da72327072c24adfc587 | /SCoder/QtGUI/sources/opencontainerpage.cpp | d5fe0d34dd16178e6d117a4cb01d80385f204394 | []
| 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 | 3,071 | cpp | ////////////////////////////////////////////////////////////////////////////////
#include "opencontainerpage.h"
////////////////////////////////////////////////////////////////////////////////
#include <cassert>
#include <QPushButton>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QLineEdit>
#include <QVariant>
#include "scoderwizard.h"
////////////////////////////////////////////////////////////////////////////////
OpenContainerPage::OpenContainerPage( QWidget* _parent /* = NULL */ )
: QWizardPage(_parent)
{
// Set title
setTitle(tr("Open container"));
setSubTitle(tr("You can open a BMP image or a WAV sound file.\n" \
"Note: only 24-bit images and 16-bit audio files are supported!"));
// Create open file button
m_Open = new QPushButton(tr("&Browse..."));
m_Open->setMaximumSize(100,30);
// Create line edit for displaying filename
m_FileName = new QLineEdit;
m_FileName->setReadOnly(true);
// Setup layout
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(m_Open);
layout->addWidget(m_FileName);
setLayout(layout);
registerField("OpenFileName*", m_FileName);
registerField("ContainerType", this);
// Connect signal to slot
connect( m_Open, SIGNAL( clicked() ), this, SLOT( OpenFile() ) );
}
////////////////////////////////////////////////////////////////////////////////
OpenContainerPage::~OpenContainerPage()
{
}
////////////////////////////////////////////////////////////////////////////////
int OpenContainerPage::nextId() const
{
// If hide mode -- go to enter text page
if ( field("IsHideMessageMode").toBool() )
return SCoderWizard::ENTER_TEXT_PAGE;
else
{
// Chose algorithm
switch ( static_cast<ContainerType>( field("ContainerType").toInt() ) )
{
case IMAGE:
return SCoderWizard::IMAGE_ALGORITHM;
case SOUND:
return SCoderWizard::SOUND_ALGORITHM;
default:
assert(0);
return 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////
void OpenContainerPage::OpenFile()
{
// Show open file dialog
QString fn = QFileDialog::getOpenFileName(this,
tr("Open File..."),
QString(),
tr("Images, Sounds (*.bmp *.wav)") );
// Display file name
if (!fn.isEmpty())
{
// Set container type
if ( fn.endsWith(".bmp", Qt::CaseInsensitive) )
setField("ContainerType", static_cast<int>(IMAGE) );
else if ( fn.endsWith(".wav", Qt::CaseInsensitive) )
setField("ContainerType", static_cast<int>(SOUND) );
// Set file name
m_FileName->setText(fn);
}
}
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]@8592428e-0b6d-11de-9036-69e38a880166"
]
| [
[
[
1,
109
]
]
]
|
239b53d4fe050f07a1eadbc1d821f5e868fa0717 | c96abf2a459249393cd9646f728646c8247071c0 | /SkylineSolver/DenseMatrix.cpp | 8ef2c44f1d009e19eaf45c2690cd290b27f511b7 | []
| no_license | yf2009017/Treu-Structure | 4d0ad2d79fca4183e39f155a90da1511b448104d | f33069c78f924ec7c8fe98a495ee3884da9d1ec9 | refs/heads/master | 2021-01-16T19:21:11.606153 | 2011-08-20T19:17:15 | 2011-08-20T19:17:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,729 | cpp | // SparseMatrix.cpp: implementation of the SparseMatrix class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "DenseMatrix.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
namespace Canguro {
namespace Analysis {
namespace Solver {
DenseMatrix::DenseMatrix(int rows, int cols)
{
init();
setSize(rows, cols);
}
DenseMatrix::!DenseMatrix()
{
delete[] m;
}
double& DenseMatrix::item (int row, int col)
{
if (transpose)
return m[col*cols+row];
else
return m[row*cols+col];
}
int DenseMatrix::getCols()
{
if (transpose)
return rows;
else
return cols;
}
int DenseMatrix::getRows()
{
if (transpose)
return cols;
else
return rows;
}
void DenseMatrix::setTranspose(bool trans)
{
transpose = trans;
}
DenseMatrix^ DenseMatrix::operator *(DenseMatrix^ m2)
{
DenseMatrix^ res = gcnew DenseMatrix();
if (getCols() == m2->getRows())
{
res->setSize(getRows(), m2->getCols());
int i, j, k;
double sum;
for (i=0; i<res->rows; i++)
for (j=0; j<res->cols; j++)
{
for (k=0, sum=0; k<getCols(); k++)
sum += item(i, k) * m2->item(k, j);
res->item(i, j) = sum;
}
}
return res;
}
DenseMatrix::DenseMatrix(DenseMatrix^ msrc)
{
cols = msrc->cols;
rows = msrc->rows;
transpose = msrc->transpose;
int size = rows*cols;
m = new double[size];
CopyMemory(m, msrc->m, size * sizeof(double));
}
DenseMatrix::DenseMatrix()
{
init();
}
System::String^ DenseMatrix::ToString()
{
int i, j, k;
System::Text::StringBuilder^ sb = gcnew System::Text::StringBuilder();
char buf[50];
for (i=0, k=0; i<rows; i++)
{
for (j=0; j<cols; j++, k++)
{
sb->Append(m[k].ToString());
sb->Append("\t");
}
sb->Append("\n\r");
}
return sb->ToString();
}
void DenseMatrix::setSize(int rows, int cols)
{
if ((this->rows != rows) || (this->cols != cols))
{
this->rows = rows;
this->cols = cols;
if (m) delete[] m;
m = new double[rows*cols];
}
ZeroMemory(m, rows*cols*sizeof(double));
}
DenseMatrix^ DenseMatrix::operator =(DenseMatrix^ msrc)
{
int oldSize = cols*rows;
cols = msrc->cols;
rows = msrc->rows;
transpose = msrc->transpose;
int size = rows*cols;
if (size != oldSize)
{
if (m) delete[] m;
m = new double[size];
}
CopyMemory(m, msrc->m, size * sizeof(double));
return this;
}
void DenseMatrix::init()
{
cols = 0;
rows = 0;
transpose = false;
m = NULL;
}
void DenseMatrix::setRowCol(int rowcol, double val, double diag)
{
int i;
if (cols == rows)
{
for (i=0; i<cols; i++)
if (i != rowcol)
item(i, rowcol) = item(rowcol, i) = val;
else
item(i, i) = diag;
}
}
double* DenseMatrix::getRowPtr(int row)
{
if (transpose)
return NULL;
return &m[row*cols];
}
void DenseMatrix::operator+=(DenseMatrix^ m2)
{
if ((getCols() == m2->getCols()) && (getRows() == m2->getRows()))
{
for (int i=0; i<rows*cols; i++)
m[i] += m2->m[i];
}
}
void DenseMatrix::Jacobi(DenseMatrix ^w2, DenseMatrix ^V, double tolerance, int maxit)
{
if (rows == cols) // debe ser una matriz cuadrada
{
int neq = rows;
int i, j, k;
double sum = 0.0, ssum, amax, aa, si, co, tol, tt;
V->setSize(rows, rows);
tol = fabs(tolerance);
for (i=0; i<neq; i++)
{
for (j=0; j<neq; j++)
{
if (tolerance > 0.0)
V->item(i, j) = 0.0;
sum += fabs(item(i, j));
}
if (tolerance > 0.0)
V->item(i, i) = 1.0;
}
if (neq == 0) return;
if (sum <= 0.0) return;
sum /= (double)(neq*neq);
do
{
ssum = 0.0;
amax = 0.0;
for (j=1; j<neq; j++)
for (i=0; i<j; i++)
{
aa = fabs(item(i, j));
if (aa > amax) amax = aa;
ssum += aa;
if (aa>=0.1*amax)
{
aa = atan2(2.0*item(i, j), item(i, i)-item(j, j)) / 2.0;
si = sin(aa);
co = cos(aa);
for (k=0; k<neq; k++)
{
tt = item(k, i);
item(k, i) = co*tt + si*item(k, j);
item(k, j) = -si*tt + co*item(k, j);
tt = V->item(k, i);
V->item(k, i) = co*tt + si*V->item(k, j);
V->item(k, j) = -si*tt + co*V->item(k, j);
}
item(i, i) = co*item(i, i) + si*item(j, i);
item(j, j) = -si*item(i, j) + co*item(j, j);
item(i, j) = 0.0;
for (k=0; k<neq; k++)
{
item(i, k) = item(k, i);
item(j, k) = item(k, j);
}
} // If
} // For j, i
} while (((fabs(ssum)/sum) > tol) && --maxit);
// Copiar eigenvalores a w2
w2->setSize(1, neq);
for (i=0; i<neq; i++)
w2->item(0, i) = item(i, i);
} // If
}
void DenseMatrix::cutRows(int newRows)
{
rows = (newRows<rows)?newRows:rows;
}
double DenseMatrix::DotProductRow(int rowLeft, DenseMatrix^ matRight, int rowRight)
{
double dot = 0.0;
if (matRight->getCols() != getCols())
throw gcnew System::InvalidOperationException("Cannot apply a dot product to vectors of different size");
for (int i=0; i<getCols(); i++)
dot += this[rowLeft, i] * matRight[rowRight, i];
return dot;
}
double DenseMatrix::DotProductCol(int colLeft, DenseMatrix^ matRight, int colRight)
{
double dot = 0.0;
if (matRight->getRows() != getRows())
throw gcnew System::InvalidOperationException("Cannot apply a dot product to vectors of different size");
for (int i=0; i<getRows(); i++)
dot += this[i, colLeft] * matRight[i, colRight];
return dot;
}
}
}
} | [
"[email protected]"
]
| [
[
[
1,
291
]
]
]
|
69514ce97f7d3e13718e38de99939c68fe9cfc72 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /LemonPlayer_2nd/Source/ImageLib/src/ImageRotator.cpp | 8f49aac8428cf587a577f21cc31b0f097fe56f6f | []
| no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,603 | cpp | /*
============================================================================
Name : ImageRotator.cpp
Author :
Version : 1.0
Copyright : Your copyright notice
Description : CImageRotator implementation
============================================================================
*/
#include <w32std.h>
#include <bitstd.h>
#include <bitdev.h>
#include <libc\math.h>
#include "ImageRotator.h"
#include "MacroUtil.h"
#define PI 3.1415926
CImageRotator::CImageRotator(CFbsBitmap *aSrcBitmap, TInt aDegree,
TRgb aBackColor) :
iSrcBitmap(aSrcBitmap), iDegree(aDegree), iBackColor(aBackColor)
{
// No implementation required
}
CImageRotator::~CImageRotator()
{
SAFE_DELETE(iTransparent);
SAFE_DELETE(iBitmap);
}
CImageRotator* CImageRotator::NewLC(CFbsBitmap *aSrcBitmap, TInt aDegree,
TRgb aBackColor)
{
CImageRotator* self = new (ELeave)CImageRotator(aSrcBitmap,aDegree, aBackColor);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CImageRotator* CImageRotator::NewL(CFbsBitmap *aSrcBitmap, TInt aDegree,
TRgb aBackColor)
{
CImageRotator* self=CImageRotator::NewLC(aSrcBitmap, aDegree, aBackColor);
CleanupStack::Pop(); // self;
return self;
}
void CImageRotator::ConstructL()
{
iBitmap = new ( ELeave ) CFbsBitmap();
// CleanupStack::PushL(iBitmap);
CalculateSize();
User::LeaveIfError(iBitmap->Create(iSize, iSrcBitmap->DisplayMode()) );
// SetBackColor();
CopyPixel();
iTransparent = CTransparentBitmap::NewL(iBitmap,KRgbMagenta);
}
void CImageRotator::CalculateSize()
{
iRadian = (2* PI *iDegree)/360;
sine = sin(iRadian);
cosine = cos(iRadian);
TInt width = iSrcBitmap->SizeInPixels().iWidth;
TInt height = iSrcBitmap->SizeInPixels().iHeight;
TInt x0 = 0;
TInt y0 = 0;
TInt x1 = (int)(height * sine);
TInt y1 = (int)(height * cosine);
TInt x2 = (int)(width * cosine + height * sine);
TInt y2 = (int)(height * cosine - width * sine);
TInt x3 = (int)(width * cosine);
TInt y3 = (int)(-width * sine);
minx = Min(x0, Min(x1, Min(x2, x3)));
miny = Min(y0, Min(y1, Min(y2, y3)));
maxx = Max(x0, Max(x1, Max(x2, x3)));
maxy = Max(y0, Max(y1, Max(y2, y3)));
iSize.iWidth = maxx - minx;
iSize.iHeight = maxy - miny;
if (minx < 0)
{
iDx = -minx;
}
if (miny < 0)
{
iDy = -miny;
}
}
void CImageRotator::SetBackColor()
{
CFbsBitmapDevice *iGD = CFbsBitmapDevice::NewL(iBitmap);
CleanupStack::PushL(iGD);
CFbsBitGc *iGC;
User::LeaveIfError(iGD->CreateContext(iGC) );
iGC->SetPenStyle(CGraphicsContext::ENullPen);
iGC->SetBrushColor(iBackColor);
iGC->SetBrushStyle(CGraphicsContext::ESolidBrush);
iGC->DrawRect(TRect(TPoint(0, 0), iBitmap->SizeInPixels()) );
iGC->SetBrushStyle(CGraphicsContext::ENullBrush);
delete iGC;
CleanupStack::PopAndDestroy(iGD);
}
void CImageRotator::CopyPixel()
{
TInt width = iSrcBitmap->SizeInPixels().iWidth;
TInt height = iSrcBitmap->SizeInPixels().iHeight;
TUint16* src = (TUint16*)iSrcBitmap->DataAddress();
TUint16* dest = (TUint16*)iBitmap->DataAddress();
sine = -sine;
TBitmapUtil orig_util(iSrcBitmap);
TBitmapUtil dest_util(iBitmap);
orig_util.Begin(TPoint(0, 0));
dest_util.Begin(TPoint(0, 0), orig_util);
for (TInt y=miny; y<maxy; y++)
for (TInt x=minx; x<maxx; x++)
{
TInt srcx = (TInt)(x*cosine + y*sine);
TInt srcy = (TInt)(y*cosine - x*sine);
TInt destx = x+iDx;
TInt desty = y+iDy;
if (srcx>=width || srcx<0 || srcy>=height || srcy<0)
{
}
else
{
orig_util.SetPos(TPoint(srcx, srcy));
dest_util.SetPos(TPoint(destx, desty));
dest_util.SetPixel(orig_util);
}
}
orig_util.End();
dest_util.End();
sine = -sine;
}
CFbsBitmap* CImageRotator::Bitmap()
{
return iBitmap;
}
void CImageRotator::SetRetatePos(TInt aRotatePosX, TInt aRotatePosY)
{
iRotatePosX = (TInt)(aRotatePosX*cosine + aRotatePosY*sine)-aRotatePosX;
iRotatePosY = (TInt)(aRotatePosY*cosine - aRotatePosX*sine)-aRotatePosY;
}
void CImageRotator::SetRetateCenter()
{
SetRetatePos(iSize.iWidth>>1,iSize.iHeight>>1);
}
void CImageRotator::Draw(CFbsBitGc& gc, TInt aX, TInt aY)
{
// gc.BitBlt(TPoint(aX-iDx-iRotatePosX, aY-iDy-iRotatePosY), iBitmap);
iTransparent->Draw(gc,aX-iDx-iRotatePosX,aY-iDy-iRotatePosY);
}
void CImageRotator::DrawCenter(CFbsBitGc& gc, TInt aX, TInt aY)
{
TInt x = aX-(iSize.iWidth>>1);
TInt y = aY-(iSize.iHeight>>1);
// gc.BitBlt(TPoint(x, y), iBitmap);
iTransparent->Draw(gc,x,y);
}
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
180
]
]
]
|
082badf4234fa1480a5925eb3657f1771fb6b930 | 0b1111e870b496aae0d6210806eebf1c942c9d3a | /LinearAlgebra/zgeev_jacobi.cpp | 40d77115f3b9302772ebd1adffbca78b761dbdc0 | [
"WTFPL"
]
| permissive | victorliu/Templated-Numerics | 8ca3fabd79435fa40e95e9c8c944ecba42a0d8db | 35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9 | refs/heads/master | 2016-09-05T16:32:22.250276 | 2009-12-30T07:48:03 | 2009-12-30T07:48:03 | 318,857 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,800 | cpp | #include <cstddef>
#include <cmath>
#include <complex>
#include <iostream>
// A non-parallel implementation of:
// A parallel algorithm for the eigenvalues
// and eigenvectors of a general complex matrix
// by Guatam M. Shroff
// Numerische Mathematik 58, pages 779-805 (1991)
// The matrix is only reduced to upper triangular form,
// but in practice it is always diagonal.
// Returns the unitary transformation parameters
// Returns the reduction in lower triangular norm
static inline double
pnrj_unitary(size_t n, size_t lda, std::complex<double> *A, size_t p, size_t q, std::complex<double> cs[3]){
std::complex<double> Apq = A[p+q*lda];
double aApq2 = std::norm(Apq);
if(0 != aApq2){
std::complex<double> Aqp = A[q+p*lda];
std::complex<double> dpq = 0.5*(A[p+p*lda] - A[q+q*lda]);
std::complex<double> root = sqrt(dpq*dpq + Apq*Aqp);
std::complex<double> dmax_plus = dpq + root;
std::complex<double> dmax_minus = dpq - root;
std::complex<double> dmax;
if(std::norm(dmax_plus) > std::norm(dmax_minus)){
dmax = dmax_plus;
}else{
dmax = dmax_minus;
}
// At this point we should choose
// tan x = exp(i theta) Apq/dmax
// such that theta makes tan x real
// The resulting parameters are then
// [ cs[0] cs[2] ]
// [ cs[1] cs[3] ]
// where
// cs[0] = cs[3] = cos x, cs[1] = exp(i theta) sin x
// cs[2] = -exp(-i theta) sin x
//
// Thus, tan x = std::abs(Apq/dmax)
dmax = Apq/dmax; // we use dmax as Aqp/dmax
double tanx = std::abs(dmax);
std::complex<double> exp_i_theta = tanx/dmax; // this is actually exp(-i theta)
if(tanx > 1){ tanx = 1; } // limit the maximum rotation angle
// Now cos^2 = 1/(1+tan^2), sin^2 = tan^2 cos^2
cs[0] = double(1)/sqrt(tanx*tanx+1);
//cs[3] = cs[0];
cs[1] = tanx*cs[0]; // cs[1] = sin x
cs[2] = cs[1];
cs[1] *= exp_i_theta;
cs[2] /= -exp_i_theta;
}else{
cs[0] = 1; // cs[3] = cs[0];
cs[1] = cs[2] = 0;
}
return aApq2;
}
static inline double
pnrj_shear(size_t n, size_t lda, std::complex<double> *A, size_t p, size_t q, std::complex<double> cs[3]){
double Gpq = 0;
std::complex<double> cpq(0);
for(size_t j = 0; j < n; ++j){
cpq += (A[p+j*lda]*std::conj(A[q+j*lda]) - std::conj(A[j+p*lda])*A[j+q*lda]);
if(j == p || j == q){ continue; }
double Gterm = 0;
Gterm += std::norm(A[p+j*lda]);
Gterm += std::norm(A[q+j*lda]);
Gterm += std::norm(A[j+p*lda]);
Gterm += std::norm(A[j+q*lda]);
Gpq += Gterm;
}
std::complex<double> dpq = A[q+q*lda] - A[p+p*lda];
// xi_pq = exp(i alpha) Aqp + exp(-i alpha) Apq
// alpha = arg(cpq) - pi/2
// Thus, xi_pq = -i exp(i arg(cpq)) Aqp + i exp(-i arg(cpq)) Apq
// But exp(i arg(cpq)) is simply cpq/|cpq|
double acpq = std::abs(cpq);
if(0 == acpq){
cs[0] = 1;
cs[1] = cs[2] = 0;
return 0;
}
std::complex<double> eialpha = std::complex<double>(0,-1)*(cpq/acpq);
std::complex<double> xipq = eialpha*A[q+p*lda] + A[p+q*lda]/eialpha;
// Now, we will generate the transformation
// [ cs[0] cs[2] ]
// [ cs[1] cs[3] ]
// where
// cs[0] = cs[3] = cosh y,
// cs[1] = i exp(-i alpha) sinh y
// cs[2] = -i exp( i alpha) sinh y
// and
// tanh y = -|cpq| / (2*(|dpq|^2 + |xipq|^2) + Gpq)
double tanhy = -acpq / (2*(std::norm(dpq) + std::norm(xipq)) + Gpq);
// cosh^2 - sinh^2 = 1, tanh = sinh/cosh
double coshy = double(1)/sqrt(double(1) - tanhy*tanhy);
cs[0] = coshy; // cs[3] = cs[0]
double sinhy = coshy*tanhy;
cs[1] = std::complex<double>(0, sinhy)/eialpha;
cs[2] = std::complex<double>(0,-sinhy)*eialpha;
return 0;
}
static inline double
pnrj_diagonal(size_t n, size_t lda, std::complex<double> *A, size_t j, double *t){
double g = 0;
double h = 0;
for(size_t i = 0; i < n; ++i){
if(i == j){ continue; }
g += std::norm(A[i+j*lda]);
h += std::norm(A[j+i*lda]);
}
g = sqrt(g); h = sqrt(h);
*t = sqrt(h/g);
static const double tlimit = 1e8;
if(*t > tlimit){
*t = tlimit;
h = tlimit*tlimit*g;
}else if(*t < double(1)/tlimit){
*t = double(1)/tlimit;
g = h/(tlimit*tlimit);
}
// Compute the estimate of norm reduction
g -= h;
return g*g;
}
inline static void
pnrj_apply_rotation_L(size_t n, size_t lda, std::complex<double>* A, size_t p, size_t q, std::complex<double> cs[3]){
// Apply rotation to matrix A, A' = J^{-1} A
for (size_t j = 0; j < n; j++){
std::complex<double> Apj = A[p+j*lda];
std::complex<double> Aqj = A[q+j*lda];
A[p+j*lda] = Apj * cs[0] - Aqj * cs[2];
A[q+j*lda] = -Apj * cs[1] + Aqj * cs[0]; // cs[3]
}
}
inline static void
pnrj_apply_rotation_R(size_t n, size_t lda, std::complex<double>* A, size_t p, size_t q, std::complex<double> cs[3]){
// Apply rotation to matrix A, A' = A J
for(size_t i = 0; i < n; i++){
std::complex<double> Aip = A[i+p*lda];
std::complex<double> Aiq = A[i+q*lda];
A[i+p*lda] = Aip * cs[0] + Aiq * cs[1];
A[i+q*lda] = Aip * cs[2] + Aiq * cs[0]; // cs[3]
}
}
inline static void
pnrj_diagonal_L(size_t n, size_t lda, std::complex<double>* A, size_t j, double t){
t = (double)1/t;
// Apply diagonal to matrix A, A' = A J
for(size_t i = 0; i < n; i++){
A[j+i*lda] *= t;
}
}
inline static void
pnrj_diagonal_R(size_t n, size_t lda, std::complex<double>* A, size_t j, double t){
// Apply diagonal to matrix A, A' = A J
for(size_t i = 0; i < n; i++){
A[i+j*lda] *= t;
}
}
int zgeev_jacobi(size_t n, size_t lda, std::complex<double>* A, std::complex<double>* eval, size_t ldvec, std::complex<double>* evec, unsigned int max_iter, unsigned int *nrot){
for(size_t p = 0; p < n; ++p){
for(size_t q = 0; q < n; ++q){
if(p == q){
evec[q+p*ldvec] = 1;
}else{
evec[q+p*ldvec] = 0;
}
}
eval[p] = 0;
}
double normL = std::numeric_limits<double>::max();
double normL_prev;
const double normL_threshold = n*n/2 * std::numeric_limits<double>::epsilon();
size_t iter = 0;
do{
normL_prev = normL;
// Compute the Frobenius norm of the lower triangle
normL = 0;
for(size_t q = 0; q < n-1; ++q){ // column
for(size_t p = q+1; p < n; ++p){
double absLpq2 = std::norm(A[p+q*lda]);
normL += absLpq2;
}
}
normL = sqrt(normL);
std::cout << "norm = " << normL << std::endl;
if(normL < normL_threshold){
break;
}
// Perform a sweep
// A sweep is a set of rotations followed by a set of diagonal
// transformations. A rotation is a shear followed by a unitary
// transformation. Rotations are performed on all subdiagonal
// elements, while diagonal transformations are applied to each
// element of the diagonal.
// Apply all rotations
for(size_t q = 0; q < n-1; ++q){
for(size_t p = q+1; p < n; ++p){
std::complex<double> cs[3];
pnrj_shear(n, lda, A, p, q, cs);
pnrj_apply_rotation_L(n, lda, A, p, q, cs);
pnrj_apply_rotation_R(n, lda, A, p, q, cs);
pnrj_apply_rotation_R(n, ldvec, evec, p, q, cs);
pnrj_unitary(n, lda, A, p, q, cs);
pnrj_apply_rotation_L(n, lda, A, p, q, cs);
pnrj_apply_rotation_R(n, lda, A, p, q, cs);
pnrj_apply_rotation_R(n, ldvec, evec, p, q, cs);
}
}
// Apply all diagonal transformations
for(size_t j = 0; j < n; ++j){
double t;
pnrj_diagonal(n, lda, A, j, &t);
pnrj_diagonal_L(n, lda, A, j, t);
pnrj_diagonal_R(n, lda, A, j, t);
pnrj_diagonal_R(n, ldvec, evec, j, t);
}
// max_iter ~<~ 2 + 2.8 log2(n)
}while(iter++ <= max_iter);
*nrot = iter;
for(size_t p = 0; p < n; p++){
eval[p] = A[p+p*lda];
}
if(iter == max_iter){ return 1; }
return 0;
}
void print(size_t rows, size_t lda, std::complex<double> *A){
std::cout << "{";
for(size_t i = 0; i < rows; ++i){
std::cout << "{";
for(size_t j = 0; j < rows; ++j){
std::cout << A[i+j*lda];
if(j != rows-1){
std::cout << ", ";
}
}
std::cout << "}";
if(i != rows-1){
std::cout << ",";
}
std::cout << std::endl;
}
std::cout << "}";
}
void print(size_t n, std::complex<double> *V){
std::cout << "{";
for(size_t i = 0; i < n; ++i){
std::cout << V[i];
if(i != n-1){
std::cout << ", ";
}
}
std::cout << "}";
}
void makesym(size_t rows, size_t lda, std::complex<double> *A){
for(size_t i = 0; i < rows; ++i){
for(size_t j = i+1; j < rows; ++j){
std::complex<double> v = 0.5*(A[i+j*lda]+A[j+i*lda]);
A[i+j*lda] = A[j+i*lda] = v;
}
}
}
void makeid(size_t rows, size_t lda, std::complex<double> *A){
for(size_t i = 0; i < rows; ++i){
for(size_t j = 0; j < rows; ++j){
if(i == j){
A[j+i*lda] = 1;
}else{
A[j+i*lda] = 0;
}
}
}
}
double frand(){
return (double)rand()/(double)RAND_MAX;
}
int main(){
srand(time(0));
size_t n = 4;
std::complex<double> *A = new std::complex<double>[n*n];
for(size_t i = 0; i < n; ++i){
for(size_t j = 0; j < n; ++j){
A[i+j*n] = std::complex<double>(frand(), frand());
}
}
/*
makeid(n,n,A);
A[1+0*n] = frand();
A[2+1*n] = frand();
A[2+0*n] = frand();
makesym(n,n,A);
*/
//print(n,n,A); std::cout << std::endl;
std::complex<double> *evals = new std::complex<double>[n];
std::complex<double> *evecs = new std::complex<double>[n*n];
size_t nrot;
size_t max_iter = (int)(2+2.8*log((double)n)/log(2.0));
if(max_iter < 8){ max_iter = 8; }
std::cout << "theoretical num sweeps = " << max_iter << std::endl;
zgeev_jacobi(n,n,A,evals,n,evecs, max_iter, &nrot);
print(n,n,A); std::cout << std::endl;
//print(n,evals); std::cout << std::endl;
//print(n,n,evecs); std::cout << std::endl;
delete [] A;
delete [] evecs;
delete [] evals;
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
351
]
]
]
|
2060427e72cc31ee4a8a1fc2a38c689d82233bb8 | 3920e5fc5cbc2512701a3d2f52e072fd50debb83 | /Source/Common/itkManagedObjectAutoPtr.cxx | ed975cc3fe4b63c019ca56d672bdfd04389f5d62 | [
"MIT"
]
| permissive | amirsalah/manageditk | 4063a37d7370dcbcd08bfe9d24d22015d226ceaf | 1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761 | refs/heads/master | 2016-08-12T05:38:03.377086 | 2010-08-02T08:17:32 | 2010-08-02T08:17:32 | 52,595,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,889 | cxx | /*=============================================================================
Project: ManagedITK
Program: Insight Segmentation & Registration Toolkit
Module: itkManagedObjectAutoPtr.cxx
Language: C++/CLI
Author: Dan Mueller
Date: $Date: 2008-03-09 19:29:02 +0100 (Sun, 09 Mar 2008) $
Revision: $Revision: 8 $
This file was based on the following article:
"Best Practices for Writing Efficient and Reliable Code with C++/CLI"
by Kenny Kerr (May 2006)
http://msdn.microsoft.com/library/en-us/dnvs05/html/CplusCLIBP.asp
Copyright (c) 2007-2008 Daniel Mueller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=============================================================================*/
#pragma once
#pragma warning( disable : 4635 ) // Disable warnings about XML doc comments
#ifndef __itkObjectAutoPtr_cxx
#define __itkObjectAutoPtr_cxx
using namespace System::Diagnostics;
namespace itk
{
template <typename T>
ref struct itkObjectAutoPtr
{
private:
T* m_ptr;
bool m_disposed;
public:
itkObjectAutoPtr( ) : m_ptr( NULL ), m_disposed( false ) { }
itkObjectAutoPtr( T* ptr ) : m_ptr( ptr ), m_disposed( false )
{
if ( ptr != NULL )
ptr->Register( );
}
itkObjectAutoPtr( itkObjectAutoPtr<T>% right ) : m_ptr( right.Release() ), m_disposed( false ) { }
//~itkObjectAutoPtr()
//{
// if (!m_disposed) Reset();
// m_disposed = true;
//}
//!itkObjectAutoPtr()
//{
// // Dispose of the managed pointer if the user forgot
// if ( !m_Disposed )
// delete this;
//}
T* operator->( )
{
return m_ptr;
}
T* Get( )
{
return m_ptr;
}
T* Release( )
{
T* released = m_ptr;
m_ptr = NULL;
return released;
}
void Reset( )
{
Reset( NULL );
}
void Reset(T* ptr)
{
try
{
if ( m_ptr != NULL && ptr != m_ptr )
{
// Free the existing native pointer
m_ptr->RemoveAllObservers( );
m_ptr->SetReferenceCount( 0 );
}
// Set the new native pointer (sets to NULL if ptr = NULL)
m_ptr = ptr;
// Register the new pointer to keep it alive
if ( m_ptr != NULL )
{
m_ptr->Register( );
}
}
catch (...)
{
// HACK: Consume the exception, even though it is bad practice.
// NOTE: This method tends to throw System.AccessViolationExceptions,
// probably because the memory has been previously freed.
}
}
};
} // end namespace itk
#endif
| [
"dan.muel@a4e08166-d753-0410-af4e-431cb8890a25"
]
| [
[
[
1,
131
]
]
]
|
4b8794d02a9ad0431af71799095b004e3b115a34 | bbc02822aeffdfaa8050907c1d9bd41ff4e9f3f3 | /MinecraftPSP/MinecraftPSP/Display.h | b1f4bf31cdb8030af8cade4b590351ba16541ea9 | []
| no_license | DragonNeos/minecraft-psp | 5184361c0beab2a4a25d789ba24a5cf185ef18cf | fde4e012c8ecc94f52bf222738f29e5efac47d0e | refs/heads/master | 2020-03-26T15:06:44.654834 | 2011-03-01T09:38:49 | 2011-03-01T09:38:49 | 40,795,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | h | // Author: Mouhamad Abdallah
// Date: 29 December 2010 (Modified by Mouhamad Abdallah Tuesday 8th February 2011)
// Modifications: All modifications are documented via Repository on google-code page
#ifndef DISPLAY_H
#define DISPLAY_H
#include <stdlib.h>
class Display
{
public:
int window;
float width, height;
Display();
void enableTextures();
void disableTextures();
void enableTransparency();
void disableTransparency();
void enableCulling();
void disableCulling();
void initialise();
void initialise(float width, float height);
void smoothShading();
void flatShading();
void cullFront();
void cullBack();
void cullBoth();
void resetOrigin();
void translate(float x, float y, float z);
void rotate(float rotationAngle, float x, float y, float z);
void pushMatrix();
void popMatrix();
void update();
void clearBuffers();
};
#endif | [
"[email protected]"
]
| [
[
[
1,
46
]
]
]
|
360d884a0cef5994f2a8c4e7e541d889f76afbf5 | a36d7a42310a8351aa0d427fe38b4c6eece305ea | /core_billiard/Geometry.h | 973873a9285912dbe9bcc9edbab3dd582c20a7c1 | []
| no_license | newpolaris/mybilliard01 | ca92888373c97606033c16c84a423de54146386a | dc3b21c63b5bfc762d6b1741b550021b347432e8 | refs/heads/master | 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | h | #pragma once
namespace my_render {
MY_INTERFACE Geometry : EXTENDS_INTERFACE( Base ), EXTENDS_INTERFACE( Displayable ) {
virtual GeometryMesh * getMesh() PURE;
};
}
| [
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
]
| [
[
[
1,
12
]
]
]
|
6b9993693e58f5cf075fcf30dc7003960f00f7e8 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/src/MyGUI_Button.cpp | 8d8a1bada0b1b1ed604bc4e93745e6b7a5f791f0 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,227 | cpp | /*!
@file
@author Albert Semenov
@date 11/2007
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_Button.h"
#include "MyGUI_ResourceSkin.h"
#include "MyGUI_StaticImage.h"
#include "MyGUI_InputManager.h"
namespace MyGUI
{
Button::Button() :
mIsMousePressed(false),
mIsMouseFocus(false),
mStateSelected(false),
mImage(nullptr),
mModeImage(false)
{
}
void Button::initialiseOverride()
{
Base::initialiseOverride();
assignWidget(mImage, "Image");
}
void Button::shutdownOverride()
{
mImage = nullptr;
Base::shutdownOverride();
}
void Button::onMouseSetFocus(Widget* _old)
{
_setMouseFocus(true);
Base::onMouseSetFocus(_old);
}
void Button::onMouseLostFocus(Widget* _new)
{
_setMouseFocus(false);
Base::onMouseLostFocus(_new);
}
void Button::onMouseButtonPressed(int _left, int _top, MouseButton _id)
{
if (_id == MouseButton::Left)
{
mIsMousePressed = true;
updateButtonState();
}
Base::onMouseButtonPressed(_left, _top, _id);
}
void Button::onMouseButtonReleased(int _left, int _top, MouseButton _id)
{
if (_id == MouseButton::Left)
{
mIsMousePressed = false;
updateButtonState();
}
Base::onMouseButtonReleased(_left, _top, _id);
}
void Button::setImageIndex(size_t _index)
{
if (mImage)
mImage->setImageIndex(_index);
}
size_t Button::getImageIndex()
{
if (mImage)
return mImage->getImageIndex();
return ITEM_NONE;
}
void Button::updateButtonState()
{
if (mStateSelected)
{
if (!getEnabled())
{
if (!_setState("disabled_checked"))
_setState("disabled");
}
else if (mIsMousePressed)
{
if (!_setState("pushed_checked"))
_setState("pushed");
}
else if (mIsMouseFocus)
{
if (!_setState("highlighted_checked"))
_setState("pushed");
}
else
_setState("normal_checked");
}
else
{
if (!getEnabled())
_setState("disabled");
else if (mIsMousePressed)
_setState("pushed");
else if (mIsMouseFocus)
_setState("highlighted");
else
_setState("normal");
}
}
void Button::setStateSelected(bool _check)
{
if (mStateSelected == _check)
return;
mStateSelected = _check;
updateButtonState();
}
void Button::_setMouseFocus(bool _focus)
{
mIsMouseFocus = _focus;
updateButtonState();
}
void Button::baseUpdateEnable()
{
updateButtonState();
if (!getEnabled())
{
mIsMouseFocus = false;
}
}
void Button::setModeImage(bool _value)
{
mModeImage = _value;
updateButtonState();
}
bool Button::_setState(const std::string& _value)
{
if (mModeImage)
{
if (mImage)
mImage->setItemName(_value);
setState(_value);
return true;
}
return setState(_value);
}
void Button::setImageResource(const std::string& _name)
{
if (mImage)
mImage->setItemResource(_name);
updateButtonState();
}
void Button::setPropertyOverride(const std::string& _key, const std::string& _value)
{
/// @wproperty{Button, StateSelected, bool} Set state selected.
if (_key == "StateSelected") setStateSelected(utility::parseValue<bool>(_value));
else if (_key == "ModeImage") setModeImage(utility::parseValue<bool>(_value));
else if (_key == "ImageResource") setImageResource(_value);
else
{
Base::setPropertyOverride(_key, _value);
return;
}
eventChangeProperty(this, _key, _value);
}
} // namespace MyGUI
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
203
]
]
]
|
2f3ada521bf271235406298b8be99ca072f1445b | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_Bitwise.h | 7fa119bfad076ee373074a142d18cb35f72f434d | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,855 | h | /*!
@file
@author Albert Semenov
@date 06/2009
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_BITWISE_H__
#define __MYGUI_BITWISE_H__
#include "MyGUI_Prerequest.h"
namespace MyGUI
{
class Bitwise
{
public:
/** Returns the closest power-of-two number greater or equal to value.
*/
template<typename Type>
static MYGUI_FORCEINLINE Type firstPO2From(Type _value)
{
--_value;
_value |= _value >> 16;
_value |= _value >> 8;
_value |= _value >> 4;
_value |= _value >> 2;
_value |= _value >> 1;
++_value;
return _value;
}
/** Determines whether the number is power-of-two or not. */
template<typename Type>
static MYGUI_FORCEINLINE bool isPO2(Type _value)
{
return (_value & (_value - 1)) == 0;
}
/** Returns the number of bits a pattern must be shifted right by to
remove right-hand zeros.
*/
template<typename Type>
static MYGUI_FORCEINLINE size_t getBitShift(Type _mask)
{
if (_mask == 0)
return 0;
size_t result = 0;
while ((_mask & 1) == 0)
{
++result;
_mask >>= 1;
}
return result;
}
};
} // namespace MyGUI
#endif // __MYGUI_BITWISE_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
77
]
]
]
|
9f48beb14a6d5856465bb3daa6ca45bce5139c77 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/MapRenderer/include/loaders/MapPatches.h | d303c924e417b50ce648d232c3a34832b9ed6a64 | []
| 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 | 1,569 | h | //
// File: MapPatches.h
// Created by: Alexander Oster - [email protected]
//
/*****
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*****/
#ifndef _MAPPATCHES_H_
#define _MAPPATCHES_H_
#ifdef WIN32
#include <windows.h>
#endif
#include "SDL/SDL.h"
#include "../uotype.h"
class UOMapPatches
{
private:
public:
virtual void AddPatch(struct StaticPatch patch) = 0;
virtual void DelPatch(unsigned int blockx, unsigned int blocky, unsigned int obj_id) = 0;
virtual int GetNewID(int blockx, int blocky) = 0;
virtual int GetNewStaticSize(int orig_count, unsigned int blockx, unsigned int blocky, bool &apply_needed) = 0;
virtual void ApplyPatch(unsigned int blockx, unsigned int blocky, unsigned int oldcount, unsigned int newcount, struct staticinfo * src, struct staticinfo * dst) = 0;
};
#endif //_MAP_H_
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
50
]
]
]
|
d35eec61e3c7cd43b02a229fdedb8e18772689ea | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/spirit/example/qi/mini_c/mini_cd.cpp | 6df0315bfdb978e5be5e7f0d82b0df1fffa66175 | [
"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 | 648 | cpp | /*=============================================================================
Copyright (c) 2001-2007 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include "mini_cd.hpp"
// This is not really called. Its only purpose is to
// instantiate the constructor of the grammar.
void instantiate_program()
{
typedef std::string::const_iterator iterator_type;
std::vector<int> code;
program<iterator_type> g(code);
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
16
]
]
]
|
0471135b5517a2feeac1aa0321fd864824ff8787 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/ExpSCAN.cpp | 13c0aa8f66acb59cc8715926880e6cea9b78d699 | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,242 | cpp | #ifdef PRECOMPILED_HEADER
#include "common.h"
#endif
#include "AluminizerApp.h"
#include "GlobalsPage.h"
#include "Voltages2.h"
#include "ExpSCAN.h"
#include "TransitionPage.h"
#include "Numerics.h"
#include "scan_variable.h"
#include "data_plot.h"
#include "histogram_plot.h"
using namespace std;
using namespace numerics;
using namespace physics;
ExpSCAN::ExpSCAN(const string& sPageName,
ExperimentsSheet* pSheet,
const char*, unsigned page_id) :
ExperimentPage(sPageName, pSheet, page_id),
pSignalChannel(0),
unused_fit(false),
pScan(0),
pFit(0),
ScanType("Scan type", "Frequency\nTime\nContinuous\nVoltage\nB-field\nLockIn\nGeneral\nMotor\n", &m_TxtParams, "Frequency", &m_vParameters),
ScanVariables("Scan variable", "", &m_TxtParams, "", &m_vParameters),
Priority("Priority", &m_TxtParams, "1", &m_vParameters),
LinkedParams("Linked params", &m_TxtParams, "true", &m_vParameters),
AutomaticParams("Auto-span", &m_TxtParams, "true", &m_vParameters),
NumScans("Scans", &m_TxtParams, "1", &m_vParameters),
NumDataPoints("Data points", &m_TxtParams, "50", &m_vParameters),
RotationAngle("Rotation angle [pi]", &m_TxtParams, "1", &m_vParameters),
Span("Span", &m_TxtParams, "1", &m_vParameters),
FCenterFit("Fitted center", &m_TxtParams, "", &m_vParameters, true),
Start("Start", &m_TxtParams, "0.0", &m_vParameters),
Stop("Stop", &m_TxtParams, "1.0", &m_vParameters),
Step("Step", &m_TxtParams, "", &m_vParameters, true),
Gain(Span),
Modulation(Step),
LockCenter(FCenterFit),
GoodFit("Good fit", &m_TxtParams, "false", &m_vParameters, true),
IgnoreFit("Ignore fit", &m_TxtParams, "false", &m_vParameters, true),
FitMinContrast("Min. fit contrast", &m_TxtParams, "0.7", &m_vParameters),
TFittedPiTime("Fitted pi time [us]", &m_TxtParams, "", &m_vParameters, true),
FitMinAmplitude("Min. fit amplitude", &m_TxtParams, "5", &m_vParameters),
EnablePlot("Enable Plot", &m_TxtParams, "1", &m_vParameters, false),
Histogram("Histogram", &m_TxtParams, "false", &m_vParameters, false),
ScanTime("Scan time [s]", &m_TxtParams, "", &m_vParameters, true),
progress("Scan progress", &m_TxtParams, "0", &m_vParameters),
LogShots("Log shots", &m_TxtParams, "false", &m_vParameters),
NumMeasurements("Measurements [#]", &m_TxtParams, "3", &m_vParameters),
initial_delay(0),
scan_name("scan"),
exp_run_time(0),
data_plotW(0),
hist_plotW(0),
cci(0),
scanGUImode(0),
oldScanSource(0)
{
ScanTime.SetReadOnly(true);
NumDataPoints.setToolTip("Number of points per scan");
AutomaticParams.setToolTip("Automatically calculate scan range");
NumMeasurements.setToolTip("Number of servo measurement points to acquire before signaling IDLE");
//allows plots to be setup from non-GUI threads
QObject::connect(this, SIGNAL(signal_setup_plots()),
this, SLOT(slot_setup_plots()), Qt::BlockingQueuedConnection);
Step.setPrecision(9);
Span.setPrecision(9);
Start.setPrecision(9);
Stop.setPrecision(9);
FCenterFit.setPrecision(9);
/*
updateScanSourcesGUI();
updateScanGUI();
updateScanSpan();
updateScanStartStop();
updateScanStep();
*/
}
ExpSCAN::~ExpSCAN()
{
if (pScan)
delete pScan;
if (pFit)
delete pFit;
if (data_plotW)
{
data_plotW->close();
delete data_plotW;
}
if (hist_plotW)
{
hist_plotW->close();
delete hist_plotW;
}
}
TransitionPage* ExpSCAN::GetCurrentTransition()
{
return 0;
}
void ExpSCAN::AddAvailableActions(std::vector<std::string>* v)
{
ExperimentPage::AddAvailableActions(v);
if (pScan)
{
string fname = pScan->debugFileName();
if (fname.length())
v->push_back("DEBUG");
}
if (!m_pSheet->scan_scheduler.IsRunning(this, 0))
{
if (unused_fit)
v->push_back("USE FIT");
if (get_data_plot())
if (get_data_plot()->canPrint())
v->push_back("PRINT");
}
}
void ExpSCAN::slot_setup_plots()
{
//clear old plot windows
if (data_plotW)
{
data_plotW->close();
delete data_plotW;
data_plotW = 0;
}
if (hist_plotW)
{
hist_plotW->close();
delete hist_plotW;
hist_plotW = 0;
}
if (EnablePlot)
{
string extended_title = Title() + " " + pRunObject->GetStartTimeS();
bool bPlotAverages = !IsContinuousScan(ScanType);
bool bHasLegend = true;
if (cci)
if (cci->pX)
if (cci->pX->acceptCalibrationPlot(0, 0))
bHasLegend = cci->pX->wantsPlotLegend();
data_plot* plot = new data_plot(this, bPlotAverages, pGlobals->PlotLineWidth, extended_title, "", "", bHasLegend);
bool bNeedsPlotW = true;
//allow page that the launched calibration to handle the plot
if (cci)
if (cci->pX)
bNeedsPlotW = !(cci->pX->acceptCalibrationPlot(cci, plot));
//otherwise create a separate plot window
if (bNeedsPlotW)
{
data_plotW = new plot_window(this, plot, extended_title, Title() + "data");
data_plotW->show();
}
}
if (Histogram)
{
histogram_plot* hist_plot = new histogram_plot(this, "", "");
string title = "Histogram --" + Title();
hist_plotW = new plot_window(this, hist_plot, title);
hist_plotW->show();
}
}
void ExpSCAN::on_action(const std::string& s)
{
if (s == "PRINT" && data_plotW)
dynamic_cast<data_plot*>(data_plotW->pPlot)->print();
if (s == "USE FIT" && unused_fit)
{
unused_fit = false;
bool bOld = IgnoreFit;
IgnoreFit.SetValue(false);
if (IsTimeScan(ScanType))
useFit(TFittedPiTime);
else
useFit(FCenterFit);
IgnoreFit.SetValue(bOld);
PostUpdateData();
PostUpdateActions();
}
else
if (s == "SHIFT F0")
{
/* TODO: re-implement
TransitionPage* pTX = GetCurrentTransition();
if( IsLinkedScan() && IsFreqScan(ScanType) && pTX && unused_frequency_fit)
{
double delta_f = 0; //(FCenterFit - FCenter) * 1e6;
if(delta_f != 0)
{
GetCurrentTransition()->ShiftAllFrequencies(delta_f);
}
unused_frequency_fit = false;
PostUpdateData();
PostUpdateActions();
} */
}
else
{
if (s == "DEBUG")
{
if (pScan)
{
string fname = pScan->debugFileName();
if (fname.length())
LaunchEditor(fname);
}
}
ExperimentPage::on_action(s);
}
}
//Update the GUI
bool ExpSCAN::RecalculateParameters()
{
bool Changed = ExperimentPage::RecalculateParameters();
// if(GetCurrentTransition())
// GetCurrentTransition()->UpdatePolarizationGUI(&Polarization, &(GetCurrentTransition()->tx), GroundState());
if ( IsLinkedScan() && GetCurrentTransition() )
{
// Changed |= GetCurrentTransition()->LinkSidebandPiTimeTo(&InterrogationTime, CurrentLine());
}
else
{
// Changed |= InterrogationTime.SetName(GetITimeName());
}
Changed |= updateScanSourcesGUI();
Changed |= updateScanGUI();
Changed |= updateScanSpan();
Changed |= updateScanStartStop();
Changed |= updateScanStep();
return Changed;
}
void ExpSCAN::InitExperimentStart()
{
emit signal_setup_plots();
GoodFit.SetValue(false);
unused_fit = false;
if (LinkedParams)
pX = GetCurrentTransition();
else
pX = 0;
pRunObject->SetDataFileName(GetDataFileName());
//save all parameters of all pages in the current directory
m_pSheet->SaveAllParameters("./");
//save all parameters of all pages into the output directory
m_pSheet->SaveAllParameters(pRunObject->GetOutputDirectory());
if (pScan)
{
delete pScan;
pScan = 0;
}
pScan = CreateScan();
pScan->InitializeScan();
ofstream DataFilesList("DataFilesList.csv", ios_base::app);
DataFilesList << pRunObject->GetDataFileName() << "," << 7 << endl;
DataFilesList.close();
}
void ExpSCAN::FinishRun()
{
cout << "[ExpSCAN::FinishRun] entry" << endl;
QWriteLocker lock(&page_lock);
if (pScan)
{
Scan_Fittable* pScanFittable = dynamic_cast<Scan_Fittable*>(pScan);
if ( pScan->CanFit() && pScanFittable)
{
if (pFit)
{
delete pFit;
pFit = 0;
}
pFit = pScanFittable->RunFit(this);
if (get_data_plot())
if (pGlobals->SavePlotType.Value() != "None")
get_data_plot()->replot(true, pGlobals->SavePlotType.Value());
if (cci)
if (cci->pX)
{
calibration_item ci = *cci;
ci.pX->DidCalibration(cci, pFit);
cci = 0;
}
}
}
cci = 0;
cout << "[ExpSCAN::FinishRun] updating data" << endl;
PostUpdateData();
cout << "[ExpSCAN::FinishRun] exit" << endl;
}
data_plot* ExpSCAN::get_data_plot()
{
if (cci)
if (cci->pX)
{
data_plot* pDP = cci->pX->get_data_plot(cci, Title());
if (pDP)
return pDP;
}
if (data_plotW)
return dynamic_cast<data_plot*>(data_plotW->pPlot);
else
return 0;
}
histogram_plot* ExpSCAN::get_hist_plot()
{
if (hist_plotW)
return dynamic_cast<histogram_plot*>(hist_plotW->pPlot);
else
return 0;
}
bool ExpSCAN::UpdateFittedCenter(double fFit, bool bGoodFit)
{
GoodFit.SetValue( bGoodFit );
FCenterFit.SetValue( fFit );
unused_fit = true;
return false;
}
bool ExpSCAN::UpdateFittedPiTime(double tFit, double t0, bool bGoodFit)
{
GoodFit.SetValue( bGoodFit );
TFittedPiTime.SetValue( tFit );
initial_delay = t0;
if (fabs(initial_delay + tFit) < fabs(initial_delay))
initial_delay += tFit;
if (fabs(initial_delay - tFit) < fabs(initial_delay))
initial_delay -= tFit;
cout << "initial_delay = " << initial_delay << endl;
unused_fit = true;
return false;
}
//in MHz
double ExpSCAN::GetRabiRate()
{
// scan_pulse p(CurrentLine());
// GetCurrentTransition()->CalculatePulse(p);
throw runtime_error("[ExpSCAN::GetRabiRate] not implemented");
return 1;
}
bool ExpSCAN::IsRamseyFScan()
{
return ::IsRamseyFScan(ScanType);
}
bool ExpSCAN::IsRamseyPScan()
{
return ::IsRamseyPScan(ScanType);
}
Scan_Base* ExpSCAN::CreateScan()
{
vector<scan_variable*> scan_variables;
if (IsLockInScan(ScanType))
if (LockInParams * pLockInParams = dynamic_cast<LockInParams*>(this))
if (ScanSource * ss = currentScanSource())
{
scan_variables.push_back(new source_scan_variable(ss));
return new LockInScan(this, scan_variables, pLockInParams, ss);
}
if (ScanSource * ss = currentScanSource())
{
scan_variables.push_back(new source_scan_variable(ss));
return new SourceScan(this, scan_variables, ss);
}
if (IsContinuousScan(ScanType))
return new ContinuousScan(this, vector<scan_variable*>(0));
throw runtime_error("[ExpSCAN::CreateScan] failure: unknown scan type");
}
//called after every interruption of the scan, e.g. lost ions, or scan repitition
void ExpSCAN::InitExperimentSwitch()
{
if (pScan)
pScan->InitExperimentSwitch();
}
void ExpSCAN::DefaultExperimentState()
{
if (pScan)
pScan->DefaultExperimentState();
}
void ExpSCAN::UpdateFrequency(double)
{
}
void ExpSCAN::UpdateTime(double)
{
}
void ExpSCAN::UpdatePhase(double)
{
}
//Must be called from a non-GUI thread to avoid deadlock.
void ExpSCAN::DoCalibration(calibration_item* ci, RunObject* pOwner)
{
{
QWriteLocker lock(&page_lock);
cci = ci;
SetCurrentScan(ci);
LinkedParams.SetValue(true);
}
mutexPU.lock();
PostUpdateData();
page_updated.wait(&mutexPU);
mutexPU.unlock();
// cout << "[ExpSCAN::DoCalibration] start = " << Start.Value() << " stop = " << Stop.Value() << endl;
if (pOwner)
RunOwnedThread(pOwner);
else
m_pSheet->RunExperiment(Title());
}
void ExpSCAN::SetCurrentScan(const calibration_item* ci)
{
QWriteLocker lock(&page_lock);
DriveLine(ci->l);
ScanType.SetValue(ci->scan_type);
ScanVariables.SetValue(ci->scan_variable);
if (ci->span != 0)
{
AutomaticParams.SetValue(false);
Span.SetValue(ci->span);
}
else
AutomaticParams.SetValue(true);
if (ci->start != ci->stop)
{
Start.SetValue(ci->start);
Stop.SetValue(ci->stop);
}
if (ci->num_exp)
setNumExp(ci->num_exp);
updateScanSourcesGUI(true);
updateScanGUI(true);
updateScanSpan();
updateScanStartStop();
updateScanStep();
if (ci->num_scans)
NumScans.SetValue(ci->num_scans);
if (ci->num_points)
NumDataPoints.SetValue(ci->num_points);
if (ci->num_flops && ci->IsTimeScan())
{
AutomaticParams.SetValue(false);
Start.SetValue(0.0);
Stop.SetValue(ci->num_flops * GetInterrogationTime());
// Span.SetValue(Stop - Start);
// cout << "[ExpSCAN::SetCurrentScan] start = " << Start.Value() << " stop = " << Stop.Value() << endl;
}
else
AutomaticParams.SetValue(true);
GUI_ttl* pWaitPulse = dynamic_cast<GUI_ttl*>(FindParameter("Wait"));
if (pWaitPulse)
pWaitPulse->setTime(ci->wait);
cout << "Scan type = " << ci->scan_type << endl;
cout << "Scan variable = " << ScanVariables.Value() << endl;
}
double ExpSCAN::GetNewFrequencyAfterFit()
{
if (GoodFit)
return FCenterFit;
else
return GetCenterFrequency();
}
double ExpSCAN::GetNewPiTimeAfterFit()
{
if (GoodFit)
return TFittedPiTime;
else
// return InterrogationTime;
return 1;
}
bool ExpSCAN::IsLinkedScan()
{
return LinkedParams;
}
bool ExpSCAN::IsScatterScan()
{
return pGlobals->ScatterScan;
}
string ExpSCAN::GetDataFileName()
{
ostringstream name;
name << GetName() << " " << ScanType;
ScanSource* cSS = currentScanSource();
if (cSS)
if (cSS->pParam)
name << "(" << cSS->pParam->get_display_label() << ")";
string s = name.str();
//replace ' ' and '/' with '_'
for (size_t i = 0; i < s.length(); i++)
if (s[i] == ' ' || s[i] == '/')
s[i] = '_';
return s;
}
physics::line ExpSCAN::CurrentLine()
{
return line(getGroundState(),
getExcitedState(),
getSideband(),
RotationAngle * M_PI);
}
double ExpSCAN::getGroundState()
{
GUI_double* pGS = dynamic_cast<GUI_double*>(FindParameter("Ground state"));
if (pGS)
return pGS->Value();
else
return 0;
}
double ExpSCAN::getExcitedState()
{
return getGroundState() + getPolarization();
}
int ExpSCAN::getPolarization()
{
GUI_int* pPol = dynamic_cast<GUI_int*>(FindParameter("Polarization"));
if (pPol)
return pPol->Value();
else
return 0;
}
int ExpSCAN::getSideband()
{
GUI_int* pSB = dynamic_cast<GUI_int*>(FindParameter("Sideband"));
if (pSB)
return pSB->Value();
else
return 0;
}
TransitionPage* ExpSCAN::FindTransitionPage(const std::string& name)
{
for (size_t i = 0; i < m_pSheet->NumPages(); i++)
if (TransitionPage * p = dynamic_cast<TransitionPage*>(m_pSheet->GetPage(i)))
if (p->TransitionName() == name)
return p;
return 0;
}
double ExpSCAN::AOMdelay(const string&)
{
return 0; //GetCurrentTransition()->GetAOMdelay();
}
double ExpSCAN::GetXoffset()
{
pX = GetCurrentTransition();
if (pX)
{
line l = CurrentLine();
l.sb = 0;
double f0 = pX->AOMFrequency(l) * 1e-6;
if (fabs(GetCenterFrequency() - f0) < 100)
return f0;
}
return 0;
}
//add a DDS pulse scan source to the list if it's not already there
void ExpSCAN::addScanSource(GUI_dds* pPulseDDS)
{
bool bExist = false;
for (unsigned i = 0; i < p_scan_sources.size(); i++)
{
if (p_scan_sources[i]->pParam->get_fpga_name() == pPulseDDS->get_fpga_name())
{
bExist = true;
break;
}
}
if (!bExist)
{
p_scan_sources.push_back(new FScanSource(pFPGA, get_page_id(), pPulseDDS));
p_scan_sources.push_back(new TScanSource(pFPGA, get_page_id(), pPulseDDS));
updateScanSourcesGUI();
}
}
void ExpSCAN::AddParams()
{
ExperimentPage::AddParams();
//add scan sources to list for this page
for (size_t i = 0; i < m_vParameters.size(); i++)
{
GUI_dds* pPulseDDS = dynamic_cast<GUI_dds*>(m_vParameters[i]);
if (pPulseDDS)
{
p_scan_sources.push_back(new FScanSource(pFPGA, get_page_id(), pPulseDDS));
p_scan_sources.push_back(new TScanSource(pFPGA, get_page_id(), pPulseDDS));
}
GUI_ttl* pPulseTTL = dynamic_cast<GUI_ttl*>(m_vParameters[i]);
if (pPulseTTL)
p_scan_sources.push_back(new TScanSource(pFPGA, get_page_id(), pPulseTTL));
GUI_double* pDouble = dynamic_cast<GUI_double*>(m_vParameters[i]);
if (pDouble)
{
DoubleScanSource* dss = new DoubleScanSource(pFPGA, get_page_id(), pDouble);
p_scan_sources.push_back(dss);
}
}
// SafeRecalculateParameters();
}
void ExpSCAN::setScanUnit(const std::string& unit)
{
//update units for scan parameters
string unit_str = unit.size() == 0 ? "" : "[" + unit + "]";
if (IsLockInScan(ScanType))
{
Gain.SetName("Gain");
Gain.setToolTip("Positive gain locks to peaks, negative to dips.");
Modulation.SetName("Modulation");
LockCenter.SetName("Lock center");
}
else
{
Start.SetName(string("Start ") + unit_str);
Stop.SetName(string("Stop ") + unit_str);
Step.SetName(string("Step ") + unit_str);
Span.SetName(string("Span ") + unit_str);
Span.setToolTip("Start - Stop");
}
}
void ExpSCAN::setScanMode(unsigned u)
{
//update scan GUI mode
// 0 - continuous, no scan parameters
// 1 - center/span mode. start/stop are automatically calculated
// 2 - start/stop mode. center/span are automatically calculated
scanGUImode = u;
if (u == 0)
showScanGUI(false);
else
showScanGUI(true);
if (IsLockInScan(ScanType))
{
Span.SetReadOnly(false);
Step.SetReadOnly(false);
Gain.SetReadOnly(false);
}
else
{
Span.SetReadOnly(u == 2);
Start.SetReadOnly(u == 1);
Stop.SetReadOnly(u == 1);
Step.SetReadOnly(true);
}
/*
ScanSource* cSS = currentScanSource();
if(cSS)
cSS->initScanPageGUI(this);
*/
}
void ExpSCAN::showScanGUI(bool bShow)
{
Span.Show(bShow);
Step.Show(bShow);
FCenterFit.Show(bShow);
if (IsLockInScan(ScanType))
bShow = false;
NumScans.Show(bShow);
NumDataPoints.Show(bShow);
Start.Show(bShow);
Stop.Show(bShow);
FitMinAmplitude.Show(bShow);
FitMinContrast.Show(bShow);
TFittedPiTime.Show(bShow);
AutomaticParams.Show(bShow);
GoodFit.Show(bShow);
}
bool ExpSCAN::updateScanStartStop()
{
bool bChanged = false;
if (scanGUImode == 1)
{
ScanSource* fSS = dynamic_cast<FScanSource*>(currentScanSource());
if (fSS && (GetInterrogationTime() != 0))
{
if (AutomaticParams && !IsLockInScan(ScanType))
{
TransitionPage* pX = GetCurrentTransition();
double span = pX ?
4 * pX->AOMFrequencyFourierLimit(GetInterrogationTime()) :
4 / fabs( GetInterrogationTime() );
bChanged |= Span.SetValue( fabs(span) );
Span.SetReadOnly( true );
}
else
Span.SetReadOnly( false );
// cout << "[ExpSCAN::updateScanStartStop] start = " << Start.Value() << " stop = " << Stop.Value() << endl;
}
ScanSource* cSS = currentScanSource();
if (cSS)
{
bChanged |= Start.SetValue(cSS->getNonScanningValue() - Span / 2);
bChanged |= Stop.SetValue(cSS->getNonScanningValue() + Span / 2);
// cout << "[ExpSCAN::updateScanStartStop] start = " << Start.Value() << " stop = " << Stop.Value() << endl;
}
}
return bChanged;
}
bool ExpSCAN::updateScanSpan()
{
if (IsLockInScan(ScanType))
return false;
bool bChanged = false;
if (scanGUImode == 2)
{
ScanSource* tSS = dynamic_cast<TScanSource*>(currentScanSource());
if (tSS) //crashes here?
{
double tPi = tSS->getNonScanningValue();
if (tSS && (tPi != 0))
{
if (AutomaticParams)
{
bChanged |= Start.SetValue(0.1);
bChanged |= Stop.SetValue( 2 * NumFlops() * tPi );
Start.SetReadOnly(true);
Stop.SetReadOnly(true);
if (debugQ("[ExpSCAN::updateScanSpan]", ""))
cout << "[ExpSCAN::updateScanSpan] start = " << Start.Value() << " stop = " << Stop.Value() << endl;
}
else
{
Start.SetReadOnly(false);
Stop.SetReadOnly(false);
}
}
}
bChanged |= Span.SetValue(Stop - Start);
}
return bChanged;
}
bool ExpSCAN::updateScanStep()
{
if (IsLockInScan(ScanType))
return false;
else
return Step.SetValue((Stop - Start) / (NumDataPoints - 1));
}
bool ExpSCAN::updateScanGUI(bool bForceUpdate)
{
QWriteLocker lock(&page_lock);
//figure out what should be scanned
ScanSource* cSS = currentScanSource();
//is the current scan source different from before?
if (cSS != oldScanSource || bForceUpdate)
{
//if so, make sure any fit information is no longer used
unused_fit = false;
//if there was an earlier scan source, un-highlight this
if (oldScanSource)
{
ParameterGUI_Base* pOld = oldScanSource->pParam;
//this function changes the parameter background to indicate that it will be scanned or not
//it results in a signal that causes the actual GUI update
if (pOld)
pOld->selectScanTarget(oldScanSource->getType(), false);
}
if (cSS)
{
//highlight the new scan source
ParameterGUI_Base* pNew = cSS->pParam;
if (pNew)
pNew->selectScanTarget(cSS->getType(), true);
}
oldScanSource = cSS;
if (cSS != 0)
{
//update the units for the new scan
setScanUnit(cSS->GetUnit());
//select start/stop or center/span mode depending on the type of scan (frequency/time/whatever)
setScanMode(cSS->GetMode());
return true;
}
else
setScanMode(0);
}
return false;
}
ScanSource* ExpSCAN::currentScanSource()
{
QWriteLocker lock(&page_lock);
string ssType = ScanType;
string ssName = ScanVariables;
for (size_t i = 0; i < g_scan_sources.size(); i++)
{
if (g_scan_sources[i]->isCompatibleScanType(ScanType.Value()))
if (g_scan_sources[i]->getName() == ssName)
return g_scan_sources[i];
}
for (size_t i = 0; i < p_scan_sources.size(); i++)
{
if (p_scan_sources[i]->isCompatibleScanType(ScanType.Value()))
if (p_scan_sources[i]->getName() == ssName)
return p_scan_sources[i];
}
return 0;
}
scan_variable* ExpSCAN::currentScanVariable()
{
if (pScan)
return pScan->currentScanVariable();
else
return 0;
}
bool ExpSCAN::updateScanSourcesGUI(bool bForceUpdate)
{
QWriteLocker lock(&page_lock);
ScanSource* css = currentScanSource();
if (css)
if (css->getName() != ScanVariables.Value())
bForceUpdate = true;
if (bForceUpdate || (oldScanType != ScanType.Value()) )
{
bIgnoreGUISignals = true;
oldScanType = ScanType.Value();
string oSS = ScanVariables.Value();
ScanVariables.clearChoices();
//add globally available scan sources
for (size_t i = 0; i < g_scan_sources.size(); i++)
{
if (g_scan_sources[i]->isCompatibleScanType(ScanType.Value()))
// cout << "Add scan source " << g_scan_sources[i]->getName() << endl;
ScanVariables.AddChoice(g_scan_sources[i]->getName());
}
//add scan sources for this page
for (size_t i = 0; i < p_scan_sources.size(); i++)
{
if (p_scan_sources[i]->isCompatibleScanType(ScanType.Value()))
// cout << "Add page scan source " << p_scan_sources[i]->getName() << endl;
ScanVariables.AddChoice(p_scan_sources[i]->getName());
}
if (oSS.length())
ScanVariables.SetValue(oSS);
bIgnoreGUISignals = false;
updateScanGUI(true);
return true;
}
return false;
}
DDS_Pulse_Widget* ExpSCAN::DriveLine(const physics::line& l)
{
GUI_int* pSB = dynamic_cast<GUI_int*>(FindParameter("Sideband"));
GUI_double* pGS = dynamic_cast<GUI_double*>(FindParameter("Ground state"));
GUI_int* pPol = dynamic_cast<GUI_int*>(FindParameter("Polarization"));
if (pSB)
pSB->SetValue(l.sb);
if (pGS)
pGS->SetValue(l.mFg);
if (pPol)
pPol->SetValue(l.Polarization());
RecalculateParameters();
return 0;
}
bool debug_lock = true;
ExpSCAN_L::ExpSCAN_L(const string& sPageName, ExperimentsSheet* pSheet,
const char* TargetStates, unsigned page_id) :
ExpSCAN(sPageName, pSheet, TargetStates, page_id)
{
}
ExpSCAN_L::~ExpSCAN_L()
{
}
scan_variable* ExpSCAN_L::getLockVariable()
{
return currentScanVariable();
}
void ExpSCAN_L::modulateOutput(double d)
{
if (debug_lock)
printf("[ExpSCAN_L::modOutput] %12.9f\r\n", d);
SetOutput(GetCenter() + d);
}
void ExpSCAN_L::SetOutput(double d)
{
if (debug_lock)
printf("[ExpSCAN_L::SetOutput] %12.9f\r\n", d);
return getLockVariable()->set_scan_position(d);
}
double ExpSCAN_L::GetOutput()
{
return getLockVariable()->get_scan_position();
}
double ExpSCAN_L::GetModulation()
{
RecalculateModulation();
return Modulation;
}
void ExpSCAN_L::ShiftCenter(double d)
{
SetCenter(GetCenter() + d);
}
void ExpSCAN_L::SetCenter(double d)
{
if (d != GetCenter())
{
getLockVariable()->set_default_state(d);
LockCenter.SetValue(d);
LockCenter.PostUpdateGUI();
char buff[128];
sprintf(buff, "%s = %9.3f %s", GetLockVariableName().c_str(), d, pScan->GetScanUnit().c_str());
pScan->getPlot()->setMarkerText(buff);
}
if (debug_lock)
printf("[ExpSCAN_L::SetCenter (%f)] %12.9f\r\n", fmod(CurrentTime_s(), 100), d);
}
double ExpSCAN_L::GetCenter()
{
double d = getLockVariable()->get_default_state();
if (debug_lock)
printf("[ExpSCAN_L::GetCenter (%f)] %12.9f\r\n", fmod(CurrentTime_s(), 100), d);
return d;
}
double ExpSCAN_L::GetGain()
{
return Gain;
}
int ExpSCAN_L::GetNumMeasurements()
{
return NumMeasurements;
}
double ExpSCAN_L::GetSignal()
{
return pSignalChannel->GetAverage();
}
std::string ExpSCAN_L::GetLockVariableName()
{
return currentScanSource()->getName();
}
double ExpSCAN_L::GetInitialCenter()
{
return GetCenter();
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
1180
]
]
]
|
531231f08eb3f0b2f0b07f6169eabfabe53aa046 | 00b979f12f13ace4e98e75a9528033636dab021d | /zfs/zfs/src/modules/sdk/include/ziafs_sdk.hh | 8bd2bf5167c0cbddd8114c6e499831663f8b0d09 | []
| no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 723 | hh | //
// ziafs_sdk.hh for in
//
// Made by texane
// Login <[email protected]>
//
// Started on Sun Jan 22 00:01:22 2006 texane
// Last update Thu Jan 26 02:59:19 2006 texane
//
#ifndef ZIAFS_SDK_HH
# define ZIAFS_SDK_HH
// ?
// Include this file when
// developping your own modules
// Forward declarations
namespace net { class module; }
namespace net { class session; }
// Export a function with this macro
#if defined (_WIN32)
# define MOD_EXPORT(f) extern "C" __declspec(dllexport) status::error f
#else
# define MOD_EXPORT(f) extern "C" status::error f
#endif // _WIN32
# define HK_STRFY( s ) #s
# define HK_SYM( sym ) HK_STRFY( sym )
#endif // ! ZIAFS_SDK_HH
| [
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
]
| [
[
[
1,
38
]
]
]
|
11d8779066978068c51ebc3ebb85732144b95414 | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnMesh/Source/GLoadButtonLabel.cpp | 7e79b56d33c5ae11c74f1858da33074ffd99125d | []
| no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,983 | cpp | //
// GLoadButtonLabel.cpp
// Core
//
// Created by Max Yoon on 11. 8. 5..
// Copyright 2011년 __MyCompanyName__. All rights reserved.
//
#include "GnGamePCH.h"
#include "GLoadButtonLabel.h"
GLoadButtonLabel* GLoadButtonLabel::CreateLabel(gtuint uiNumButton, guint32 uiModeLevel, guint32 uiNumStage)
{
GLoadButtonLabel* label = GnNew GLoadButtonLabel();
const gchar* modeName[3] = {
"StartScene/level select/340_131 340_169 340_206.png",
"StartScene/level select/340_131 340_169 340_206.png",
"StartScene/level select/340_131 340_169 340_206.png"
};
label->CreateDefaultImage( modeName[uiModeLevel] );
label->CreateLabelStage( uiNumStage );
label->SetPosition( uiNumButton, uiModeLevel );
label->GetParentUseNode()->addChild( label->mLabelNumStage.GetParentUseNode(), INTERFACE_ZORDER + 1 );
//label->SetIsDisableCantpushBlind( true );
label->SetIsCantPush( true );
return label;
}
void GLoadButtonLabel::CreateLabelStage(guint32 uiNumStage)
{
gstring fullPath;
GetFullPathFromWorkPath( "StartScene/level select/386_129.png", fullPath );
mLabelNumStage.Init( "0", fullPath.c_str(), 12, 18, '.' );
mLabelNumStage.SetMaxDigit( 2, "%02d" );
mLabelNumStage.SetNumber( uiNumStage );
}
void GLoadButtonLabel::SetPosition(gtuint uiNumButton, guint32 uiModeLevel)
{
float modePositionX = 0.0f;
float stagePositionY = 0.0f;
float numStagePositionX = .0f;
float numStagePositionY = .0f;
if( uiNumButton == 0 )
{
stagePositionY = 130.0f;
numStagePositionY = 127.0f;
}
else if( uiNumButton == 1 )
{
stagePositionY = 170.0f;
numStagePositionY = 167.0f;
}
else
{
stagePositionY = 210.0f;
numStagePositionY = 207.0f;
}
if( uiModeLevel == 1 )
modePositionX = 340.0f;
else
modePositionX = 340.0f;
numStagePositionX = 391.0f;
SetUIPosition( this, modePositionX, stagePositionY );
SetUIPosition( &mLabelNumStage, numStagePositionX, numStagePositionY );
} | [
"[email protected]"
]
| [
[
[
1,
72
]
]
]
|
03739905b5881498ed91c5bdf33218c01eb833f7 | 22b6d8a368ecfa96cb182437b7b391e408ba8730 | /addins/QuanticVortexAddin_Irrlicht/include/qvIrrlichtHumanView.h | 848910f775a1e6e66f4ad69a6875a977cafe2f40 | [
"MIT"
]
| permissive | drr00t/quanticvortex | 2d69a3e62d1850b8d3074ec97232e08c349e23c2 | b780b0f547cf19bd48198dc43329588d023a9ad9 | refs/heads/master | 2021-01-22T22:16:50.370688 | 2010-12-18T12:06:33 | 2010-12-18T12:06:33 | 85,525,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,479 | h | /**************************************************************************************************
//This code is part of QuanticVortex for latest information, see http://www.quanticvortex.org
//
//Copyright (c) 2009-2010 QuanticMinds Software Ltda.
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
**************************************************************************************************/
#ifndef _IRRLICHT_HUMAN_VIEW_H_
#define _IRRLICHT_HUMAN_VIEW_H_
#include "qvAddinIrrlichtConfig.h"
#include "qvHumanView.h"
namespace irr
{
class IrrlichtDevice;
}
namespace qv
{
struct SGameParams;
namespace views
{
class SceneElementView;
}
}
namespace qv
{
namespace addins
{
static const qv::views::GVI_GAME_VIEW_ID GVI_IRRLICHT_HUMAN_VIEW("GVI_IRRLICHT_HUMAN_VIEW");
class _QUANTICVORTEX_ADDIN_IRRLICHT_API_ IrrlichtHumanView: public qv::views::HumanView
/// human view irrlicht implementation.
{
public:
IrrlichtHumanView(qv::Game* game);
virtual ~IrrlichtHumanView();
// virtual void update(u32 elapsedTimeMs);
/// update all view elements, process and all other thing
/// sibling to render system, animated gui and mesh
virtual void render( u32 currentTimeMs, u32 elapsedTimeMs);
/// render all element view data (scene, gui, shaders)
private:
irr::IrrlichtDevice* mDevice;
qv::SGameParams mGameParams;
qv::views::SceneElementView* mScene;
};
}
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
0af6fb251ec1b98637733d472a2dbf5bd700fcd1 | 7466d6ec10a4c0e7844cdc0d8ada82b66c9d8898 | /core/main.cpp | adb33b84d4c7e80f323cf9b6b91353649b45a6b4 | []
| no_license | LittleCVR/MaoPPM | 380897afcd30a09229504d3dc91d922f551bced8 | 56d8d813b96f7954021ad58ce8cd21eaca29c05d | refs/heads/master | 2020-05-20T10:08:42.350721 | 2011-09-07T16:29:42 | 2011-09-07T16:29:42 | 1,853,546 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | /*
* =====================================================================================
*
* Filename: main.cpp
*
* Description: File that contains functions to control main workflow.
*
* Version: 1.0
* Created: 2011-03-23 11:27:02
*
* Author: Chun-Wei Huang (LittleCVR),
* Company: Communication & Multimedia Laboratory,
* Department of Computer Science & Information Engineering,
* National Taiwan University
*
* =====================================================================================
*/
/*----------------------------------------------------------------------------
* header files of our own
*----------------------------------------------------------------------------*/
#include "System.h"
/*----------------------------------------------------------------------------
* using namespaces
*----------------------------------------------------------------------------*/
using namespace MaoPPM;
int main(int argc, char ** argv)
{
System system(argc, argv);
return system.exec();
} /* ---------- end of function main ---------- */
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
415d2f27d3dbb6460e47036bf7494075a61b446b | 651639abcfc06818971a0296944703b3dd050e8d | /ShotEvent.hpp | 4e42f618f92b4d75b12ab115955493634fd4fa9d | []
| no_license | reanag/snailfight | 5256dc373e3f3f3349f77c7e684cb0a52ccc5175 | c4f157226faa31d526684233f3c5cd4572949698 | refs/heads/master | 2021-01-19T07:34:17.122734 | 2010-01-20T17:16:36 | 2010-01-20T17:16:36 | 34,893,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | hpp | #ifndef SHOTEVENT_HPP
#define SHOTEVENT_HPP
#include "Event.hpp"
#include <string>
using namespace std;
class ShotEvent: public GameEvent{
public:
ShotEvent();
ShotEvent(string s);
string EventToString();
};
#endif
| [
"[email protected]@96fa20d8-dc45-11de-8f20-5962d2c82ea8"
]
| [
[
[
1,
21
]
]
]
|
5effd2432196e2120774109eeff6f1b5abc765fe | fad6f9883d4ad2686c196dc532a9ecb9199500ee | /NXP-LPC/CommTest/CommTest/SvrOptionView.cpp | 59053b405338c695c495391079b7da235f865235 | []
| no_license | aquarius20th/nxp-lpc | fe83d6a140d361a1737d950ff728c6ea9a16a1dd | 4abfb804daf0ac9c59bd90d879256e7a3c1b2f30 | refs/heads/master | 2021-01-10T13:54:40.237682 | 2009-12-22T14:54:59 | 2009-12-22T14:54:59 | 48,420,260 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,945 | cpp | // SvrOptionView.cpp : 实现文件
//
#include "stdafx.h"
#include "CommTest.h"
#include "SvrOptionView.h"
#include "SvrCommDoc.h"
// CSvrOptionView
IMPLEMENT_DYNCREATE(CSvrOptionView, CBCGPFormView)
CSvrOptionView::CSvrOptionView()
: CBCGPFormView(CSvrOptionView::IDD)
, m_nPortNum(999)
{
}
CSvrOptionView::~CSvrOptionView()
{
}
void CSvrOptionView::DoDataExchange(CDataExchange* pDX)
{
CBCGPFormView::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_SVR_PORTNUM_OPT, m_nPortNum);
}
BEGIN_MESSAGE_MAP(CSvrOptionView, CBCGPFormView)
ON_BN_CLICKED(IDC_BUTTON_SVR_START, &CSvrOptionView::OnBnClickedButtonSvrStart)
ON_WM_CREATE()
END_MESSAGE_MAP()
// CSvrOptionView 诊断
#ifdef _DEBUG
void CSvrOptionView::AssertValid() const
{
CBCGPFormView::AssertValid();
}
#ifndef _WIN32_WCE
void CSvrOptionView::Dump(CDumpContext& dc) const
{
CBCGPFormView::Dump(dc);
}
#endif
#endif //_DEBUG
// CSvrOptionView 消息处理程序
int CSvrOptionView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CBCGPFormView::OnCreate(lpCreateStruct) == -1)
return -1;
EnableVisualManagerStyle();
// TODO: 在此添加您专用的创建代码
return 0;
}
void CSvrOptionView::OnBnClickedButtonSvrStart()
{
// TODO: 在此添加控件通知处理程序代码
CSvrCommDoc *pDoc = (CSvrCommDoc *) GetDocument();
ASSERT(pDoc);
if (pDoc == NULL)
return;
CWnd *pWnd = GetDlgItem(IDC_BUTTON_SVR_START);
ASSERT(pWnd);
pWnd->EnableWindow(FALSE);
UpdateData(TRUE);
CComboBox *pBox =(CComboBox *) GetDlgItem(IDC_COMBO_HOST_IP_OPT);
ASSERT(pBox);
if (pDoc->m_SvrComm.m_bStart == FALSE)
{
if (pBox)
{
CString szIp ;
pBox->GetWindowText(szIp);
pDoc->m_SvrComm.m_dwLocalIp = htonl( inet_addr(CW2A(szIp)));
}
pDoc->m_SvrComm.m_bStart = pDoc->StartTask();
if (pDoc->m_SvrComm.m_bStart)
{
pWnd->SetWindowText(_T("停止"));
}
}
else
{
pDoc->StopTask();
pDoc->m_SvrComm.m_bStart = FALSE;
pWnd->SetWindowText(_T("开始"));
}
pWnd->EnableWindow();
}
void CSvrOptionView::OnUpdate(CView* /*pSender*/, LPARAM /*lHint*/, CObject* /*pHint*/)
{
// TODO: 在此添加专用代码和/或调用基类
std::list<std::string> ip_list;
bool bRet = false;
bRet = CUEServer::GetIpList(ip_list);
CComboBox *pBox =(CComboBox *) GetDlgItem(IDC_COMBO_HOST_IP_OPT);
ASSERT(pBox);
if(pBox)
{
pBox->ResetContent();
CString szTxt;
if(bRet && ip_list.size())
{
std::list <std::string>::iterator iter = ip_list.begin();
for ( ; iter != ip_list.end(); ++iter)
{
szTxt = CA2W(iter->c_str());
pBox->AddString( szTxt );
}
}
szTxt = _T("0.0.0.0");
pBox->AddString( szTxt );
// if (pBox->GetCount() <= 0)
// {
// szTxt = _T("127.0.0.1");
// pBox->AddString( szTxt );
// }
if (pBox->GetCount())
{
pBox->SetCurSel(0);
}
}
}
| [
"lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2"
]
| [
[
[
1,
139
]
]
]
|
faf6059aa199856dc7e9615d47658a4f718f284d | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/tools/napplauncher.cc | 612aff10c77c02edc6a5f074249124ba3237d6e3 | []
| 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 | 7,141 | cc | #include "precompiled/pchntoollib.h"
//------------------------------------------------------------------------------
// napplauncher.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "tools/napplauncher.h"
#include "kernel/nfileserver2.h"
#ifdef __WIN32__
#include <windows.h>
#include <shellapi.h>
#elif defined(__LINUX__)
#include <limits.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
//------------------------------------------------------------------------------
/**
*/
nAppLauncher::nAppLauncher(nKernelServer* ks) :
kernelServer(ks),
noConsoleWindow(false)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nAppLauncher::~nAppLauncher()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
bool
nAppLauncher::LaunchWait() const
{
n_assert(!this->exec.IsEmpty());
n_assert(this->kernelServer);
#ifdef __WIN32__
STARTUPINFO startupInfo = { sizeof(STARTUPINFO), 0 };
PROCESS_INFORMATION processInfo = { 0 };
// mangle paths
nString execMangled = nFileServer2::Instance()->ManglePath(this->exec.Get());
nString dirMangled = nFileServer2::Instance()->ManglePath(this->dir.Get());
// build a command line
nString cmdLine = execMangled;
cmdLine.Append(" ");
cmdLine.Append(this->args.Get());
DWORD creationFlags = 0;
if (this->noConsoleWindow)
{
creationFlags |= CREATE_NO_WINDOW;
}
if (!CreateProcess(NULL, // lpApplicationName
(LPSTR) cmdLine.Get(), // lpCommandLine
NULL, // lpProcessAttributes
NULL, // lpThreadAttributes
FALSE, // bInheritsHandle
creationFlags, // dwCreationFlags
NULL, // lpEnvironment
dirMangled.Get(), // lpCurrentDirectory
&startupInfo, // lpStartupInfo
&processInfo)) // lpProcessInformation
{
return false;
}
// wait until process exits
WaitForSingleObject(processInfo.hProcess, INFINITE);
// cleanup
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
#elif defined(__LINUX__)
return this->LaunchHelper(true);
#else
return false;
#endif
return true;
}
//------------------------------------------------------------------------------
/**
The path of executable file and directory are should be specified
before launching the application by calling nAppLauncher::SetExecutable() and
nAppLauncher::SetWorkingDirectory().
And aguments can be specified by calling nAppLauncher::SetArguments() if
those are needed.
- 15-Oct-04 kims fixed a string invalidation bug on 'execmangled' and
'dirMangled' variables.
*/
bool
nAppLauncher::Launch() const
{
n_assert(!this->exec.IsEmpty());
n_assert(this->kernelServer);
nString execMangled;
nString dirMangled;
// mangle paths
const char* filePath = 0;
if (!this->url.IsEmpty())
{
filePath = this->url.Get();
}
else
{
execMangled = nFileServer2::Instance()->ManglePath(this->exec.Get());
filePath = execMangled.Get();
}
const char* dirPtr = 0;
if (!this->dir.IsEmpty())
{
dirMangled = nFileServer2::Instance()->ManglePath(this->dir.Get());
dirPtr = dirMangled.Get();
}
#ifdef __WIN32__
const char* argPtr = 0;
if (!this->args.IsEmpty())
{
argPtr = this->args.Get();
}
HINSTANCE retval = ShellExecute(NULL, // hWnd
"open", // lpOperation
filePath, // lpFile
argPtr, // lpParameters
dirPtr, // lpDirectory
SW_SHOW); // nShowCmd
return (size_t(retval) > 32);
#elif defined(__LINUX__)
return this->LaunchHelper(false);
#else
return false;
#endif
}
#ifdef __LINUX__
bool
nAppLauncher::LaunchHelper(bool waitForChild) const
{
// No exec, no lunch.
if (this->exec.IsEmpty())
return false;
// mangle paths
nString execMangled = nFileServer2::Instance()->ManglePath(this->exec.Get());
nString dirMangled = nFileServer2::Instance()->ManglePath(this->dir.Get());
// If executable path contains '/' then we convert it to absolute
// path. Otherwise we will use `execvp' to resolve executable name
// using `PATH' enviroment variable.
nString execCmd;
if (this->exec.FindChar('/', 0) != -1 && this->exec.Get()[0] != '/')
{
// NOTE: This is `glibc' exstension to `POSIX.1'.
char *cwd = getcwd(NULL, 0);
execCmd.Format("%s/%s", cwd, this->exec.Get());
free(cwd);
}
else
execCmd = this->exec;
// fork this process, and replace it with intended target
int pid = fork();
if (pid == 0) {
// Change to working directory.
if (!dirMangled.IsEmpty())
{
if (chdir(dirMangled.Get()))
exit(-1);
}
// +2 -> 1 for the command name, 1 for the NULL
char *argv[ARG_MAX + 2];
argv[0] = strdup(execMangled.Get());
int argc = 1;
// tokenize command line
char *argTmp = strdup(this->args.Get());
char *end = argTmp + strlen(argTmp);
char *ptr = argTmp;
while ((argc < ARG_MAX) && (ptr < end))
{
char* c;
while ((' ' == *ptr) || ('\t' == *ptr))
ptr++;
if (('"' == *ptr) && (c = strchr(++ptr, '"')))
{
*c++ = 0;
argv[argc++] = ptr;
ptr = c;
}
else if ((c = strpbrk(ptr, N_WHITESPACE)))
{
*c++ = 0;
argv[argc++] = ptr;
ptr = c;
}
else
{
argv[argc++] = ptr;
break;
}
}
argv[argc] = NULL;
// we have the args, so now we can exec the new process
execvp(execCmd.Get(), argv);
free(argv[0]);
free(argTmp);
exit(-1);
} else if (pid > 0) {
// Wait for the child...
int status = 0;
if (waitForChild)
{
waitpid(pid, &status, 0);
}
else
{
waitpid(pid, &status, WNOHANG);
}
} else {
// Failed to fork
return false;
}
return true;
}
#endif
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
244
]
]
]
|
8424cedb6bc46561495be8410bc77d2ec71e9b93 | cc5b962dfd2dc6acc0d401b1ab7b456c99c7e8c4 | /Bomberman 1.0/unbreakableobject.h | 87e7afc39f711da7569efb5d4d9801da2c81d710 | []
| no_license | andreapachas/bomberman-tsbk05 | c9e47b784982185077eec2d659a217897abbacc7 | 8ca28cb3095428e41db12d0060fc5573b614d3de | refs/heads/master | 2021-05-30T06:30:25.413561 | 2007-04-25T07:52:39 | 2007-04-25T07:52:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | h | #include "object.h"
#ifndef UNBREAKABLEOBJECT_H
#define UNBREAKABLEOBJECT_H
class UnbreakableObject : public Object {
public:
UnbreakableObject(Model*, GLfloat, GLfloat, GLfloat = 0, GLfloat = 0, GLfloat = 1);
};
#endif
| [
"jonas.lindgren@774f44fe-ff29-0410-bf63-e573c7ae51ad",
"mrrayan@774f44fe-ff29-0410-bf63-e573c7ae51ad"
]
| [
[
[
1,
10
]
],
[
[
11,
11
]
]
]
|
1b9626be0723a18c71302f5fa65a58d2587e92e5 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/MATHAND1/BELTCNV.H | d2234d743133019106ecb9f865c7abbd06693ae1 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,224 | h | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992
#ifndef __BELTCNV_H
#define __BELTCNV_H
#ifndef __SC_DEFS_H
#include "sc_defs.h"
#endif
#ifndef __M_BASE_H
#include "m_base.h"
#endif
#ifndef __MTRLOGIC_H
#include "mtrlogic.h"
#endif
#ifndef __SP_QUEUE_H
#include "sp_queue.h"
#endif
#ifdef __BELTCNV_CPP
#define DllImportExport DllExport
#elif !defined(MatHand1)
#define DllImportExport DllImport
#else
#define DllImportExport
#endif
//===========================================================================
DEFINE_TAGOBJ(BeltCnv);
class BeltCnv : public MdlNode
{
public:
BeltCnv(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach);
virtual ~BeltCnv();
virtual void BuildDataDefn(DataDefnBlk & DDB);
virtual flag DataXchg(DataChangeBlk & DCB);
virtual flag ValidateData(ValidateDataBlk & VDB);
virtual void CollectElectrics(CNodeElectricsArray & TSCA);
virtual void ConnectElectrics();
virtual flag GetOtherData(FilingControlBlock &FCB);
virtual flag PutOtherData(FilingControlBlock &FCB);
virtual void SetState(eScdMdlStateActs RqdState);
virtual void StartSolution();
virtual void PostConnect(int IONo);
virtual void PreDisConnect(int IONo);
virtual void ConfigureJoins();
virtual void StartStep();
virtual void EvalJoinPressures(long JoinMask);
virtual flag EvalFlowEquations(eScdFlwEqnTasks Task, CSpPropInfo *pProps, int IONo, int FE, int LnkNo);
virtual void EvalProducts(CNodeEvalIndex & NEI);
virtual void EvalPowerRequired();
virtual void EvalCtrlActions(eScdCtrlTasks Tasks=CO_All);
virtual void EvalDiscrete();
virtual void ClosureInfo();
virtual dword ModelStatus();
// ConditionBlk Override
DEFINE_CI(BeltCnv, MdlNode, 4);
protected:
typedef CArray < double, double > CWtMtrPosArray;
public:
SpQueue m_Q;
CWtMtrPosArray &m_WtMtrPos;
//CDVector FdPos, PrPos;
CIO_MtrSpdBlk m_BeltSB;
CPwrUser m_Pwr;
CDirectFlwIO m_Spill;
CDirectFlwIO m_Vent;
CDirectFlwIO m_AccIn;
CDirectFlwIO m_AccOut;
CDirectAccCalc m_AccCalc;
double m_MaxVelocity;
double m_MaxSpillLoading;
double m_MaxStallLoading;
double m_MinLoading;
long m_MaxTurnDown;
long m_ProfPts;
long m_ProfDispType;
flag m_fShowProfile;
flag m_fStartIfStalled;
flag m_fWasRunning;
double m_NLPower;
double m_FLPower;
double m_Power;
//Strng m_SpillName;
};
//===========================================================================
//
//
//
//===========================================================================
#undef DllImportExport
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
58
],
[
60,
61
],
[
63,
110
]
],
[
[
59,
59
],
[
62,
62
]
]
]
|
790aa4af8006794656ca531c2192c91bac467881 | 928b250a42ffbe1d1c1009b4af7fd3f6a1f46266 | /forlijia/ForlijiaEx/ForlijiaEx/MatchAddress.cpp | a8548419897a0b4478ceb206c12128d7210e894f | []
| no_license | jimcoly/comyitian | 81044cc6e5d06613e1f2bda8b658457e8337ab8f | 6f70e202907be1071d3310bfe1441567ebffed1e | refs/heads/master | 2020-05-31T17:54:26.448254 | 2011-09-01T07:28:07 | 2011-09-01T07:28:07 | 33,866,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | #include "StdAfx.h"
#include "MatchAddress.h"
MatchAddress::MatchAddress(void)
{
}
MatchAddress::~MatchAddress(void)
{
}
| [
"sdy63420@3919fc08-f352-11de-9907-777483041811"
]
| [
[
[
1,
12
]
]
]
|
481e9e7b6e64b8e3f83d9d8403fc55b41602f6df | 927e18c69355c4bf87b59dffefe59c2974e86354 | /super-go-proj/UCTTree.cpp | a4cfe69b79fadf7fe353990127aea95d0249ffdd | []
| no_license | lqhl/iao-gim-ca | 6fc40adc91a615fa13b72e5b4016a8b154196b8f | f177268804d1ba6edfd407fa44a113a44203ec30 | refs/heads/master | 2020-05-18T17:07:17.972573 | 2011-06-17T03:54:51 | 2011-06-17T03:54:51 | 32,191,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,128 | cpp | #include "UCTTree.h"
#include "Poco/Hashmap.h"
#include "SuperGoGame.h"
#include "GoBoard.h"
#include "GoBoardUtil.h"
#include "util/util.h"
#include <assert.h>
#undef max
using Poco::HashMap;
using GoBoardUtil::getGoNeighbors;
Random UCTTree::rand;
UCTTree::UCTTree(SuperGoGame* game, int numNodes) {
this->game = game;
this->preprocChildren = game->preprocessChildren;
this->numNodes = numNodes;
node = new UCTNode[numNodes];
freeList.clear();
freeList.reserve(numNodes);
for(int i=0; i<numNodes; ++i) {
freeList.push_back(i);
node[i].level = RESERVED;
}
UCTNode* n = allocateNode();
n->level = 0;
root = n - node;
board = &game->board;
}
void UCTTree::prune(int count) {
for(int i=0; i<numNodes; ++i) {
if (node[i].level != RESERVED && node[i].visitCount < count) {
node[i].level = RESERVED;
freeList.push_back(i);
}
}
}
void UCTTree::deleteSubtree(UCTNode* n) {
for(vector<UCTNode*>::iterator it = n->children.begin(); it != n->children.end(); ++it) {
deleteSubtree(*it);
}
recycleNode(n);
}
// result is #black-stone - #white-stone
void UCTTree::updateStat(vector<SgPoint>& seqIn, vector<SgPoint>& seqOut, COUNT result) {
// TODO assert the color
int MAX_DEPTH = numeric_limits<int>::max();
int moveDepth[2][SG_MAXPOINT];
fill(moveDepth[0], moveDepth[0] + SG_MAXPOINT, MAX_DEPTH);
fill(moveDepth[1], moveDepth[1] + SG_MAXPOINT, MAX_DEPTH);
int rootLevel = rootNode()->level;
int k = 1;
vector<SgPoint>::iterator it;
for(it = seqIn.begin(); it != seqIn.end(); ++it) {
++k;
}
for(it = seqOut.begin(); it != seqOut.end(); ++it) {
int player = 1 - (rootLevel + k) % 2;
if (moveDepth[player][*it] == MAX_DEPTH) {
moveDepth[player][*it] = k;
}
++k;
}
VALUE delta = 0.5;
if (result > game->getKomi()) delta = 1;
else if (result < game->getKomi()) delta = 0;
COUNT weight = game->resultWeight(result);
// from root go down
UCTNode* p = rootNode();
p->updateVisit(weight, delta);
for(vector<int>::iterator it = seqIn.begin(); it != seqIn.end(); ++it) {
vector<UCTNode*>& children = p->children;
vector<UCTNode*>::iterator j = children.begin();
UCTNode* next = NULL;
for(; j != children.end(); ++j) {
UCTNode& c = *(*j);
if (c.move == *it) {
next = &c;
c.updateVisit(weight, delta);
}
else {
int d = moveDepth[p->level % 2][c.move];
if (d != MAX_DEPTH)
c.updateRave(1 - (double)(d) / k, delta);
}
}
poco_assert(next != NULL);
p = next;
}
}
void UCTTree::update(SgPoint move) {
// TODO maybe the move is pass, and we simply reconstruct a new tree
poco_assert(move != SG_NULLMOVE);
UCTNode* next = NULL;
UCTNode* n = rootNode();
vector<UCTNode*>& children = n->children;
for(vector<UCTNode*>::iterator it = children.begin(); it != children.end(); ++it) {
if ((*it)->move == move) {
next = *it;
continue;
}
deleteSubtree(*it);
}
// A PASS MOVE, maybe
if (next == NULL) {
next = allocateNode();
next->level = n->level + 1;
}
recycleNode(n);
root = next - node;
}
inline bool IsSimpleEye(const GoBoard& bd, SgPoint p,
SgBlackWhite c)
{
// Function is inline despite its large size, because it returns quickly
// on average, which makes the function call an overhead
SgBlackWhite opp = SgOppBW(c);
if (bd.HasEmptyNeighbors(p) || bd.HasNeighbors(p, opp))
return false;
SgArrayList<SgPoint,2> anchors;
SgArrayList<SgPoint, 4> nb_p;
getGoNeighbors(bd, p, nb_p);
for (SgArrayList<SgPoint, 4>::Iterator it(nb_p); it; ++it)
{
SgPoint nbPoint = *it;
if (bd.IsBorder(nbPoint))
continue;
poco_assert(bd.GetColor(nbPoint) == c);
SgPoint nbAnchor = bd.Anchor(nbPoint);
if (! anchors.Contains(nbAnchor))
{
if (anchors.Length() > 1)
return false;
anchors.PushBack(nbAnchor);
}
}
if (anchors.Length() == 1)
return true;
for (GoBoard::LibertyIterator it(bd, anchors[0]); it; ++it)
{
SgPoint lib = *it;
if (lib == p)
continue;
bool isSecondSharedEye = true;
SgArrayList<SgPoint,2> foundAnchors;
SgArrayList<SgPoint, 4> nb_lib;
getGoNeighbors(bd, p, nb_lib);
for (SgArrayList<SgPoint, 4>::Iterator it2(nb_lib); it2; ++it2)
{
SgPoint nbPoint = *it2;
if (bd.IsBorder(nbPoint))
continue;
if (bd.GetColor(nbPoint) != c)
{
isSecondSharedEye = false;
break;
}
SgPoint nbAnchor = bd.Anchor(nbPoint);
if (! anchors.Contains(nbAnchor))
{
isSecondSharedEye = false;
break;
}
if (! foundAnchors.Contains(nbAnchor))
foundAnchors.PushBack(nbAnchor);
}
if (isSecondSharedEye && foundAnchors.Length() == 2)
return true;
}
return false;
}
bool UCTTree::tryExpand(GoBoard* board, UCTNode* node, SuperGoGame* game, BoardState& state) {
if (node->fullyExpanded) {
vector<UCTNode*> children = node->children;
if (children.size() > 1) {
swap(children[0], children[rand.next(children.size())]);
}
return true;
}
SgBlackWhite toPlay = node->level % 2 == 0 ? SG_BLACK : SG_WHITE;
bool asChild[SG_MAXPOINT];
fill(asChild, asChild + SG_MAXPOINT, false);
vector<UCTNode*>& children = node->children;
for (vector<UCTNode*>::iterator it = children.begin(); it != children.end(); ++it) {
asChild[(*it)->move] = true;
}
int total = board->Size() * board->Size();
if (node->level < total)
children.reserve(total - node->level + 10);
vector<UCTNode*> newChildren;
for (GoBoard::Iterator it(*board); it; ++it) {
if (!asChild[*it] && board->GetColor(*it) == SG_EMPTY
&& board->IsLegal(*it) && !IsSimpleEye(*board, *it, toPlay)) {
UCTNode* n = allocateNode();
if (n == NULL) return false;
n->level = node->level+1;
n->move = *it;
preprocess(board, n);
children.push_back(n);
newChildren.push_back(n);
}
}
preprocessChildren(board, node, newChildren);
node->fullyExpanded = true;
if (children.empty()) {
COUNT res = game->evaluate(board);
if (res > game->getKomi()) state = BLACK_WIN;
else if (res == game->getKomi()) state = DRAW;
else state = WHITE_WIN;
return true;
}
// do some initialization
{
vector<UCTNode*> children = node->children;
if (children.size() > 1) {
swap(children[0], children[rand.next(children.size())]);
}
}
// Logger& logger = Util::getTreeLogger();
// if (logger.getLevel() >= 7) {
// logger.debug("children");
// for(int i=0; i<node->children.size(); ++i) {
// poco_debug_f2(logger, "move = %d, level = %d", node->children[i]->move, node->children[i]->level);
// }
//
// }
return true;
}
| [
"[email protected]"
]
| [
[
[
1,
263
]
]
]
|
5bc7630a5ba8b1755ec978f3246015fbe8816d4d | 8c420a18fa238742201a84845d1cae5a3f281879 | /StockDayDataUnit.h | 1445a9ce8bbeb8dacf94a4a41033c3a159e4ddfc | []
| no_license | gjj2828/stock-record | 7d41f4a85bdb5d70dd49bfffe40c6d82ed788f9c | 148b2140f9fe278519c0467056a336aca0fe3d30 | refs/heads/master | 2016-09-06T17:15:15.472000 | 2009-02-26T06:29:55 | 2009-02-26T06:29:55 | 32,394,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 810 | h | /***************************************************************
* Name: StockDayDataUnit.h
* Purpose: Defines StockDayDataUnit Class
* Author: gaojiongjiong ()
* Created: 2009-02-25
* Copyright: gaojiongjiong ()
* License:
**************************************************************/
#ifndef STOCKDAYDATAUNIT_H
#define STOCKDAYDATAUNIT_H
class StockDayDataUnit
{
private:
Date m_date;
PriceAmount buy[ENTRUST_GRADE];
PriceAmount sell[ENTRUST_GRADE];
char m_name[STOCK_NAME_LENGTH];
float m_close;
float m_prev_close;
float m_open;
float m_low;
float m_high;
float m_amount;
float m_volumn;
float m_buying;
float m_selling;
float m_shift;
};
#endif //STOCKDAYDATAUNIT_H
| [
"gjj2828@8d41a414-030e-11de-9d1d-173cc1d06e3c"
]
| [
[
[
1,
32
]
]
]
|
8b89c6ab3e1865afc1d5a2f0d1c14c900fe92434 | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/AranIk_Test/BwMain.cpp | c26a59f73af37b137b883b90a8b3278da977261f | []
| 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 | 22,412 | cpp | #include "BwPch.h"
#include "BwMain.h"
#include "BwTopWindow.h"
#include "BwOpenGlWindow.h"
#include "BwAppContext.h"
#include "BwWin32Timer.h"
#include "BwDrawingOptionsWindow.h"
#include "BwPlaybackSlider.h"
#include "SliderInput.h"
namespace fs = boost::filesystem;
void idle_cb(void* ac);
#if !HAVE_GL
#error OpenGL in FLTK not enabled.
#endif
struct SceneButtonsHolder
{
BwAppContext* ac;
MessageHandleResult mhr;
};
void dump_cb(Fl_Widget *o, void *ac_raw)
{
}
void print_rb0_cb(Fl_Widget *o, void *ac_raw)
{
}
void load_cb(Fl_Widget *o, void *ac_raw)
{
}
static inline double
FootHeight(double t, double stepLength, double maxStepHeight)
{
if (t <= 0 || t >= stepLength)
return 0;
else
return -4.0*maxStepHeight*t*(t-stepLength)/(stepLength*stepLength);
}
static ArnSceneGraphPtr
ConfigureTestScene(const char* sceneFileName, const ArnViewportData* avd)
{
ArnSceneGraphPtr ret(ArnSceneGraph::createFrom(sceneFileName));
if (!ret)
{
fprintf(stderr, " *** Scene graph file %s is not loaded correctly.\n",
sceneFileName);
fprintf(stderr, " Check your input XML scene file.\n");
return ArnSceneGraphPtr();
}
ret->interconnect(ret.get());
std::cout << " Scene file " << sceneFileName
<< " loaded successfully." << std::endl;
return ret;
}
static ArnSceneGraphPtr
ConfigureNextTestSceneWithRetry(int& curSceneIndex, int nextSceneIndex,
const std::vector<std::string>& sceneList,
const ArnViewportData& avd)
{
assert(nextSceneIndex < (int)sceneList.size());
curSceneIndex = nextSceneIndex;
unsigned int retryCount = 0;
ArnSceneGraphPtr ret;
while (!ret) {
ret = ConfigureTestScene(sceneList[curSceneIndex].c_str(), &avd);
if (ret) {
return ret;
} else {
curSceneIndex = (curSceneIndex + 1) % sceneList.size();
++retryCount;
}
if (retryCount >= sceneList.size()) {
std::cerr << " *** All provided scene files have errors." << std::endl;
return ArnSceneGraphPtr();
}
}
return ret;
}
static ArnSceneGraphPtr
ReloadCurrentScene(int& curSceneIndex,
const std::vector<std::string>& sceneList,
const ArnViewportData& avd)
{
return ConfigureNextTestSceneWithRetry(curSceneIndex, curSceneIndex,
sceneList, avd);
}
static void
Cleanup()
{
ArnCleanupXmlParser();
ArnCleanupImageLibrary();
ArnCleanupPhysics();
ArnCleanupGl();
}
static void
GetActiveCamAndLight(ArnCamera*& activeCam, ArnLight*& activeLight,
ArnSceneGraph* sg)
{
activeCam = sg->getFirstCamera();
assert(activeCam);
activeCam->recalcLocalXform();
activeCam->recalcAnimLocalXform();
//activeCam->printCameraOrientation();
activeLight = reinterpret_cast<ArnLight*>(sg->findFirstNodeOfType(NDT_RT_LIGHT));
assert(activeLight);
}
static int
LoadSceneList(std::vector<std::string>& sceneList)
{
// Load first scene file from SceneList.txt
assert(sceneList.size() == 0);
std::ifstream sceneListStream("SceneList.txt");
std::string sceneFile;
if (!sceneListStream.is_open()) {
std::cout << " *** WARN: SceneList.txt file is not available.\n";
return 0; // No scene loaded.
}
int sceneCount = 0;
while (std::getline(sceneListStream, sceneFile)) {
sceneList.push_back(sceneFile);
++sceneCount;
}
return sceneCount;
}
static void
UpdateScene(BwAppContext& ac, float fElapsedTime)
{
// Physics simulation frequency (Hz)
// higher --> accurate, stable, slow
// lower --> errors, unstable, fast
static const unsigned int simFreq = 600;
// Maximum simulation step iteration count for clamping
// to keep app from advocating all resources to step further.
static const unsigned int simMaxIteration = 100;
unsigned int simLoop = (unsigned int)(fElapsedTime * simFreq);
if (simLoop > simMaxIteration)
simLoop = simMaxIteration;
else if (simLoop == 0)
simLoop = 2;
simLoop = 2; // TODO: Simulation frequency
for (unsigned int step = 0; step < simLoop; ++step) {
//printf("frame duration: %d / simloop original: %d / current simstep %d\n", frameDurationMs, (unsigned int)(frameDurationMs / 1000.0 * simFreq), step);
if (ac.swPtr)
ac.swPtr->updateFrame(1.0 / simFreq);
}
if (ac.sgPtr) {
ac.sgPtr->update(ac.timer.getTicks() / 1000.0, fElapsedTime);
}
foreach (ArnIkSolver* ikSolver, ac.ikSolvers) {
ikSolver->update();
Node* selNode = ikSolver->getSelectedEndeffector();
if (selNode) {
}
}
if (ac.bNextCamera) {
ac.activeCam = ac.sgPtr->getNextCamera(ac.activeCam);
ac.bNextCamera = false;
}
ArnVec3 cameraDiff(0, 0, 0);
static const float cameraDiffAmount = 0.1f;
if (ac.activeCam) {
ac.activeCam->setLocalXform_Trans( ac.activeCam->getLocalXform_Trans() + cameraDiff );
ac.activeCam->recalcLocalXform();
}
ac.isects.clear();
ac.verticalLineIsects.clear();
ac.supportPolygon.clear();
bool useGroundPlaneBodyIntersection = true;
if (ac.trunk) {
// Update COM pos
ArnVec3 bipedComPos;
ac.trunk->calculateLumpedComAndMass(&bipedComPos, &ac.bipedMass);
ac.bipedComPos.push_back(bipedComPos); // Save the trail of COM for visualization
if (useGroundPlaneBodyIntersection) {
// Needed for support polygon visualization
//ac.trunk->calculateLumpedGroundIntersection(ac.isects);
ac.trunk->calculateLumpedIntersection(ac.isects, ac.contactCheckPlane);
} else {
const unsigned int swContactCount = ac.swPtr->getContactCount();
for (unsigned int i = 0; i < swContactCount; ++i) {
ArnVec3 contactPos;
ac.swPtr->getContactPosition(i, &contactPos);
ac.isects.push_back(contactPos);
}
}
}
}
static void
AddToSceneGraphList( const ArnNode* node, Fl_Browser* list, int depth )
{
std::string itemName("@s@f");
for (int i = 0; i < depth; ++i)
itemName += " ";
if (strlen(node->getName()))
itemName += node->getName();
else
itemName += "<unnamed>";
list->add(itemName.c_str());
foreach (const ArnNode* child, node->getChildren()) {
AddToSceneGraphList(child, list, depth+1);
}
}
static void
UpdateSceneGraphList( BwAppContext& ac )
{
if (ac.sceneGraphList) {
ac.sceneGraphList->clear();
if (ac.sgPtr)
AddToSceneGraphList(ac.sgPtr->getSceneRoot(), ac.sceneGraphList, 0);
}
}
/*!
* @brief Scene graph가 새로 로드되었을 때 수행되는 초기화 (렌더러와 무관)
*/
static int
InitializeRendererIndependentsFromSg(BwAppContext& ac)
{
ac.frames = 0;
assert(ac.sgPtr);
ac.swPtr.reset(SimWorld::createFrom(ac.sgPtr.get()));
GetActiveCamAndLight(ac.activeCam, ac.activeLight, ac.sgPtr.get());
foreach (ArnIkSolver* ikSolver, ac.ikSolvers) {
delete ikSolver;
}
ac.ikSolvers.clear();
ac.bipedComPos.clear();
if (ac.swPtr) {
ac.trunk = ac.swPtr->getBodyByNameFromSet("Trunk");
// Create ArnSkeleton from rigid body links!
if (ac.trunk) {
ac.bipedComPos.clear();
ArnVec3 comPos;
ac.trunk->calculateLumpedComAndMass(&comPos, &ac.bipedMass);
ac.bipedComPos.push_back(comPos);
std::cout << " - Biped total mass: " << ac.bipedMass << std::endl;
ArnSkeleton* trunkSkel = ac.trunk->createLumpedArnSkeleton(ac.swPtr);
trunkSkel->setName("Autogenerated Skeleton");
ac.sgPtr->attachChildToFront(trunkSkel);
}
}
// TODO: Attaching ArnIkSolver onto specific skeletons makes crash for some cases
//ArnCreateArnIkSolversOnSceneGraph(ac.ikSolvers, ac.sgPtr);
UpdateSceneGraphList(ac);
return 0;
}
/*!
* @brief Scene graph가 새로 로드되었을 때 수행되는 초기화 (렌더러 종속)
*/
static int
InitializeRendererDependentsFromSg(BwAppContext& ac)
{
if (ac.sgPtr.get())
ArnInitializeRenderableObjectsGl(ac.sgPtr.get());
return 0;
}
static int
InitializeRendererDependentOnce(BwAppContext& ac)
{
// OpenGL context available from this line.
if (!glGetString( GL_VENDOR ) || !glGetString( GL_RENDERER ) || !glGetString( GL_VERSION )) {
printf(" OpenGL context is not availble yet. Aborting...\n");
return -1234;
}
printf( "Vendor : %s\n", glGetString( GL_VENDOR ) );
printf( "Renderer : %s\n", glGetString( GL_RENDERER ) );
printf( "Version : %s\n", glGetString( GL_VERSION ) );
//printf( "Extensions : %s\n", glGetString( GL_EXTENSIONS ) );
printf("\n");
/// OpenGL 플래그를 설정합니다.
/// 이러한 전역 OpenGL 스테이트를 변경하는 것은 최대한 여기서
/// 초기화 단계에 한번만 하는 것으로 해야 합니다.
/// 일부분 코드에 대해서만 스테이트를 잠시 변경할 필요가 있을 때는
/// 반드시 glAttribPush/Pop() 함수를 이용하여
/// 전역 설정이 완전히 변경되는 경우가 없도록 해야 합니다.
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
// Enables Depth Testing
glShadeModel(GL_SMOOTH);
// Enable Smooth Shading
//glShadeModel(GL_FLAT);
// Enable Smooth Shading
glClearDepth(1.0f);
// Depth Buffer Setup
glDepthFunc(GL_LEQUAL);
// The Type Of Depth Testing To Do
// Really Nice Perspective Calculations
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glEnable(GL_NORMALIZE);
for (int lightId = 0; lightId < 8; ++lightId)
{
glDisable(GL_LIGHT0 + lightId);
}
/// OpenGL 확장 기능을 초기화합니다.
if (ArnInitGlExtFunctions() < 0)
{
std::cerr << " *** OpenGL extensions needed to run this program are not available." << std::endl;
std::cerr << " Check whether you are in the remote control display or have a legacy graphics adapter." << std::endl;
std::cerr << " Aborting..." << std::endl;
return -50;
}
/// ARAN OpenGL 패키지를 초기화합니다.
if (ArnInitializeGl() < 0)
{
return -3;
}
/// Mass map 텍스처를 생성합니다.
glGenTextures(1, &ac.massMapTex);
glBindTexture( GL_TEXTURE_2D, ac.massMapTex );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glBindTexture(GL_TEXTURE_2D, 0);
if (InitializeRendererDependentsFromSg(ac) < 0)
{
return -2;
}
return 0;
}
int
InitializeRendererIndependentOnce(BwAppContext& ac)
{
/*!
* 렌더러 독립적 ARAN 패키지인 ARAN Core, ARAN Physics를 초기화합니다.
* 초기화가 성공한 이후 프로그램의 치명적인 오류로 인해 실행이 중단될 경우
* 반드시 Cleanup() 을 호출해야 합니다.
* 본 초기화가 실패할 경우에는 프로그램이 종료됩니다.
*/
if (ArnInitializeXmlParser() < 0) {
Cleanup();
return -1;
}
if (ArnInitializeImageLibrary() < 0) {
Cleanup();
return -2;
}
if (ArnInitializePhysics() < 0) {
Cleanup();
return -3;
}
// Notice for 32-bit and 64-bit build: Do not confuse the size of pointers!
std::cout << " INFO Raw pointer size = " << sizeof(ArnSceneGraph*) << std::endl;
std::cout << " INFO Shared pointer size = " << sizeof(ArnSceneGraphPtr) << std::endl;
/// \c SceneList.txt 를 파싱합니다.
if (LoadSceneList(ac.sceneList) < 0) {
std::cerr << " *** Init failed..." << std::endl;
return -10;
}
memset(ac.bHoldingKeys, 0, sizeof(ac.bHoldingKeys));
// Default viewport init
ac.avd.X = 0;
ac.avd.Y = 0;
ac.avd.MinZ = 0;
ac.avd.MaxZ = 1.0f;
// View mode
ac.viewMode = VM_UNKNOWN;
ac.orthoViewDistance = 5;
// Panning by dragging
ac.bPanningButtonDown = false;
ac.panningCenter[0] = 0;
ac.panningCenter[1] = 0;
ac.panningCenter[2] = 0;
ac.dPanningCenter[0] = 0;
ac.dPanningCenter[1] = 0;
ac.dPanningCenter[2] = 0;
// Drawing options
for (int i = 0; i < do_count; ++i)
ac.drawing_options[i] = false;
// Scene graph UI
ac.sceneGraphList = 0;
// Rigid body simulation
ac.bSimulate = false;
/// 다음 카메라로 변경 플래그 초기화
ac.bNextCamera = false;
// Timer init
ac.timer.start();
// SimWorld history
ac.simWorldHistory.resize(10000);
ac.contactCheckPlane.setV0(ArnVec3(0, 0, 0.01f));
ac.contactCheckPlane.setNormal(ArnVec3(0, 0, 1.0f));
/// (있다면) 첫 장면 파일을 메모리에 로드합니다.
ac.curSceneIndex = -1;
if (ac.sceneList.size() > 0) {
ac.sgPtr = ConfigureNextTestSceneWithRetry(ac.curSceneIndex, 0, ac.sceneList, ac.avd);
if (!ac.sgPtr) {
std::cerr << " *** Scene graph loading failed..." << std::endl;
Cleanup();
return -20;
}
assert(ac.sgPtr);
/// 처음으로 로드한 모델 파일에 종속적인 데이터를 초기화합니다.
if (InitializeRendererIndependentsFromSg(ac) < 0) {
Cleanup();
return -1;
}
} else {
std::cout << "WARN: No scene file listed on SceneList.txt\n";
}
return 0;
}
// when you change the data, as in this callback, you must call redraw():
void sides_cb(Fl_Widget *o, void *p)
{
BwOpenGlWindow *sw = (BwOpenGlWindow *)p;
//sw->sides = int(((Fl_Slider *)o)->value());
sw->redraw();
}
void overlay_sides_cb(Fl_Widget *o, void *p)
{
BwOpenGlWindow *sw = (BwOpenGlWindow *)p;
//sw->overlay_sides = int(((Fl_Slider *)o)->value());
sw->redraw_overlay();
}
void update_idle_cb_attachment(BwAppContext &ac)
{
ac.bSimulate = ac.simulateButton->value() ? true : false;
if (ac.bSimulate) {
if (!Fl::has_idle(idle_cb, &ac))
Fl::add_idle(idle_cb, &ac);
} else {
if (Fl::has_idle(idle_cb, &ac))
Fl::remove_idle(idle_cb, &ac);
}
}
void step(BwAppContext &ac)
{
static double start_time = 0;
static double frameStartMs = 0;
static double frameDurationMs = 0;
static double frameEndMs = 0;
static int simFrame = 0;
if (!start_time)
start_time = ac.timer.getTicks();
frameDurationMs = frameEndMs - frameStartMs;
//printf("Total %lf FrameDuration %lf\n", frameStartMs - start_time, frameDurationMs);
frameStartMs = ac.timer.getTicks();
UpdateScene(ac, (float)(frameDurationMs / 1000.0));
frameEndMs = ac.timer.getTicks();
ac.glWindow->redraw();
if (ac.swPtr)
ac.swPtr->getSimWorldState(ac.simWorldHistory[ac.frames]);
std::stringstream ss;
ss << setiosflags(ios::fixed) << setprecision(4);
/*int frame_move_ret = 0;
char result_msg[2048] = {0,};
std::string sss(ss.str());
static char slidersss[1024];
strncpy(slidersss, sss.c_str(), 1024);
ac.slider->label(slidersss);*/
}
void idle_cb(void* ac_raw)
{
BwAppContext& ac = *(BwAppContext*)ac_raw;
if (ac.bSimulate) {
step(ac);
}
}
void simulate_button_cb(Fl_Widget *o, void *p)
{
Fl_Light_Button* widget = (Fl_Light_Button*)o;
BwAppContext& ac = *(BwAppContext*)p;
update_idle_cb_attachment(ac);
}
void real_muscle_cb(Fl_Widget *o, void *p)
{
}
void set_vel_zero_cb(Fl_Widget *o, void *p)
{
}
void scene_buttons_cb(Fl_Widget* o, void* p)
{
SceneButtonsHolder* sbh = (SceneButtonsHolder*)p;
BwAppContext& ac = *sbh->ac;
BwOpenGlWindow& openGlWindow = *sbh->ac->glWindow;
MessageHandleResult done = sbh->mhr;
int reconfigScene = false;
if (ac.sceneList.size() && (done == MHR_NEXT_SCENE || done == MHR_PREV_SCENE)) {
int nextSceneIndex;
if (done == MHR_NEXT_SCENE) {
nextSceneIndex = (ac.curSceneIndex + 1) % ac.sceneList.size();
} else {
if (ac.curSceneIndex == 0)
nextSceneIndex = ac.sceneList.size() - 1;
else
nextSceneIndex = ac.curSceneIndex - 1;
}
ac.sgPtr = ConfigureNextTestSceneWithRetry(ac.curSceneIndex, nextSceneIndex, ac.sceneList, ac.avd);
if (!ac.sgPtr) {
std::cerr << " *** Aborting..." << std::endl;
done = MHR_EXIT_APP;
} else {
reconfigScene = true;
}
} else if (done == MHR_RELOAD_SCENE) {
if (ac.sceneList.size()) {
ac.sgPtr = ReloadCurrentScene(ac.curSceneIndex, ac.sceneList, ac.avd);
if (!ac.sgPtr) {
std::cerr << " *** Aborting..." << std::endl;
done = MHR_EXIT_APP;
}
}
reconfigScene = true;
} else if (done == MHR_STEP_SIMULATION) {
step(ac);
}
if (reconfigScene) {
if (ac.sceneList.size()) {
InitializeRendererIndependentsFromSg(ac);
InitializeRendererDependentsFromSg(ac);
}
openGlWindow.redraw();
}
}
int doMain(int argc, char **argv)
{
int ret = 0;
BwAppContext ac;
if (InitializeRendererIndependentOnce(ac) < 0) {
printf("Critical error during initialization of "
"application context. Aborting...\n");
abort();
}
BwTopWindow topWindow(800, 600, "aran", ac);
std::ifstream windowPosAndSizeInput("BwWindow.txt");
if (windowPosAndSizeInput.is_open()) {
int x, y, w, h;
windowPosAndSizeInput >> x >> y >> w >> h;
topWindow.resize(x, y, w, h);
}
BwOpenGlWindow openGlWindow(210, 75,
topWindow.w()-20-400, topWindow.h()-290,
0, ac);
//openGlWindow.mode(FL_RGB | FL_DOUBLE | FL_DEPTH);
topWindow.setShapeWindow(&openGlWindow);
//sw.mode(FL_RGB);
topWindow.resizable(&openGlWindow);
SceneButtonsHolder sbh[4] = {
{&ac, MHR_RELOAD_SCENE},
{&ac, MHR_PREV_SCENE},
{&ac, MHR_NEXT_SCENE},
{&ac, MHR_STEP_SIMULATION},
};
Fl_Button reloadSceneButton(10, 5, 70, 30, "Reload");
reloadSceneButton.callback(scene_buttons_cb, &sbh[0]);
Fl_Button nextSceneButton(10+75, 5, 50, 30, "Prev");
nextSceneButton.callback(scene_buttons_cb, &sbh[1]);
Fl_Button prevSceneButton(10+75+55, 5, 50, 30, "Next");
prevSceneButton.callback(scene_buttons_cb, &sbh[2]);
Fl_Light_Button simulateButton(10, 40, 100, 30, "@> Simulate");
simulateButton.callback(simulate_button_cb, &ac);
ac.simulateButton = &simulateButton;
Fl_Button stepButton(115, 40, 40, 30, "Step");
stepButton.callback(scene_buttons_cb, &sbh[3]);
Fl_Button frameLabel(10+100+60, 40, 100, 30, "Frame");
frameLabel.box(FL_NO_BOX);
frameLabel.align(FL_ALIGN_INSIDE | FL_ALIGN_RIGHT);
frameLabel.label(ac.frameStr);
ac.frameLabel = &frameLabel;
Fl_Button load(300, 5, 100, 30, "Load");
load.callback(load_cb, &ac);
Fl_Button dump(415, 5, 100, 30, "Dump");
dump.callback(dump_cb, &ac);
Fl_Hor_Slider slider(510, 5, topWindow.w()-520, 30, "Sides");
slider.align(FL_ALIGN_INSIDE | FL_ALIGN_LEFT);
slider.callback(sides_cb, &openGlWindow);
slider.step(1);
slider.bounds(3,40);
PlaybackSlider playbackSlider(300, 40, topWindow.w()-310, 30, 0, ac);
ac.playbackSlider = &playbackSlider;
playbackSlider.bounds(0, ac.MAX_SIMULATION_FRAMES-1); // Maximum 10000 frames can be simulated.
playbackSlider.align(FL_ALIGN_LEFT);
playbackSlider.step(1);
BwDrawingOptionsWindow drawingOptions(topWindow.w()-200, 75,
190, 200, "Drawings", ac, openGlWindow);
Fl_Button print_rb0_btn(topWindow.w()-200, 740, 190, 25, "Print RB[0] State");
print_rb0_btn.callback(print_rb0_cb, &ac);
Fl_Browser sceneList(10000+topWindow.w()-200, 75+110+100, 190, 100);
Fl_Browser sceneGraphList(10000+topWindow.w()-200, 75+110+110+100,
190, topWindow.h()-90-110-110-200);
ac.sceneGraphList = &sceneGraphList;
ac.glWindow = &openGlWindow;
Fl_Button omega_label(0, 75+110+110 + (topWindow.h()-90-110-110-200), 600, 300, "text info");
omega_label.box(FL_NO_BOX);
omega_label.align(FL_ALIGN_INSIDE | FL_ALIGN_LEFT | FL_ALIGN_TOP);
ac.slider = &omega_label;
// Style table
Fl_Text_Display::Style_Table_Entry stable[] = {
// FONT COLOR FONT FACE FONT SIZE
// --------------- ----------- --------------
{ FL_RED, FL_COURIER, 10 }, // A - Red
{ FL_DARK_YELLOW, FL_COURIER, 10 }, // B - Yellow
{ FL_DARK_GREEN, FL_COURIER, 10 }, // C - Green
{ FL_BLUE, FL_COURIER, 10 }, // D - Blue
};
Fl_Browser *b = new Fl_Browser(500,75+110+110 + (topWindow.h()-90-110-110-200),500,200);
int widths[] = { 100, 100, 100, 70, 70, 40, 40, 70, 70, 50, 0 }; // widths for each column
b->textsize(9);
b->column_widths(widths);
b->column_char('\t'); // tabs as column delimiters
b->type(FL_MULTI_BROWSER);
ac.fiber_browser = b;
topWindow.setSceneList(&sceneList);
topWindow.end();
//topWindow.show(argc,argv);
topWindow.show();
openGlWindow.show();
openGlWindow.make_current();
openGlWindow.redraw_overlay();
GLenum err = glewInit();
if (GLEW_OK != err) {
printf("Error: glewInit() failed\n");
return 1;
}
InitializeRendererDependentOnce(ac);
UpdateSceneGraphList(ac);
// scene list available now
foreach (const std::string& scene, ac.sceneList) {
sceneList.add(scene.c_str());
}
ret = Fl::run();
std::ofstream windowPosAndSize("BwWindow.txt");
windowPosAndSize << topWindow.x() << " " << topWindow.y() << " "
<< topWindow.w() << " " << topWindow.h() << std::endl;
windowPosAndSize.close();
return ret;
}
int main(int argc, char **argv)
{
aran::core::PathManager pm;
pm.set_shader_dir("resources/shaders/");
pm.set_model_dir("resources/models/");
int ret = doMain(argc, argv);
if (ret) {
std::cout << "Error detected.\n";
}
#ifdef ARNOBJECT_GLOBAL_MANAGEMENT_FOR_DEBUGGING
// Simple check for the memory leak of ArnObjects.
std::cout << "ArnObject ctor count: " << ArnObject::getCtorCount() << std::endl;
std::cout << "ArnObject dtor count: " << ArnObject::getDtorCount() << std::endl;
ArnObject::printInstances();
#endif // #ifdef ARNOBJECT_GLOBAL_MANAGEMENT_FOR_DEBUGGING
return ret;
}
| [
"[email protected]"
]
| [
[
[
1,
718
]
]
]
|
bb8724095046f920bf90e216ace38d6c64613e3c | 741b36f4ddf392c4459d777930bc55b966c2111a | /incubator/happylib/HappyLib/LWPPanel.h | 88ab5675ee449a73797cee8533bd469dc9318ec1 | []
| no_license | BackupTheBerlios/lwpp-svn | d2e905641f60a7c9ca296d29169c70762f5a9281 | fd6f80cbba14209d4ca639f291b1a28a0ed5404d | refs/heads/master | 2021-01-17T17:01:31.802187 | 2005-10-16T22:12:52 | 2005-10-16T22:12:52 | 40,805,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,008 | h |
#ifndef _LWPPANEL_H
#define _LWPPANEL_H
//// wrapper for LWValue [DOCUMENTME] ////
class LWPValue
{
protected:
mutable LWValue lwvalue;
public:
operator LWValue * () const { return &lwvalue; }
};
class LWPValString : public LWPValue
{
public:
LWPValString(char * buf, int bufLen)
{
lwvalue.type = LWT_STRING;
lwvalue.str.buf = buf;
lwvalue.str.bufLen = bufLen;
}
};
class LWPValPtr : public LWPValue
{
public:
LWPValPtr(void * value)
{
lwvalue.type = LWT_INTEGER;
lwvalue.intv.value = (int)value;
lwvalue.intv.defVal = (int)value;
}
};
class LWPValInt : public LWPValue
{
public:
LWPValInt() // [FIXME] make default constructor for the other types too
{
lwvalue.type = LWT_INTEGER;
}
LWPValInt(int value)
{
lwvalue.type = LWT_INTEGER;
lwvalue.intv.value = value;
lwvalue.intv.defVal = value;
}
LWPValInt(int value, int defVal)
{
lwvalue.type = LWT_INTEGER;
lwvalue.intv.value = value;
lwvalue.intv.defVal = defVal;
}
int value() { return lwvalue.intv.value; } // [FIXME] make this for the other types too
};
class LWPValFloat : public LWPValue
{
public:
LWPValFloat(double value)
{
lwvalue.type = LWT_FLOAT;
lwvalue.flt.value = value;
lwvalue.flt.defVal = value;
}
LWPValFloat(double value, double defVal)
{
lwvalue.type = LWT_FLOAT;
lwvalue.flt.value = value;
lwvalue.flt.defVal = defVal;
}
};
class LWPValIVector : public LWPValue
{
public:
LWPValIVector()
{
lwvalue.type = LWT_VINT;
}
LWPValIVector(int val[3])
{
lwvalue.type = LWT_VINT;
memcpy(&lwvalue.ivec.val, &val, sizeof(int[3]));
lwvalue.ivec.defVal = val[0];
}
LWPValIVector(int val[3], int defVal)
{
lwvalue.type = LWT_VINT;
memcpy(&lwvalue.ivec.val, &val, sizeof(int[3]));
lwvalue.ivec.defVal = defVal;
}
void value(int val[3]) { memcpy(val, lwvalue.ivec.val, 3*sizeof(int)); }
};
class LWPValFVector : public LWPValue
{
public:
LWPValFVector(double val[3])
{
lwvalue.type = LWT_VFLOAT;
memcpy(&lwvalue.fvec.val, &val, sizeof(int[3]));
lwvalue.fvec.defVal = val[0];
}
LWPValFVector(double val[3], double defVal)
{
lwvalue.type = LWT_VFLOAT;
memcpy(&lwvalue.fvec.val, &val, sizeof(int[3]));
lwvalue.fvec.defVal = defVal;
}
};
class LWPValCustom : public LWPValue
{
public:
LWPValCustom(int val[4])
{
lwvalue.type = LWT_CUSTOM;
memcpy(&lwvalue.cust.val, &val, sizeof(int[4]));
}
};
//// wrapper for LWPanControlDesc [DOCUMENTME] ////
class LWPControlDesc
{
protected:
mutable LWPanControlDesc desc;
public:
operator LWPanControlDesc * () const { return &desc; }
};
class LWPStringDesc : public LWPControlDesc
{
public:
LWPStringDesc(int width)
{
desc.type = LWT_STRING;
desc.string.width = width;
}
};
class LWPChoiceDesc : public LWPControlDesc
{
public:
LWPChoiceDesc(char const ** items, int vertical)
{
desc.type = LWT_CHOICE;
desc.choice.items = items;
desc.choice.vertical = vertical;
}
};
class LWPTextDesc : public LWPControlDesc
{
public:
LWPTextDesc(char const ** text)
{
desc.type = LWT_TEXT;
desc.text.text = text;
}
};
class LWPRangeDesc : public LWPControlDesc
{
public:
LWPRangeDesc(int width, int min, int max)
{
desc.type = LWT_RANGE;
desc.range.width = width;
desc.range.min = min;
desc.range.max = max;
}
};
class LWPAreaDesc : public LWPControlDesc
{
public:
LWPAreaDesc(int width, int height)
{
desc.type = LWT_AREA;
desc.area.width = width;
desc.area.height = height;
}
};
class LWPLWItemDesc : public LWPControlDesc
{
public:
LWPLWItemDesc(int itemType, char ** list, int count, int width)
{
desc.type = LWT_LWITEM;
desc.lwitem.global = LWPPlugin::globalFunc;
desc.lwitem.itemType = itemType;
desc.lwitem.list = list;
desc.lwitem.count = count;
desc.lwitem.width = width;
}
};
class LWPPopupDesc : public LWPControlDesc
{
public:
LWPPopupDesc(int width,
int (*countFn)(void *),
char * (*nameFn)(void *, int))
{
desc.type = LWT_POPUP;
desc.popup.width = width;
desc.popup.countFn = countFn;
desc.popup.nameFn = nameFn;
}
};
class LWPListBoxDesc : public LWPControlDesc
{
public:
LWPListBoxDesc(int width, int visItems, int top,
int (*countFn)(void *),
char * (*nameFn)(void *, int))
{
desc.type = LWT_POPUP;
desc.listbox.width = width; // width in pixels
desc.listbox.visItems = visItems; // height in items
desc.listbox.top = top; // top visible item
desc.listbox.countFn = countFn;
desc.listbox.nameFn = nameFn;
}
};
class LWPXPanDesc : public LWPControlDesc
{
public:
LWPXPanDesc(int width, int height, void * xpan)
{
desc.type = LWT_XPANEL;
desc.xpanel.width = width;
desc.xpanel.height = height;
desc.xpanel.xpan = xpan;
}
};
class LWPMultiListBoxDesc : public LWPControlDesc
{
public:
LWPMultiListBoxDesc(int width, int visItems, int top,
int (*countFn)(void *),
char * (*nameFn)(void *, int, int col),
int (*colWidth)(void *, int col))
{
desc.type = LWT_MLIST;
desc.multiList.width = width; // width in pixels
desc.multiList.visItems = visItems; // height in items
desc.multiList.top = top; // top visible item
desc.multiList.countFn = countFn;
desc.multiList.nameFn = nameFn;
desc.multiList.colWidth = colWidth; // pixel width of column col, up to 8 columns terminate with 0
}
};
class LWPTreeDesc : public LWPControlDesc
{
public:
LWPTreeDesc(int width, int height,
int (*countFn)(void *data, void *node),
void *(*leafFn)(void *data, void *node, int i),
char *(*infoFn)(void *data, void *node, int *nodeFlags),
void (*moveFn)(void *data, void *node, void *parentNode, int i))
{
desc.type = LWT_TREE;
desc.tree.width = width;
desc.tree.height = height;
desc.tree.countFn = countFn; // return number of leafs under given node, NULL node is root
desc.tree.leafFn = leafFn; // return leaf i of node, NULL node is root
desc.tree.infoFn = infoFn; // return "name" for node, fill 0 flags, or save non-zero flags
desc.tree.moveFn = moveFn; // NULL prevents moves, or called when user moves node, with new parent, position
}
};
//// wraper for LWPanel [DOCUMENTME] ////
class LWPPanel
{
protected:
mutable LWPanelID panel;
public:
operator LWPanelID () const { return panel; }
LWPPanel() : panel(0) {}
LWPPanel(LWPanelID panel) : panel(panel) {}
~LWPPanel() {}
// low level wraps
int open(int flags) { return LWPPlugin::panelFuncs->open(panel, flags); }
// see flag bits PANF_ etc.
int handle(int eventBits) { return LWPPlugin::panelFuncs->handle(panel, eventBits); }
// process input manually after non-blocking open, use EVNT_ bits to process async. or synchronously
void draw(DrMode md) { LWPPlugin::panelFuncs->draw(panel, md); }
void close() { LWPPlugin::panelFuncs->close(panel); }
void destroy() { LWPPlugin::panelFuncs->destroy(panel); panel = 0; }
void get(pTag tag, void * value) const { LWPPlugin::panelFuncs->get(panel, tag, value); }
void set(pTag tag, void * value) { LWPPlugin::panelFuncs->set(panel, tag, value); }
LWControl * addControl(char *type, ControlDesc *data, char *label) { return LWPPlugin::panelFuncs->addControl(panel, type, data, label); }
LWControl * nextControl(LWControlID ctl) { return LWPPlugin::panelFuncs->nextControl(panel, ctl); }
DrawFuncs * drawFuncs() { return LWPPlugin::panelFuncs->drawFuncs; }
// medium level wraps [FIXME] more functions needed like the following:
int getInt(pTag tag) const { int i; get(tag, &i); return i; }
void setData(void * data) { set(PAN_USERDATA, data); }
void setClose(XCALL_(void)(*event)(LWPanelID, void *)) { set(PAN_USERCLOSE, event); }
void setKeys(XCALL_(void)(*event)(LWPanelID, void *, LWDualKey)) { set(PAN_USERKEYS, event); }
void setDraw(XCALL_(void)(*event)(LWPanelID, DrMode)) { set(PAN_USERDRAW, event); }
void setX(int x) { set(PAN_X, &x); }
void setY(int y) { set(PAN_Y, &y); }
void setW(int w) { set(PAN_W, &w); }
void setH(int h) { set(PAN_H, &h); }
// high level wraps [FIXME] more functions needed like the following:
int getResult() const { return getInt(PAN_RESULT); }
int getX() const { return getInt(PAN_X); }
int getY() const { return getInt(PAN_Y); }
int getW() const { return getInt(PAN_W); }
int getH() const { return getInt(PAN_H); }
void setWH(int w, int h) { setW(w); setH(h); }
void setXY(int x, int y) { setX(x); setY(y); }
int good() const { return !!panel; }
int init(char const * title, void * data)
{
if (panel) destroy();
if (LWPPlugin::panelFuncs)
{
panel = LWPPlugin::panelFuncs->create((char*)title, data);
LWPPlugin::panelFuncs->globalFun = LWPPlugin::globalFunc;
}
return good();
}
void center()
{
setXY((drawFuncs()->dispMetrics()->width - getW()) / 2, (drawFuncs()->dispMetrics()->height - getH()) / 2);
}
// [FIXME] need more opening functions like these:
void openBlocking()
{
open(PANF_BLOCKING);
}
};
//// wrapper for LWControl [DOCUMENTME] ////
class LWPControl
{
public:
static LWPControl * create(LWPPanel panel, char const * type, LWPControlDesc & desc, char const * label)
{
return (LWPControl*)LWPPlugin::panelFuncs->addControl(panel, (char*)type, desc, (char*)label);
}
void draw(DrMode md) { ((LWControl*)this)->draw(((LWControl*)this), md); }
// low level wraps
void get(cTag tag, LWPValue & value) const { ((LWControl*)this)->get(((LWControl*)this), tag, value); }
void set(cTag tag, LWPValue & value) { ((LWControl*)this)->set(((LWControl*)this), tag, value); }
// medium level wraps [FIXME] more functions needed like the following:
int getInt(cTag tag) const { LWPValInt i; get(tag, i); return i.value(); }
int getInt() const { return getInt(CTL_VALUE); }
void getIvec(int val[3]) const { LWPValIVector i; get(CTL_VALUE, i); i.value(val); }
void setX(int x) { set(CTL_X, LWPValInt(x)); }
void setY(int y) { set(CTL_Y, LWPValInt(y)); }
void setData(void * data) { set(CTL_USERDATA, LWPValPtr(data)); }
void setDraw(XCALL_(void) (*draw)(LWPControl *, void *, DrMode)) { set(CTL_USERDRAW, LWPValPtr(draw)); }
void setEvent(XCALL_(void) (*event)(LWPControl *, void *)) { set(CTL_USEREVENT, LWPValPtr(event)); }
// high level wraps [FIXME] more functions needed like the following:
int getX() const { return getInt(CTL_X); }
int getY() const { return getInt(CTL_Y); }
int getHotX() const { return getInt(CTL_HOTX); }
int getHotY() const { return getInt(CTL_HOTY); }
int getHotW() const { return getInt(CTL_HOTW); }
int getHotH() const { return getInt(CTL_HOTH); }
int getMouseX() const { return getInt(CTL_MOUSEX); }
int getMouseY() const { return getInt(CTL_MOUSEY); }
LWPPanel getPanel() const { return (LWPanelID)getInt(CTL_PANEL); }
void setXY(int x, int y) { setX(x); setY(y); }
};
#endif
| [
"lightwolf@dac1304f-7ce9-0310-a59f-f2d444f72a61"
]
| [
[
[
1,
385
]
]
]
|
cfefcf95a60a6cd7f937504aa31c69ced41251e2 | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_KeyCode.h | 8c58ede385184f589374b3767b7592ba01248170 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,549 | h | /*!
@file
@author Albert Semenov
@date 03/2008
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_KEY_CODE_H__
#define __MYGUI_KEY_CODE_H__
#include "MyGUI_Prerequest.h"
namespace MyGUI
{
struct MYGUI_EXPORT KeyCode
{
enum Enum
{
None = 0x00,
Escape = 0x01,
One = 0x02,
Two = 0x03,
Three = 0x04,
Four = 0x05,
Five = 0x06,
Six = 0x07,
Seven = 0x08,
Eight = 0x09,
Nine = 0x0A,
Zero = 0x0B,
Minus = 0x0C, /* - on main keyboard */
Equals = 0x0D,
Backspace = 0x0E, /* Backspace */
Tab = 0x0F,
Q = 0x10,
W = 0x11,
E = 0x12,
R = 0x13,
T = 0x14,
Y = 0x15,
U = 0x16,
I = 0x17,
O = 0x18,
P = 0x19,
LeftBracket = 0x1A,
RightBracket = 0x1B,
Return = 0x1C, /* Enter on main keyboard */
LeftControl = 0x1D,
A = 0x1E,
S = 0x1F,
D = 0x20,
F = 0x21,
G = 0x22,
H = 0x23,
J = 0x24,
K = 0x25,
L = 0x26,
Semicolon = 0x27,
Apostrophe = 0x28,
Grave = 0x29, /* Accent grave ( ~ ) */
LeftShift = 0x2A,
Backslash = 0x2B,
Z = 0x2C,
X = 0x2D,
C = 0x2E,
V = 0x2F,
B = 0x30,
N = 0x31,
M = 0x32,
Comma = 0x33,
Period = 0x34, /* . on main keyboard */
Slash = 0x35, /* '/' on main keyboard */
RightShift = 0x36,
Multiply = 0x37, /* * on numeric keypad */
LeftAlt = 0x38, /* Left Alt */
Space = 0x39,
Capital = 0x3A,
F1 = 0x3B,
F2 = 0x3C,
F3 = 0x3D,
F4 = 0x3E,
F5 = 0x3F,
F6 = 0x40,
F7 = 0x41,
F8 = 0x42,
F9 = 0x43,
F10 = 0x44,
NumLock = 0x45,
ScrollLock = 0x46, /* Scroll Lock */
Numpad7 = 0x47,
Numpad8 = 0x48,
Numpad9 = 0x49,
Subtract = 0x4A, /* - on numeric keypad */
Numpad4 = 0x4B,
Numpad5 = 0x4C,
Numpad6 = 0x4D,
Add = 0x4E, /* + on numeric keypad */
Numpad1 = 0x4F,
Numpad2 = 0x50,
Numpad3 = 0x51,
Numpad0 = 0x52,
Decimal = 0x53, /* . on numeric keypad */
OEM_102 = 0x56, /* < > | on UK/Germany keyboards */
F11 = 0x57,
F12 = 0x58,
F13 = 0x64, /* (NEC PC98) */
F14 = 0x65, /* (NEC PC98) */
F15 = 0x66, /* (NEC PC98) */
Kana = 0x70, /* (Japanese keyboard) */
ABNT_C1 = 0x73, /* / ? on Portugese (Brazilian) keyboards */
Convert = 0x79, /* (Japanese keyboard) */
NoConvert = 0x7B, /* (Japanese keyboard) */
Yen = 0x7D, /* (Japanese keyboard) */
ABNT_C2 = 0x7E, /* Numpad . on Portugese (Brazilian) keyboards */
NumpadEquals = 0x8D, /* = on numeric keypad (NEC PC98) */
PrevTrack = 0x90, /* Previous Track (KC_CIRCUMFLEX on Japanese keyboard) */
At = 0x91, /* (NEC PC98) */
Colon = 0x92, /* (NEC PC98) */
Underline = 0x93, /* (NEC PC98) */
Kanji = 0x94, /* (Japanese keyboard) */
Stop = 0x95, /* (NEC PC98) */
AX = 0x96, /* (Japan AX) */
Unlabeled = 0x97, /* (J3100) */
NextTrack = 0x99, /* Next Track */
NumpadEnter = 0x9C, /* Enter on numeric keypad */
RightControl = 0x9D,
Mute = 0xA0,
Calculator = 0xA1,
PlayPause = 0xA2, /* Play / Pause */
MediaStop = 0xA4, /* Media Stop */
VolumeDown = 0xAE, /* Volume - */
VolumeUp = 0xB0, /* Volume + */
WebHome = 0xB2, /* Web home */
NumpadComma = 0xB3, /* , on numeric keypad (NEC PC98) */
Divide = 0xB5, /* / on numeric keypad */
SysRq = 0xB7,
RightAlt = 0xB8, /* Right Alt */
Pause = 0xC5,
Home = 0xC7, /* Home on arrow keypad */
ArrowUp = 0xC8, /* UpArrow on arrow keypad */
PageUp = 0xC9, /* PgUp on arrow keypad */
ArrowLeft = 0xCB, /* LeftArrow on arrow keypad */
ArrowRight = 0xCD, /* RightArrow on arrow keypad */
End = 0xCF, /* End on arrow keypad */
ArrowDown = 0xD0, /* DownArrow on arrow keypad */
PageDown = 0xD1, /* PgDn on arrow keypad */
Insert = 0xD2, /* Insert on arrow keypad */
Delete = 0xD3, /* Delete on arrow keypad */
LeftWindows = 0xDB, /* Left Windows key */
RightWindow = 0xDC, /* Right Windows key */
RightWindows = 0xDC, /* Right Windows key - Correct spelling :) */
AppMenu = 0xDD, /* AppMenu key */
Power = 0xDE, /* System Power */
Sleep = 0xDF, /* System Sleep */
Wake = 0xE3, /* System Wake */
WebSearch = 0xE5,
WebFavorites = 0xE6,
WebRefresh = 0xE7,
WebStop = 0xE8,
WebForward = 0xE9,
WebBack = 0xEA,
MyComputer = 0xEB,
Mail = 0xEC,
MediaSelect = 0xED
};
KeyCode(Enum _value = None) : value(_value) { }
friend bool operator < (KeyCode const& a, KeyCode const& b)
{
return (a.value < b.value);
}
friend bool operator >= (KeyCode const& a, KeyCode const& b)
{
return !(a < b);
}
friend bool operator > (KeyCode const& a, KeyCode const& b)
{
return (b < a);
}
friend bool operator <= (KeyCode const& a, KeyCode const& b)
{
return !(a > b);
}
friend bool operator == (KeyCode const& a, KeyCode const& b)
{
return !(a < b) && !(a > b);
}
friend bool operator != (KeyCode const& a, KeyCode const& b)
{
return !(a == b);
}
int toValue() const
{
return (int)value;
}
private:
Enum value;
};
} // namespace MyGUI
#endif // __MYGUI_KEY_CODE_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
221
]
]
]
|
687739d7f3ae72325f03c1f42250d6645a29c520 | 640a36607eb5b185eceb733643dda918221a40a4 | /Sever/lib/Net/MsgPackageManage.h | bd9dba2fc55d53364df511f02b6cbdc1062498ae | []
| no_license | degravata/simple-flash-mmorpg | 13cc97665e89dc8a0c6218a9a6ebc5c44217fc7d | 71138defc786ce757eae8d6fc6bd53d16bf44e63 | refs/heads/master | 2016-09-12T10:38:44.046533 | 2011-01-25T07:51:25 | 2011-01-25T07:51:25 | 56,880,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | h | #include "MsgPackage.h"
#include <vector>
#pragma once
namespace SevenSmile{
struct StructMsgPackage{
char* lpcMsgPackage;
unsigned int uiPackageLength;
};
typedef std::vector<StructMsgPackage*> MsgPackageArr;
namespace Net{
extern "C" class MsgPackageManage
{
public:
__declspec(dllexport) MsgPackageManage(char* i_lpChar,unsigned int i_uiPackageLength);
__declspec(dllexport) ~MsgPackageManage(void);
__declspec(dllexport) MsgPackageArr& GetMsgPackages();
//MsgPackage* GetMsgPackages();
private:
MsgPackageArr _lpMpArr;
char* _lpChar;
void ExeMsgPackage(char* i_lpChar,unsigned int i_uiPackageLength);
};
}
}
| [
"fangtong8752@60e69123-55e6-9807-5f38-cd17b4386222"
]
| [
[
[
1,
32
]
]
]
|
23d374d19a8b88fa4389f3ed6a0d37316788e15d | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/drivers/argus.cpp | 566c5f67d66e80dc96479c6fad651a20850bf839 | []
| no_license | neonichu/iMame4All-for-iPad | 72f56710d2ed7458594838a5152e50c72c2fb67f | 4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611 | refs/heads/master | 2020-04-21T07:26:37.595653 | 2011-11-26T12:21:56 | 2011-11-26T12:21:56 | 2,855,022 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,620 | cpp | #include "../vidhrdw/argus.cpp"
/***************************************************************************
Argus (Early NMK driver 1986-1987)
-------------------------------------
driver by Yochizo
Special thanks to :
=====================
- Gerardo Oporto Jorrin for dipswitch informations.
- Suzuki2go for screenshots of Argus and Valtric.
- Jarek Parchanski for Psychic5 driver.
Supported games :
==================
Argus (C) 1986 NMK / Jaleco
Valtric (C) 1986 NMK / Jaleco
Butasan (C) 1987 NMK / Jaleco
System specs :
===============
Argus
---------------------------------------------------------------
CPU : Z80 (4MHz) + Z80 (4MHz, Sound)
Sound : YM2203 x 1
Layers : BG0, BG1, Sprite, Text [BG0 is controlled by VROMs]
Colors : 832 colors
Sprite : 128 colors
BG0 : 256 colors
BG1 : 256 colors
Text : 256 colors
Others : Brightness controller (Emulated)
Half transparent color (Not emulated)
Valtric
---------------------------------------------------------------
CPU : Z80 (5MHz) + Z80 (5MHz, Sound)
Sound : YM2203 x 2
Layers : BG1, Sprite, Text
Colors : 768 colors
Sprite : 256 colors
BG1 : 256 colors
Text : 256 colors
Others : Brightness controller (Emulated)
Half transparent color (Not emulated)
Mosaic effect (Not emulated)
Butasan
---------------------------------------------------------------
CPU : Z80 (5MHz) + Z80 (5MHz, Sound)
Sound : YM2203 x 2
Layers : BG0, BG1, Sprite, Text [BG0 and BG1 is not shown simultaneously]
Colors : 672 colors
Sprite : 16x4 + 8x8 = 128 colors
BG0 : 256 colors
BG1 : 32 colors
Text : 256 colors
Others : 2 VRAM pages (Emulated)
Various sprite sizes (Emulated)
Note :
=======
- To enter test mode, press coin 2 key at start in Argus and Valtric.
Known issues :
===============
- Mosaic effect in Valtric is not implemented.
- Half transparent color (50% alpha blending) is not emulated.
- Sprite priority switch of Butasan is shown in test mode. What will be
happened when set it ? JFF is not implemented this mistery switch too.
- In Butasan, text layer will corrupt completely when you take a special
item.
- Data proms of Butasan does exist. But I don't know what is used for.
- Though clock speed of Argus is actually 4 MHz, major sprite problems
are broken out in the middle of slowdown. So, it is set 5 MHz now.
- Sprite locations of Argus delay around 1 or 2 frames when horizontal
scroll occurs.
****************************************************************************/
#include "driver.h"
#include "vidhrdw/generic.h"
/***************************************************************************
Variables
***************************************************************************/
extern unsigned char *argus_paletteram;
extern unsigned char *argus_txram;
extern unsigned char *argus_bg0ram;
extern unsigned char *argus_bg0_scrollx;
extern unsigned char *argus_bg0_scrolly;
extern unsigned char *argus_bg1ram;
extern unsigned char *argus_bg1_scrollx;
extern unsigned char *argus_bg1_scrolly;
extern unsigned char *butasan_bg1ram;
int argus_vh_start (void);
int valtric_vh_start (void);
int butasan_vh_start (void);
void argus_vh_stop (void);
void butasan_vh_stop (void);
void argus_vh_screenrefresh (struct osd_bitmap *bitmap,int full_refresh);
void valtric_vh_screenrefresh (struct osd_bitmap *bitmap,int full_refresh);
void butasan_vh_screenrefresh (struct osd_bitmap *bitmap,int full_refresh);
static unsigned char argus_bank_latch = 0x00;
static unsigned char butasan_page_latch = 0x00;
READ_HANDLER( argus_txram_r );
READ_HANDLER( butasan_txram_r );
READ_HANDLER( argus_bg1ram_r );
READ_HANDLER( butasan_bg0ram_r );
READ_HANDLER( butasan_bg1ram_r );
READ_HANDLER( argus_paletteram_r );
READ_HANDLER( butasan_txbackram_r );
READ_HANDLER( butasan_bg0backram_r );
WRITE_HANDLER( argus_txram_w );
WRITE_HANDLER( butasan_txram_w );
WRITE_HANDLER( argus_bg1ram_w );
WRITE_HANDLER( butasan_bg0ram_w );
WRITE_HANDLER( butasan_bg1ram_w );
WRITE_HANDLER( argus_bg0_scrollx_w );
WRITE_HANDLER( argus_bg0_scrolly_w );
WRITE_HANDLER( butasan_bg0_scrollx_w );
WRITE_HANDLER( argus_bg1_scrollx_w );
WRITE_HANDLER( argus_bg1_scrolly_w );
WRITE_HANDLER( argus_bg_status_w );
WRITE_HANDLER( valtric_bg_status_w );
WRITE_HANDLER( butasan_bg0_status_w );
WRITE_HANDLER( argus_flipscreen_w );
WRITE_HANDLER( argus_paletteram_w );
WRITE_HANDLER( valtric_paletteram_w );
WRITE_HANDLER( butasan_paletteram_w );
WRITE_HANDLER( butasan_txbackram_w );
WRITE_HANDLER( butasan_bg0backram_w );
WRITE_HANDLER( butasan_bg1_status_w );
/***************************************************************************
Interrupt(s)
***************************************************************************/
static int argus_interrupt(void)
{
if (cpu_getiloops() == 0)
return 0xd7; /* RST 10h */
else
return 0xcf; /* RST 08h */
}
/* Handler called by the YM2203 emulator when the internal timers cause an IRQ */
static void irqhandler(int irq)
{
cpu_set_irq_line(1, 0, irq ? ASSERT_LINE : CLEAR_LINE);
}
static struct YM2203interface argus_ym2203_interface =
{
1, /* 1 chip */
6000000 / 4, /* 1.5 MHz */
{ YM2203_VOL(50,15) },
{ 0 },
{ 0 },
{ 0 },
{ 0 },
{ irqhandler }
};
static struct YM2203interface valtric_ym2203_interface =
{
2, /* 2 chips */
6000000 / 4, /* 1.5 MHz */
{ YM2203_VOL(50,15), YM2203_VOL(50,15) },
{ 0 },
{ 0 },
{ 0 },
{ 0 },
{ irqhandler }
};
/* Volume setting is different from the others. */
static struct YM2203interface butasan_ym2203_interface =
{
2, /* 2 chips */
6000000 / 4, /* 1.5 MHz */
{ YM2203_VOL(100,30), YM2203_VOL(100,30) },
{ 0 },
{ 0 },
{ 0 },
{ 0 },
{ irqhandler }
};
/***************************************************************************
Memory Handler(s)
***************************************************************************/
/*static READ_HANDLER( argus_bankselect_r )
{
return argus_bank_latch;
}*/
static WRITE_HANDLER( argus_bankselect_w )
{
unsigned char *RAM = memory_region(REGION_CPU1);
int bankaddress;
if (data != argus_bank_latch)
{
argus_bank_latch = data;
bankaddress = 0x10000 + ((data & 7) * 0x4000);
cpu_setbank(1, &RAM[bankaddress]); /* Select 8 banks of 16k */
}
}
static WRITE_HANDLER( butasan_pageselect_w )
{
butasan_page_latch = data;
}
static READ_HANDLER( butasan_pagedram_r )
{
if (!(butasan_page_latch & 0x01))
{
if (offset < 0x0800) /* BG0 RAM */
{
return butasan_bg0ram_r( offset );
}
else if (offset < 0x1000) /* Back BG0 RAM */
{
return butasan_bg0backram_r( offset - 0x0800 );
}
}
else
{
if (offset < 0x0800) /* Text RAM */
{
return butasan_txram_r( offset );
}
else if (offset < 0x1000) /* Back text RAM */
{
return butasan_txbackram_r( offset - 0x0800 );
}
}
return 0;
}
static WRITE_HANDLER( butasan_pagedram_w )
{
if (!(butasan_page_latch & 0x01))
{
if (offset < 0x0800) /* BG0 RAM */
{
butasan_bg0ram_w( offset, data );
}
else if (offset < 0x1000) /* Back BG0 RAM */
{
butasan_bg0backram_w( offset - 0x0800, data );
}
}
else
{
if (offset < 0x0800) /* Text RAM */
{
butasan_txram_w( offset, data );
}
else if (offset < 0x1000) /* Back text RAM */
{
butasan_txbackram_w( offset - 0x0800, data );
}
}
}
/***************************************************************************
Memory Map(s)
***************************************************************************/
static struct MemoryReadAddress argus_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xbfff, MRA_BANK1 },
{ 0xc000, 0xc000, input_port_0_r }, // Coin
{ 0xc001, 0xc001, input_port_1_r }, // Player 1
{ 0xc002, 0xc002, input_port_2_r }, // Player 2
{ 0xc003, 0xc003, input_port_3_r }, // DSW 1
{ 0xc004, 0xc004, input_port_4_r }, // DSW 2
{ 0xc400, 0xcfff, argus_paletteram_r, },
{ 0xd000, 0xd7ff, argus_txram_r },
{ 0xd800, 0xdfff, argus_bg1ram_r },
{ 0xe000, 0xf1ff, MRA_RAM },
{ 0xf200, 0xf7ff, MRA_RAM },
{ 0xf800, 0xffff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress argus_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0x8000, 0xbfff, MWA_BANK1 },
{ 0xc200, 0xc200, soundlatch_w },
{ 0xc201, 0xc201, argus_flipscreen_w },
{ 0xc202, 0xc202, argus_bankselect_w },
{ 0xc300, 0xc301, argus_bg0_scrollx_w, &argus_bg0_scrollx },
{ 0xc302, 0xc303, argus_bg0_scrolly_w, &argus_bg0_scrolly },
{ 0xc308, 0xc309, argus_bg1_scrollx_w, &argus_bg1_scrollx },
{ 0xc30a, 0xc30b, argus_bg1_scrolly_w, &argus_bg1_scrolly },
{ 0xc30c, 0xc30c, argus_bg_status_w },
{ 0xc400, 0xcfff, argus_paletteram_w, &argus_paletteram },
{ 0xd000, 0xd7ff, argus_txram_w, &argus_txram },
{ 0xd800, 0xdfff, argus_bg1ram_w, &argus_bg1ram },
{ 0xe000, 0xf1ff, MWA_RAM },
{ 0xf200, 0xf7ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf800, 0xffff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress valtric_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xbfff, MRA_BANK1 },
{ 0xc000, 0xc000, input_port_0_r }, // Coin
{ 0xc001, 0xc001, input_port_1_r }, // Player 1
{ 0xc002, 0xc002, input_port_2_r }, // Player 2
{ 0xc003, 0xc003, input_port_3_r }, // DSW 1
{ 0xc004, 0xc004, input_port_4_r }, // DSW 2
{ 0xc400, 0xcfff, argus_paletteram_r, },
{ 0xd000, 0xd7ff, argus_txram_r },
{ 0xd800, 0xdfff, argus_bg1ram_r },
{ 0xe000, 0xf1ff, MRA_RAM },
{ 0xf200, 0xf7ff, MRA_RAM },
{ 0xf800, 0xffff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress valtric_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0x8000, 0xbfff, MWA_BANK1 },
{ 0xc200, 0xc200, soundlatch_w },
{ 0xc201, 0xc201, argus_flipscreen_w },
{ 0xc202, 0xc202, argus_bankselect_w },
{ 0xc308, 0xc309, argus_bg1_scrollx_w, &argus_bg1_scrollx },
{ 0xc30a, 0xc30b, argus_bg1_scrolly_w, &argus_bg1_scrolly },
{ 0xc30c, 0xc30c, valtric_bg_status_w },
{ 0xc400, 0xcfff, valtric_paletteram_w, &argus_paletteram },
{ 0xd000, 0xd7ff, argus_txram_w, &argus_txram },
{ 0xd800, 0xdfff, argus_bg1ram_w, &argus_bg1ram },
{ 0xe000, 0xf1ff, MWA_RAM },
{ 0xf200, 0xf7ff, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf800, 0xffff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress butasan_readmem[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0xbfff, MRA_BANK1 },
{ 0xc000, 0xc000, input_port_0_r }, // Coin
{ 0xc001, 0xc001, input_port_1_r }, // Player 1
{ 0xc002, 0xc002, input_port_2_r }, // Player 2
{ 0xc003, 0xc003, input_port_3_r }, // DSW 1
{ 0xc004, 0xc004, input_port_4_r }, // DSW 2
{ 0xc400, 0xc7ff, butasan_bg1ram_r },
{ 0xc800, 0xcfff, argus_paletteram_r },
{ 0xd000, 0xdfff, butasan_pagedram_r },
{ 0xe000, 0xefff, MRA_RAM },
{ 0xf000, 0xf67f, MRA_RAM },
{ 0xf680, 0xffff, MRA_RAM },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress butasan_writemem[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0x8000, 0xbfff, MWA_BANK1 },
{ 0xc200, 0xc200, soundlatch_w },
{ 0xc201, 0xc201, argus_flipscreen_w },
{ 0xc202, 0xc202, argus_bankselect_w },
{ 0xc203, 0xc203, butasan_pageselect_w },
{ 0xc300, 0xc301, butasan_bg0_scrollx_w, &argus_bg0_scrollx },
{ 0xc302, 0xc303, argus_bg0_scrolly_w, &argus_bg0_scrolly },
{ 0xc304, 0xc304, butasan_bg0_status_w },
{ 0xc308, 0xc309, argus_bg1_scrollx_w, &argus_bg1_scrollx },
{ 0xc30a, 0xc30b, argus_bg1_scrolly_w, &argus_bg1_scrolly },
{ 0xc30c, 0xc30c, butasan_bg1_status_w },
{ 0xc400, 0xc7ff, butasan_bg1ram_w, &butasan_bg1ram },
{ 0xc800, 0xcfff, butasan_paletteram_w, &argus_paletteram },
{ 0xd000, 0xdfff, butasan_pagedram_w },
{ 0xe000, 0xefff, MWA_RAM },
{ 0xf000, 0xf67f, MWA_RAM, &spriteram, &spriteram_size },
{ 0xf680, 0xffff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sound_readmem_a[] =
{
{ 0x0000, 0x7fff, MRA_ROM },
{ 0x8000, 0x87ff, MRA_RAM },
{ 0xc000, 0xc000, soundlatch_r },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sound_writemem_a[] =
{
{ 0x0000, 0x7fff, MWA_ROM },
{ 0x8000, 0x87ff, MWA_RAM },
{ -1 } /* end of table */
};
static struct MemoryReadAddress sound_readmem_b[] =
{
{ 0x0000, 0xbfff, MRA_ROM },
{ 0xc000, 0xc7ff, MRA_RAM },
{ 0xe000, 0xe000, soundlatch_r },
{ -1 } /* end of table */
};
static struct MemoryWriteAddress sound_writemem_b[] =
{
{ 0x0000, 0xbfff, MWA_ROM },
{ 0xc000, 0xc7ff, MWA_RAM },
{ -1 } /* end of table */
};
static struct IOReadPort sound_readport_1[] =
{
{ 0x0000, 0x0000, YM2203_status_port_0_r },
{ 0x0001, 0x0001, YM2203_read_port_0_r },
{ -1 } /* end of table */
};
static struct IOWritePort sound_writeport_1[] =
{
{ 0x00, 0x00, YM2203_control_port_0_w },
{ 0x01, 0x01, YM2203_write_port_0_w },
{ -1 } /* end of table */
};
static struct IOReadPort sound_readport_2[] =
{
{ 0x0000, 0x0000, YM2203_status_port_0_r },
{ 0x0001, 0x0001, YM2203_read_port_0_r },
{ 0x0080, 0x0080, YM2203_status_port_1_r },
{ 0x0081, 0x0081, YM2203_read_port_1_r },
{ -1 } /* end of table */
};
static struct IOWritePort sound_writeport_2[] =
{
{ 0x00, 0x00, YM2203_control_port_0_w },
{ 0x01, 0x01, YM2203_write_port_0_w },
{ 0x80, 0x80, YM2203_control_port_1_w },
{ 0x81, 0x81, YM2203_write_port_1_w },
{ -1 } /* end of table */
};
/***************************************************************************
Input Port(s)
***************************************************************************/
INPUT_PORTS_START( argus )
PORT_START /* System control (0) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_START /* Player 1 control (1) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* Player 2 controls (2) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* DSW 1 (3) */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x06, 0x06, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x04, "Easy" )
PORT_DIPSETTING( 0x06, "Medium" )
PORT_DIPSETTING( 0x02, "Hard" )
PORT_DIPSETTING( 0x00, "Hardest" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Free_Play ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Cabinet) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x10, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x80, "2" )
PORT_DIPSETTING( 0xc0, "3" )
PORT_DIPSETTING( 0x40, "4" )
PORT_DIPSETTING( 0x00, "5" )
PORT_START /* DSW 2 (4) */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x1c, 0x1c, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x0C, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x1C, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x14, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_4C ) )
PORT_DIPNAME( 0xe0, 0xe0, DEF_STR( Coin_A) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 1C_4C ) )
INPUT_PORTS_END
INPUT_PORTS_START( valtric )
PORT_START /* System control (0) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_START /* Player 1 control (1) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* Player 2 controls (2) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* DSW 1 (3) */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x06, 0x06, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x04, "Easy" )
PORT_DIPSETTING( 0x06, "Medium" )
PORT_DIPSETTING( 0x02, "Hard" )
PORT_DIPSETTING( 0x00, "Hardest" )
PORT_DIPNAME( 0x08, 0x08, DEF_STR( Free_Play ) )
PORT_DIPSETTING( 0x08, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x10, 0x00, DEF_STR( Cabinet) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x10, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Demo_Sounds ) )
PORT_DIPSETTING( 0x20, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x00, "2" )
PORT_DIPSETTING( 0xc0, "3" )
PORT_DIPSETTING( 0x80, "4" )
PORT_DIPSETTING( 0x40, "5" )
PORT_START /* DSW 2 (4) */
PORT_BITX( 0x01, 0x01, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x1c, 0x1c, DEF_STR( Coin_A ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x0C, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x1C, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x14, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_4C ) )
PORT_DIPNAME( 0xe0, 0xe0, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 1C_4C ) )
INPUT_PORTS_END
INPUT_PORTS_START( butasan )
PORT_START /* System control (0) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_SERVICE( 0x20, IP_ACTIVE_LOW )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_START /* Player 1 control (1) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* Player 2 controls (2) */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_COCKTAIL )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* DSW 1 (3) */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Free_Play ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_BITX( 0x02, 0x02, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Invulnerability", IP_KEY_NONE, IP_JOY_NONE )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x0c, "3" )
PORT_DIPSETTING( 0x08, "4" )
PORT_DIPSETTING( 0x04, "5" )
PORT_DIPSETTING( 0x00, "6" )
PORT_DIPNAME( 0x30, 0x30, DEF_STR( Difficulty ) )
PORT_DIPSETTING( 0x30, "Rank 1 (Medium)" )
PORT_DIPSETTING( 0x20, "Rank 2" )
PORT_DIPSETTING( 0x10, "Rank 3" )
PORT_DIPSETTING( 0x00, "Rank 4" )
PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x40, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x80, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_START /* DSW 2 (4) */
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) )
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unused ) )
PORT_DIPSETTING( 0x02, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x1c, 0x1c, DEF_STR( Coin_A ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x1c, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x14, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 1C_4C ) )
PORT_DIPNAME( 0xe0, 0xe0, DEF_STR( Coin_B ) )
PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) )
PORT_DIPSETTING( 0x20, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x40, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 1C_4C ) )
INPUT_PORTS_END
/***************************************************************************
Machine Driver(s)
***************************************************************************/
static struct GfxLayout charlayout =
{
8,8, /* 8x8 characters */
1024, /* 1024 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8 },
32*8
};
static struct GfxLayout tilelayout_256 =
{
16,16, /* 16x16 characters */
256, /* 256 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28,
64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8,
32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8 },
128*8
};
static struct GfxLayout tilelayout_512 =
{
16,16, /* 16x16 characters */
512, /* 512 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28,
64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8,
32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8 },
128*8
};
static struct GfxLayout tilelayout_1024 =
{
16,16, /* 16x16 characters */
1024, /* 1024 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28,
64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8,
32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8 },
128*8
};
static struct GfxLayout tilelayout_2048 =
{
16,16, /* 16x16 characters */
2048, /* 2048 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28,
64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8,
32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8 },
128*8
};
static struct GfxLayout tilelayout_4096 =
{
16,16, /* 16x16 characters */
4096, /* 4096 characters */
4, /* 4 bits per pixel */
{ 0, 1, 2, 3 },
{ 0, 4, 8, 12, 16, 20, 24, 28,
64*8, 64*8+4, 64*8+8, 64*8+12, 64*8+16, 64*8+20, 64*8+24, 64*8+28 },
{ 0*8, 4*8, 8*8, 12*8, 16*8, 20*8, 24*8, 28*8,
32*8, 36*8, 40*8, 44*8, 48*8, 52*8, 56*8, 60*8 },
128*8
};
static struct GfxDecodeInfo argus_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_1024, 0*16, 8 },
{ REGION_GFX2, 0, &tilelayout_1024, 8*16, 16 },
{ REGION_GFX3, 0, &tilelayout_256, 24*16, 16 },
{ REGION_GFX4, 0, &charlayout, 40*16, 16 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo valtric_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_1024, 0*16, 16 },
{ REGION_GFX2, 0, &tilelayout_2048, 16*16, 16 },
{ REGION_GFX3, 0, &charlayout, 32*16, 16 },
{ -1 } /* end of array */
};
static struct GfxDecodeInfo butasan_gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &tilelayout_4096, 0*16, 16 },
{ REGION_GFX2, 0, &tilelayout_1024, 16*16, 16 },
{ REGION_GFX3, 0, &tilelayout_512, 12*16, 16 },
{ REGION_GFX4, 0, &charlayout, 32*16, 16 },
{ -1 } /* end of array */
};
static struct MachineDriver machine_driver_argus =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 4 MHz */
argus_readmem, argus_writemem, 0, 0,
argus_interrupt, 2
},
{
CPU_Z80 | CPU_AUDIO_CPU,
5000000, /* 4 MHz */
sound_readmem_a, sound_writemem_a,
sound_readport_1, sound_writeport_1,
ignore_interrupt, 0
}
},
54, DEFAULT_60HZ_VBLANK_DURATION, /* This value is refered to psychic5 driver */
10,
0,
/* video hardware */
32*16, 32*16, { 0*8, 32*8-1, 2*8, 30*8-1 },
argus_gfxdecodeinfo,
56*16, 56*16,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
argus_vh_start,
argus_vh_stop,
argus_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_YM2203,
&argus_ym2203_interface
}
}
};
static struct MachineDriver machine_driver_valtric =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 MHz */
valtric_readmem, valtric_writemem, 0, 0,
argus_interrupt, 2
},
{
CPU_Z80 | CPU_AUDIO_CPU,
5000000, /* 5 MHz */
sound_readmem_a, sound_writemem_a,
sound_readport_2, sound_writeport_2,
ignore_interrupt, 0
}
},
54, DEFAULT_60HZ_VBLANK_DURATION, /* This value is refered to psychic5 driver */
10,
0,
/* video hardware */
32*16, 32*16, { 0*8, 32*8-1, 2*8, 30*8-1 },
valtric_gfxdecodeinfo,
48*16, 48*16,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
valtric_vh_start,
0,
valtric_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_YM2203,
&valtric_ym2203_interface
}
}
};
static struct MachineDriver machine_driver_butasan =
{
/* basic machine hardware */
{
{
CPU_Z80,
5000000, /* 5 MHz */
butasan_readmem, butasan_writemem, 0, 0,
argus_interrupt, 2
},
{
CPU_Z80 | CPU_AUDIO_CPU,
5000000, /* 5 MHz */
sound_readmem_b, sound_writemem_b,
sound_readport_2, sound_writeport_2,
ignore_interrupt, 0
}
},
54, DEFAULT_60HZ_VBLANK_DURATION, /* This value is refered to psychic5 driver */
10,
0,
/* video hardware */
32*16, 32*16, { 0*8, 32*8-1, 1*8, 31*8-1 },
butasan_gfxdecodeinfo,
48*16, 48*16,
0,
VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE,
0,
butasan_vh_start,
butasan_vh_stop,
butasan_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_YM2203,
&butasan_ym2203_interface
}
}
};
/***************************************************************************
Game driver(s)
***************************************************************************/
ROM_START( argus )
ROM_REGION( 0x28000, REGION_CPU1 ) /* Main CPU */
ROM_LOAD( "ag_02.bin", 0x00000, 0x08000, 0x278a3f3d )
ROM_LOAD( "ag_03.bin", 0x10000, 0x08000, 0x3a7f3bfa )
ROM_LOAD( "ag_04.bin", 0x18000, 0x08000, 0x76adc9f6 )
ROM_LOAD( "ag_05.bin", 0x20000, 0x08000, 0xf76692d6 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */
ROM_LOAD( "ag_01.bin", 0x00000, 0x04000, 0x769e3f57 )
ROM_REGION( 0x20000, REGION_GFX1| REGIONFLAG_DISPOSE ) /* Sprite */
ROM_LOAD( "ag_09.bin", 0x00000, 0x08000, 0x6dbc1c58 )
ROM_LOAD( "ag_08.bin", 0x08000, 0x08000, 0xce6e987e )
ROM_LOAD( "ag_07.bin", 0x10000, 0x08000, 0xbbb9638d )
ROM_LOAD( "ag_06.bin", 0x18000, 0x08000, 0x655b48f8 )
ROM_REGION( 0x20000, REGION_GFX2| REGIONFLAG_DISPOSE ) /* BG0 */
ROM_LOAD( "ag_13.bin", 0x00000, 0x08000, 0x20274268 )
ROM_LOAD( "ag_14.bin", 0x08000, 0x08000, 0xceb8860b )
ROM_LOAD( "ag_11.bin", 0x10000, 0x08000, 0x99ce8556 )
ROM_LOAD( "ag_12.bin", 0x18000, 0x08000, 0xe0e5377c )
ROM_REGION( 0x08000, REGION_GFX3| REGIONFLAG_DISPOSE ) /* BG1 */
ROM_LOAD( "ag_17.bin", 0x00000, 0x08000, 0x0f12d09b )
ROM_REGION( 0x08000, REGION_GFX4| REGIONFLAG_DISPOSE ) /* Text */
ROM_LOAD( "ag_10.bin", 0x00000, 0x04000, 0x2de696c4 )
ROM_REGION( 0x08000, REGION_USER1 ) /* Map */
ROM_LOAD( "ag_15.bin", 0x00000, 0x08000, 0x99834c1b )
ROM_REGION( 0x08000, REGION_USER2 ) /* Pattern */
ROM_LOAD( "ag_16.bin", 0x00000, 0x08000, 0x39a51714 )
ROM_END
ROM_START( valtric )
ROM_REGION( 0x30000, REGION_CPU1 ) /* Main CPU */
ROM_LOAD( "vt_04.bin", 0x00000, 0x08000, 0x709c705f )
ROM_LOAD( "vt_06.bin", 0x10000, 0x10000, 0xc9cbb4e4 )
ROM_LOAD( "vt_05.bin", 0x20000, 0x10000, 0x7ab2684b )
ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */
ROM_LOAD( "vt_01.bin", 0x00000, 0x08000, 0x4616484f )
ROM_REGION( 0x20000, REGION_GFX1| REGIONFLAG_DISPOSE ) /* Sprite */
ROM_LOAD( "vt_02.bin", 0x00000, 0x10000, 0x66401977 )
ROM_LOAD( "vt_03.bin", 0x10000, 0x10000, 0x9203bbce )
ROM_REGION( 0x40000, REGION_GFX2| REGIONFLAG_DISPOSE ) /* BG */
ROM_LOAD( "vt_08.bin", 0x00000, 0x10000, 0x661dd338 )
ROM_LOAD( "vt_09.bin", 0x10000, 0x10000, 0x085a35b1 )
ROM_LOAD( "vt_10.bin", 0x20000, 0x10000, 0x09c47323 )
ROM_LOAD( "vt_11.bin", 0x30000, 0x10000, 0x4cf800b5 )
ROM_REGION( 0x08000, REGION_GFX3| REGIONFLAG_DISPOSE ) /* Text */
ROM_LOAD( "vt_07.bin", 0x00000, 0x08000, 0xd5f9bfb9 )
ROM_END
ROM_START( butasan )
ROM_REGION( 0x30000, REGION_CPU1 ) /* Main CPU */
ROM_LOAD( "buta-04.bin", 0x00000, 0x08000, 0x47ff4ca9 )
ROM_LOAD( "buta-03.bin", 0x10000, 0x10000, 0x69fd88c7 )
ROM_LOAD( "buta-02.bin", 0x20000, 0x10000, 0x519dc412 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* Sound CPU */
ROM_LOAD( "buta-01.bin", 0x00000, 0x10000, 0xc9d23e2d )
ROM_REGION( 0x80000, REGION_GFX1| REGIONFLAG_DISPOSE ) /* Sprite */
ROM_LOAD( "buta-16.bin", 0x00000, 0x10000, 0xe0ce51b6 )
ROM_LOAD( "buta-15.bin", 0x10000, 0x10000, 0x3ed19daa )
ROM_LOAD( "buta-14.bin", 0x20000, 0x10000, 0x8ec891c1 )
ROM_LOAD( "buta-13.bin", 0x30000, 0x10000, 0x5023e74d )
ROM_LOAD( "buta-12.bin", 0x40000, 0x10000, 0x44f59905 )
ROM_LOAD( "buta-11.bin", 0x50000, 0x10000, 0xb8929f1d )
ROM_LOAD( "buta-10.bin", 0x60000, 0x10000, 0xfd4d3baf )
ROM_LOAD( "buta-09.bin", 0x70000, 0x10000, 0x7da4c0fd )
ROM_REGION( 0x20000, REGION_GFX2| REGIONFLAG_DISPOSE ) /* BG0 */
ROM_LOAD( "buta-05.bin", 0x00000, 0x10000, 0xb8e026b0 )
ROM_LOAD( "buta-06.bin", 0x10000, 0x10000, 0x8bbacb81 )
ROM_REGION( 0x10000, REGION_GFX3| REGIONFLAG_DISPOSE ) /* BG1 */
ROM_LOAD( "buta-07.bin", 0x00000, 0x10000, 0x3a48d531 )
ROM_REGION( 0x08000, REGION_GFX4| REGIONFLAG_DISPOSE ) /* Text */
ROM_LOAD( "buta-08.bin", 0x00000, 0x08000, 0x5d45ce9c )
ROM_REGION( 0x00200, REGION_PROMS ) /* Data proms ??? */
ROM_LOAD( "buta-01.prm", 0x00000, 0x00100, 0x45baedd0 )
ROM_LOAD( "buta-02.prm", 0x00100, 0x00100, 0x0dcb18fc )
ROM_END
/* ( YEAR NAME PARENT MACHINE INPUT INIT MONITOR COMPANY FULLNAME ) */
GAME( 1986, argus, 0, argus, argus, 0, ROT270, "[NMK] (Jaleco license)", "Argus" )
GAME( 1986, valtric, 0, valtric, valtric, 0, ROT270, "[NMK] (Jaleco license)", "Valtric" )
GAME( 1987, butasan, 0, butasan, butasan, 0, ROT0, "[NMK] (Jaleco license)", "Butasan (Japan)" )
| [
"[email protected]"
]
| [
[
[
1,
1076
]
]
]
|
93d3b51825f33e9d043204c03a0cf014977e85ad | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/WireKeys/MiscUtils.cpp | b7e79d0c1f196070bd62939918003585919eecb6 | []
| no_license | meiercn/wiredplane-wintools | b35422570e2c4b486c3aa6e73200ea7035e9b232 | 134db644e4271079d631776cffcedc51b5456442 | refs/heads/master | 2021-01-19T07:50:42.622687 | 2009-07-07T03:34:11 | 2009-07-07T03:34:11 | 34,017,037 | 2 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 49,530 | cpp | /*#pragma comment(lib, "Delayimp.lib")
#pragma comment(linker, "/DELAYLOAD:Winmm.dll")
#pragma comment(linker, "/DELAYLOAD:Wsock32.dll")
#pragma comment(linker, "/DELAYLOAD:Shell32.dll")
#pragma comment(linker, "/DELAYLOAD:Ole32.dll")
#pragma comment(linker, "/DELAYLOAD:Oleaut32.dll")
#pragma comment(linker, "/DELAYLOAD:Setupapi.dll")
#pragma comment(linker, "/DELAYLOAD:Rpcrt4.dll")
#pragma comment(linker, "/DELAYLOAD:Riched20.dll")
#pragma comment(linker, "/DELAYLOAD:Shlwapi.dll")
#pragma comment(linker, "/DELAYLOAD:Userenv.dll")*/
#include "stdafx.h"
#include "_common.h"
#include "_externs.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
void SmartWarning(const char* szText, const char* szTitle, long* bAnswerHolder, DWORD dwTimer)
{_XLOG_
if(bAnswerHolder && *bAnswerHolder!=0){_XLOG_
return;
}
InfoWndStruct* info=new InfoWndStruct();
info->iIcon=IDI_ICON_INFO_AST;
info->sText=szText;
info->sTitle=szTitle;
info->bCenterUnderMouse=TRUE;
info->dwStaticPars=DT_CENTER|DT_VCENTER;
info->sOkButtonText=_l("OK");
info->dwDontAskHolder=bAnswerHolder;
info->dwTimer=dwTimer;
Alert(info);
}
int AskYesNo(const char* szText, const char* szTitle, long* bAnswerHolder, CWnd* pParent)
{_XLOG_
if(bAnswerHolder){_XLOG_
if(*bAnswerHolder==1){_XLOG_
return IDYES;
}
if(*bAnswerHolder==2){_XLOG_
return IDNO;
}
}
AsyncPlaySoundSys("SystemQuestion");
InfoWndStruct* info=new InfoWndStruct();
info->bAsModal=TRUE;
info->iIcon=IDI_ICON_ASK;
info->sText=szText;
info->sTitle=szTitle;
info->bCenterUnderMouse=TRUE;
info->dwStaticPars=DT_CENTER|DT_VCENTER;
info->sOkButtonText=_l("Yes");
info->sCancelButtonText=_l("No");
info->dwDontAskHolder=bAnswerHolder;
info->pParent=pParent;
int iRes=(LRESULT)Alert(info);
if(iRes==1){_XLOG_
return IDYES;
}
return IDNO;
}
void AddError(const char* szError, BOOL bSystem)
{_XLOG_
#ifndef _DEBUG
if(bSystem)
#endif
{_XLOG_
ShowBaloon(szError,"Error",3000,1);
#ifndef _DEBUG
LOGERROR1("Syserror:%s",szError);
#endif
}
//CString sError=_l("Error occured")+": "+szError;
//AsyncPlaySound(SND_ERROR);
}
InfoWnd* Alert(const char* szText, const char* szTitle, DWORD dwTimeOut)
{_XLOG_
TRACE2(">>>>>>>>> Alert:%s %s\n",CString(szText,128), szTitle);
InfoWndStruct* info=new InfoWndStruct();
info->sText=szText;
info->sTitle=szTitle;
info->bCenterUnderMouse=TRUE;
if(strstr(szText,"\\n")==0){_XLOG_
info->dwStaticPars=DT_CENTER|DT_VCENTER;
}else{_XLOG_
info->dwStaticPars=DT_CENTER;
}
if(dwTimeOut!=0){_XLOG_
info->dwTimer=dwTimeOut;
}
return Alert(info);
}
InfoWnd* Alert(const char* szText, DWORD dwTime, BOOL bStartHided, BOOL bStaticPars)
{_XLOG_
InfoWndStruct* info=new InfoWndStruct();
info->sText=szText;
info->dwTimer=dwTime;
info->bCenterUnderMouse=TRUE;
info->iIcon=IDI_ICON_INFO_AST;
info->bStartHided=bStartHided;
if(bStaticPars==-1){_XLOG_
info->dwStaticPars=DT_CENTER|DT_VCENTER|DT_SINGLELINE;
}else{_XLOG_
info->dwStaticPars=bStaticPars;
}
return Alert(info);
}
InfoWnd* Alert(const char* szText)
{_XLOG_
return Alert(szText,DWORD(0));
}
InfoWnd* Alert(InfoWndStruct* pInfo)
{_XLOG_
if(pMainDialogWindow && pMainDialogWindow->GetSafeHwnd()){_XLOG_
return (InfoWnd*)(pMainDialogWindow->SendMessage(FIREALERT,NULL,LPARAM(pInfo)));
}
if(WKUtils::isWKUpAndRunning()){_XLOG_
AfxMessageBox(pInfo->sText);
}
return NULL;
}
void deleteFont(CFont* font)
{_XLOG_
if(font==NULL){_XLOG_
return;
}
if(font!=NULL){_XLOG_
VERIFY(font->DeleteObject()!=FALSE);
delete font;
}
}
void deleteBrush(CBrush* br)
{_XLOG_
if(br==NULL){_XLOG_
return;
}
if(br!=NULL){_XLOG_
VERIFY(br->DeleteObject()!=FALSE);
delete br;
}
}
void GetWindowTitleAndData(HWND pCurActivWnd,CString& sNewTitle,CRect& ActiveWndRect)
{_XLOG_
sNewTitle="";
ActiveWndRect.bottom=ActiveWndRect.top=0;
ActiveWndRect.left=ActiveWndRect.right=0;
SafeGetWindowText(pCurActivWnd,sNewTitle);
::GetWindowRect(pCurActivWnd,ActiveWndRect);
objSettings.hFocusWnd=GetLastFocusWindowByHook(pCurActivWnd);
/*
// Зачем??????????????????????
DWORD dwCurWinProcID=0;
DWORD dwThisThread=GetCurrentThreadId();
DWORD dwCurWinThreadID=GetWindowThreadProcessId(pCurActivWnd,&dwCurWinProcID);
DWORD dwThisProcess=GetCurrentProcessId();
BOOL bRes=FALSE;
if(dwThisProcess!=dwCurWinProcID){_XLOG_
bRes=AttachThreadInput(dwThisThread,dwCurWinThreadID,TRUE);
}
objSettings.hFocusWnd=::GetFocus();
if(bRes){_XLOG_
bRes=AttachThreadInput(dwThisThread,dwCurWinThreadID,FALSE);
}
*/
}
BOOL GetActiveWindowTitle(CString& sNewTitle, CRect& ActiveWndRect, HWND* pActivWnd, BOOL bUnderCursor, BOOL bCheckInvis)
{_XLOG_
sNewTitle="NoActiveWindowFound";
ActiveWndRect.SetRect(0,0,0,0);
HWND pCurActivWnd=NULL;
if(bUnderCursor){_XLOG_
POINT pt;
::GetCursorPos(&pt);
pCurActivWnd=::WindowFromPoint(pt);
}else{_XLOG_
pCurActivWnd=::GetForegroundWindow();
}
if(!pCurActivWnd || !IsWindow(pCurActivWnd)){_XLOG_
return 1;
}
DWORD dwPropT=(DWORD)::GetProp(pCurActivWnd,"WKP_INVIS");
if(dwPropT==1 && bCheckInvis){_XLOG_
// Это окно невидимо для WK
//PerformKBInit(NULL);
pCurActivWnd=0;
}
if(pMainDialogWindow && pCurActivWnd == pMainDialogWindow->GetSafeHwnd()){_XLOG_
return 2;
}
if(pActivWnd){_XLOG_
*pActivWnd=pCurActivWnd;
}else{_XLOG_
objSettings.hHotMenuWnd=pCurActivWnd;
}
if(pCurActivWnd){_XLOG_
GetWindowTitleAndData(pCurActivWnd,sNewTitle,ActiveWndRect);
}else{_XLOG_
sNewTitle="";
ActiveWndRect=CRect(0,0,0,0);
}
#ifdef _DEBUG
//ShowBaloon(sNewTitle,"Active window",1000);
#endif
return 0;
}
BOOL PtInWindowRect(POINT pt, CWnd* wnd)
{_XLOG_
CRect rect;
wnd->GetWindowRect(rect);
return rect.PtInRect(pt);
}
BOOL MouseInWndRect(CWnd* wnd)
{_XLOG_
POINT p;
GetCursorPos(&p);
return PtInWindowRect(p,wnd);
}
HRESULT FileToStream(LPCTSTR szFile, IStream* *ppStream)
{_XLOG_
HRESULT hr;
HGLOBAL hGlobal = NULL;
// open file
HANDLE hFile = ::CreateFile(szFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (INVALID_HANDLE_VALUE == hFile)
return HRESULT_FROM_WIN32(::GetLastError());
// get file size
DWORD dwBytesRead = 0, dwFileSize = ::GetFileSize(hFile, NULL);
if (-1 != dwFileSize)
{_XLOG_
hGlobal = ::GlobalAlloc(GMEM_MOVEABLE|GMEM_ZEROINIT, dwFileSize);
if (NULL != hGlobal)
{_XLOG_
PVOID pvData = ::GlobalLock(hGlobal);
ATLASSERT(NULL != pvData);
// read file and store in global memory
::ReadFile(hFile, pvData, dwFileSize, &dwBytesRead, NULL);
::GlobalUnlock(hGlobal);
if (dwFileSize != dwBytesRead)
{_XLOG_
VERIFY(::GlobalFree(hGlobal)==NULL);
hr = E_FAIL;
}
else
hr = S_OK;
}
else
hr = E_OUTOFMEMORY;
}
else
hr = HRESULT_FROM_WIN32(::GetLastError());
::CloseHandle(hFile);
// create IStream* from global memory
if (SUCCEEDED(hr))
hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, ppStream);
return hr;
}
DWORD WINAPI PlaySoundInThread(LPVOID lpdwstatus)
{_XLOG_
long static iSoundTracker=0;
SimpleTracker Track(iSoundTracker);
char* szSName=(char*)lpdwstatus;
if(szSName==NULL){_XLOG_
return 0;
}
CString sWav=szSName;
delete szSName;
if(objSettings.lDisableSounds){_XLOG_
return 0;
}
if(sWav==SND_ERROR){_XLOG_
if(objSettings.bErrorSound){_XLOG_
sWav=objSettings.sErrorSound;
}else{_XLOG_
return 0;
}
}
if(sWav==CLIP_COPY){_XLOG_
if(objSettings.bClipCopySound){_XLOG_
sWav=objSettings.sClipCopyWav;
}else{_XLOG_
return 0;
}
}
if(sWav==CLIP_PASTE){_XLOG_
if(objSettings.bClipPasteSound){_XLOG_
sWav=objSettings.sClipPasteWav;
}else{_XLOG_
return 0;
}
}
if(sWav==CONV_TEXT){_XLOG_
if(objSettings.bOnLConv){_XLOG_
sWav=objSettings.sOnLConvWav;
}else{_XLOG_
return 0;
}
}
if(sWav==TAKE_SSHOT){_XLOG_
if(objSettings.bSShot){_XLOG_
sWav=objSettings.sSShotWav;
}else{_XLOG_
return 0;
}
}
if(sWav==CALC_TEXT){_XLOG_
if(objSettings.bSCalc){_XLOG_
sWav=objSettings.sSCalcWav;
}else{_XLOG_
return 0;
}
}
if(sWav==HK_TEXT){_XLOG_
if(objSettings.bSHk){_XLOG_
sWav=objSettings.sSHkWav;
}else{_XLOG_
return 0;
}
}
if(sWav.GetLength()>0){_XLOG_
int iCount=1;
int iAlarmPos=sWav.Find("alarm=");
if(iAlarmPos>-1){_XLOG_
CString sAlarmCount=sWav.Mid(iAlarmPos+strlen("alarm="));
if(sAlarmCount.SpanExcluding("?&")=="h12"){_XLOG_
iCount=COleDateTime::GetCurrentTime().GetHour();
iCount=iCount%12;
if(iCount==0){_XLOG_
iCount=12;
}
}else{_XLOG_
iCount=atol(sAlarmCount);
}
}
int iSleep=2000;
int iSleepPos=sWav.Find("sleep=");
if(iSleepPos>-1){_XLOG_
iSleep=atol(sWav.Mid(iSleepPos+strlen("sleep=")));
}
sWav=sWav.SpanExcluding("?&");
CString sWavFile;
if(sWav.Find(SOUND_CATALOG"\\")==0 || sWav.Find(SOUND_CATALOG"/")==0){_XLOG_
sWavFile=CString(GetApplicationDir())+sWav;
}else{_XLOG_
sWavFile=sWav;
}
if(isFileExist(sWavFile)){_XLOG_
for(int k=0;k<iCount;k++){_XLOG_
getWinmm().myPlaySound(sWavFile,NULL,SND_FILENAME|SND_ASYNC);//SND_FILENAME|SND_NODEFAULT|SND_NOSTOP|SND_NOWAIT|SND_ASYNC - падает! :(
if(k<iCount-1){_XLOG_
Sleep(iSleep);
}
}
}
}
return 0;
}
void AsyncPlaySound(const char* szSoundName)
{_XLOG_
if(objSettings.lDisableSounds){_XLOG_
return;
}
if(!szSoundName || szSoundName[0]==0){_XLOG_
return;
}
char* szStr=new char[strlen(szSoundName)+1];
strcpy(szStr,szSoundName);
DWORD dwThreadID=0;
HANDLE hThread = CreateThread( NULL, 0, PlaySoundInThread, (void*)szStr, 0, &dwThreadID);
CloseHandle(hThread);
}
CString getLinkedID(const char* szLinkID)
{_XLOG_
CString sOut=szLinkID;
sOut+="L";
return sOut;
}
void InitTRIconList(CComboBoxEx& list)
{_XLOG_
int iCount=0,iCount2=TR_ICONS_OFFSET;
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
AddComboBoxExItem(&list,iCount++,"",iCount2++);
}
CString getClipHotKeyDsc(int iClip,BOOL bCopy)
{_XLOG_
int i=(iClip-1)*2+(bCopy?0:1);
return GetIHotkeyName(objSettings.DefClipMapHK[i]);
}
CString getActionHotKeyDsc(CIHotkey& hk,const char* szBefore, const char* szAfter, const char* szIfNull)
{_XLOG_
BOOL bShrink=0;
CString sRes=GetIHotkeyName(hk,0,bShrink);
sRes=TrimMessage(sRes,25,1);
if(szBefore[0]=='\t'){_XLOG_
/*if(sRes.GetLength()>10){_XLOG_
sRes=sRes.Left(10)+"...";
}*/
}
if(szIfNull && sRes==""){_XLOG_
sRes=szIfNull;
}
if(szBefore){_XLOG_
if(sRes!=""){_XLOG_
sRes=CString(szBefore)+sRes;
};
};
if(szAfter){_XLOG_
if(sRes!=""){_XLOG_
sRes+=szAfter;
};
};
return sRes;
}
CString getActionHotKeyDsc(int iActionNum,const char* szBefore, const char* szAfter, const char* szIfNull)
{_XLOG_
return getActionHotKeyDsc(objSettings.DefActionMapHK[iActionNum],szBefore, szAfter, szIfNull);
};
/*
Поддержка компрессии в NT Оценить
От: Lonely Dog
- RtlDecompressBuffer
- RtlCompressBuffer
RtlCompressBuffer имеет следующий прототип:
NTSYSAPI
ULONG
NTAPI
RtlCompressBuffer (
IN USHORT CompressionFormatAndEngine,
IN PUCHAR UncompressedBuffer,
IN ULONG UncompressedBufferSize,
OUT PUCHAR CompressedBuffer,
IN ULONG CompressedBufferSize,
IN ULONG UncompressedChunkSize,
OUT PULONG FinalCompressedSize,
IN PVOID WorkSpace
);
Если ты разобрался с этой функцией,
то может подскажежешь, что такое WorkSpace?
и каким должен быть его размер
Кстати в ntifs.h определено
#define COMPRESSION_FORMAT_LZNT1 (0x0002)
#define COMPRESSION_ENGINE_MAXIMUM (0x0100)
#define COMPRESSION_ENGINE_HIBER (0x0200)
но у меня работает только COMPRESSION_FORMAT_LZNT1 (WinXP)
Вот пример работы с RtlCompressBuffer. (Из этого можно сделать простейший архиватор,
если усекать файл до сжатого размера)
#include <windows.h>
#include <stdio.h>
#define NTSYSAPI extern "C"
#define COMPRESSION_FORMAT_NONE (0x0000) // winnt
#define COMPRESSION_FORMAT_DEFAULT (0x0001) // winnt
#define COMPRESSION_FORMAT_LZNT1 (0x0002) // winnt
#define COMPRESSION_ENGINE_STANDART (0x0000) // winnt
#define COMPRESSION_ENGINE_MAXIMUM (0x0100) // winnt
#define COMPRESSION_ENGINE_HIBER (0x0200) // winnt
NTSYSAPI
ULONG
NTAPI
RtlGetCompressionWorkSpaceSize (
IN USHORT CompressionFormatAndEngine,
OUT PULONG CompressBufferWorkSpaceSize,
OUT PULONG CompressFragmentWorkSpaceSize
);
NTSYSAPI
ULONG
NTAPI
RtlCompressBuffer (
IN USHORT CompressionFormatAndEngine,
IN PUCHAR UncompressedBuffer,
IN ULONG UncompressedBufferSize,
OUT PUCHAR CompressedBuffer,
IN ULONG CompressedBufferSize,
IN ULONG UncompressedChunkSize,
OUT PULONG FinalCompressedSize,
IN PVOID WorkSpace
);
int main(int argc, char *argv[])
{
if (argc != 3) return 0;
HANDLE hFile1 = CreateFile(argv[1], GENERIC_READ,
FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
HANDLE hFile2 = CreateFile(argv[2], GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ULONG n = GetFileSize(hFile1, 0);
HANDLE hMapping1 = CreateFileMapping(hFile1, 0, PAGE_READONLY, 0, 0, 0);
HANDLE hMapping2 = CreateFileMapping(hFile2, 0, PAGE_READWRITE, 0, n, 0);
PUCHAR p = PUCHAR(MapViewOfFileEx(hMapping1, FILE_MAP_READ, 0, 0, 0, 0));
PUCHAR q = PUCHAR(MapViewOfFileEx(hMapping2, FILE_MAP_WRITE, 0, 0, 0, 0));
ULONG ulBufferWsSize, ulFragmentWsSize;
ULONG st;
ULONG ulFormat = COMPRESSION_FORMAT_LZNT1 | COMPRESSION_ENGINE_STANDART;
st = RtlGetCompressionWorkSpaceSize(ulFormat, &ulBufferWsSize, &ulFragmentWsSize);
DWORD dwSize = 0;
PVOID pv = GlobalAlloc(GPTR, ulBufferWsSize);
DWORD dwSize1;
st = RtlCompressBuffer(ulFormat,
p, n,
q, n,
n,
&dwSize,
pv);
printf("mem: %d\nSize = %d\n", ulBufferWsSize, dwSize);
getchar();
return 0;
}
PS: Эту фигню надо линковать с ntdll.lib из DDK.
PPS: COMPRESSION_FORMAT_LZNT1 - Алгоритм сжатия. (При проектировании NT, ребята из MS хотели добавить возможность расширения системы новыми
алгоритмами сжатия, но сделали ли они это или нет, я не знаю.)
COMPRESSION_ENGINE_XXX - Степень сжатия.
Реально Hiber от standart отличается процентоа на 10 по степени сжатия,
но standart намного быстрее.
*/
DWORD GetDirectorySize(const char* szDirPath)
{_XLOG_
HANDLE hFind;
DWORD dwAllSize=0;
WIN32_FIND_DATA FindData;
CString sFileMask=szDirPath;
sFileMask+="\\*.*";
hFind=FindFirstFile(sFileMask,&FindData);
int isFound=1;
DWORD SavedRep=0;
while(hFind!=INVALID_HANDLE_VALUE && isFound!=0){_XLOG_
if (FindData.cFileName[0]!=TEXT('.') && FindData.cFileName[0] != 0)
if( (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==0 )
dwAllSize+=FindData.nFileSizeLow;
isFound=FindNextFile(hFind,&FindData);
};
if (hFind!=INVALID_HANDLE_VALUE )
FindClose(hFind);
return dwAllSize;
}
//
int RemoveFirstFile(const char* szDirPath)
{_XLOG_
HANDLE hFind;
DWORD dwAllSize=0;
WIN32_FIND_DATA FindData;
DWORD dwFileSize=0;
char szFileName[1024]="";
FILETIME ftFirst;
CString sFileMask=szDirPath;
sFileMask+="\\*.*";
hFind=FindFirstFile(sFileMask,&FindData);
int isFound=1;
DWORD SavedRep=0;
while(hFind!=INVALID_HANDLE_VALUE && isFound!=0){_XLOG_
if (FindData.cFileName[0]!=TEXT('.') && FindData.cFileName[0] != 0)
if( (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==0 ){_XLOG_
if (!strcmp(szFileName,"") || CompareFileTime(&ftFirst,&FindData.ftCreationTime)>0){_XLOG_
strcpy(szFileName,FindData.cFileName);
ftFirst=FindData.ftCreationTime;
dwFileSize=FindData.nFileSizeLow;
}
}
isFound=FindNextFile(hFind,&FindData);
};
if (hFind!=INVALID_HANDLE_VALUE)
FindClose(hFind);
if (strcmp(szFileName,"")){_XLOG_
CString sFileToDelete=(CString(szDirPath)+"\\")+szFileName;
SetFileAttributes(sFileToDelete,FILE_ATTRIBUTE_NORMAL);
if(DeleteFile(sFileToDelete)==0){_XLOG_
Alert(Format("Can`t delete file '%s', %s",sFileToDelete,GetCOMError(GetLastError())));
}
}
return dwFileSize;
}
BOOL GetFileDateTime(const char* szFile, FILETIME* tOut)
{_XLOG_
if(!tOut){_XLOG_
return 0;
}
memset(tOut,0,sizeof(FILETIME));
HANDLE hFile = ::CreateFile(szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile==INVALID_HANDLE_VALUE ){_XLOG_
return 0;
}
FILETIME CreationTime,LastAccessTime;
memset(&CreationTime,0,sizeof(FILETIME));
memset(&LastAccessTime,0,sizeof(FILETIME));
BOOL bRes=::GetFileTime(hFile,&CreationTime,&LastAccessTime,NULL);
::CloseHandle(hFile);
if(!bRes){_XLOG_
return 0;
}
memcpy(tOut,&CreationTime,sizeof(FILETIME));
return TRUE;
}
DWORD dwLastSysRefreshTime=0;
void RefreshProcessListIfNeeded()
{_XLOG_
__FLOWLOG;
if((GetTickCount()-dwLastSysRefreshTime)>5000){_XLOG_
EnumProcesses();
dwLastSysRefreshTime=GetTickCount();
}
}
void GetWndIcon(HWND& hSlayerWnd,HICON& hIcon, HICON* hBigOut)
{_XLOG_
ClearIcon(hIcon);
HICON hTmpIcon=NULL;
HICON hTmpIconBig=NULL;
if(hTmpIcon==NULL){_XLOG_
hTmpIcon=(HICON)::SendMessage(hSlayerWnd,WM_GETICON,ICON_SMALL,0);
}
if(hTmpIcon==NULL){_XLOG_
hTmpIcon=(HICON)GetClassLong(hSlayerWnd, GCL_HICONSM);
}
if(hTmpIconBig==NULL){_XLOG_
hTmpIconBig=(HICON)::SendMessage(hSlayerWnd,WM_GETICON,ICON_BIG,0);
}
if (hTmpIconBig==NULL){_XLOG_
hTmpIconBig=(HICON)GetClassLong(hSlayerWnd, GCL_HICON);
}
if(hTmpIconBig==NULL){_XLOG_
hTmpIconBig=hTmpIcon;
}else if(hTmpIcon==NULL){_XLOG_
hTmpIcon=hTmpIconBig;
}
if(hBigOut){_XLOG_
*hBigOut=CopyIcon(hTmpIconBig);
}
if(hTmpIcon!=NULL){_XLOG_
hIcon=CopyIcon(hTmpIcon);
}
if(hIcon==NULL){_XLOG_
CString sPath="";
DWORD dwProcID=0;
DWORD dwThread=GetWindowThreadProcessId(hSlayerWnd,&dwProcID);
if(dwProcID!=0){_XLOG_
RefreshProcessListIfNeeded();
CProcInfo* info=NULL;
GetProcessInfo(dwProcID,info);
if(info){_XLOG_
GetExeFileIcon(info->sProcExePath,hIcon);
}
}
}
if(hIcon==NULL){_XLOG_
hIcon=theApp.MainImageList.ExtractIcon(APP_ICONS_OFFSET);
}
}
CString GetOrAddPathIconIndex(CString sKey, HICON& hIcon)
{_XLOG_
BOOL bDoNotCache=FALSE;
CString sBmpID=":(";
if(sKey!=""){_XLOG_
CString sVal;
if(objSettings.aIconsMap.Lookup(sKey,sVal)){_XLOG_
bDoNotCache=TRUE;
sBmpID=sVal;
}else{_XLOG_
if(hIcon!=NULL){_XLOG_
// Устанавливаем
sBmpID=CString("PROCIC_")+sKey;
_bmp().AddBmpRaw(sBmpID,hIcon);
}else{_XLOG_
sBmpID="";
}
}
}
if(!bDoNotCache && sBmpID!=""){_XLOG_
objSettings.aIconsMap.SetAt(sKey,sBmpID);
}
return sBmpID;
}
CString GetExeIconIndex(const char* szExePath, BOOL bRawGet,BOOL bAllowRecheck, BOOL bUseSH)
{_XLOG_
if(szExePath==0 || *szExePath==0){_XLOG_
return "";
}
HICON hIcon=NULL;
CString sRes=GetOrAddPathIconIndex(szExePath, hIcon);
if(sRes==":("){_XLOG_
if(!bRawGet){_XLOG_
return "";
}else{// Даем второй шанс
objSettings.aIconsMap.RemoveKey(szExePath);
sRes="";
}
}
if(sRes==""){_XLOG_
ClearIcon(hIcon);
if(bUseSH){_XLOG_
GetExeFileIcon(szExePath, hIcon, bRawGet, 1);
}else if(isFolder(szExePath)){_XLOG_
hIcon=_bmp().CloneAsIcon(_IL(5));
}else{_XLOG_
CString sFile=szExePath;
sFile.TrimLeft(" \"");
sFile.TrimRight(" \"");
CString sExt=GetPathPart(sFile,0,0,0,1);
sExt.MakeLower();
if(sExt==".lnk"){_XLOG_
hIcon=_bmp().CloneAsIcon(_IL(22));
}else{_XLOG_
if(bAllowRecheck){_XLOG_
CString sEAssoc=GetExtensionAssociatedAction(sExt,"");
if(sEAssoc!="" && sEAssoc!=sExt && isFileExist(sEAssoc)){_XLOG_
// Тащим реальный Exe-file
return GetExeIconIndex(sEAssoc,bRawGet,0);
}
}
GetExeFileIcon(sFile, hIcon, bRawGet);
}
}
if(hIcon!=NULL){_XLOG_
sRes=GetOrAddPathIconIndex(szExePath, hIcon);
}else{_XLOG_
hIcon=::LoadIcon(0,IDI_APPLICATION);
sRes=GetOrAddPathIconIndex(szExePath, hIcon);
//objSettings.aIconsMap.SetAt(szExePath,":(");
//return "";
}
}
ClearIcon(hIcon);
return sRes;
}
CString GetProcIconIndex(CProcInfo& info)
{_XLOG_
return GetExeIconIndex(info.sProcExePath, TRUE);
}
extern CCriticalSection pCahLock;
void GetProcessesIcons()
{_XLOG_
__FLOWLOG;
CCSLock lpc(&pCahLock,1);
for(int iPrCount=0;iPrCount<GetProccessCash().GetSize();iPrCount++){_XLOG_
CProcInfo& pInfo=GetProccessCash()[iPrCount];
pInfo.sIconIndex=GetProcIconIndex(pInfo);
}
}
// fkill forces a kill -- it will attempt to enable SeDebugPrivilege
// before opening its process handles, allowing it to kill processes
// running under builtin\system (LocalSystem, to the users out there).
int KillProcess(DWORD pid, const char* szFileTitle)
{_XLOG_
if(szFileTitle){_XLOG_
if(GetAppWnd()){_XLOG_
SetForegroundWindow(GetAppWnd()->GetSafeHwnd());
}
CString sTitle=szFileTitle;
DWORD dwRes=AskYesNo(_l("Do you want to kill")+"\r\n"+Format("'%s'?",TrimMessage(sTitle,40)),_l("Confirmation"),&objSettings.bAskForKill,GetAppWnd());
if(dwRes!=IDYES){_XLOG_
objSettings.bAskForKill=0;// Если NO, то в следующий раз спросим снова
return 0;
}
}
DWORD dwRes=0;
EnableDebugPriv();
HANDLE hProcess = OpenProcess( PROCESS_TERMINATE, FALSE, pid);
if (!( (hProcess) == NULL || (hProcess) == INVALID_HANDLE_VALUE )){_XLOG_
if (TerminateProcess( hProcess, (DWORD) -1 )){_XLOG_
dwRes=1;
}
CloseHandle( hProcess );
}
if(!dwRes){_XLOG_
AsyncPlaySound(SND_ERROR);
}
return dwRes;
}
CString GetCurrentDesktop()
{_XLOG_
HDESK hCurDesk=NULL;
char szDesktopID[DEF_DESKNAMESIZE]="";
if(objSettings.bUnderWindows98 ||!(hCurDesk=GetThreadDesktop(GetCurrentThreadId()))){_XLOG_
GetDesktopInternalName(0,szDesktopID);
return szDesktopID;
}
DWORD dwRealLen=0;
GetUserObjectInformation(hCurDesk,UOI_NAME,szDesktopID,sizeof(szDesktopID),&dwRealLen);
return szDesktopID;
};
int GetCurrentDesktopNumber()
{_XLOG_
CString sDName=GetCurrentDesktop();
char szDesktopID[DEF_DESKNAMESIZE]="";
GetDesktopInternalName(0,szDesktopID);
if(sDName==szDesktopID){_XLOG_
return 0;
}
int iPos=strcspn(sDName,"01234567890");
return atol(sDName.Mid(iPos));
};
BOOL SetCurrentDesktop()
{_XLOG_
if(!objSettings.bUnderWindows98){_XLOG_
// Чтобы пахало на нужно десктопе...
char szDesktopID[DEF_DESKNAMESIZE]="";
GetDesktopInternalName(objSettings.lLastActiveDesktop,szDesktopID);
HDESK hDesktop=::OpenDesktop(szDesktopID,DF_ALLOWOTHERACCOUNTHOOK,FALSE,MAXIMUM_ALLOWED);
if(hDesktop){_XLOG_
BOOL bRes=SetThreadDesktop(hDesktop);
CloseDesktop(hDesktop);
return bRes;
}
}
return FALSE;
}
typedef BOOL (WINAPI *_SaveDesktopIcons)(const char*);
typedef BOOL (WINAPI *_RestoreDesktopIcons)(const char*,BOOL);
BOOL RestoreDesktopIcons()
{_XLOG_
__FLOWLOG;
BOOL bRes=FALSE;
CString sFrom;
char szDesktopID[DEF_DESKNAMESIZE]="";
GetDesktopInternalName(objSettings.lLastActiveDesktop,szDesktopID);
CreateDirIfNotExist(getFileFullName("Desktop\\",TRUE));
CString sFile=getFileFullName(Format("Desktop\\icons-%s.conf",szDesktopID));
HINSTANCE hUtils=LoadLibrary(GetAppFolder()+"WKUtils.dll");
if(hUtils){_XLOG_
_RestoreDesktopIcons fp=(_RestoreDesktopIcons)DBG_GETPROC(hUtils,"RestoreDesktopIcons");
if(fp){_XLOG_
bRes=(*fp)(sFile,objSettings.lRestorePreservRes);
}
}
FreeLibrary(hUtils);
return bRes;
}
BOOL SaveDesktopIcons()
{_XLOG_
__FLOWLOG;
BOOL bRes=FALSE;
// Приписываем результат в нужный десктоп
char szDesktopID[DEF_DESKNAMESIZE]="";
GetDesktopInternalName(objSettings.lLastActiveDesktop,szDesktopID);
CreateDirIfNotExist(getFileFullName("Desktop\\",TRUE));
CString sFile=getFileFullName(Format("Desktop\\icons-%s.conf",szDesktopID));
HINSTANCE hUtils=LoadLibrary(GetAppFolder()+"WKUtils.dll");
if(hUtils){_XLOG_
_SaveDesktopIcons fp=(_SaveDesktopIcons)DBG_GETPROC(hUtils,"SaveDesktopIcons");
if(fp){_XLOG_
bRes=(*fp)(sFile);
}
}
FreeLibrary(hUtils);
return bRes;
}
HWND GetSysTrayNotifyWnd()
{_XLOG_
HWND hWnd1 = ::FindWindow("Shell_TrayWnd",NULL);
if(hWnd1 == 0){_XLOG_
return 0;
}
HWND hWnd2 = FindWindowEx(hWnd1,0,"TrayNotifyWnd",NULL);
if(hWnd2 == 0){_XLOG_
return 0;
}
return hWnd2;
}
HWND GetSysClockWnd()
{_XLOG_
HWND hWnd2 = GetSysTrayNotifyWnd();
if(hWnd2 == 0){_XLOG_
return 0;
}
HWND hWnd3 = FindWindowEx(hWnd2,0,"TrayClockWClass",NULL);
if(hWnd3 == 0){_XLOG_
return 0;
}
return hWnd3;
}
HWND GetSysTrayWnd()
{_XLOG_
HWND hWnd2 = GetSysTrayNotifyWnd();
if(hWnd2 == 0){_XLOG_
return 0;
}
HWND hWnd3 = FindWindowEx(hWnd2,0,"ToolbarWindow32",NULL);
if(hWnd3 == 0){_XLOG_
return 0;
}
return hWnd3;
}
BOOL GetGUIThreadInfoMy(DWORD dwCurWinThreadID, MYGUITHREADINFO* gui)
{_XLOG_
BOOL bRes=FALSE;
HINSTANCE hUser32=LoadLibrary("user32.dll");
if(hUser32){_XLOG_
_GetGUIThreadInfo fp=(_GetGUIThreadInfo)DBG_GETPROC(hUser32,"GetGUIThreadInfo");
if(fp){_XLOG_
memset(gui,0,sizeof(MYGUITHREADINFO));
gui->cbSize=sizeof(MYGUITHREADINFO);
bRes=(*fp)(dwCurWinThreadID, gui);
}
FreeLibrary(hUser32);
}
return bRes;
}
SetWaitTrayIcon::SetWaitTrayIcon(CSystemTray* pTray)
{_XLOG_
hPrev=NULL;
m_pTray=NULL;
hCur=SetCursor(LoadCursor(NULL,MAKEINTRESOURCE(IDC_WAIT)));
if(pTray && !objSettings.bUnderWindows98){_XLOG_
m_pTray=pTray;
hPrev=m_pTray->GetIcon();
if(hPrev){_XLOG_
HICON hWaitIcon=CopyIcon(::AfxGetApp()->LoadIcon(IDR_MAINICOW));
HICON hIcon=PutOverlayInIconSz(hPrev,hWaitIcon,_bmp().MenuIconSize.cx,_bmp().MenuIconSize.cy,0,0,0,TRUE);
m_pTray->SetIcon(hIcon);
}
}
};
SetWaitTrayIcon::~SetWaitTrayIcon()
{_XLOG_
if(hPrev){_XLOG_
HICON hTemp=m_pTray->GetIcon();
m_pTray->SetIcon(hPrev);
ClearIcon(hTemp);
}
if(hCur){_XLOG_
SetCursor(hCur);
}
};
long getCharAsInt(char c)
{_XLOG_
if(c>='0' && c<='9'){_XLOG_
return int(c)-int('0');
}
if(c>='a' && c<='z'){_XLOG_
return int(c)-int('a')+10;
}
if(c>='A' && c<='Z'){_XLOG_
return int(c)-int('A')+10;
}
return -1;
}
BOOL ParsedAsArithmeticalExpr(CString& sExpr)
{_XLOG_
static long lLock=0;
if(lLock>0){// Уже что-то считается...
return -1;
}
SimpleTracker tr(lLock);
int iRes=0;
CString sResPrefix="";
// Возможно просто случай - число в 10 или 16
if(sExpr.Right(1)!="="){_XLOG_
sExpr.TrimRight("=");
if(sExpr.SpanIncluding("0123456789")==sExpr){_XLOG_
sExpr+="(10->16)=";
sResPrefix="0x";
}
if(sExpr.GetLength()>2 && sExpr.Left(2)=="0x" && sExpr.SpanIncluding("0123456789xabcdefABCDEF")==sExpr){_XLOG_
sExpr=sExpr.Mid(2);
sExpr+="(16->10)=";
}
if(sExpr.SpanIncluding("0123456789+-*/().,")==sExpr){_XLOG_
sExpr+="=";
}
}
if(sExpr.Right(1)=="="){_XLOG_
long lResultIn=0;
long lResultTo=0;
BOOL bConversion=PatternMatch(sExpr,"*(*>*)=");
if(!bConversion){_XLOG_
bConversion=PatternMatch(sExpr,"*(*to*)=");
}
if(!bConversion){_XLOG_
bConversion=PatternMatch(sExpr,"*(*2*)=");
}
if(bConversion){_XLOG_
int iPos=sExpr.ReverseFind('(');
int iPos2=sExpr.ReverseFind('>');
if(iPos2==-1){_XLOG_
iPos2=sExpr.Find("to",iPos);
if(iPos2!=-1){_XLOG_
iPos2++;
}
}
if(iPos2==-1){_XLOG_
iPos2=sExpr.Find("2",iPos);
}
if(iPos2>0){_XLOG_
CString sTp=sExpr.Mid(iPos2+1);
sTp.MakeLower();
sTp.TrimLeft();
sTp.TrimRight();
if(sTp!=""){_XLOG_
if(sTp[0]=='b'){_XLOG_
lResultTo=2;
}else if(sTp[0]=='d'){_XLOG_
lResultTo=10;
}else if(sTp[0]=='o'){_XLOG_
lResultTo=8;
}else if(sTp[0]=='h'){_XLOG_
lResultTo=16;
}else{_XLOG_
lResultTo=atol(sTp);
if(lResultTo==0){_XLOG_
lResultTo=16;
}
}
}
}
if(iPos>0){_XLOG_
bConversion=1;
CString sTp=sExpr.Mid(iPos+1);
sExpr=sExpr.Left(iPos);
sTp.MakeLower();
sTp.TrimLeft();
sTp.TrimRight();
if(sTp[0]=='b'){_XLOG_
lResultIn=2;
}else if(sTp[0]=='d'){_XLOG_
lResultIn=10;
}else if(sTp[0]=='o'){_XLOG_
lResultIn=8;
}else if(sTp[0]=='h'){_XLOG_
lResultIn=16;
}else{_XLOG_
lResultIn=atol(sTp);
if(lResultIn==0){_XLOG_
lResultIn=10;
}
}
}
}
if(!bConversion){_XLOG_
if(sExpr.Find("(b)=")!=-1 || sExpr.Find("(B)=")!=-1){_XLOG_
bConversion=1;
lResultIn=10;
lResultTo=2;
}
if(sExpr.Find("(h)=")!=-1 || sExpr.Find("(H)=")!=-1){_XLOG_
bConversion=1;
lResultIn=10;
lResultTo=16;
}
if(sExpr.Find("(o)=")!=-1 || sExpr.Find("(O)=")!=-1){_XLOG_
bConversion=1;
lResultIn=10;
lResultTo=8;
}
if(sExpr.Find("(d)=")!=-1 || sExpr.Find("(D)=")!=-1){_XLOG_
bConversion=1;
lResultIn=16;
lResultTo=10;
}
}
sExpr.TrimRight("=");
CString sScript=Format("var RESULT=0;with(Math){RESULT=eval(unescape('%s'));};RESULT;",EscapeString(sExpr));
if(bConversion && sExpr.SpanExcluding("0123456789abcdefABCDEF to")==""){_XLOG_
iRes=1;
sScript=sExpr;
}else{_XLOG_
iRes=CalculateExpression_Ole(sScript, "JScript", bConversion);
}
if(bConversion && lResultIn>0 && lResultTo>0){_XLOG_
if(iRes!=1){_XLOG_
// Это было невычисляемо, значит
// просто переводим текст
sScript=sExpr;
}
long lValue=0;
long lCharValue=0;
sScript.MakeUpper();
while(sScript!="" && (lCharValue=getCharAsInt(sScript[0]))>=0){_XLOG_
lValue=lValue*lResultIn+lCharValue;
sScript=sScript.Mid(1);
}
char szBuffer[128]="";
_itoa(lValue,szBuffer,lResultTo);
sScript=szBuffer;
sScript.MakeUpper();
iRes=1;
}else if(iRes && sScript.Find(",")!=-1 && sScript.GetLength()>2){_XLOG_
// Исправляем запятые на точки
char* szScriptPos=sScript.GetBuffer(sScript.GetLength());
for(long i=1;i<long(strlen(szScriptPos)-1);i++){_XLOG_
if(szScriptPos[i]==',' && szScriptPos[i-1]>='0' && szScriptPos[i-1]<='9' && szScriptPos[i+1]>='0' && szScriptPos[i+1]<='9'){_XLOG_
szScriptPos[i]='.';
}
}
sScript.ReleaseBuffer();
}
sExpr=CString(iRes==1?sResPrefix:"")+sScript;
}
return iRes;
}
DWORD WINAPI PasteClipText(LPVOID pData)
{_XLOG_
TRACETHREAD;
char* szChar=(char*)pData;
if(!szChar){_XLOG_
return 0;
}
CString sText=szChar;
delete[] szChar;
CString sTextToSet=sText;
if(objSettings.bUseRegexps && objSettings.sRegexpWhat.GetLength()>0){_XLOG_
sText.Replace("\"","\\\"");
CString sRegexp=CString("\"")+sText+"\".replace(/"+objSettings.sRegexpWhat+"/ig,\""+objSettings.sRegexpTo+"\")=";
CString sRegexpOrig=sRegexp;
if(ParsedAsArithmeticalExpr(sRegexp)!=1){_XLOG_
return 0;
}
if(sRegexpOrig!=sRegexp){_XLOG_
sTextToSet=sRegexp;
}
}
AsyncPlaySound(CLIP_PASTE);
PutSelectedTextInFocusWnd(sTextToSet,0,objSettings.lLeaveInClipOnPaste);
return 0;
}
BOOL ClipAddTextToPinned(const char* szText, const char* szHistName,BOOL bToPinned, const char* szDsc, const char* szApp)
{_XLOG_
static CCriticalSection cs;
CLocker locker(&cs);
CStringArrayX tmp;
if(!objSettings.sClipHistory.Lookup(szHistName,tmp)){_XLOG_
objSettings.sClipHistory.SetAt(szHistName,tmp);
}
if(bToPinned){_XLOG_
while(objSettings.sClipHistory[szHistName].GetSize()<objSettings.lClipHistoryDepth){_XLOG_
CPairItem item("",szDsc,szApp);
objSettings.sClipHistory[szHistName].Add(item);
}
// переноcим на новое если это раньше был обычный кусок
CPairItem item(szText,szDsc,szApp);
objSettings.sClipHistory[szHistName].Add(item);
}else{_XLOG_
CPairItem item(szText,szDsc,szApp);
objSettings.sClipHistory[szHistName].InsertAt(0,item);
if(objSettings.sClipHistory[szHistName].GetSize()>objSettings.lClipHistoryDepth){_XLOG_
objSettings.sClipHistory[szHistName].RemoveAt(objSettings.lClipHistoryDepth);
}
}
static DWORD dwLastOperTime=GetTickCount();
if(objSettings.lSaveClipContentPer && GetTickCount()-dwLastOperTime>5*60*1000){_XLOG_
dwLastOperTime=GetTickCount();
objSettings.SaveHistories("");
}
return TRUE;
}
DWORD WINAPI NotifyClip(LPVOID p)
{
CWKSYSEvent pEvent;
pEvent.iEventType=IsBMP((char*)p)?WKSYSEVENTTYPE_COPYCLIPIMG:WKSYSEVENTTYPE_COPYTOCLIPB;
pEvent.pData=p;
GlobalNotifyAboutSystemEvent(&pEvent);
free(p);
return 0;
}
BOOL SetTextToClip(int iClip, CString& sText, BOOL bCheckAllHistory)
{_XLOG_
if(iClip==0 && !IsBMP(sText)){
FORK(NotifyClip,strdup(sText));
}
if(iClip>=0 && iClip<objSettings.sClipBuffer.GetSize() && sText.GetLength()!=0){_XLOG_
SimpleLocker l(&csClipBuffer);
objSettings.sClipBuffer[iClip]=sText;
if(objSettings.sClipHistory[GetClipHistoryName(iClip)].GetSize()>0){_XLOG_
if(bCheckAllHistory){_XLOG_
CString sTextToCheck;
if(IsBMP(sText)){_XLOG_
sTextToCheck=CDataXMLSaver::GetInstringPart(BMP_SPECPREFIX"[","]",sText);
int iPos=sTextToCheck.Find(",");
if(iPos!=-1){_XLOG_
sTextToCheck=sTextToCheck.Mid(iPos);
}
}else{_XLOG_
sTextToCheck=sText;
}
for(int i=0;i<objSettings.sClipHistory[GetClipHistoryName(iClip)].GetSize();i++){_XLOG_
CString sItemToCheck;
if(IsBMP(objSettings.sClipHistory[GetClipHistoryName(iClip)][i].sItem)){_XLOG_
sItemToCheck=CDataXMLSaver::GetInstringPart(BMP_SPECPREFIX"[","]",objSettings.sClipHistory[GetClipHistoryName(iClip)][i].sItem);
int iPos=sItemToCheck.Find(",");
if(iPos!=-1){_XLOG_
sItemToCheck=sItemToCheck.Mid(iPos);
}
}else{_XLOG_
sItemToCheck=objSettings.sClipHistory[GetClipHistoryName(iClip)][i].sItem;
}
if(sTextToCheck==sItemToCheck){_XLOG_
return FALSE;
}
}
}else{_XLOG_
if(sText==objSettings.sClipHistory[GetClipHistoryName(iClip)][0].sItem){_XLOG_
return FALSE;
}
}
}
// Активное в данный момент окно
char szDsc[256]="";
CString szApp;
HWND hFore=::GetForegroundWindow();
CString sDsc;
if(hFore){_XLOG_
::GetWindowText(hFore,szDsc,sizeof(szDsc));
sDsc=szDsc;
sDsc+="\n["+_l("Time")+": "+COleDateTime::GetCurrentTime().Format(0,LANG_USER_DEFAULT)+"]";//Format("%x",LOCALE_NOUSEROVERRIDE);
szApp=GetExeFromHwnd(hFore);
}
ClipAddTextToPinned(sText,GetClipHistoryName(iClip),(GetAsyncKeyState(VK_RWIN)<0),sDsc,szApp);
return TRUE;
}
return FALSE;
}
void SendCtrlV(BOOL m_bUseWMCOPY, HWND hTargetWnd);
DWORD WINAPI TransmitTextToTarget(LPVOID pData)
{_XLOG_
TRACETHREAD;
char* szText=(char*)pData;
CString sText=szText;
free((LPVOID)szText);
if(objSettings.hWndToTransmitTo!=NULL && ::IsWindow(objSettings.hWndToTransmitTo)){_XLOG_
HWND hCurrent=GetForegroundWindow();
SwitchToWindow(objSettings.hWndToTransmitTo,TRUE);
PutSelectedTextInFocusWnd(sText,0,1);
SwitchToWindow(hCurrent,TRUE);
return TRUE;
}
objSettings.lClipTransmitMode=0;
objSettings.hWndToTransmitTo=NULL;
AsyncPlaySound(SND_ERROR);
return FALSE;
}
DWORD WINAPI ShowBaloon_InThread(LPVOID pData)
{_XLOG_
TRACETHREAD;
static long lLock=0;
/*if(lLock>0){_XLOG_
return 0;
}*/
SimpleTracker tr(lLock);
long lLockAtStart=lLock;
BaloonInfo* bi=(BaloonInfo*)pData;
if(!pMainDialogWindow || !bi){_XLOG_
return 0;
}
if(pMainDialogWindow->m_STray.Visible()){_XLOG_
pMainDialogWindow->m_STray.PopupBaloonTooltip("","");
pMainDialogWindow->m_STray.PopupBaloonTooltip(bi->sTitle,bi->sText,0,10000);
Sleep(bi->dwTimeout);
if(lLockAtStart==lLock && pMainDialogWindow && pMainDialogWindow->iRunStatus!=-2){_XLOG_
pMainDialogWindow->m_STray.PopupBaloonTooltip("","");
}
}else if(!bi->bBaloonOnly){_XLOG_
Alert(bi->sText,bi->sTitle,bi->dwTimeout);
}
delete bi;
return 1;
}
void ShowBaloon(const char* szText, const char* szTitle, DWORD dwTimeout, BOOL bBaloonOnly)
{_XLOG_
BaloonInfo* bi=new BaloonInfo();
bi->sText=szText;
bi->sTitle=szTitle;
bi->dwTimeout=dwTimeout;
bi->bBaloonOnly=bBaloonOnly;
FORK(ShowBaloon_InThread,bi);
}
void SubstMyVariablesWK(CString& sText, BOOL bJScriptSafe)
{_XLOG_
__FLOWLOG;
BOOL bNeedActive=(sText.Find("%ACTIVE")!=-1);
bNeedActive|=(sText.Find("%E_ACTIVE")!=-1);
if(bNeedActive){_XLOG_
char szTitle[1024]="";
HWND hCurWnd=GetForegroundWindow();
CString sExe="",sFile="";
if(hCurWnd){_XLOG_
sExe=GetExeFromHwnd(hCurWnd);
::GetWindowText(hCurWnd,szTitle,sizeof(szTitle));
char szFile[MAX_PATH]="";
_splitpath(sExe,NULL,NULL,szFile,NULL);
sFile=szFile;
}
CString sWnd=szTitle;
sFile.MakeUpper();
sText.Replace("%ACTIVEAPP",sFile);
sText.Replace("%E_ACTIVEAPP",EscapeString(sFile));
sText.Replace("%ACTIVEEXE",sExe);
sText.Replace("%E_ACTIVEEXE",EscapeString(sExe));
sText.Replace("%ACTIVEWND",sWnd);
sText.Replace("%E_ACTIVEWND",EscapeString(sWnd));
}
int iPrECount=0;
int iIsRunPos=sText.Find("%ISRUN:");
CCSLock lpc(&pCahLock,1);
while(iIsRunPos!=-1){_XLOG_
if(iPrECount==0){_XLOG_
EnumProcesses();
}
iPrECount++;
CString sRes="0";
CString sExeName=sText.Mid(iIsRunPos+strlen("%ISRUN:")).SpanExcluding(" ;\"',/*=![](){}~@#$%^&");
for(int iProcNum=0; iProcNum<GetProccessCash().GetSize();iProcNum++){_XLOG_
CProcInfo& info=GetProccessCash()[iProcNum];
if(info.sProcName.CompareNoCase(sExeName)==0){_XLOG_
sRes="1";
}
}
sText.Replace("%ISRUN:"+sExeName,sRes);
iIsRunPos=sText.Find("%ISRUN:");
}
SubstMyVariables(sText,bJScriptSafe);
}
//DEFINE_GUID(IID_IDirectDrawVideo, 0x36d39eb0, 0xdd75, 0x11ce, 0xbf, 0x0e, 0x00, 0xaa, 0x00, 0x55, 0x59, 0x5a)
BOOL ReparseWinampTitle(CString& sTitle, HWND hWAWnd, BOOL bTotOnly)
{_XLOG_
if(objSettings.lStripNumberWinampTitle){_XLOG_
int iPos=sTitle.Find(" - Winamp");
if(iPos!=-1){_XLOG_
sTitle=sTitle.Left(iPos);
}
CString sSongNumber=Format("%lu. ",atol(sTitle));
int iPos2=sTitle.Find(sSongNumber);
if(iPos2==0){_XLOG_
sTitle=sTitle.Mid(sSongNumber.GetLength());
}
}
if(objSettings.lAddTLWinampTitle && !bTotOnly){_XLOG_
int iCurMills=::SendMessage(hWAWnd,WM_USER,0,105);
if(iCurMills<0){_XLOG_
iCurMills=0;
}
sTitle+=Format(" [%02i:%02i]",int(iCurMills/1000/60),int(iCurMills/1000)%60);
if(objSettings.lAddTTWinampTitle){_XLOG_
sTitle+=" / ";
}
}
if(objSettings.lAddTTWinampTitle){_XLOG_
int iTSeconds=::SendMessage(hWAWnd,WM_USER,1,105);
if(iTSeconds<0){_XLOG_
iTSeconds=0;
}
sTitle+=Format(" [%02i:%02i]",int(iTSeconds/60),iTSeconds%60);
}
return TRUE;
};
void FillSplashParams(const char* szTitle, CSplashParams& par)
{_XLOG_
par.szText=par.sTextPrefix+TrimMessage(szTitle,objSettings.lOSDChars,1)+par.sTextPosfix;
par.bgColor=objSettings.lSplashBgColor;
par.txColor=objSettings.lSplashTextColor;
par.pFont=objSettings.pSplashFont;
par.dwTextParams=0;
par.bFade=objSettings.bUnderWindows98?0:objSettings.lDeskfadeOSD;
if(objSettings.lOSDBorder){_XLOG_
par.dwTextParams|=TXSHADOW_VCENT|TXSHADOW_FILLBG|TXSHADOW_MIXBG;////TXSHADOW_SHCOL
if(objSettings.lOSDBorder==1 || objSettings.lOSDBorder==3){_XLOG_
par.dwTextParams|=TXSHADOW_WIDE;
}
if(objSettings.lOSDBorder==1 || objSettings.lOSDBorder==2){_XLOG_
par.dwTextParams|=TXSHADOW_GLOW;
}else{_XLOG_
par.dwTextParams|=TXSHADOW_SIMPLE;
}
}
par.dwSplashAlign=SPLASH_OPACITY;
DWORD dwTextParAlign=TXSHADOW_HCENT;
if(objSettings.lStartupMsgType==0){_XLOG_
par.dwSplashAlign|=SPLASH_HIDDEN;
}
if(objSettings.lNoNeedOSD){_XLOG_
par.dwSplashAlign|=SPLASH_HIDDEN;
}
if(objSettings.lStartupMsgType==1 || objSettings.lStartupMsgType==4){_XLOG_
par.dwSplashAlign|=SPLASH_HLEFT;
dwTextParAlign=0;
}
if(objSettings.lStartupMsgType==2 || objSettings.lStartupMsgType==3){_XLOG_
par.dwSplashAlign|=SPLASH_HRIGHT;
dwTextParAlign=TXSHADOW_RIGHT;
}
if(objSettings.lStartupMsgType==1 || objSettings.lStartupMsgType==2 || objSettings.lStartupMsgType==6){_XLOG_
par.dwSplashAlign|=SPLASH_VTOP;
}
if(objSettings.lStartupMsgType==3 || objSettings.lStartupMsgType==4 || objSettings.lStartupMsgType==7){_XLOG_
par.dwSplashAlign|=SPLASH_VBOTTOM;
}
if(objSettings.lStartupMsgType==5 || objSettings.lStartupMsgType==6 || objSettings.lStartupMsgType==7){_XLOG_
par.dwSplashAlign|=SPLASH_HCENTER;
if(objSettings.lStartupMsgType==5){_XLOG_
par.dwSplashAlign|=SPLASH_VMIDDLE;
}
}
par.dwTextParams|=dwTextParAlign;
}
DWORD WINAPI ShowWTitleSplash(LPVOID pData)
{_XLOG_
CSplashParams* par=(CSplashParams*)pData;
static long lCount=0;
if(lCount>0){_XLOG_
delete par;
return 0;
}
SimpleTracker tr(lCount);
if(par){_XLOG_
if(!objSettings.lNoNeedOSD){// Показываем сплэш-стринг
CSplashWindow OSD(par);
Sleep(objSettings.lWinampOSDTime*1000);
}
delete par;
}
return 0;
}
void ExecuteMacroByString(CString sExe)
{_XLOG_
HWND hMainI=FindWindow("WK_MAIN",0);
HWND hMain=(HWND)GetProp(hMainI,"MAIN_WND");
if(hMain==0 || !IsWindow(hMain)){_XLOG_
CString sErr=_l("Error")+": "+_l("To activate this action, "PROGNAME" must be started already")+"!";
#ifdef _DEBUG
sErr+=Format("\n%x/%x",hMainI,hMain);
#endif
AfxMessageBox(sErr);
}else{_XLOG_
COPYDATASTRUCT cpd;
cpd.dwData = MAKELONG(0,WM_CREATE);
cpd.cbData = strlen(sExe)+1;
cpd.lpData = (void*)(sExe.GetBuffer(1));
BOOL b=SendMessage( hMain, WM_COPYDATA, (WPARAM)AppMainApp::m_pFakeWnd->GetSafeHwnd(), (LPARAM)&cpd );
}
}
BOOL GetRegSetting(const char* szFName, const char* szRegSettingsName, char* szOut, size_t dwOutSize)
{_XLOG_
CRegKey key;
CString sKeyPath=CString(PROG_REGKEY);
if(szFName && szFName[0]){_XLOG_
sKeyPath+="\\";
sKeyPath+=szFName;
}
if(key.Open(HKEY_CURRENT_USER, sKeyPath)!=ERROR_SUCCESS){_XLOG_
key.Create(HKEY_CURRENT_USER, sKeyPath);
}
if(key.m_hKey!=NULL){_XLOG_
DWORD dwType=REG_SZ;
DWORD dwSize=dwOutSize;
RegQueryValueEx(key.m_hKey, szRegSettingsName, NULL, &dwType, (LPBYTE)szOut, &dwSize);
}
return TRUE;
}
BOOL SetRegSetting(const char* szFName, const char* szRegSettingsName, char* szOut)
{_XLOG_
CRegKey key;
CString sKeyPath=CString(PROG_REGKEY);
if(szFName && szFName[0]){_XLOG_
sKeyPath+="\\";
sKeyPath+=szFName;
}
if(key.Open(HKEY_CURRENT_USER, sKeyPath)!=ERROR_SUCCESS){_XLOG_
key.Create(HKEY_CURRENT_USER, sKeyPath);
}
if(key.m_hKey!=NULL){_XLOG_
DWORD dwType=REG_SZ,dwSize=0;
RegSetValueEx(key.m_hKey,szRegSettingsName,0,REG_SZ,(BYTE*)(LPCSTR)szOut,lstrlen(szOut)+1);
}
return TRUE;
}
typedef unsigned __int32 uint32_t;
bool UTF2U(const char* src,CString& outc)
{_XLOG_
bool res = true;
int mState = 0;
int mUcs4 = 0;
int mBytes = 1;
int iLen=strlen(src);
wchar_t* out=new wchar_t[iLen];
memset(out,0,sizeof(wchar_t)*iLen);
int iw=0;
for(const char *in = src; in-src<iLen; in++)
{_XLOG_
if(0 == mState) {_XLOG_
if( 0 == (0x80 & (*in))) {_XLOG_
// ASCII
out[iw++] = *in;
mBytes =1;
} else if( 0xC0 == (0xE0 & (*in))) {_XLOG_
// 2-х байтный UTF8
mUcs4 = (uint32_t)(*in);
mUcs4 = (mUcs4 << 6) & 0x000007C0L;
mState=1;
mBytes =2;
} else if( 0xE0 == (0xF0 & (*in))) {_XLOG_
// 3-х байтный UTF8
mUcs4 = (uint32_t)(*in);
mUcs4 = (mUcs4 << 12) & 0x0000F000L;
mState=2;
mBytes =3;
} else if( 0xF0 == (0xF8 & (*in))) {_XLOG_
// 4-х байтный UTF8
mUcs4 = (uint32_t)(*in);
mUcs4 = (mUcs4 << 18) & 0x001F0000L;
mState=3;
mBytes =4;
} else if( 0xF8 == (0xFC & (*in))) {_XLOG_
// 5-х байтный UTF8
mUcs4 = (uint32_t)(*in);
mUcs4 = (mUcs4 << 24) & 0x03000000L;
mState=4;
mBytes =5;
} else if( 0xFC == (0xFE & (*in))) {_XLOG_
// 6-х байтный UTF8
mUcs4 = (uint32_t)(*in);
mUcs4 = (mUcs4 << 30) & 0x40000000L;
mState=5;
mBytes =6;
} else {_XLOG_
res = false;
break;
}
} else {_XLOG_
if(0x80 == (0xC0 & (*in))) {_XLOG_
uint32_t tmp = (*in);
uint32_t shift = (mState-1) * 6;
tmp = (tmp << shift ) & ( 0x0000003FL << shift);
mUcs4 |= tmp;
if(0 == --mState) {_XLOG_
if(mUcs4 >= 0x00010000) {_XLOG_
if(mUcs4 >= 0x00110000) {_XLOG_
out[iw++] = (wchar_t)0xFFFD;
} else {_XLOG_
mUcs4 -= 0x00010000;
out[iw++] = (wchar_t)(0xD800 | (0x000003FF & (mUcs4 >> 10)));
out[iw++] = (wchar_t)(0xDC00 | (0x000003FF & mUcs4));
}
} else {_XLOG_
// from Unicode 3.1, non-shortest form is illegal
if(((2==mBytes) && (mUcs4 < 0x0080)) ||
((3==mBytes) && (mUcs4 < 0x0800)) ||
((4==mBytes) && (mUcs4 < 0x1000)) ||
(5==mBytes) ||
(6==mBytes))
{_XLOG_
res = false;
break;
}
if( 0xfeff != mUcs4 ) // ignore BOM
{
out[iw++] = (wchar_t)mUcs4;
}
}
mState = 0;// cached expected number of bytes per UTF8 character sequence
mUcs4 = 0;// cached Unicode character
mBytes = 1;
}
} else {_XLOG_
res = false;
break;
}
}
}
outc=out;
delete[] out;
return(res);
}
CString getHotKeyStr(CIHotkey oHotKey, BOOL bWithFollowers)
{_XLOG_
CString sRes=GetIHotkeyName(oHotKey,bWithFollowers);
if(sRes==""){_XLOG_
sRes="<";
sRes+=_l("not defined");
sRes+=">";
}
return sRes;
}
CString& GetPluginsDirectory()
{_XLOG_
static CString sDir;
return sDir;
}
CString getHotKeyStrAlt(CIHotkey oHotKey,CString sPrefix)
{_XLOG_
CString sRes="";
if(oHotKey.pNextHK){_XLOG_
sRes=GetIHotkeyName(*oHotKey.pNextHK,TRUE);
}
if(sRes!=""){_XLOG_
sRes=sPrefix+sRes;
}
return sRes;
}
BOOL WINAPI GetFileDescription(const char* szFileName, char szDescOut[256])
{_XLOG_
memset(szDescOut,0,sizeof(szDescOut));
CFileVersionInfo fVer;
if(fVer.Open(szFileName)){_XLOG_
fVer.QueryStringValue(VI_STR_FILEDESCRIPTION,szDescOut,256);
return 1;
}
char szD[MAX_PATH]="";
char szP[MAX_PATH]="";
char szN[MAX_PATH]="";
char szE[MAX_PATH]="";
_splitpath(szFileName,szD,szP,szN,szE);
strcpy(szDescOut,szN);
return 0;
}
| [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
]
| [
[
[
1,
1722
]
]
]
|
2c6fbf89d78b97b47df4b2e90f040f5dc874f69b | fb8e78a63b0a222bc32694659cc98889ebe231f0 | /addons/ofxFft/src/ofxFft.cpp | c5b5add3bde980e29cd27b75e962bf1cb1cb3135 | []
| no_license | dopuskh3/ofx-projects | ac8bdef343bcfcf4aecc57eec1041fbec838b8d0 | 42db4ab24b94794c5541b46ab9c88445d19bafae | refs/heads/master | 2021-01-25T06:05:36.738619 | 2010-04-05T10:57:14 | 2010-04-05T10:57:14 | 324,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,956 | cpp | #include "ofxFft.h"
//#include "ofxFftBasic.h"
#include "ofxFftw.h"
ofxFft* ofxFft::create(int signalSize, fftWindowType windowType, fftImplementation implementation) {
ofxFft* fft;
if(implementation == OF_FFT_BASIC) {
//fft = new ofxFftBasic();
} else if(implementation == OF_FFT_FFTW) {
fft = new ofxFftw();
}
fft->setup(signalSize, windowType);
return fft;
}
void ofxFft::setup(int signalSize, fftWindowType windowType) {
this->signalSize = signalSize;
this->bins = signalSize / 2;
signal = new float[signalSize];
real = new float[bins];
imag = new float[bins];
amplitude = new float[bins];
phase = new float[bins];
polarReady = false;
cartesianReady = false;
signalReady = true;
window = new float[signalSize];
setWindowType(windowType);
}
int ofxFft::getBinSize() {
return bins;
}
int ofxFft::getSignalSize() {
return signalSize;
}
void ofxFft::setWindowType(fftWindowType windowType) {
this->windowType = windowType;
if(windowType == OF_FFT_RECTANGULAR) {
for(int i = 0; i < signalSize; i++)
window[i] = 1; // only used for windowSum
} else if(windowType == OF_FFT_BARTLETT) {
for (int i = 0; i < signalSize / 2; i++) {
window[i] = (i / (signalSize / 2));
window[i + (signalSize / 2)] = (1.0 - (i / (signalSize / 2)));
}
} else if(windowType == OF_FFT_HANN) {
for(int i = 0; i < signalSize; i++)
window[i] = .5 * (1 - cos((TWO_PI * i) / (signalSize - 1)));
} else if(windowType == OF_FFT_HAMMING) {
for(int i = 0; i < signalSize; i++)
window[i] = .54 - .46 * cos((TWO_PI * i) / (signalSize - 1));
} else if(windowType == OF_FFT_SINE) {
for(int i = 0; i < signalSize; i++)
window[i] = sin((PI * i) / (signalSize - 1));
}
windowSum = 0;
for(int i = 0; i < signalSize; i++)
windowSum += window[i];
}
ofxFft::~ofxFft() {
delete[] window, signal, real, imag, amplitude, phase;
}
void ofxFft::draw(float x, float y) {
draw(x, y, getWidth(), getHeight());
}
void ofxFft::draw(float x, float y, float width, float height) {
ofPushStyle();
ofPushMatrix();
ofTranslate(x, y);
ofNoFill();
ofRect(0, 0, width, height);
ofBeginShape();
getAmplitude();
for (int i = 0; i < bins; i++)
ofVertex(i, amplitude[i] * height);
ofEndShape();
ofPopMatrix();
ofPopStyle();
}
float ofxFft::getWidth() {
return bins;
}
float ofxFft::getHeight() {
return bins / 2;
}
void ofxFft::setSignal(float* signal) {
memcpy(this->signal, signal, sizeof(float) * signalSize);
}
void ofxFft::setReal(float* real) {
memcpy(this->real, real, sizeof(float) * bins);
}
void ofxFft::setImaginary(float* imag) {
memcpy(this->imag, imag, sizeof(float) * bins);
}
void ofxFft::setAmplitude(float* amplitude) {
memcpy(this->amplitude, amplitude, sizeof(float) * bins);
}
void ofxFft::setPhase(float* phase) {
memcpy(this->phase, phase, sizeof(float) * bins);
}
float* ofxFft::getSignal() {
if(!signalReady) {
float normalizer = 2. / windowSum;
for (int i = 0; i < bins; i++)
signal[i] *= normalizer;
signalReady = true;
}
return signal;
}
float* ofxFft::getReal() {
if(!cartesianReady)
updateCartesian();
return real;
}
float* ofxFft::getImaginary() {
if(!cartesianReady)
updateCartesian();
return imag;
}
float* ofxFft::getAmplitude() {
if(!polarReady)
updatePolar();
return amplitude;
}
float* ofxFft::getPhase() {
if(!polarReady)
updatePolar();
return phase;
}
void ofxFft::updateCartesian() {
for(int i = 0; i < bins; i++) {
real[i] = cos(phase[i]) * amplitude[i];
phase[i] = sin(phase[i]) * amplitude[i];
}
cartesianReady = true;
}
void ofxFft::updatePolar() {
float normalizer = 2. / windowSum;
for(int i = 0; i < bins; i++) {
amplitude[i] = cartesianToAmplitude(real[i], imag[i]) * normalizer;
phase[i] = cartesianToPhase(real[i], imag[i]);
}
polarReady = true;
}
| [
"[email protected]"
]
| [
[
[
1,
172
]
]
]
|
56ed9285759743ebda982d4f3c013356edf3c9de | 2a47a0a9749be9adae403d99f6392f9d412fca53 | /OpenGL/Puppet/iguana.cpp | 218661dde6eeee57c9114dcadc14f2b03b373d1c | []
| no_license | waseemilahi/waseem | 153bed6788475a88d234d75a323049a9d8ec47fe | 0bb2bddcc8758477f0ad5db85bfc927db2ae07af | refs/heads/master | 2020-03-30T14:59:17.066002 | 2008-11-22T01:21:04 | 2008-11-22T01:21:04 | 32,640,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,546 | cpp | /*Puppet Program by Waseem Ilahi*/
#include <Windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
void DrawTail(void);
void DrawLegs(void);
void DrawNeck(void);
void DrawFace(void);
void DrawEyes(void);
float dist = -17.0; /* distance from camera to object */
float yaw = 0.0; /* rotate about Y axis */
float pitch = 0.0; /* rotate about X axis */
/* shading values */
float ambiantmat[]={0.19225};
float diffusemat[]={0.50754};
float specularmat[]={0.508273};
float shininessmat=59.2;
float ambiantmattail[]={0.0};
float diffusemattail[]={0.01};
float specularmattail[]={0.5};
float tailshininessmat=32;
float ambiantmatlegs[]={0.0};
float diffusematlegs[]={0.01};
float specularmatlegs[]={0.5};
float legsshininessmat=32;
float ambiantmateyes[]={0.0};
float diffusemateyes[]={0.01};
float specularmateyes[]={0.5};
float eyesshininessmat=32;
float Iguana_position[3] = {0.0, 0.0, 0.0};
int rgb = GL_TRUE;
int doubleBuffer = GL_TRUE;
int windType;
GLdouble translate_increment;
GLint windW, windH;
GLUquadricObj *myQuadricObj;
static void set_material(GLfloat *ambient, GLfloat *diffuse, GLfloat *specular, GLfloat shininess)
{
glMaterialfv (GL_FRONT, GL_AMBIENT, ambient);
glMaterialfv (GL_FRONT, GL_DIFFUSE, diffuse);
glMaterialfv (GL_FRONT, GL_SPECULAR, specular);
glMaterialf (GL_FRONT, GL_SHININESS, shininess);
}
//The init function.
static void Init(void)
{
float ambiantlight[]={1};
float diffuselight[]={1};
float specularlight[]={1};
float positionlight[4]={50.0,0.0,0.0,1.0};
/* Set background color */
glClearColor(0.2, 0.8, 1.0, 0.0); /* blue sky */
/* Enable depth buffer */
glEnable(GL_DEPTH_TEST);
/* Set polygon attributes */
glPolygonMode (GL_FRONT, GL_FILL);
//glEnable (GL_CULL_FACE);
//glCullFace (GL_BACK);
/* Set shading & lighting values*/
glShadeModel (GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_POSITION,positionlight );
glLightfv(GL_LIGHT0, GL_AMBIENT, ambiantlight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuselight);
glLightfv(GL_LIGHT0, GL_SPECULAR, specularlight);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
/* Create quadric object for all of the puppet's parts */
myQuadricObj = gluNewQuadric();
gluQuadricDrawStyle(myQuadricObj, (GLenum)GLU_FILL);
gluQuadricNormals(myQuadricObj, (GLenum)GLU_SMOOTH);
}
/* Window size has changed:
adjust viewport and perspective transformations */
static void Reshape(int width, int height)
{
float aspect;
windW = (GLint)width;
windH = (GLint)height;
aspect = (float)windW / (float)windH;
translate_increment=0.1;
/* Viewport fills the entire window */
glViewport(0, 0, width, height);
/* Use perspective projection */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective (60.0, aspect, 1.0, 1000.0); /* fovy, aspect, near, far */
/* Return to modelview mode */
glMatrixMode(GL_MODELVIEW);
}
/* Set modeling and viewing transformations,
then draw the letter polygons */
#define BUFSIZE 64
#define BODY_RADIUS 2.0
#define NECK_RADIUS 0.8
#define FACE_RADIUS 0.8
#define TOP_RADIUS 1.0
#define LEG_WIDTH 0.25
#define LEG_LENGTH 6.0 /* actually, a scale */
#define LEG_SHIFT 2.25 /* MIDDLE_RADIUS + 1/2 of LEG_LENGTH */
#define TAIL_WIDTH 0.25
#define TAIL_LENGTH 6.0 /* actually, a scale */
#define TAIL_SHIFT 2.25
static void DrawIguana(void)
{
/* Transformation for entire Iguana */
glLoadIdentity();
glTranslatef(0.0, 0.0, dist); /* step back */
glRotatef(pitch, 1.0, 0.0, 0.0); /* spin on X axis */
glRotatef(yaw, 0.0, 1.0, 0.0); /* spin on Y axis */
/* Draw the body of the Iguana (The root of the hierarchy) */
glScalef(2.5,1.0,1.0);
set_material( ambiantmat, diffusemat, specularmat, shininessmat);
glTranslatef(Iguana_position[0], Iguana_position[1], Iguana_position[2]);
gluSphere (myQuadricObj, BODY_RADIUS, 50, 50);
//Draw Tail.
DrawTail();
/* Draw the 4 legs */
DrawLegs();
//Draw the neck and face on it
DrawNeck();
}
void DrawNeck()
{
glPushMatrix(); // save Tx for body of Iguana
set_material( ambiantmat, diffusemat, specularmat, shininessmat);
glRotatef(-25,0.0,0.0,1.0);
glTranslatef(-BODY_RADIUS,0.0,0.0);
gluSphere (myQuadricObj, NECK_RADIUS, 50, 50);
//Draw the face
DrawFace();
glPopMatrix(); // restore Tx for body of Iguana
}
void DrawFace()
{
glPushMatrix(); // save Tx for neck of Iguana
glRotatef(-10,0.0,0.0,1.0);
glScalef(0.5,1.0,1.0);
glTranslatef(-NECK_RADIUS-.5,0.0,0.0);
gluSphere (myQuadricObj, FACE_RADIUS, 50, 50);
//Draw the Eyes
DrawEyes();
glPopMatrix(); // restore Tx for neck of Iguana
}
void DrawEyes()
{
//Left
glPushMatrix(); // save Tx for face of Iguana
set_material(ambiantmateyes,diffusemateyes,specularmateyes,eyesshininessmat);
glScalef(0.8,1.0,1.0);
glTranslatef(-FACE_RADIUS+0.3,0.32,0.5);
glutSolidSphere (TOP_RADIUS/6.0, 10, 6); // left eye
glPopMatrix(); // restore Tx for face of Iguana
//Right
glPushMatrix(); // save Tx for face of Iguana
set_material(ambiantmateyes,diffusemateyes,specularmateyes,eyesshininessmat);
glScalef(0.8,1.0,1.0);
glTranslatef(-FACE_RADIUS+0.3,0.32,-0.5);
glutSolidSphere (TOP_RADIUS/6.0, 10, 6); // right eye
glPopMatrix(); // restore Tx for face of Iguana
}
void DrawTail()
{
glPushMatrix(); // save Tx for body of Iguana
set_material(ambiantmattail,diffusemattail,specularmattail,tailshininessmat);
glRotatef(-5,0.0,0.0,1.0);
glTranslatef(BODY_RADIUS-0.6,-0.6,2.0);
glRotatef(90,0.0,1.0,0.0);
glRotatef(90,0.0,0.0,1.0);
glTranslatef(0.0, -BODY_RADIUS, 0.0);
glScalef(TAIL_LENGTH/2, 1.0, 1.0);
glTranslatef(TAIL_WIDTH/2.0,0.0 , 0.0); /* shift inner edge to origin */
gluCylinder(myQuadricObj,0.2,0.0,2.5,40,40);
glPopMatrix(); // restore Tx for body of Iguana
}
void DrawLegs()
{
//Front left
glPushMatrix(); // save Tx for body of Iguana
set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat);
glTranslatef(-0.8,-0.7,1.2);
glRotatef(90,1.0,0.0,0.0);
gluCylinder(myQuadricObj,0.1,0.025,2,40,40);
glPopMatrix(); // restore Tx for body of Iguana
//Front right
glPushMatrix(); // save Tx for body of Iguana
set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat);
glTranslatef(-0.8,-0.7,-1.2);
glRotatef(90,1.0,0.0,0.0);
gluCylinder(myQuadricObj,0.1,0.025,2,40,40);
glPopMatrix(); // restore Tx for body of Iguana
//Hind left
glPushMatrix(); // save Tx for body of Iguana
set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat);
glTranslatef(0.8,-0.7,1.2);
glRotatef(90,1.0,0.0,0.0);
gluCylinder(myQuadricObj,0.1,0.025,2,40,40);
glPopMatrix(); // restore Tx for body of Iguana
//Hind right
glPushMatrix(); // save Tx for body of Iguana
set_material(ambiantmatlegs,diffusematlegs,specularmatlegs,legsshininessmat);
glTranslatef(0.8,-0.7,-1.2);
glRotatef(90,1.0,0.0,0.0);
gluCylinder(myQuadricObj,0.1,0.025,2,40,40);
glPopMatrix(); // restore Tx for body of Iguana
}
static void Draw(void)
{
/* clear the screen */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* draw the Iguana */
DrawIguana();
/* update the screen */
glFlush(); /* force all changes to be applied to buffer */
glutSwapBuffers(); /* display what you just drew */
}
/* Arrow keys change angle of rotation */
static void Key2(int key, int x, int y)
{
switch (key) {
case GLUT_KEY_LEFT: /* decrease angle about Y axis */
yaw -= 5.0;
break;
case GLUT_KEY_RIGHT: /* increase angle about Y axis */
yaw += 5.0;
break;
case GLUT_KEY_UP: /* decrease angle about Z axis */
pitch -= 5.0;
break;
case GLUT_KEY_DOWN: /* increase angle about X axis */
pitch += 5.0;
break;
default:
return;
}
glutPostRedisplay(); /* force update of the display */
}
/* Handle other keys */
static void Key(unsigned char key, int x, int y)
{
switch (key) {
case 27: /* ESC to quit */
exit(1);
case '+':
dist += 1.0; /* move camera closer */
break;
case '-':
dist -= 1.0; /* move camera back */
break;
default:
return;
}
glutPostRedisplay(); /* force update of the display */
}
int main()
{
/* Setup the window that logo will appear in */
windW = 1220;
windH = 900;
glutInitWindowPosition(10, 10);
glutInitWindowSize( windW, windH);
windType = GLUT_DEPTH;
windType |= (rgb) ? GLUT_RGB : GLUT_INDEX;
windType |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE;
glutInitDisplayMode(( GLenum)windType);
if (glutCreateWindow("Iguana") == GL_FALSE) {
exit(1);
}
Init();
glutKeyboardFunc(Key);
glutSpecialFunc(Key2);
glutReshapeFunc(Reshape);
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}
| [
"waseemilahi@b30cb682-9650-11dd-b20a-03c46e462ecf"
]
| [
[
[
1,
387
]
]
]
|
46bfa8b705429566647e40e6db316a4a293393a0 | 11af1673bab82ca2329ef8b596d1f3d2f8b82481 | /source/cgame/cg_draw.cpp | 378e9dfcab9213f8589c11dac1eba425ce1687ab | []
| no_license | legacyrp/legacyojp | 8b33ecf24fd973bee5e7adbd369748cfdd891202 | d918151e917ea06e8698f423bbe2cf6ab9d7f180 | refs/heads/master | 2021-01-10T20:09:55.748893 | 2011-04-18T21:07:13 | 2011-04-18T21:07:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215,497 | cpp | // Copyright (C) 1999-2000 Id Software, Inc.
//
// cg_draw.c -- draw all of the graphical elements during
// active (after loading) gameplay
#include "cg_local.h"
#include "bg_saga.h"
#include "../ui/ui_shared.h"
#include "../ui/ui_public.h"
//[AddText]
char atText[64][64] = {""};
int atYPos[64] = {0};
int atTime[64] = {0};
int atCount = 0;
//[/AddText]
extern float CG_RadiusForCent( centity_t *cent );
qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y);
qboolean CG_CalcMuzzlePoint( int entityNum, vec3_t muzzle );
static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam);
static void CG_DrawSiegeDeathTimer( int timeRemaining );
// nmckenzie: DUEL_HEALTH
void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist );
// used for scoreboard
extern displayContextDef_t cgDC;
menuDef_t *menuScoreboard = NULL;
vec4_t bluehudtint = {0.5, 0.5, 1.0, 1.0};
vec4_t redhudtint = {1.0, 0.5, 0.5, 1.0};
float *hudTintColor;
int sortedTeamPlayers[TEAM_MAXOVERLAY];
int numSortedTeamPlayers;
int lastvalidlockdif;
extern float zoomFov; //this has to be global client-side
char systemChat[256];
char teamChat1[256];
char teamChat2[256];
// The time at which you died and the time it will take for you to rejoin game.
int cg_siegeDeathTime = 0;
//[NewHud]
#define MAX_OJPHUD_TICS 8
//#define MAX_HUD_TICS 4
const char *armorTicName[MAX_OJPHUD_TICS] =
//const char *armorTicName[MAX_HUD_TICS] =
//[/NewHud]
{
"armor_tic1",
"armor_tic2",
"armor_tic3",
"armor_tic4",
//[NewHud]
"armor_tic5",
"armor_tic6",
"armor_tic7",
"armor_tic8",
//[/NewHud]
};
//[NewHud]
const char *forceTicName[MAX_OJPHUD_TICS] =
//const char *forceTicName[MAX_HUD_TICS] =
//[/NewHud]
{
"force_tic1",
"force_tic2",
"force_tic3",
"force_tic4",
//[NewHud]
"force_tic5",
"force_tic6",
"force_tic7",
"force_tic8",
//[/NewHud]
};
//[DodgeSys]
const char *dodgeTicName[MAX_OJPHUD_TICS] =
{
"dodge_tic1",
"dodge_tic2",
"dodge_tic3",
"dodge_tic4",
"dodge_tic5",
"dodge_tic6",
"dodge_tic7",
"dodge_tic8",
};
//[/DodgeSys]
//[NewHud]
const char *ammoTicName[MAX_OJPHUD_TICS] =
//const char *ammoTicName[MAX_HUD_TICS] =
{
"ammo_tic1",
"ammo_tic2",
"ammo_tic3",
"ammo_tic4",
//[NewHud]
"ammo_tic5",
"ammo_tic6",
"ammo_tic7",
"ammo_tic8",
};
const char *mishapTicName[] =
{
"mishap_tic1",
"mishap_tic2",
"mishap_tic3",
"mishap_tic4",
"mishap_tic5",
"mishap_tic6",
"mishap_tic7",
"mishap_tic8",
"mishap_tic9",
"mishap_tic10",
"mishap_tic11",
"mishap_tic12",
"mishap_tic13",
"mishap_tic14",
"mishap_tic15",
//[/NewHud]
};
char *showPowersName[] =
{
"HEAL2",//FP_HEAL
"JUMP2",//FP_LEVITATION
"SPEED2",//FP_SPEED
"PUSH2",//FP_PUSH
"PULL2",//FP_PULL
"MINDTRICK2",//FP_TELEPTAHY
"GRIP2",//FP_GRIP
"LIGHTNING2",//FP_LIGHTNING
"DARK_RAGE2",//FP_RAGE
"PROTECT2",//FP_MANIPULATE
"ABSORB2",//FP_ABSORB
"TEAM_HEAL2",//FP_TEAM_HEAL
"TEAM_REPLENISH2",//FP_LIFT
"DRAIN2",//FP_DRAIN
"SEEING2",//FP_SEE
"SABER_OFFENSE2",//FP_SABER_OFFENSE
"SABER_DEFENSE2",//FP_SABER_DEFENSE
"SABER_THROW2",//FP_SABERTHROW
NULL
};
//Called from UI shared code. For now we'll just redirect to the normal anim load function.
int UI_ParseAnimationFile(const char *filename, animation_t *animset, qboolean isHumanoid)
{
return BG_ParseAnimationFile(filename, animset, isHumanoid);
}
int MenuFontToHandle(int iMenuFont)
{
switch (iMenuFont)
{
case FONT_SMALL: return cgDC.Assets.qhSmallFont;
case FONT_SMALL2: return cgDC.Assets.qhSmall2Font;
case FONT_MEDIUM: return cgDC.Assets.qhMediumFont;
case FONT_LARGE: return cgDC.Assets.qhMediumFont;//cgDC.Assets.qhBigFont;
//fixme? Big fonr isn't registered...?
}
return cgDC.Assets.qhMediumFont;
}
int CG_Text_Width(const char *text, float scale, int iMenuFont)
{
int iFontIndex = MenuFontToHandle(iMenuFont);
return trap_R_Font_StrLenPixels(text, iFontIndex, scale);
}
int CG_Text_Height(const char *text, float scale, int iMenuFont)
{
int iFontIndex = MenuFontToHandle(iMenuFont);
return trap_R_Font_HeightPixels(iFontIndex, scale);
}
#include "../qcommon/qfiles.h" // for STYLE_BLINK etc
void CG_Text_Paint(float x, float y, float scale, vec4_t color, const char *text, float adjust, int limit, int style, int iMenuFont)
{
int iStyleOR = 0;
int iFontIndex = MenuFontToHandle(iMenuFont);
switch (style)
{
case ITEM_TEXTSTYLE_NORMAL: iStyleOR = 0;break; // JK2 normal text
case ITEM_TEXTSTYLE_BLINK: iStyleOR = STYLE_BLINK;break; // JK2 fast blinking
case ITEM_TEXTSTYLE_PULSE: iStyleOR = STYLE_BLINK;break; // JK2 slow pulsing
case ITEM_TEXTSTYLE_SHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this )
case ITEM_TEXTSTYLE_OUTLINED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this )
case ITEM_TEXTSTYLE_OUTLINESHADOWED: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this )
case ITEM_TEXTSTYLE_SHADOWEDMORE: iStyleOR = (int)STYLE_DROPSHADOW;break; // JK2 drop shadow ( need a color for this )
}
trap_R_Font_DrawString( x, // int ox
y, // int oy
text, // const char *text
color, // paletteRGBA_c c
iStyleOR | iFontIndex, // const int iFontHandle
!limit?-1:limit, // iCharLimit (-1 = none)
scale // const float scale = 1.0f
);
}
/*
================
CG_DrawZoomMask
================
*/
static void CG_DrawZoomMask( void )
{
vec4_t color1;
float level;
static qboolean flip = qtrue;
// int ammo = cg_entities[0].gent->client->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex];
float cx, cy;
// int val[5];
float max, fi;
// Check for Binocular specific zooming since we'll want to render different bits in each case
if ( cg.predictedPlayerState.zoomMode == 2 )
{
int val, i;
float off;
// zoom level
level = (float)(80.0f - cg.predictedPlayerState.zoomFov) / 80.0f;
// ...so we'll clamp it
if ( level < 0.0f )
{
level = 0.0f;
}
else if ( level > 1.0f )
{
level = 1.0f;
}
// Using a magic number to convert the zoom level to scale amount
level *= 162.0f;
// draw blue tinted distortion mask, trying to make it as small as is necessary to fill in the viewable area
trap_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 34, 48, 570, 362, cgs.media.binocularStatic );
// Black out the area behind the numbers
trap_R_SetColor( colorTable[CT_BLACK]);
CG_DrawPic( 212, 367, 200, 40, cgs.media.whiteShader );
// Numbers should be kind of greenish
color1[0] = 0.2f;
color1[1] = 0.4f;
color1[2] = 0.2f;
color1[3] = 0.3f;
trap_R_SetColor( color1 );
// Draw scrolling numbers, use intervals 10 units apart--sorry, this section of code is just kind of hacked
// up with a bunch of magic numbers.....
val = ((int)((cg.refdef.viewangles[YAW] + 180) / 10)) * 10;
off = (cg.refdef.viewangles[YAW] + 180) - val;
for ( i = -10; i < 30; i += 10 )
{
val -= 10;
if ( val < 0 )
{
val += 360;
}
// we only want to draw the very far left one some of the time, if it's too far to the left it will
// poke outside the mask.
if (( off > 3.0f && i == -10 ) || i > -10 )
{
// draw the value, but add 200 just to bump the range up...arbitrary, so change it if you like
CG_DrawNumField( 155 + i * 10 + off * 10, 374, 3, val + 200, 24, 14, NUM_FONT_CHUNKY, qtrue );
CG_DrawPic( 245 + (i-1) * 10 + off * 10, 376, 6, 6, cgs.media.whiteShader );
}
}
CG_DrawPic( 212, 367, 200, 28, cgs.media.binocularOverlay );
color1[0] = sin( cg.time * 0.01f ) * 0.5f + 0.5f;
color1[0] = color1[0] * color1[0];
color1[1] = color1[0];
color1[2] = color1[0];
color1[3] = 1.0f;
trap_R_SetColor( color1 );
CG_DrawPic( 82, 94, 16, 16, cgs.media.binocularCircle );
// Flickery color
color1[0] = 0.7f + crandom() * 0.1f;
color1[1] = 0.8f + crandom() * 0.1f;
color1[2] = 0.7f + crandom() * 0.1f;
color1[3] = 1.0f;
trap_R_SetColor( color1 );
CG_DrawPic( 0, 0, SCREEN_HEIGHT, SCREEN_WIDTH, cgs.media.binocularMask );
CG_DrawPic( 4, 282 - level, 16, 16, cgs.media.binocularArrow );
// The top triangle bit randomly flips
if ( flip )
{
CG_DrawPic( 330, 60, -26, -30, cgs.media.binocularTri );
}
else
{
CG_DrawPic( 307, 40, 26, 30, cgs.media.binocularTri );
}
if ( random() > 0.98f && ( cg.time & 1024 ))
{
flip = (qboolean)(!flip);
}
}
else if ( cg.predictedPlayerState.zoomMode == 1 && cg.predictedPlayerState.weapon != WP_BOWCASTER)
{
// disruptor zoom mode
level = (float)(50.0f - zoomFov) / 50.0f;//(float)(80.0f - zoomFov) / 80.0f;
// ...so we'll clamp it
if ( level < 0.0f )
{
level = 0.0f;
}
else if ( level > 1.0f )
{
level = 1.0f;
}
// Using a magic number to convert the zoom level to a rotation amount that correlates more or less with the zoom artwork.
level *= 103.0f;
// Draw target mask
trap_R_SetColor( colorTable[CT_WHITE] );
CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, cgs.media.disruptorMask );
// apparently 99.0f is the full zoom level
if ( level >= 96)
{
// Fully zoomed, so make the rotating insert pulse
color1[0] = 1.0f;
color1[1] = 1.0f;
color1[2] = 1.0f;
color1[3] = 0.7f + sin( cg.time * 0.01f ) * 0.3f;
trap_R_SetColor( color1 );
}
// Draw rotating insert
CG_DrawRotatePic2( 320, 240, SCREEN_WIDTH, SCREEN_HEIGHT, -level, cgs.media.disruptorInsert );
if ( (cg.snap->ps.eFlags & EF_DOUBLE_AMMO) )
{
max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / ((float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max*2.0f);
}
else
{
max = cg.snap->ps.ammo[weaponData[WP_DISRUPTOR].ammoIndex] / (float)ammoData[weaponData[WP_DISRUPTOR].ammoIndex].max;
}
if ( max > 1.0f )
{
max = 1.0f;
}
color1[0] = (1.0f - max) * 2.0f;
color1[1] = max * 1.5f;
color1[2] = 0.0f;
color1[3] = 1.0f;
// If we are low on health, make us flash
if ( max < 0.15f && ( cg.time & 512 ))
{
VectorClear( color1 );
}
if ( color1[0] > 1.0f )
{
color1[0] = 1.0f;
}
if ( color1[1] > 1.0f )
{
color1[1] = 1.0f;
}
trap_R_SetColor( color1 );
max *= 58.0f;
for (fi = 18.5f; fi <= 18.5f + max; fi+= 3 ) // going from 15 to 45 degrees, with 5 degree increments
{
cx = 320 + sin( (fi+90.0f)/57.296f ) * 190;
cy = 240 + cos( (fi+90.0f)/57.296f ) * 190;
CG_DrawRotatePic2( cx, cy, 12, 24, 90 - fi, cgs.media.disruptorInsertTick );
}
if ( cg.predictedPlayerState.weaponstate == WEAPON_CHARGING_ALT )
{
trap_R_SetColor( colorTable[CT_WHITE] );
// draw the charge level
max = ( cg.time - cg.predictedPlayerState.weaponChargeTime ) / ( 50.0f * 30.0f ); // bad hardcodedness 50 is disruptor charge unit and 30 is max charge units allowed.
if ( max > 1.0f )
{
max = 1.0f;
}
trap_R_DrawStretchPic(257, 435, 134*max, 34, 0, 0, max, 1, cgs.media.disruptorChargeShader);
}
// trap_R_SetColor( colorTable[CT_WHITE] );
// CG_DrawPic( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, cgs.media.disruptorMask );
}
}
/*
================
CG_Draw3DModel
================
*/
void CG_Draw3DModel( float x, float y, float w, float h, qhandle_t model, void *ghoul2, int g2radius, qhandle_t skin, vec3_t origin, vec3_t angles ) {
refdef_t refdef;
refEntity_t ent;
if ( !cg_draw3dIcons.integer || !cg_drawIcons.integer ) {
return;
}
memset( &refdef, 0, sizeof( refdef ) );
memset( &ent, 0, sizeof( ent ) );
AnglesToAxis( angles, ent.axis );
VectorCopy( origin, ent.origin );
ent.hModel = model;
ent.ghoul2 = ghoul2;
ent.radius = g2radius;
ent.customSkin = skin;
ent.renderfx = RF_NOSHADOW; // no stencil shadows
refdef.rdflags = RDF_NOWORLDMODEL;
AxisClear( refdef.viewaxis );
refdef.fov_x = 30;
refdef.fov_y = 30;
refdef.x = x;
refdef.y = y;
refdef.width = w;
refdef.height = h;
refdef.time = cg.time;
trap_R_ClearScene();
trap_R_AddRefEntityToScene( &ent );
trap_R_RenderScene( &refdef );
}
/*
================
CG_DrawHead
Used for both the status bar and the scoreboard
================
*/
void CG_DrawHead( float x, float y, float w, float h, int clientNum, vec3_t headAngles )
{
clientInfo_t *ci;
if (clientNum >= MAX_CLIENTS)
{ //npc?
return;
}
ci = &cgs.clientinfo[ clientNum ];
CG_DrawPic( x, y, w, h, ci->modelIcon );
// if they are deferred, draw a cross out
if ( ci->deferred )
{
CG_DrawPic( x, y, w, h, cgs.media.deferShader );
}
}
/*
================
CG_DrawFlagModel
Used for both the status bar and the scoreboard
================
*/
void CG_DrawFlagModel( float x, float y, float w, float h, int team, qboolean force2D ) {
qhandle_t cm;
float len;
vec3_t origin, angles;
vec3_t mins, maxs;
qhandle_t handle;
if ( !force2D && cg_draw3dIcons.integer ) {
VectorClear( angles );
cm = cgs.media.redFlagModel;
// offset the origin y and z to center the flag
trap_R_ModelBounds( cm, mins, maxs );
origin[2] = -0.5 * ( mins[2] + maxs[2] );
origin[1] = 0.5 * ( mins[1] + maxs[1] );
// calculate distance so the flag nearly fills the box
// assume heads are taller than wide
len = 0.5 * ( maxs[2] - mins[2] );
origin[0] = len / 0.268; // len / tan( fov/2 )
angles[YAW] = 60 * sin( cg.time / 2000.0 );;
if( team == TEAM_RED ) {
handle = cgs.media.redFlagModel;
} else if( team == TEAM_BLUE ) {
handle = cgs.media.blueFlagModel;
} else if( team == TEAM_FREE ) {
handle = 0;//cgs.media.neutralFlagModel;
} else {
return;
}
CG_Draw3DModel( x, y, w, h, handle, NULL, 0, 0, origin, angles );
} else if ( cg_drawIcons.integer ) {
gitem_t *item;
if( team == TEAM_RED ) {
item = BG_FindItemForPowerup( PW_REDFLAG );
} else if( team == TEAM_BLUE ) {
item = BG_FindItemForPowerup( PW_BLUEFLAG );
} else if( team == TEAM_FREE ) {
item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
} else {
return;
}
if (item) {
CG_DrawPic( x, y, w, h, cg_items[ ITEM_INDEX(item) ].icon );
}
}
}
/*
================
DrawAmmo
================
*/
void DrawAmmo()
{
int x, y;
x = SCREEN_WIDTH-80;
y = SCREEN_HEIGHT-80;
}
/*
================
CG_DrawHealth
================
*/
void CG_DrawHealth( menuDef_t *menuHUD )
{
vec4_t calcColor;
playerState_t *ps;
int healthAmt;
//[NewHud]
//int i,currValue,inc;
//[/NewHud]
itemDef_t *focusItem;
//[NewHud]
//float percent;
//[/NewHud]
// Can we find the menu?
if (!menuHUD)
{
return;
}
ps = &cg.snap->ps;
// What's the health?
healthAmt = ps->stats[STAT_HEALTH];
if (healthAmt > ps->stats[STAT_MAX_HEALTH])
{
healthAmt = ps->stats[STAT_MAX_HEALTH];
}
//[NewHud]
focusItem = Menu_FindItemByName(menuHUD, "health_tic1");
if (focusItem) // This is bad
{
if (healthAmt <= 0) // don't show tic
{
}
else
{
calcColor[0] = calcColor[1] = calcColor[2] = calcColor[3] = 1;
if (healthAmt < ps->stats[STAT_MAX_HEALTH])
{
calcColor[1] = calcColor[2] = (float) healthAmt / (float) ps->stats[STAT_MAX_HEALTH];
}
trap_R_SetColor( calcColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
}
//[/NewHud]
// Print the mueric amount
focusItem = Menu_FindItemByName(menuHUD, "healthamount");
if (focusItem)
{
// Print health amount
trap_R_SetColor( focusItem->window.foreColor );
CG_DrawNumField (
focusItem->window.rect.x,
focusItem->window.rect.y,
3,
ps->stats[STAT_HEALTH],
focusItem->window.rect.w,
focusItem->window.rect.h,
NUM_FONT_SMALL,
qfalse);
}
}
/*
================
CG_DrawArmor
================
*/
void CG_DrawArmor( menuDef_t *menuHUD )
{
vec4_t calcColor;
playerState_t *ps;
int armor, maxArmor;
itemDef_t *focusItem;
float percent,quarterArmor;
int i,currValue,inc;
//ps = &cg.snap->ps;
ps = &cg.predictedPlayerState;
// Can we find the menu?
if (!menuHUD)
{
return;
}
//[NewHud]
//draw shield tic frame
focusItem = Menu_FindItemByName(menuHUD, "armorshell");
if (focusItem)
{
trap_R_SetColor(hudTintColor);
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
//[/NewHud]
armor = ps->stats[STAT_ARMOR];
maxArmor = ps->stats[STAT_MAX_HEALTH];
if (armor> maxArmor)
{
armor = maxArmor;
}
currValue = armor;
//[NewHud]
inc = (float) maxArmor / MAX_OJPHUD_TICS;
//inc = (float) maxArmor / MAX_HUD_TICS;
//[/NewHud]
memcpy(calcColor, hudTintColor, sizeof(vec4_t));
//[NewHud]
for (i=(MAX_OJPHUD_TICS-1);i>=0;i--)
//for (i=(MAX_HUD_TICS-1);i>=0;i--)
//[/NewHud]
{
focusItem = Menu_FindItemByName(menuHUD, armorTicName[i]);
if (!focusItem) // This is bad
{
continue;
}
memcpy(calcColor, hudTintColor, sizeof(vec4_t));
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
percent = (float) currValue / inc;
calcColor[3] *= percent;
}
trap_R_SetColor( calcColor);
//[NewHud]
if ((i==(MAX_OJPHUD_TICS-1)) && (currValue < inc))
//if ((i==(MAX_HUD_TICS-1)) && (currValue < inc))
//[/NewHud]
{
if (cg.HUDArmorFlag)
{
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
}
else
{
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
currValue -= inc;
}
focusItem = Menu_FindItemByName(menuHUD, "armoramount");
if (focusItem)
{
// Print armor amount
trap_R_SetColor( focusItem->window.foreColor );
CG_DrawNumField (
focusItem->window.rect.x,
focusItem->window.rect.y,
3,
armor,
focusItem->window.rect.w,
focusItem->window.rect.h,
NUM_FONT_SMALL,
qfalse);
}
// If armor is low, flash a graphic to warn the player
if (armor) // Is there armor? Draw the HUD Armor TIC
{
quarterArmor = (float) (ps->stats[STAT_MAX_HEALTH] / 4.0f);
// Make tic flash if armor is at 25% of full armor
if (ps->stats[STAT_ARMOR] < quarterArmor) // Do whatever the flash timer says
{
if (cg.HUDTickFlashTime < cg.time) // Flip at the same time
{
cg.HUDTickFlashTime = cg.time + 400;
if (cg.HUDArmorFlag)
{
cg.HUDArmorFlag = qfalse;
}
else
{
cg.HUDArmorFlag = qtrue;
}
}
}
else
{
cg.HUDArmorFlag=qtrue;
}
}
else // No armor? Don't show it.
{
cg.HUDArmorFlag=qfalse;
}
}
/*
================
CG_DrawSaberStyle
If the weapon is a light saber (which needs no ammo) then draw a graphic showing
the saber style (fast, medium, strong)
================
*/
static void CG_DrawSaberStyle( centity_t *cent, menuDef_t *menuHUD)
{
itemDef_t *focusItem;
if (!cent->currentState.weapon ) // We don't have a weapon right now
{
return;
}
if ( cent->currentState.weapon != WP_SABER )
{
return;
}
// Can we find the menu?
if (!menuHUD)
{
return;
}
// draw the current saber style in this window
switch ( cg.predictedPlayerState.fd.saberDrawAnimLevel )
{
case 1://FORCE_LEVEL_1:
//[SaberSys]
//Created new icon for desann's saber style.
//case 5://FORCE_LEVEL_5://Tavion
//[/SaberSys]
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_fast");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
case 2://FORCE_LEVEL_2:
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_medium");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
case 6://SS_DUAL
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_dual");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
case 7://SS_STAFF
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_staff");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
case 3://FORCE_LEVEL_3:
//[SaberSys]
//Created new icon for desann's saber style.
//case 4://FORCE_LEVEL_4://Desann
//[/SaberSys]
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_slow");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
//[SaberSys]
//Created new icon for desann's saber style.
case 4://FORCE_LEVEL_4://Desann
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_desann");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
//Created new icon for desann's saber style.
case 5://FORCE_LEVEL_5://Tavion
focusItem = Menu_FindItemByName(menuHUD, "saberstyle_tavion");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
break;
//[/SaberSys]
}
}
//[SaberSys]
static void CG_DrawBalance( centity_t *cent, menuDef_t *menuHUD)
{//render the balance/mishap meter.
itemDef_t *focusItem;
int i;
// Can we find the menu?
if (!menuHUD)
{
return;
}
for (i = cg.snap->ps.saberAttackChainCount-1; i >= 0; i--)
{
focusItem = Menu_FindItemByName(menuHUD, mishapTicName[i]);
if (focusItem)
{
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
}
}
//[/SaberSys]
/*
================
CG_DrawAmmo
================
*/
static void CG_DrawAmmo( centity_t *cent,menuDef_t *menuHUD)
{
playerState_t *ps;
int i;
vec4_t calcColor;
float value,inc = 0.0f,percent;
itemDef_t *focusItem;
ps = &cg.snap->ps;
// Can we find the menu?
if (!menuHUD)
{
return;
}
if (!cent->currentState.weapon ) // We don't have a weapon right now
{
return;
}
value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex];
if (value < 0) // No ammo
{
return;
}
focusItem = Menu_FindItemByName(menuHUD, "ammoamount");
trap_R_SetColor( hudTintColor );
if (weaponData[cent->currentState.weapon].energyPerShot == 0 &&
weaponData[cent->currentState.weapon].altEnergyPerShot == 0)
{ //just draw "infinite"
//[NewHud]
inc = 8 / MAX_OJPHUD_TICS;
//inc = 8 / MAX_HUD_TICS;
//[/NewHud]
value = 8;
focusItem = Menu_FindItemByName(menuHUD, "ammoinfinite");
trap_R_SetColor( hudTintColor );
if (focusItem)
{
UI_DrawProportionalString(focusItem->window.rect.x, focusItem->window.rect.y, "--", NUM_FONT_SMALL, focusItem->window.foreColor);
}
}
else
{
focusItem = Menu_FindItemByName(menuHUD, "ammoamount");
trap_R_SetColor( hudTintColor );
if (focusItem)
{
if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) )
{
//[NewHud]
inc = (float) (ammoData[weaponData[cent->currentState.weapon].ammoIndex].max*2.0f) / MAX_OJPHUD_TICS;
//inc = (float) (ammoData[weaponData[cent->currentState.weapon].ammoIndex].max*2.0f) / MAX_HUD_TICS;
//[NewHud]
}
else
{
//[NewHud]
inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_OJPHUD_TICS;
//inc = (float) ammoData[weaponData[cent->currentState.weapon].ammoIndex].max / MAX_HUD_TICS;
//[/NewHud]
}
value = ps->ammo[weaponData[cent->currentState.weapon].ammoIndex];
CG_DrawStringExt(
focusItem->window.rect.x,
focusItem->window.rect.y,
va("%i/%i",(int)value,cg.snap->ps.stats[STAT_AMMOPOOL]),
0,
qfalse,
qfalse,
focusItem->window.rect.w,
focusItem->window.rect.h,
8);
}
}
// Draw tics
//[NewHud]
for (i=MAX_OJPHUD_TICS-1;i>=0;i--)
//for (i=MAX_HUD_TICS-1;i>=0;i--)
//[/NewHud]
{
focusItem = Menu_FindItemByName(menuHUD, ammoTicName[i]);
if (!focusItem)
{
continue;
}
memcpy(calcColor, hudTintColor, sizeof(vec4_t));
if ( value <= 0 ) // done
{
break;
}
else if (value < inc) // partial tic
{
percent = value / inc;
calcColor[3] = percent;
}
trap_R_SetColor( calcColor);
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
value -= inc;
}
}
//[DodgeSys]
/*
================
CG_DrawForcePower
================
*/
//[NewHud]
#define DPBAR_H 65.0f
#define DPBAR_W 13.0f
#define DPBAR_X 538.0f
#define DPBAR_Y 367.0f
//[/NewHud]
void CG_DrawDodge( menuDef_t *menuHUD )
{
//[NewHud]
vec4_t aColor;
itemDef_t *focusItem;
float percent = ((float)cg.snap->ps.stats[STAT_DODGE]/DODGE_MAX)*DPBAR_H;
//color of the bar
aColor[0] = 0.0f;
aColor[1] = .613f;
aColor[2] = .097f;
aColor[3] = 0.8f;
// Make the hud flash by setting forceHUDTotalFlashTime above cg.time
if (cg.snap->ps.stats[STAT_MAX_DODGE] > DODGE_CRITICALLEVEL //our maximum level is lower than the standard critical level.
&& cg.snap->ps.stats[STAT_DODGE] < DODGE_CRITICALLEVEL)
{
//color of the bar
aColor[0] = 1.0f;
aColor[1] = 0.0f;
aColor[2] = 0.0f;
aColor[3] = 0.8f;
if (cg.dodgeHUDNextFlashTime < cg.time)
{
cg.dodgeHUDNextFlashTime = cg.time + 400;
trap_S_StartSound (NULL, 0, CHAN_LOCAL, cgs.media.noforceSound );
}
}
else // turn HUD back on if it had just finished flashing time.
{
cg.dodgeHUDNextFlashTime = 0;
}
if (percent > DPBAR_H)
{//clamp to MAX_DODGE
percent = DPBAR_H;
}
if (percent < 0.1f)
{
percent = 0.1f;
}
//now draw the part to show how much health there is in the color specified
CG_FillRect(DPBAR_X, DPBAR_Y+(DPBAR_H-percent), DPBAR_W, DPBAR_H-(DPBAR_H-percent), aColor);
//[/NewHud]
focusItem = Menu_FindItemByName(menuHUD, "dodgeamount");
if (focusItem)
{
// Print force amount
trap_R_SetColor( focusItem->window.foreColor );
CG_DrawNumField (
focusItem->window.rect.x,
focusItem->window.rect.y,
3,
cg.snap->ps.stats[STAT_DODGE],
focusItem->window.rect.w,
focusItem->window.rect.h,
NUM_FONT_SMALL,
qfalse);
}
}
//[/DodgeSys]
/*
================
CG_DrawForcePower
================
*/
//[NewHud]
#define FPBAR_H 65.0f
#define FPBAR_W 13.0f
#define FPBAR_X 565.0f
#define FPBAR_Y 367.0f
//[/NewHud]
void CG_DrawForcePower( menuDef_t *menuHUD )
{
//[NewHud]
vec4_t aColor;
itemDef_t *focusItem;
float percent = ((float)cg.snap->ps.fd.forcePower/115.0f)*FPBAR_H;
//color of the bar
aColor[0] = 0.503f;
aColor[1] = 0.375f;
aColor[2] = 0.996f;
aColor[3] = 0.8f;
if (cg.forceHUDTotalFlashTime > cg.time || (cg_entities[cg.snap->ps.clientNum].currentState.userInt3 & ( 1 << FLAG_FATIGUED)))
//if (cg.forceHUDTotalFlashTime > cg.time )
//[/FatigueSys]
{
//color of the bar
aColor[0] = 1.0f;
aColor[1] = 0.0f;
aColor[2] = 0.0f;
aColor[3] = 0.8f;
if (cg.forceHUDNextFlashTime < cg.time)
{
cg.forceHUDNextFlashTime = cg.time + 400;
trap_S_StartSound (NULL, 0, CHAN_LOCAL, cgs.media.noforceSound );
}
}
else // turn HUD back on if it had just finished flashing time.
{
cg.forceHUDNextFlashTime = 0;
}
if (percent > FPBAR_H)
{
return;
}
if (percent < 0.1f)
{
percent = 0.1f;
}
//now draw the part to show how much health there is in the color specified
CG_FillRect(FPBAR_X, FPBAR_Y+(FPBAR_H-percent), FPBAR_W, FPBAR_H-(FPBAR_H-percent), aColor);
//[/NewHud]
focusItem = Menu_FindItemByName(menuHUD, "forceamount");
if (focusItem)
{
// Print force amount
trap_R_SetColor( focusItem->window.foreColor );
CG_DrawNumField (
focusItem->window.rect.x,
focusItem->window.rect.y,
3,
cg.snap->ps.fd.forcePower,
focusItem->window.rect.w,
focusItem->window.rect.h,
NUM_FONT_SMALL,
qfalse);
}
}
//[AddText]
void CG_AddToAddText(char *text)
{
if(strlen(text) >= 64)
{
CG_Printf("AddText ERROR: Text length is bigger then 64 characters!\n");
return;
}
if(atCount >= 64)
{
CG_Printf("AddText ERROR: Already have 64 items on AddText box! (And can't add anymoar currently)\n");
return;
}
strcpy(atText[atCount], text);
if(atCount > 0)
{
for(int i = 0;i < atCount;i++)
{
atYPos[i] += 20;
}
}
atTime[atCount] = cg.time + 5000;
atCount++;
}
void CG_RemoveFromAddText()
{
//atText[0] = "";
//atPos[0] = 0;
for(int i = 1;i < atCount; i++)
{
strcpy(atText[i-1],atText[i]);
atYPos[i-1] = atYPos[i];
atTime[i-1] = atTime[i];
}
strcpy(atText[atCount-1], "");
atCount--;
}
void CG_UpdateAddText()
{
if(atCount > 0 && atTime[0] <= cg.time)
CG_RemoveFromAddText();
}
float CG_DrawAddText(float y)
{
int i = 0;
CG_UpdateAddText();
y += 10;
for(i = 0;i < 20; i++)
{
if(atText[i] != NULL && Q_stricmp(atText[i],""))
{
CG_Text_Paint(700 - CG_Text_Width(atText[i],1.0f,FONT_SMALL), y + atYPos[i], 1.0f, colorWhite, atText[i], 0, 0, 0, FONT_SMALL2);
}
}
return y;
}
//[/AddText]
/*
================
CG_DrawHUD
================
*/
void CG_DrawHUD(centity_t *cent)
{
menuDef_t *menuHUD = NULL;
itemDef_t *focusItem = NULL;
const char *scoreStr = NULL;
int scoreBias;
char scoreBiasStr[16];
if (cg_hudFiles.integer)
{
int x = 0;
int y = SCREEN_HEIGHT-80;
char ammoString[64];
int weapX = x;
UI_DrawProportionalString( x+16, y+40, va( "%i", cg.snap->ps.stats[STAT_HEALTH] ),
UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_RED] );
UI_DrawProportionalString( x+18+14, y+40+14, va( "%i", cg.snap->ps.stats[STAT_ARMOR] ),
UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_GREEN] );
if (cg.snap->ps.weapon == WP_SABER)
{
if (cg.snap->ps.fd.saberDrawAnimLevel == SS_DUAL)
{
Com_sprintf(ammoString, sizeof(ammoString), "AKIMBO");
weapX += 16;
}
else if (cg.snap->ps.fd.saberDrawAnimLevel == SS_STAFF)
{
Com_sprintf(ammoString, sizeof(ammoString), "STAFF");
weapX += 16;
}
else if (cg.snap->ps.fd.saberDrawAnimLevel == FORCE_LEVEL_3)
{
Com_sprintf(ammoString, sizeof(ammoString), "STRONG");
weapX += 16;
}
else if (cg.snap->ps.fd.saberDrawAnimLevel == FORCE_LEVEL_2)
{
Com_sprintf(ammoString, sizeof(ammoString), "MEDIUM");
weapX += 16;
}
else
{
Com_sprintf(ammoString, sizeof(ammoString), "FAST");
}
}
else
{
Com_sprintf(ammoString, sizeof(ammoString), "%i", cg.snap->ps.ammo[weaponData[cent->currentState.weapon].ammoIndex]);
}
UI_DrawProportionalString( SCREEN_WIDTH-(weapX+16+32), y+40, va( "%s", ammoString ),
UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_HUD_ORANGE] );
UI_DrawProportionalString( SCREEN_WIDTH-(x+18+14+32), y+40+14, va( "%i", cg.snap->ps.fd.forcePower),
UI_SMALLFONT|UI_DROPSHADOW, colorTable[CT_ICON_BLUE] );
return;
}
//[NewHud]
//the new hud looks ugly if set with team colors.
hudTintColor = colorTable[CT_WHITE];
//[/NewHud]
// Draw the left HUD
menuHUD = Menus_FindByName("lefthud");
if (menuHUD)
{
itemDef_t *focusItem;
// Print scanline
focusItem = Menu_FindItemByName(menuHUD, "scanline");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
// Print frame
focusItem = Menu_FindItemByName(menuHUD, "frame");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
if (cg.predictedPlayerState.pm_type != PM_SPECTATOR)
{
CG_DrawArmor(menuHUD);
CG_DrawHealth(menuHUD);
}
}
else
{
//CG_Error("CG_ChatBox_ArrayInsert: unable to locate HUD menu file ");
}
//scoreStr = va("Score: %i", cgs.clientinfo[cg.snap->ps.clientNum].score);
if ( cgs.gametype == GT_DUEL )
{//A duel that requires more than one kill to knock the current enemy back to the queue
//show current kills out of how many needed
scoreStr = va("%s: %i/%i", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE], cgs.fraglimit);
}
else if (0 && cgs.gametype < GT_TEAM )
{ // This is a teamless mode, draw the score bias.
scoreBias = cg.snap->ps.persistant[PERS_SCORE] - cgs.scores1;
if (scoreBias == 0)
{ // We are the leader!
if (cgs.scores2 <= 0)
{ // Nobody to be ahead of yet.
Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), "");
}
else
{
scoreBias = cg.snap->ps.persistant[PERS_SCORE] - cgs.scores2;
if (scoreBias == 0)
{
Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (Tie)");
}
else
{
Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (+%d)", scoreBias);
}
}
}
else // if (scoreBias < 0)
{ // We are behind!
Com_sprintf(scoreBiasStr, sizeof(scoreBiasStr), " (%d)", scoreBias);
}
scoreStr = va("%s: %i%s", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE], scoreBiasStr);
}
else
{ // Don't draw a bias.
scoreStr = va("%s: %i", CG_GetStringEdString("MP_INGAME", "SCORE"), cg.snap->ps.persistant[PERS_SCORE]);
}
menuHUD = Menus_FindByName("righthud");
if (menuHUD)
{
if (cgs.gametype != GT_POWERDUEL)
{
focusItem = Menu_FindItemByName(menuHUD, "score_line");
if (focusItem)
{
UI_DrawScaledProportionalString(
focusItem->window.rect.x,
focusItem->window.rect.y,
scoreStr,
UI_RIGHT|UI_DROPSHADOW,
focusItem->window.foreColor,
0.7);
}
}
// Print scanline
focusItem = Menu_FindItemByName(menuHUD, "scanline");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
focusItem = Menu_FindItemByName(menuHUD, "frame");
if (focusItem)
{
trap_R_SetColor( hudTintColor );
CG_DrawPic(
focusItem->window.rect.x,
focusItem->window.rect.y,
focusItem->window.rect.w,
focusItem->window.rect.h,
focusItem->window.background
);
}
CG_DrawForcePower(menuHUD);
//[DodgeSys]
CG_DrawDodge(menuHUD);
//[/DodgeSys]
//[SaberSys]
CG_DrawBalance(cent, menuHUD);
//[/SaberSys]
// Draw ammo tics or saber style
if ( cent->currentState.weapon == WP_SABER )
{
CG_DrawSaberStyle(cent,menuHUD);
}
else
{
CG_DrawAmmo(cent,menuHUD);
}
}
else
{
//CG_Error("CG_ChatBox_ArrayInsert: unable to locate HUD menu file ");
}
}
#define MAX_SHOWPOWERS NUM_FORCE_POWERS
qboolean ForcePower_Valid(int i)
{
//[SaberSys]
//Added Saber Throw to hud selection menu.
if (i == FP_LEVITATION ||
i == FP_SABER_OFFENSE ||
i == FP_SABER_DEFENSE)
// i == FP_SABER_DEFENSE ||
// i == FP_SABERTHROW)
//[/SaberSys]
{
return qfalse;
}
if (cg.snap->ps.fd.forcePowersKnown & (1 << i))
{
return qtrue;
}
return qfalse;
}
/*
===================
CG_DrawForceSelect
===================
*/
void CG_DrawForceSelect( void )
{
int i;
int count;
int smallIconSize,bigIconSize;
int holdX,x,y,x2,y2,pad,length;
int sideLeftIconCnt,sideRightIconCnt;
int sideMax,holdCount,iconCnt;
int yOffset = 0;
x2 = 0;
y2 = 0;
// don't display if dead
if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 )
{
return;
}
if ((cg.forceSelectTime+WEAPON_SELECT_TIME)<cg.time) // Time is up for the HUD to display
{
cg.forceSelect = cg.snap->ps.fd.forcePowerSelected;
return;
}
if (!cg.snap->ps.fd.forcePowersKnown)
{
return;
}
// count the number of powers owned
count = 0;
for (i=0;i < NUM_FORCE_POWERS;++i)
{
if (ForcePower_Valid(i))
{
count++;
}
}
if (count == 0) // If no force powers, don't display
{
return;
}
sideMax = 3; // Max number of icons on the side
// Calculate how many icons will appear to either side of the center one
holdCount = count - 1; // -1 for the center icon
if (holdCount == 0) // No icons to either side
{
sideLeftIconCnt = 0;
sideRightIconCnt = 0;
}
else if (count > (2*sideMax)) // Go to the max on each side
{
sideLeftIconCnt = sideMax;
sideRightIconCnt = sideMax;
}
else // Less than max, so do the calc
{
sideLeftIconCnt = holdCount/2;
sideRightIconCnt = holdCount - sideLeftIconCnt;
}
smallIconSize = 30;
bigIconSize = 60;
pad = 12;
x = 320;
y = 425;
// Background
length = (sideLeftIconCnt * smallIconSize) + (sideLeftIconCnt*pad) +
bigIconSize + (sideRightIconCnt * smallIconSize) + (sideRightIconCnt*pad) + 12;
i = BG_ProperForceIndex(cg.forceSelect) - 1;
if (i < 0)
{
i = MAX_SHOWPOWERS;
}
trap_R_SetColor(NULL);
// Work backwards from current icon
holdX = x - ((bigIconSize/2) + pad + smallIconSize);
for (iconCnt=1;iconCnt<(sideLeftIconCnt+1);i--)
{
if (i < 0)
{
i = MAX_SHOWPOWERS;
}
if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power?
{
continue;
}
++iconCnt; // Good icon
if (cgs.media.forcePowerIcons[forcePowerSorted[i]])
{
CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]] );
holdX -= (smallIconSize+pad);
}
}
if (ForcePower_Valid(cg.forceSelect))
{
// Current Center Icon
if (cgs.media.forcePowerIcons[cg.forceSelect])
{
CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2)) + yOffset, bigIconSize, bigIconSize, cgs.media.forcePowerIcons[cg.forceSelect] ); //only cache the icon for display
}
}
i = BG_ProperForceIndex(cg.forceSelect) + 1;
if (i>MAX_SHOWPOWERS)
{
i = 0;
}
// Work forwards from current icon
holdX = x + (bigIconSize/2) + pad;
for (iconCnt=1;iconCnt<(sideRightIconCnt+1);i++)
{
if (i>MAX_SHOWPOWERS)
{
i = 0;
}
if (!ForcePower_Valid(forcePowerSorted[i])) // Does he have this power?
{
continue;
}
++iconCnt; // Good icon
if (cgs.media.forcePowerIcons[forcePowerSorted[i]])
{
CG_DrawPic( holdX, y + yOffset, smallIconSize, smallIconSize, cgs.media.forcePowerIcons[forcePowerSorted[i]] ); //only cache the icon for display
holdX += (smallIconSize+pad);
}
}
if ( showPowersName[cg.forceSelect] )
{
UI_DrawProportionalString(320, y + 30 + yOffset, CG_GetStringEdString("SP_INGAME", showPowersName[cg.forceSelect]), UI_CENTER | UI_SMALLFONT, colorTable[CT_ICON_BLUE]);
}
}
/*
===================
CG_DrawInventorySelect
===================
*/
void CG_DrawInvenSelect( void )
{
int i;
int sideMax,holdCount,iconCnt;
int smallIconSize,bigIconSize;
int sideLeftIconCnt,sideRightIconCnt;
int count;
int holdX,x,y,y2,pad;
int height;
float addX;
// don't display if dead
if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 )
{
return;
}
if ((cg.invenSelectTime+WEAPON_SELECT_TIME)<cg.time) // Time is up for the HUD to display
{
return;
}
if (!cg.snap->ps.stats[STAT_HOLDABLE_ITEM] || !cg.snap->ps.stats[STAT_HOLDABLE_ITEMS])
{
return;
}
if (cg.itemSelect == -1)
{
cg.itemSelect = bg_itemlist[cg.snap->ps.stats[STAT_HOLDABLE_ITEM]].giTag;
}
//const int bits = cg.snap->ps.stats[ STAT_ITEMS ];
// count the number of items owned
count = 0;
for ( i = 0 ; i < HI_NUM_HOLDABLE ; i++ )
{
if ((cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) )
{
count++;
}
}
if (!count)
{
y2 = 0; //err?
UI_DrawProportionalString(320, y2 + 22, "EMPTY INVENTORY", UI_CENTER | UI_SMALLFONT, colorTable[CT_ICON_BLUE]);
return;
}
sideMax = 3; // Max number of icons on the side
// Calculate how many icons will appear to either side of the center one
holdCount = count - 1; // -1 for the center icon
if (holdCount == 0) // No icons to either side
{
sideLeftIconCnt = 0;
sideRightIconCnt = 0;
}
else if (count > (2*sideMax)) // Go to the max on each side
{
sideLeftIconCnt = sideMax;
sideRightIconCnt = sideMax;
}
else // Less than max, so do the calc
{
sideLeftIconCnt = holdCount/2;
sideRightIconCnt = holdCount - sideLeftIconCnt;
}
i = cg.itemSelect - 1;
if (i<0)
{
i = HI_NUM_HOLDABLE-1;
}
smallIconSize = 40;
bigIconSize = 80;
pad = 16;
x = 320;
y = 410;
// Left side ICONS
// Work backwards from current icon
holdX = x - ((bigIconSize/2) + pad + smallIconSize);
height = smallIconSize * cg.iconHUDPercent;
addX = (float) smallIconSize * .75;
for (iconCnt=0;iconCnt<sideLeftIconCnt;i--)
{
if (i<0)
{
i = HI_NUM_HOLDABLE-1;
}
if ( !(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect )
{
continue;
}
++iconCnt; // Good icon
if (!BG_IsItemSelectable(&cg.predictedPlayerState, i))
{
continue;
}
if (cgs.media.invenIcons[i])
{
trap_R_SetColor(NULL);
CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, cgs.media.invenIcons[i] );
trap_R_SetColor(colorTable[CT_ICON_BLUE]);
holdX -= (smallIconSize+pad);
}
}
// Current Center Icon
height = bigIconSize * cg.iconHUDPercent;
if (cgs.media.invenIcons[cg.itemSelect] && BG_IsItemSelectable(&cg.predictedPlayerState, cg.itemSelect))
{
int itemNdex;
trap_R_SetColor(NULL);
CG_DrawPic( x-(bigIconSize/2), (y-((bigIconSize-smallIconSize)/2))+10, bigIconSize, bigIconSize, cgs.media.invenIcons[cg.itemSelect] );
addX = (float) bigIconSize * .75;
trap_R_SetColor(colorTable[CT_ICON_BLUE]);
itemNdex = BG_GetItemIndexByTag(cg.itemSelect, IT_HOLDABLE);
if (bg_itemlist[itemNdex].classname)
{
vec4_t textColor = { .312f, .75f, .621f, 1.0f };
char text[1024];
char upperKey[1024];
strcpy(upperKey, bg_itemlist[itemNdex].classname);
//[Flamethrower]
if ( trap_SP_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text ))
|| trap_SP_GetStringTextString( va("OJP_MENUS_%s",Q_strupr(upperKey)), text, sizeof( text )))
//if ( trap_SP_GetStringTextString( va("SP_INGAME_%s",Q_strupr(upperKey)), text, sizeof( text )))
//[/Flamethrower]
{
UI_DrawProportionalString(320, y+45, text, UI_CENTER | UI_SMALLFONT, textColor);
}
else
{
UI_DrawProportionalString(320, y+45, bg_itemlist[itemNdex].classname, UI_CENTER | UI_SMALLFONT, textColor);
}
}
}
i = cg.itemSelect + 1;
if (i> HI_NUM_HOLDABLE-1)
{
i = 0;
}
// Right side ICONS
// Work forwards from current icon
holdX = x + (bigIconSize/2) + pad;
height = smallIconSize * cg.iconHUDPercent;
addX = (float) smallIconSize * .75;
for (iconCnt=0;iconCnt<sideRightIconCnt;i++)
{
if (i> HI_NUM_HOLDABLE-1)
{
i = 0;
}
if ( !(cg.snap->ps.stats[STAT_HOLDABLE_ITEMS] & (1 << i)) || i == cg.itemSelect )
{
continue;
}
++iconCnt; // Good icon
if (!BG_IsItemSelectable(&cg.predictedPlayerState, i))
{
continue;
}
if (cgs.media.invenIcons[i])
{
trap_R_SetColor(NULL);
CG_DrawPic( holdX, y+10, smallIconSize, smallIconSize, cgs.media.invenIcons[i] );
trap_R_SetColor(colorTable[CT_ICON_BLUE]);
holdX += (smallIconSize+pad);
}
}
}
int cg_targVeh = ENTITYNUM_NONE;
int cg_targVehLastTime = 0;
qboolean CG_CheckTargetVehicle( centity_t **pTargetVeh, float *alpha )
{
int targetNum = ENTITYNUM_NONE;
centity_t *targetVeh = NULL;
if ( !pTargetVeh || !alpha )
{//hey, where are my pointers?
return qfalse;
}
*alpha = 1.0f;
//FIXME: need to clear all of these when you die?
if ( cg.predictedPlayerState.rocketLockIndex < ENTITYNUM_WORLD )
{
targetNum = cg.predictedPlayerState.rocketLockIndex;
}
else if ( cg.crosshairVehNum < ENTITYNUM_WORLD
&& cg.time - cg.crosshairVehTime < 3000 )
{//crosshair was on a vehicle in the last 3 seconds
targetNum = cg.crosshairVehNum;
}
else if ( cg.crosshairClientNum < ENTITYNUM_WORLD )
{
targetNum = cg.crosshairClientNum;
}
if ( targetNum < MAX_CLIENTS )
{//real client
if ( cg_entities[targetNum].currentState.m_iVehicleNum >= MAX_CLIENTS )
{//in a vehicle
targetNum = cg_entities[targetNum].currentState.m_iVehicleNum;
}
}
if ( targetNum < ENTITYNUM_WORLD
&& targetNum >= MAX_CLIENTS )
{
centity_t *targetVeh = &cg_entities[targetNum];
if ( targetVeh->currentState.NPC_class == CLASS_VEHICLE
&& targetVeh->m_pVehicle
&& targetVeh->m_pVehicle->m_pVehicleInfo
&& targetVeh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER )
{//it's a vehicle
cg_targVeh = targetNum;
cg_targVehLastTime = cg.time;
*alpha = 1.0f;
}
else
{
targetVeh = NULL;
}
}
if ( !targetVeh )
{
if ( cg_targVehLastTime && cg.time - cg_targVehLastTime < 3000 )
{
targetVeh = &cg_entities[cg_targVeh];;
if ( cg.time-cg_targVehLastTime < 1000 )
{//stay at full alpha for 1 sec after lose them from crosshair
*alpha = 1.0f;
}
else
{//fade out over 2 secs
*alpha = 1.0f-((cg.time-cg_targVehLastTime-1000)/2000.0f);
}
}
}
if ( targetVeh )
{
*pTargetVeh = targetVeh;
return qtrue;
}
return qfalse;
}
#define MAX_VHUD_SHIELD_TICS 12
#define MAX_VHUD_SPEED_TICS 5
#define MAX_VHUD_ARMOR_TICS 5
#define MAX_VHUD_AMMO_TICS 5
float CG_DrawVehicleShields( const menuDef_t *menuHUD, const centity_t *veh )
{
int i;
char itemName[64];
float inc, currValue,maxShields;
vec4_t calcColor;
itemDef_t *item;
float percShields;
item = Menu_FindItemByName((menuDef_t *) menuHUD, "armorbackground");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
maxShields = veh->m_pVehicle->m_pVehicleInfo->shields;
currValue = cg.predictedVehicleState.stats[STAT_ARMOR];
percShields = (float)currValue/(float)maxShields;
// Print all the tics of the shield graphic
// Look at the amount of health left and show only as much of the graphic as there is health.
// Use alpha to fade out partial section of health
inc = (float) maxShields / MAX_VHUD_ARMOR_TICS;
for (i=1;i<=MAX_VHUD_ARMOR_TICS;i++)
{
sprintf( itemName, "armor_tic%d", i );
item = Menu_FindItemByName((menuDef_t *) menuHUD, itemName);
if (!item)
{
continue;
}
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
float percent = currValue / inc;
calcColor[3] *= percent; // Fade it out
}
trap_R_SetColor( calcColor);
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
currValue -= inc;
}
return percShields;
}
int cg_vehicleAmmoWarning = 0;
int cg_vehicleAmmoWarningTime = 0;
void CG_DrawVehicleAmmo( const menuDef_t *menuHUD, const centity_t *veh )
{
int i;
char itemName[64];
float inc, currValue,maxAmmo;
vec4_t calcColor;
itemDef_t *item;
item = Menu_FindItemByName((menuDef_t *) menuHUD, "ammobackground");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[0].ammoMax;
currValue = cg.predictedVehicleState.ammo[0];
inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS;
for (i=1;i<=MAX_VHUD_AMMO_TICS;i++)
{
sprintf( itemName, "ammo_tic%d", i );
item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName);
if (!item)
{
continue;
}
if ( cg_vehicleAmmoWarningTime > cg.time
&& cg_vehicleAmmoWarning == 0 )
{
memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t));
calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f;
}
else
{
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
float percent = currValue / inc;
calcColor[3] *= percent; // Fade it out
}
}
trap_R_SetColor( calcColor);
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
currValue -= inc;
}
}
void CG_DrawVehicleAmmoUpper( const menuDef_t *menuHUD, const centity_t *veh )
{
int i;
char itemName[64];
float inc, currValue,maxAmmo;
vec4_t calcColor;
itemDef_t *item;
item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammoupperbackground");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[0].ammoMax;
currValue = cg.predictedVehicleState.ammo[0];
inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS;
for (i=1;i<MAX_VHUD_AMMO_TICS;i++)
{
sprintf( itemName, "ammoupper_tic%d", i );
item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName);
if (!item)
{
continue;
}
if ( cg_vehicleAmmoWarningTime > cg.time
&& cg_vehicleAmmoWarning == 0 )
{
memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t));
calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f;
}
else
{
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
float percent = currValue / inc;
calcColor[3] *= percent; // Fade it out
}
}
trap_R_SetColor( calcColor);
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
currValue -= inc;
}
}
void CG_DrawVehicleAmmoLower( const menuDef_t *menuHUD, const centity_t *veh )
{
int i;
char itemName[64];
float inc, currValue,maxAmmo;
vec4_t calcColor;
itemDef_t *item;
item = Menu_FindItemByName((menuDef_t *)menuHUD, "ammolowerbackground");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
maxAmmo = veh->m_pVehicle->m_pVehicleInfo->weapon[1].ammoMax;
currValue = cg.predictedVehicleState.ammo[1];
inc = (float) maxAmmo / MAX_VHUD_AMMO_TICS;
for (i=1;i<MAX_VHUD_AMMO_TICS;i++)
{
sprintf( itemName, "ammolower_tic%d", i );
item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName);
if (!item)
{
continue;
}
if ( cg_vehicleAmmoWarningTime > cg.time
&& cg_vehicleAmmoWarning == 1 )
{
memcpy(calcColor, g_color_table[ColorIndex(COLOR_RED)], sizeof(vec4_t));
calcColor[3] = sin(cg.time*0.005)*0.5f+0.5f;
}
else
{
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
float percent = currValue / inc;
calcColor[3] *= percent; // Fade it out
}
}
trap_R_SetColor( calcColor);
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
currValue -= inc;
}
}
// The HUD.menu file has the graphic print with a negative height, so it will print from the bottom up.
void CG_DrawVehicleTurboRecharge( const menuDef_t *menuHUD, const centity_t *veh )
{
itemDef_t *item;
int height;
item = Menu_FindItemByName( (menuDef_t *) menuHUD, "turborecharge");
if (item)
{
float percent=0.0f;
int diff = ( cg.time - veh->m_pVehicle->m_iTurboTime );
height = item->window.rect.h;
if (diff > veh->m_pVehicle->m_pVehicleInfo->turboRecharge)
{
percent = 1.0f;
trap_R_SetColor( colorTable[CT_GREEN] );
}
else
{
percent = (float) diff / veh->m_pVehicle->m_pVehicleInfo->turboRecharge;
if (percent < 0.0f)
{
percent = 0.0f;
}
trap_R_SetColor( colorTable[CT_RED] );
}
height *= percent;
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
height,
cgs.media.whiteShader);
}
}
qboolean cg_drawLink = qfalse;
void CG_DrawVehicleWeaponsLinked( const menuDef_t *menuHUD, const centity_t *veh )
{
qboolean drawLink = qfalse;
if ( veh->m_pVehicle
&& veh->m_pVehicle->m_pVehicleInfo
&& (veh->m_pVehicle->m_pVehicleInfo->weapon[0].linkable == 2|| veh->m_pVehicle->m_pVehicleInfo->weapon[1].linkable == 2) )
{//weapon is always linked
drawLink = qtrue;
}
else
{
//MP way:
//must get sent over network
if ( cg.predictedVehicleState.vehWeaponsLinked )
{
drawLink = qtrue;
}
}
if ( cg_drawLink != drawLink )
{//state changed, play sound
cg_drawLink = drawLink;
trap_S_StartSound (NULL, cg.predictedPlayerState.clientNum, CHAN_LOCAL, trap_S_RegisterSound( "sound/vehicles/common/linkweaps.wav" ) );
}
if ( drawLink )
{
itemDef_t *item;
item = Menu_FindItemByName( (menuDef_t *) menuHUD, "weaponslinked");
if (item)
{
trap_R_SetColor( colorTable[CT_CYAN] );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
cgs.media.whiteShader);
}
}
}
void CG_DrawVehicleSpeed( const menuDef_t *menuHUD, const centity_t *veh )
{
int i;
char itemName[64];
float inc, currValue,maxSpeed;
vec4_t calcColor;
itemDef_t *item;
item = Menu_FindItemByName((menuDef_t *) menuHUD, "speedbackground");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
maxSpeed = veh->m_pVehicle->m_pVehicleInfo->speedMax;
currValue = cg.predictedVehicleState.speed;
// Print all the tics of the shield graphic
// Look at the amount of health left and show only as much of the graphic as there is health.
// Use alpha to fade out partial section of health
inc = (float) maxSpeed / MAX_VHUD_SPEED_TICS;
for (i=1;i<=MAX_VHUD_SPEED_TICS;i++)
{
sprintf( itemName, "speed_tic%d", i );
item = Menu_FindItemByName((menuDef_t *)menuHUD, itemName);
if (!item)
{
continue;
}
if ( cg.time > veh->m_pVehicle->m_iTurboTime )
{
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
}
else // In turbo mode
{
if (cg.VHUDFlashTime < cg.time)
{
cg.VHUDFlashTime = cg.time + 200;
if (cg.VHUDTurboFlag)
{
cg.VHUDTurboFlag = qfalse;
}
else
{
cg.VHUDTurboFlag = qtrue;
}
}
if (cg.VHUDTurboFlag)
{
memcpy(calcColor, colorTable[CT_LTRED1], sizeof(vec4_t));
}
else
{
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
}
}
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
float percent = currValue / inc;
calcColor[3] *= percent; // Fade it out
}
trap_R_SetColor( calcColor);
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
currValue -= inc;
}
}
void CG_DrawVehicleArmor( const menuDef_t *menuHUD, const centity_t *veh )
{
int i;
vec4_t calcColor;
char itemName[64];
float inc, currValue,maxArmor;
itemDef_t *item;
maxArmor = veh->m_pVehicle->m_pVehicleInfo->armor;
currValue = cg.predictedVehicleState.stats[STAT_HEALTH];
item = Menu_FindItemByName( (menuDef_t *) menuHUD, "shieldbackground");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
// Print all the tics of the shield graphic
// Look at the amount of health left and show only as much of the graphic as there is health.
// Use alpha to fade out partial section of health
inc = (float) maxArmor / MAX_VHUD_SHIELD_TICS;
for (i=1;i <= MAX_VHUD_SHIELD_TICS;i++)
{
sprintf( itemName, "shield_tic%d", i );
item = Menu_FindItemByName((menuDef_t *) menuHUD, itemName);
if (!item)
{
continue;
}
memcpy(calcColor, item->window.foreColor, sizeof(vec4_t));
if (currValue <= 0) // don't show tic
{
break;
}
else if (currValue < inc) // partial tic (alpha it out)
{
float percent = currValue / inc;
calcColor[3] *= percent; // Fade it out
}
trap_R_SetColor( calcColor);
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
currValue -= inc;
}
}
enum
{
VEH_DAMAGE_FRONT=0,
VEH_DAMAGE_BACK,
VEH_DAMAGE_LEFT,
VEH_DAMAGE_RIGHT,
};
typedef struct
{
char *itemName;
short heavyDamage;
short lightDamage;
} veh_damage_t;
veh_damage_t vehDamageData[4] =
{
"vehicle_front",SHIPSURF_DAMAGE_FRONT_HEAVY,SHIPSURF_DAMAGE_FRONT_LIGHT,
"vehicle_back",SHIPSURF_DAMAGE_BACK_HEAVY,SHIPSURF_DAMAGE_BACK_LIGHT,
"vehicle_left",SHIPSURF_DAMAGE_LEFT_HEAVY,SHIPSURF_DAMAGE_LEFT_LIGHT,
"vehicle_right",SHIPSURF_DAMAGE_RIGHT_HEAVY,SHIPSURF_DAMAGE_RIGHT_LIGHT,
};
// Draw health graphic for given part of vehicle
void CG_DrawVehicleDamage(const centity_t *veh,int brokenLimbs,const menuDef_t *menuHUD,float alpha,int index)
{
itemDef_t *item;
int colorI;
vec4_t color;
int graphicHandle=0;
item = Menu_FindItemByName((menuDef_t *)menuHUD, vehDamageData[index].itemName);
if (item)
{
if (brokenLimbs & (1<<vehDamageData[index].heavyDamage))
{
colorI = CT_RED;
if (brokenLimbs & (1<<vehDamageData[index].lightDamage))
{
colorI = CT_DKGREY;
}
}
else if (brokenLimbs & (1<<vehDamageData[index].lightDamage))
{
colorI = CT_YELLOW;
}
else
{
colorI = CT_GREEN;
}
VectorCopy4 ( colorTable[colorI], color );
color[3] = alpha;
trap_R_SetColor( color );
switch ( index )
{
case VEH_DAMAGE_FRONT :
graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconFrontHandle;
break;
case VEH_DAMAGE_BACK :
graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconBackHandle;
break;
case VEH_DAMAGE_LEFT :
graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconLeftHandle;
break;
case VEH_DAMAGE_RIGHT :
graphicHandle = veh->m_pVehicle->m_pVehicleInfo->iconRightHandle;
break;
}
if (graphicHandle)
{
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
graphicHandle );
}
}
}
// Used on both damage indicators : player vehicle and the vehicle the player is locked on
void CG_DrawVehicleDamageHUD(const centity_t *veh,int brokenLimbs,float percShields,char *menuName, float alpha)
{
menuDef_t *menuHUD;
itemDef_t *item;
vec4_t color;
menuHUD = Menus_FindByName(menuName);
if ( !menuHUD )
{
return;
}
item = Menu_FindItemByName(menuHUD, "background");
if (item)
{
if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle)
{
if ( veh->damageTime > cg.time )
{//ship shields currently taking damage
//NOTE: cent->damageAngle can be accessed to get the direction from the ship origin to the impact point (in 3-D space)
float perc = 1.0f - ((veh->damageTime - cg.time) / 2000.0f);
if ( perc < 0.0f )
{
perc = 0.0f;
}
else if ( perc > 1.0f )
{
perc = 1.0f;
}
color[0] = item->window.foreColor[0];//flash red
color[1] = item->window.foreColor[1]*perc;//fade other colors back in over time
color[2] = item->window.foreColor[2]*perc;//fade other colors back in over time
color[3] = item->window.foreColor[3];//always normal alpha
trap_R_SetColor( color );
}
else
{
trap_R_SetColor( item->window.foreColor );
}
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
veh->m_pVehicle->m_pVehicleInfo->dmgIndicBackgroundHandle );
}
}
item = Menu_FindItemByName(menuHUD, "outer_frame");
if (item)
{
if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
veh->m_pVehicle->m_pVehicleInfo->dmgIndicFrameHandle );
}
}
item = Menu_FindItemByName(menuHUD, "shields");
if (item)
{
if (veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle)
{
VectorCopy4 ( colorTable[CT_HUD_GREEN], color );
color[3] = percShields;
trap_R_SetColor( color );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
veh->m_pVehicle->m_pVehicleInfo->dmgIndicShieldHandle );
}
}
//TODO: if we check nextState.brokenLimbs & prevState.brokenLimbs, we can tell when a damage flag has been added and flash that part of the ship
//FIXME: when ship explodes, either stop drawing ship or draw all parts black
CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_FRONT);
CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_BACK);
CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_LEFT);
CG_DrawVehicleDamage(veh,brokenLimbs,menuHUD,alpha,VEH_DAMAGE_RIGHT);
}
qboolean CG_DrawVehicleHud( const centity_t *cent )
{
itemDef_t *item;
menuDef_t *menuHUD;
playerState_t *ps;
centity_t *veh;
float shieldPerc,alpha;
menuHUD = Menus_FindByName("swoopvehiclehud");
if (!menuHUD)
{
return qtrue; // Draw player HUD
}
ps = &cg.predictedPlayerState;
if (!ps || !(ps->m_iVehicleNum))
{
return qtrue; // Draw player HUD
}
veh = &cg_entities[ps->m_iVehicleNum];
if ( !veh )
{
return qtrue; // Draw player HUD
}
CG_DrawVehicleTurboRecharge( menuHUD, veh );
CG_DrawVehicleWeaponsLinked( menuHUD, veh );
item = Menu_FindItemByName(menuHUD, "leftframe");
// Draw frame
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
item = Menu_FindItemByName(menuHUD, "rightframe");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
CG_DrawVehicleArmor( menuHUD, veh );
// Get animal hud for speed
// if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL)
// {
// menuHUD = Menus_FindByName("tauntaunhud");
// }
CG_DrawVehicleSpeed( menuHUD, veh );
// Revert to swoophud
// if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL)
// {
// menuHUD = Menus_FindByName("swoopvehiclehud");
// }
// if (veh->m_pVehicle->m_pVehicleInfo->type == VH_ANIMAL)
// {
shieldPerc = CG_DrawVehicleShields( menuHUD, veh );
// }
if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && !veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID)
{
CG_DrawVehicleAmmo( menuHUD, veh );
}
else if (veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID && veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID)
{
CG_DrawVehicleAmmoUpper( menuHUD, veh );
CG_DrawVehicleAmmoLower( menuHUD, veh );
}
// If he's hidden, he must be in a vehicle
if (veh->m_pVehicle->m_pVehicleInfo->hideRider)
{
CG_DrawVehicleDamageHUD(veh,cg.predictedVehicleState.brokenLimbs,shieldPerc,"vehicledamagehud",1.0f);
// Has he targeted an enemy?
if (CG_CheckTargetVehicle( &veh, &alpha ))
{
CG_DrawVehicleDamageHUD(veh,veh->currentState.brokenLimbs,((float)veh->currentState.activeForcePass/10.0f),"enemyvehicledamagehud",alpha);
}
return qfalse; // Don't draw player HUD
}
return qtrue; // Draw player HUD
}
/*
================
CG_DrawStats
================
*/
static void CG_DrawStats( void )
{
centity_t *cent;
playerState_t *ps;
qboolean drawHUD = qtrue;
cent = &cg_entities[cg.snap->ps.clientNum];
if ( cent )
{
ps = &cg.predictedPlayerState;
if ( (ps->m_iVehicleNum ) ) // In a vehicle???
{
drawHUD = CG_DrawVehicleHud( cent );
}
}
if (drawHUD)
{
CG_DrawHUD(cent);
}
}
/*
===================
CG_DrawPickupItem
===================
*/
static void CG_DrawPickupItem( void ) {
int value;
float *fadeColor;
value = cg.itemPickup;
if ( value && cg_items[ value ].icon != -1 )
{
fadeColor = CG_FadeColor( cg.itemPickupTime, 3000 );
if ( fadeColor )
{
CG_RegisterItemVisuals( value );
trap_R_SetColor( fadeColor );
CG_DrawPic( 573, 320, ICON_SIZE, ICON_SIZE, cg_items[ value ].icon );
trap_R_SetColor( NULL );
}
}
}
/*
================
CG_DrawTeamBackground
================
*/
void CG_DrawTeamBackground( int x, int y, int w, int h, float alpha, int team )
{
vec4_t hcolor;
hcolor[3] = alpha;
if ( team == TEAM_RED ) {
hcolor[0] = 1;
hcolor[1] = .2f;
hcolor[2] = .2f;
} else if ( team == TEAM_BLUE ) {
hcolor[0] = .2f;
hcolor[1] = .2f;
hcolor[2] = 1;
} else {
return;
}
// trap_R_SetColor( hcolor );
CG_FillRect ( x, y, w, h, hcolor );
// CG_DrawPic( x, y, w, h, cgs.media.teamStatusBar );
trap_R_SetColor( NULL );
}
/*
===========================================================================================
UPPER RIGHT CORNER
===========================================================================================
*/
/*
================
CG_DrawMiniScoreboard
================
*/
static float CG_DrawMiniScoreboard ( float y )
{
char temp[MAX_QPATH];
int xOffset = 0;
if ( !cg_drawScores.integer )
{
return y;
}
if (cgs.gametype == GT_SIEGE)
{ //don't bother with this in siege
return y;
}
if ( cgs.gametype >= GT_TEAM )
{
strcpy ( temp, va("%s: ", CG_GetStringEdString("MP_INGAME", "RED")));
Q_strcat ( temp, MAX_QPATH, cgs.scores1==SCORE_NOT_PRESENT?"-":(va("%i",cgs.scores1)) );
Q_strcat ( temp, MAX_QPATH, va(" %s: ", CG_GetStringEdString("MP_INGAME", "BLUE")) );
Q_strcat ( temp, MAX_QPATH, cgs.scores2==SCORE_NOT_PRESENT?"-":(va("%i",cgs.scores2)) );
CG_Text_Paint( 630 - CG_Text_Width ( temp, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, temp, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM );
y += 15;
}
return y;
}
/*
================
CG_DrawEnemyInfo
================
*/
static float CG_DrawEnemyInfo ( float y )
{
float size;
int clientNum;
const char *title;
clientInfo_t *ci;
int xOffset = 0;
if (!cg.snap)
{
return y;
}
if ( !cg_drawEnemyInfo.integer )
{
return y;
}
if ( cg.predictedPlayerState.stats[STAT_HEALTH] <= 0 )
{
return y;
}
if (cgs.gametype == GT_POWERDUEL)
{ //just get out of here then
return y;
}
if ( cgs.gametype == GT_JEDIMASTER )
{
//title = "Jedi Master";
title = CG_GetStringEdString("MP_INGAME", "MASTERY7");
clientNum = cgs.jediMaster;
if ( clientNum < 0 )
{
title = CG_GetStringEdString("MP_INGAME", "GET_SABER");
size = ICON_SIZE * 1.25;
y += 5;
CG_DrawPic( SCREEN_WIDTH - size - 12 + xOffset, y, size, size, cgs.media.weaponIcons[WP_SABER] );
y += size;
CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM );
return y + BIGCHAR_HEIGHT + 2;
}
}
else if ( cg.snap->ps.duelInProgress )
{
title = CG_GetStringEdString("MP_INGAME", "DUELING");
clientNum = cg.snap->ps.duelIndex;
}
else if ( cgs.gametype == GT_DUEL && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR)
{
title = CG_GetStringEdString("MP_INGAME", "DUELING");
if (cg.snap->ps.clientNum == cgs.duelist1)
{
clientNum = cgs.duelist2; //if power duel, should actually draw both duelists 2 and 3 I guess
}
else if (cg.snap->ps.clientNum == cgs.duelist2)
{
clientNum = cgs.duelist1;
}
else if (cg.snap->ps.clientNum == cgs.duelist3)
{
clientNum = cgs.duelist1;
}
else
{
return y;
}
}
else
{
//As of current, we don't want to draw the attacker. Instead, draw whoever is in first place.
if (cgs.duelWinner < 0 || cgs.duelWinner >= MAX_CLIENTS)
{
return y;
}
title = va("%s: %i",CG_GetStringEdString("MP_INGAME", "LEADER"), cgs.scores1);
clientNum = cgs.duelWinner;
}
if ( clientNum >= MAX_CLIENTS || !(&cgs.clientinfo[ clientNum ]) )
{
return y;
}
ci = &cgs.clientinfo[ clientNum ];
size = ICON_SIZE * 1.25;
y += 5;
if ( ci->modelIcon )
{
CG_DrawPic( SCREEN_WIDTH - size - 5 + xOffset, y, size, size, ci->modelIcon );
}
y += size;
// CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, ci->name, 0, 0, 0, FONT_MEDIUM );
CG_Text_Paint( 630 - CG_Text_Width ( ci->name, 1.0f, FONT_SMALL2 ) + xOffset, y, 1.0f, colorWhite, ci->name, 0, 0, 0, FONT_SMALL2 );
y += 15;
// CG_Text_Paint( 630 - CG_Text_Width ( title, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, title, 0, 0, 0, FONT_MEDIUM );
CG_Text_Paint( 630 - CG_Text_Width ( title, 1.0f, FONT_SMALL2 ) + xOffset, y, 1.0f, colorWhite, title, 0, 0, 0, FONT_SMALL2 );
if ( (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) && cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR)
{//also print their score
char text[1024];
y += 15;
Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[clientNum].score, cgs.fraglimit );
CG_Text_Paint( 630 - CG_Text_Width ( text, 0.7f, FONT_MEDIUM ) + xOffset, y, 0.7f, colorWhite, text, 0, 0, 0, FONT_MEDIUM );
}
// nmckenzie: DUEL_HEALTH - fixme - need checks and such here. And this is coded to duelist 1 right now, which is wrongly.
if ( cgs.showDuelHealths >= 2)
{
y += 15;
if ( cgs.duelist1 == clientNum )
{
CG_DrawDuelistHealth ( SCREEN_WIDTH - size - 5 + xOffset, y, 64, 8, 1 );
}
else if ( cgs.duelist2 == clientNum )
{
CG_DrawDuelistHealth ( SCREEN_WIDTH - size - 5 + xOffset, y, 64, 8, 2 );
}
}
return y + BIGCHAR_HEIGHT + 2;
}
/*
==================
CG_DrawSnapshot
==================
*/
static float CG_DrawSnapshot( float y ) {
char *s;
int w;
int xOffset = 0;
s = va( "time:%i snap:%i cmd:%i", cg.snap->serverTime,
cg.latestSnapshotNum, cgs.serverCommandSequence );
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F);
return y + BIGCHAR_HEIGHT + 4;
}
/*
==================
CG_DrawFPS
==================
*/
#define FPS_FRAMES 16
static float CG_DrawFPS( float y ) {
char *s;
int w;
static unsigned short previousTimes[FPS_FRAMES];
static unsigned short index;
static int previous, lastupdate;
int t, i, fps, total;
unsigned short frameTime;
const int xOffset = 0;
// don't use serverTime, because that will be drifting to
// correct for internet lag changes, timescales, timedemos, etc
t = trap_Milliseconds();
frameTime = t - previous;
previous = t;
if (t - lastupdate > 50) //don't sample faster than this
{
lastupdate = t;
previousTimes[index % FPS_FRAMES] = frameTime;
index++;
}
// average multiple frames together to smooth changes out a bit
total = 0;
for ( i = 0 ; i < FPS_FRAMES ; i++ ) {
total += previousTimes[i];
}
if ( !total ) {
total = 1;
}
fps = 1000 * FPS_FRAMES / total;
s = va( "%ifps", fps );
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F);
return y + BIGCHAR_HEIGHT + 4;
}
// nmckenzie: DUEL_HEALTH
#define MAX_HEALTH_FOR_IFACE 100
void CG_DrawHealthBarRough (float x, float y, int width, int height, float ratio, const float *color1, const float *color2)
{
float midpoint, remainder;
float color3[4] = {1, 0, 0, .7f};
midpoint = width * ratio - 1;
remainder = width - midpoint;
color3[0] = color1[0] * 0.5f;
assert(!(height%4));//this won't line up otherwise.
CG_DrawRect(x + 1, y + height/2-1, midpoint, 1, height/4+1, color1); // creme-y filling.
CG_DrawRect(x + midpoint, y + height/2-1, remainder, 1, height/4+1, color3); // used-up-ness.
CG_DrawRect(x, y, width, height, 1, color2); // hard crispy shell
}
void CG_DrawDuelistHealth ( float x, float y, float w, float h, int duelist )
{
float duelHealthColor[4] = {1, 0, 0, 0.7f};
float healthSrc = 0.0f;
float ratio;
if ( duelist == 1 )
{
healthSrc = cgs.duelist1health;
}
else if (duelist == 2 )
{
healthSrc = cgs.duelist2health;
}
ratio = healthSrc / MAX_HEALTH_FOR_IFACE;
if ( ratio > 1.0f )
{
ratio = 1.0f;
}
if ( ratio < 0.0f )
{
ratio = 0.0f;
}
duelHealthColor[0] = (ratio * 0.2f) + 0.5f;
CG_DrawHealthBarRough (x, y, w, h, ratio, duelHealthColor, colorTable[CT_WHITE]); // new art for this? I'm not crazy about how this looks.
}
/*
=====================
CG_DrawRadar
=====================
*/
float cg_radarRange = 2500.0f;
#define RADAR_RADIUS 60
const int RADAR_X = (580 - RADAR_RADIUS);
const int RADAR_CHAT_DURATION = 6000;
static int radarLockSoundDebounceTime = 0;
static int impactSoundDebounceTime = 0;
const float RADAR_MISSILE_RANGE = 3000.0f;
const float RADAR_ASTEROID_RANGE = 10000.0f;
const float RADAR_MIN_ASTEROID_SURF_WARN_DIST = 1200.0f;
float CG_DrawRadar ( float y )
{
vec4_t color;
vec4_t teamColor;
float arrow_w;
float arrow_h;
clientInfo_t *cl;
clientInfo_t *local;
int i;
float arrowBaseScale;
float zScale;
int xOffset = 0;
if (!cg.snap)
{
return y;
}
// Make sure the radar should be showing
if ( cg.snap->ps.stats[STAT_HEALTH] <= 0 )
{
return y;
}
if ( (cg.predictedPlayerState.pm_flags & PMF_FOLLOW) || cg.predictedPlayerState.persistant[PERS_TEAM] == TEAM_SPECTATOR )
{
return y;
}
local = &cgs.clientinfo[ cg.snap->ps.clientNum ];
if ( !local->infoValid )
{
return y;
}
// Draw the radar background image
color[0] = color[1] = color[2] = 1.0f;
color[3] = 0.6f;
trap_R_SetColor ( color );
CG_DrawPic( RADAR_X + xOffset, y, RADAR_RADIUS*2, RADAR_RADIUS*2, cgs.media.radarShader );
//Always green for your own team.
VectorCopy ( g_color_table[ColorIndex(COLOR_GREEN)], teamColor );
teamColor[3] = 1.0f;
// Draw all of the radar entities. Draw them backwards so players are drawn last
for ( i = cg.radarEntityCount -1 ; i >= 0 ; i-- )
{
vec3_t dirLook;
vec3_t dirPlayer;
float angleLook;
float anglePlayer;
float angle;
float distance, actualDist;
centity_t* cent;
cent = &cg_entities[cg.radarEntities[i]];
// Get the distances first
VectorSubtract ( cg.predictedPlayerState.origin, cent->lerpOrigin, dirPlayer );
dirPlayer[2] = 0;
actualDist = distance = VectorNormalize ( dirPlayer );
if ( distance > cg_radarRange * 0.8f)
{
if ( (cent->currentState.eFlags & EF_RADAROBJECT)//still want to draw the direction
|| ( cent->currentState.eType==ET_NPC//FIXME: draw last, with players...
&& cent->currentState.NPC_class == CLASS_VEHICLE
&& cent->currentState.speed > 0 ) )//always draw vehicles
{
distance = cg_radarRange*0.8f;
}
else
{
continue;
}
}
distance = distance / cg_radarRange;
distance *= RADAR_RADIUS;
AngleVectors ( cg.predictedPlayerState.viewangles, dirLook, NULL, NULL );
dirLook[2] = 0;
anglePlayer = atan2(dirPlayer[0],dirPlayer[1]);
VectorNormalize ( dirLook );
angleLook = atan2(dirLook[0],dirLook[1]);
angle = angleLook - anglePlayer;
switch ( cent->currentState.eType )
{
default:
{
float x;
float ly;
qhandle_t shader;
vec4_t color;
x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance;
ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance;
arrowBaseScale = 9.0f;
shader = 0;
zScale = 1.0f;
//we want to scale the thing up/down based on the relative Z (up/down) positioning
if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2])
{ //higher, scale up (between 16 and 24)
float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]);
//max out to 1.5x scale at 512 units above local player's height
dif /= 1024.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale += dif;
}
else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2])
{ //lower, scale down (between 16 and 8)
float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]);
//half scale at 512 units below local player's height
dif /= 1024.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale -= dif;
}
arrowBaseScale *= zScale;
if (cent->currentState.brokenLimbs)
{ //slightly misleading to use this value, but don't want to add more to entstate.
//any ent with brokenLimbs non-0 and on radar is an objective ent.
//brokenLimbs is literal team value.
char objState[1024];
int complete;
//we only want to draw it if the objective for it is not complete.
//frame represents objective num.
trap_Cvar_VariableStringBuffer(va("team%i_objective%i", cent->currentState.brokenLimbs, cent->currentState.frame), objState, 1024);
complete = atoi(objState);
if (!complete)
{
// generic enemy index specifies a shader to use for the radar entity.
if ( cent->currentState.genericenemyindex )
{
color[0] = color[1] = color[2] = color[3] = 1.0f;
shader = cgs.gameIcons[cent->currentState.genericenemyindex];
}
else
{
if (cg.snap &&
cent->currentState.brokenLimbs == cg.snap->ps.persistant[PERS_TEAM])
{
VectorCopy ( g_color_table[ColorIndex(COLOR_RED)], color );
}
else
{
VectorCopy ( g_color_table[ColorIndex(COLOR_GREEN)], color );
}
shader = cgs.media.siegeItemShader;
}
}
}
else
{
color[0] = color[1] = color[2] = color[3] = 1.0f;
// generic enemy index specifies a shader to use for the radar entity.
if ( cent->currentState.genericenemyindex )
{
shader = cgs.gameIcons[cent->currentState.genericenemyindex];
}
else
{
shader = cgs.media.siegeItemShader;
}
}
if ( shader )
{
// Pulse the alpha if time2 is set. time2 gets set when the entity takes pain
if ( (cent->currentState.time2 && cg.time - cent->currentState.time2 < 5000) ||
(cent->currentState.time2 == 0xFFFFFFFF) )
{
if ( (cg.time / 200) & 1 )
{
color[3] = 0.1f + 0.9f * (float) (cg.time % 200) / 200.0f;
}
else
{
color[3] = 1.0f - 0.9f * (float) (cg.time % 200) / 200.0f;
}
}
trap_R_SetColor ( color );
CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, shader );
}
}
break;
case ET_NPC://FIXME: draw last, with players...
if ( cent->currentState.NPC_class == CLASS_VEHICLE
&& cent->currentState.speed > 0 )
{
if ( cent->m_pVehicle && cent->m_pVehicle->m_pVehicleInfo->radarIconHandle )
{
float x;
float ly;
x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance;
ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance;
arrowBaseScale = 9.0f;
zScale = 1.0f;
//we want to scale the thing up/down based on the relative Z (up/down) positioning
if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2])
{ //higher, scale up (between 16 and 24)
float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]);
//max out to 1.5x scale at 512 units above local player's height
dif /= 4096.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale += dif;
}
else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2])
{ //lower, scale down (between 16 and 8)
float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]);
//half scale at 512 units below local player's height
dif /= 4096.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale -= dif;
}
arrowBaseScale *= zScale;
if ( cent->currentState.m_iVehicleNum //vehicle has a driver
&& cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].infoValid )
{
if ( cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].team == local->team )
{
trap_R_SetColor ( teamColor );
}
else
{
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
}
}
else
{
trap_R_SetColor ( NULL );
}
CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cent->m_pVehicle->m_pVehicleInfo->radarIconHandle );
}
}
break; //maybe do something?
case ET_MOVER:
if ( cent->currentState.speed//the mover's size, actually
&& actualDist < (cent->currentState.speed+RADAR_ASTEROID_RANGE)
&& cg.predictedPlayerState.m_iVehicleNum )
{//a mover that's close to me and I'm in a vehicle
qboolean mayImpact = qfalse;
float surfaceDist = (actualDist-cent->currentState.speed);
if ( surfaceDist < 0.0f )
{
surfaceDist = 0.0f;
}
if ( surfaceDist < RADAR_MIN_ASTEROID_SURF_WARN_DIST )
{//always warn!
mayImpact = qtrue;
}
else
{//not close enough to always warn, yet, so check its direction
vec3_t asteroidPos, myPos, moveDir;
int predictTime, timeStep = 500;
float newDist;
for ( predictTime = timeStep; predictTime < 5000; predictTime+=timeStep )
{
//asteroid dir, speed, size, + my dir & speed...
BG_EvaluateTrajectory( ¢->currentState.pos, cg.time+predictTime, asteroidPos );
//FIXME: I don't think it's calcing "myPos" correctly
AngleVectors( cg.predictedVehicleState.viewangles, moveDir, NULL, NULL );
VectorMA( cg.predictedVehicleState.origin, cg.predictedVehicleState.speed*predictTime/1000.0f, moveDir, myPos );
newDist = Distance( myPos, asteroidPos );
if ( (newDist-cent->currentState.speed) <= RADAR_MIN_ASTEROID_SURF_WARN_DIST )//200.0f )
{//heading for an impact within the next 5 seconds
mayImpact = qtrue;
break;
}
}
}
if ( mayImpact )
{//possible collision
vec4_t asteroidColor = {0.5f,0.5f,0.5f,1.0f};
float x;
float ly;
float asteroidScale = (cent->currentState.speed/2000.0f);//average asteroid radius?
if ( actualDist > RADAR_ASTEROID_RANGE )
{
actualDist = RADAR_ASTEROID_RANGE;
}
distance = (actualDist/RADAR_ASTEROID_RANGE)*RADAR_RADIUS;
x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance;
ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance;
if ( asteroidScale > 3.0f )
{
asteroidScale = 3.0f;
}
else if ( asteroidScale < 0.2f )
{
asteroidScale = 0.2f;
}
arrowBaseScale = (9.0f*asteroidScale);
if ( impactSoundDebounceTime < cg.time )
{
vec3_t soundOrg;
if ( surfaceDist > RADAR_ASTEROID_RANGE*0.66f )
{
impactSoundDebounceTime = cg.time + 1000;
}
else if ( surfaceDist > RADAR_ASTEROID_RANGE/3.0f )
{
impactSoundDebounceTime = cg.time + 400;
}
else
{
impactSoundDebounceTime = cg.time + 100;
}
VectorMA( cg.refdef.vieworg, -500.0f*(surfaceDist/RADAR_ASTEROID_RANGE), dirPlayer, soundOrg );
trap_S_StartSound( soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, trap_S_RegisterSound( "sound/vehicles/common/impactalarm.wav" ) );
}
//brighten it the closer it is
if ( surfaceDist > RADAR_ASTEROID_RANGE*0.66f )
{
asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.7f;
}
else if ( surfaceDist > RADAR_ASTEROID_RANGE/3.0f )
{
asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 0.85f;
}
else
{
asteroidColor[0] = asteroidColor[1] = asteroidColor[2] = 1.0f;
}
//alpha out the longer it's been since it was considered dangerous
if ( (cg.time-impactSoundDebounceTime) > 100 )
{
asteroidColor[3] = (float)((cg.time-impactSoundDebounceTime)-100)/900.0f;
}
trap_R_SetColor ( asteroidColor );
CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, trap_R_RegisterShaderNoMip( "gfx/menus/radar/asteroid" ) );
}
}
break;
case ET_MISSILE:
if ( //cent->currentState.weapon == WP_ROCKET_LAUNCHER &&//a rocket
cent->currentState.owner > MAX_CLIENTS //belongs to an NPC
&& cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE )
{//a rocket belonging to an NPC, FIXME: only tracking rockets!
float x;
float ly;
x = (float)RADAR_X + (float)RADAR_RADIUS + (float)sin (angle) * distance;
ly = y + (float)RADAR_RADIUS + (float)cos (angle) * distance;
arrowBaseScale = 3.0f;
if ( cg.predictedPlayerState.m_iVehicleNum )
{//I'm in a vehicle
//if it's targetting me, then play an alarm sound if I'm in a vehicle
if ( cent->currentState.otherEntityNum == cg.predictedPlayerState.clientNum || cent->currentState.otherEntityNum == cg.predictedPlayerState.m_iVehicleNum )
{
if ( radarLockSoundDebounceTime < cg.time )
{
vec3_t soundOrg;
int alarmSound;
if ( actualDist > RADAR_MISSILE_RANGE * 0.66f )
{
radarLockSoundDebounceTime = cg.time + 1000;
arrowBaseScale = 3.0f;
alarmSound = trap_S_RegisterSound( "sound/vehicles/common/lockalarm1.wav" );
}
else if ( actualDist > RADAR_MISSILE_RANGE/3.0f )
{
radarLockSoundDebounceTime = cg.time + 500;
arrowBaseScale = 6.0f;
alarmSound = trap_S_RegisterSound( "sound/vehicles/common/lockalarm2.wav" );
}
else
{
radarLockSoundDebounceTime = cg.time + 250;
arrowBaseScale = 9.0f;
alarmSound = trap_S_RegisterSound( "sound/vehicles/common/lockalarm3.wav" );
}
if ( actualDist > RADAR_MISSILE_RANGE )
{
actualDist = RADAR_MISSILE_RANGE;
}
VectorMA( cg.refdef.vieworg, -500.0f*(actualDist/RADAR_MISSILE_RANGE), dirPlayer, soundOrg );
trap_S_StartSound( soundOrg, ENTITYNUM_WORLD, CHAN_AUTO, alarmSound );
}
}
}
zScale = 1.0f;
//we want to scale the thing up/down based on the relative Z (up/down) positioning
if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2])
{ //higher, scale up (between 16 and 24)
float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]);
//max out to 1.5x scale at 512 units above local player's height
dif /= 1024.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale += dif;
}
else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2])
{ //lower, scale down (between 16 and 8)
float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]);
//half scale at 512 units below local player's height
dif /= 1024.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale -= dif;
}
arrowBaseScale *= zScale;
if ( cent->currentState.owner >= MAX_CLIENTS//missile owned by an NPC
&& cg_entities[cent->currentState.owner].currentState.NPC_class == CLASS_VEHICLE//NPC is a vehicle
&& cg_entities[cent->currentState.owner].currentState.m_iVehicleNum <= MAX_CLIENTS//Vehicle has a player driver
&& cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum-1].infoValid ) //player driver is valid
{
cl = &cgs.clientinfo[cg_entities[cent->currentState.owner].currentState.m_iVehicleNum-1];
if ( cl->team == local->team )
{
trap_R_SetColor ( teamColor );
}
else
{
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
}
}
else
{
trap_R_SetColor ( NULL );
}
CG_DrawPic ( x - 4 + xOffset, ly - 4, arrowBaseScale, arrowBaseScale, cgs.media.mAutomapRocketIcon );
}
break;
case ET_PLAYER:
{
vec4_t color;
cl = &cgs.clientinfo[ cent->currentState.number ];
// not valid then dont draw it
if ( !cl->infoValid )
{
continue;
}
VectorCopy4 ( teamColor, color );
arrowBaseScale = 16.0f;
zScale = 1.0f;
// Pulse the radar icon after a voice message
if ( cent->vChatTime + 2000 > cg.time )
{
float f = (cent->vChatTime + 2000 - cg.time) / 3000.0f;
arrowBaseScale = 16.0f + 4.0f * f;
color[0] = teamColor[0] + (1.0f - teamColor[0]) * f;
color[1] = teamColor[1] + (1.0f - teamColor[1]) * f;
color[2] = teamColor[2] + (1.0f - teamColor[2]) * f;
}
trap_R_SetColor ( color );
//we want to scale the thing up/down based on the relative Z (up/down) positioning
if (cent->lerpOrigin[2] > cg.predictedPlayerState.origin[2])
{ //higher, scale up (between 16 and 32)
float dif = (cent->lerpOrigin[2] - cg.predictedPlayerState.origin[2]);
//max out to 2x scale at 1024 units above local player's height
dif /= 1024.0f;
if (dif > 1.0f)
{
dif = 1.0f;
}
zScale += dif;
}
else if (cent->lerpOrigin[2] < cg.predictedPlayerState.origin[2])
{ //lower, scale down (between 16 and 8)
float dif = (cg.predictedPlayerState.origin[2] - cent->lerpOrigin[2]);
//half scale at 512 units below local player's height
dif /= 1024.0f;
if (dif > 0.5f)
{
dif = 0.5f;
}
zScale -= dif;
}
arrowBaseScale *= zScale;
arrow_w = arrowBaseScale * RADAR_RADIUS / 128;
arrow_h = arrowBaseScale * RADAR_RADIUS / 128;
CG_DrawRotatePic2( RADAR_X + RADAR_RADIUS + sin (angle) * distance + xOffset,
y + RADAR_RADIUS + cos (angle) * distance,
arrow_w, arrow_h,
(360 - cent->lerpAngles[YAW]) + cg.predictedPlayerState.viewangles[YAW], cgs.media.mAutomapPlayerIcon );
break;
}
}
}
arrowBaseScale = 16.0f;
arrow_w = arrowBaseScale * RADAR_RADIUS / 128;
arrow_h = arrowBaseScale * RADAR_RADIUS / 128;
trap_R_SetColor ( colorWhite );
CG_DrawRotatePic2( RADAR_X + RADAR_RADIUS + xOffset, y + RADAR_RADIUS, arrow_w, arrow_h,
0, cgs.media.mAutomapPlayerIcon );
return y+(RADAR_RADIUS*2);
}
/*
=================
CG_DrawTimer
=================
*/
static float CG_DrawTimer( float y ) {
char *s;
int w;
int mins, seconds, tens;
int msec;
int xOffset = 0;
msec = cg.time - cgs.levelStartTime;
seconds = msec / 1000;
mins = seconds / 60;
seconds -= mins * 60;
tens = seconds / 10;
seconds -= tens * 10;
s = va( "%i:%i%i", mins, tens, seconds );
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString( 635 - w + xOffset, y + 2, s, 1.0F);
return y + BIGCHAR_HEIGHT + 4;
}
/*
=================
CG_DrawTeamOverlay
=================
*/
extern const char *CG_GetLocationString(const char *loc); //cg_main.c
static float CG_DrawTeamOverlay( float y, qboolean right, qboolean upper ) {
int x, w, h, xx;
int i, j, len;
const char *p;
vec4_t hcolor;
int pwidth, lwidth;
int plyrs;
char st[16];
clientInfo_t *ci;
gitem_t *item;
int ret_y, count;
int xOffset = 0;
if ( !cg_drawTeamOverlay.integer ) {
return y;
}
if ( cg.snap->ps.persistant[PERS_TEAM] != TEAM_RED && cg.snap->ps.persistant[PERS_TEAM] != TEAM_BLUE ) {
return y; // Not on any team
}
plyrs = 0;
// max player name width
pwidth = 0;
count = (numSortedTeamPlayers > 8) ? 8 : numSortedTeamPlayers;
for (i = 0; i < count; i++) {
ci = cgs.clientinfo + sortedTeamPlayers[i];
if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) {
plyrs++;
len = CG_DrawStrlen(ci->name);
if (len > pwidth)
pwidth = len;
}
}
if (!plyrs)
return y;
if (pwidth > TEAM_OVERLAY_MAXNAME_WIDTH)
pwidth = TEAM_OVERLAY_MAXNAME_WIDTH;
// max location name width
lwidth = 0;
for (i = 1; i < MAX_LOCATIONS; i++) {
p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+i));
if (p && *p) {
len = CG_DrawStrlen(p);
if (len > lwidth)
lwidth = len;
}
}
if (lwidth > TEAM_OVERLAY_MAXLOCATION_WIDTH)
lwidth = TEAM_OVERLAY_MAXLOCATION_WIDTH;
w = (pwidth + lwidth + 4 + 7) * TINYCHAR_WIDTH;
if ( right )
x = SCREEN_WIDTH - w;
else
x = 0;
h = plyrs * TINYCHAR_HEIGHT;
if ( upper ) {
ret_y = y + h;
} else {
y -= h;
ret_y = y;
}
if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_RED ) {
hcolor[0] = 1.0f;
hcolor[1] = 0.0f;
hcolor[2] = 0.0f;
hcolor[3] = 0.33f;
} else { // if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_BLUE )
hcolor[0] = 0.0f;
hcolor[1] = 0.0f;
hcolor[2] = 1.0f;
hcolor[3] = 0.33f;
}
trap_R_SetColor( hcolor );
CG_DrawPic( x + xOffset, y, w, h, cgs.media.teamStatusBar );
trap_R_SetColor( NULL );
for (i = 0; i < count; i++) {
ci = cgs.clientinfo + sortedTeamPlayers[i];
if ( ci->infoValid && ci->team == cg.snap->ps.persistant[PERS_TEAM]) {
hcolor[0] = hcolor[1] = hcolor[2] = hcolor[3] = 1.0;
xx = x + TINYCHAR_WIDTH;
CG_DrawStringExt( xx + xOffset, y,
ci->name, hcolor, qfalse, qfalse,
TINYCHAR_WIDTH, TINYCHAR_HEIGHT, TEAM_OVERLAY_MAXNAME_WIDTH);
if (lwidth) {
p = CG_GetLocationString(CG_ConfigString(CS_LOCATIONS+ci->location));
if (!p || !*p)
p = "unknown";
len = CG_DrawStrlen(p);
if (len > lwidth)
len = lwidth;
// xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth +
// ((lwidth/2 - len/2) * TINYCHAR_WIDTH);
xx = x + TINYCHAR_WIDTH * 2 + TINYCHAR_WIDTH * pwidth;
CG_DrawStringExt( xx + xOffset, y,
p, hcolor, qfalse, qfalse, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
TEAM_OVERLAY_MAXLOCATION_WIDTH);
}
CG_GetColorForHealth( ci->health, ci->armor, hcolor );
Com_sprintf (st, sizeof(st), "%3i %3i", ci->health, ci->armor);
xx = x + TINYCHAR_WIDTH * 3 +
TINYCHAR_WIDTH * pwidth + TINYCHAR_WIDTH * lwidth;
CG_DrawStringExt( xx + xOffset, y,
st, hcolor, qfalse, qfalse,
TINYCHAR_WIDTH, TINYCHAR_HEIGHT, 0 );
// draw weapon icon
xx += TINYCHAR_WIDTH * 3;
if ( cg_weapons[ci->curWeapon].weaponIcon ) {
CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
cg_weapons[ci->curWeapon].weaponIcon );
} else {
CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
cgs.media.deferShader );
}
// Draw powerup icons
if (right) {
xx = x;
} else {
xx = x + w - TINYCHAR_WIDTH;
}
for (j = 0; j <= PW_NUM_POWERUPS; j++) {
if (ci->powerups & (1 << j)) {
item = BG_FindItemForPowerup( j );
if (item) {
CG_DrawPic( xx + xOffset, y, TINYCHAR_WIDTH, TINYCHAR_HEIGHT,
trap_R_RegisterShader( item->icon ) );
if (right) {
xx -= TINYCHAR_WIDTH;
} else {
xx += TINYCHAR_WIDTH;
}
}
}
}
y += TINYCHAR_HEIGHT;
}
}
return ret_y;
//#endif
}
static void CG_DrawPowerupIcons(int y)
{
int j;
int ico_size = 64;
//int y = ico_size/2;
int xOffset = 0;
gitem_t *item;
if (!cg.snap)
{
return;
}
y += 16;
for (j = 0; j <= PW_NUM_POWERUPS; j++)
{
if (cg.snap->ps.powerups[j] > cg.time)
{
int secondsleft = (cg.snap->ps.powerups[j] - cg.time)/1000;
item = BG_FindItemForPowerup( j );
if (item)
{
int icoShader = 0;
if (cgs.gametype == GT_CTY && (j == PW_REDFLAG || j == PW_BLUEFLAG))
{
if (j == PW_REDFLAG)
{
icoShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" );
}
else
{
icoShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" );
}
}
else
{
icoShader = trap_R_RegisterShader( item->icon );
}
CG_DrawPic( (SCREEN_WIDTH-(ico_size*1.1)) + xOffset, y, ico_size, ico_size, icoShader );
y += ico_size;
if (j != PW_REDFLAG && j != PW_BLUEFLAG && secondsleft < 999)
{
UI_DrawProportionalString((SCREEN_WIDTH-(ico_size*1.1))+(ico_size/2) + xOffset, y-8, va("%i", secondsleft), UI_CENTER | UI_BIGFONT | UI_DROPSHADOW, colorTable[CT_WHITE]);
}
y += (ico_size/3);
}
}
}
}
/*
=====================
CG_DrawUpperRight
=====================
*/
static void CG_DrawUpperRight( void ) {
float y=0;
trap_R_SetColor( colorTable[CT_WHITE] );
//[CoOp]
//allow overlays in CoOp.
if ( cgs.gametype >= GT_SINGLE_PLAYER && cg_drawTeamOverlay.integer == 1 ) {
//if ( cgs.gametype >= GT_TEAM && cg_drawTeamOverlay.integer == 1 ) {
//[/CoOp]
y = CG_DrawTeamOverlay( y, qtrue, qtrue );
}
if ( cg_drawSnapshot.integer ) {
y = CG_DrawSnapshot( y );
}
if ( cg_drawFPS.integer ) {
y = CG_DrawFPS( y );
}
if ( cg_drawTimer.integer ) {
y = CG_DrawTimer( y );
}
if ( ( cgs.gametype >= GT_TEAM || cg.predictedPlayerState.m_iVehicleNum )
&& cg_drawRadar.integer )
{//draw Radar in Siege mode or when in a vehicle of any kind
y = CG_DrawRadar ( y );
}
y = CG_DrawEnemyInfo ( y );
y = CG_DrawMiniScoreboard ( y );
y = CG_DrawAddText(y);
CG_DrawPowerupIcons(y);
}
/*
===================
CG_DrawReward
===================
*/
#ifdef JK2AWARDS
static void CG_DrawReward( void ) {
float *color;
int i, count;
float x, y;
char buf[32];
if ( !cg_drawRewards.integer ) {
return;
}
color = CG_FadeColor( cg.rewardTime, REWARD_TIME );
if ( !color ) {
if (cg.rewardStack > 0) {
for(i = 0; i < cg.rewardStack; i++) {
cg.rewardSound[i] = cg.rewardSound[i+1];
cg.rewardShader[i] = cg.rewardShader[i+1];
cg.rewardCount[i] = cg.rewardCount[i+1];
}
cg.rewardTime = cg.time;
cg.rewardStack--;
color = CG_FadeColor( cg.rewardTime, REWARD_TIME );
trap_S_StartLocalSound(cg.rewardSound[0], CHAN_ANNOUNCER);
} else {
return;
}
}
trap_R_SetColor( color );
if ( cg.rewardCount[0] >= 10 ) {
y = 56;
x = 320 - ICON_SIZE/2;
CG_DrawPic( x, y, ICON_SIZE-4, ICON_SIZE-4, cg.rewardShader[0] );
Com_sprintf(buf, sizeof(buf), "%d", cg.rewardCount[0]);
x = ( SCREEN_WIDTH - SMALLCHAR_WIDTH * CG_DrawStrlen( buf ) ) / 2;
CG_DrawStringExt( x, y+ICON_SIZE, buf, color, qfalse, qtrue,
SMALLCHAR_WIDTH, SMALLCHAR_HEIGHT, 0 );
}
else {
count = cg.rewardCount[0];
y = 56;
x = 320 - count * ICON_SIZE/2;
for ( i = 0 ; i < count ; i++ ) {
CG_DrawPic( x, y, ICON_SIZE-4, ICON_SIZE-4, cg.rewardShader[0] );
x += ICON_SIZE;
}
}
trap_R_SetColor( NULL );
}
#endif
/*
===============================================================================
LAGOMETER
===============================================================================
*/
#define LAG_SAMPLES 128
typedef struct {
int frameSamples[LAG_SAMPLES];
int frameCount;
int snapshotFlags[LAG_SAMPLES];
int snapshotSamples[LAG_SAMPLES];
int snapshotCount;
} lagometer_t;
lagometer_t lagometer;
/*
==============
CG_AddLagometerFrameInfo
Adds the current interpolate / extrapolate bar for this frame
==============
*/
void CG_AddLagometerFrameInfo( void ) {
int offset;
offset = cg.time - cg.latestSnapshotTime;
lagometer.frameSamples[ lagometer.frameCount & ( LAG_SAMPLES - 1) ] = offset;
lagometer.frameCount++;
}
/*
==============
CG_AddLagometerSnapshotInfo
Each time a snapshot is received, log its ping time and
the number of snapshots that were dropped before it.
Pass NULL for a dropped packet.
==============
*/
void CG_AddLagometerSnapshotInfo( snapshot_t *snap ) {
// dropped packet
if ( !snap ) {
lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = -1;
lagometer.snapshotCount++;
return;
}
// add this snapshot's info
lagometer.snapshotSamples[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->ping;
lagometer.snapshotFlags[ lagometer.snapshotCount & ( LAG_SAMPLES - 1) ] = snap->snapFlags;
lagometer.snapshotCount++;
}
/*
==============
CG_DrawDisconnect
Should we draw something differnet for long lag vs no packets?
==============
*/
static void CG_DrawDisconnect( void ) {
float x, y;
int cmdNum;
usercmd_t cmd;
const char *s;
int w; // bk010215 - FIXME char message[1024];
if (cg.mMapChange)
{
s = CG_GetStringEdString("MP_INGAME", "SERVER_CHANGING_MAPS"); // s = "Server Changing Maps";
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString( 320 - w/2, 100, s, 1.0F);
s = CG_GetStringEdString("MP_INGAME", "PLEASE_WAIT"); // s = "Please wait...";
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString( 320 - w/2, 200, s, 1.0F);
return;
}
// draw the phone jack if we are completely past our buffers
cmdNum = trap_GetCurrentCmdNumber() - CMD_BACKUP + 1;
trap_GetUserCmd( cmdNum, &cmd );
if ( cmd.serverTime <= cg.snap->ps.commandTime
|| cmd.serverTime > cg.time ) { // special check for map_restart // bk 0102165 - FIXME
return;
}
// also add text in center of screen
s = CG_GetStringEdString("MP_INGAME", "CONNECTION_INTERRUPTED"); // s = "Connection Interrupted"; // bk 010215 - FIXME
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString( 320 - w/2, 100, s, 1.0F);
// blink the icon
if ( ( cg.time >> 9 ) & 1 ) {
return;
}
x = SCREEN_WIDTH - 48;
y = SCREEN_HEIGHT - 48;
CG_DrawPic( x, y, 48, 48, trap_R_RegisterShader("gfx/2d/net.tga" ) );
}
#define MAX_LAGOMETER_PING 900
#define MAX_LAGOMETER_RANGE 300
/*
==============
CG_DrawLagometer
==============
*/
static void CG_DrawLagometer( void ) {
int a, x, y, i;
float v;
float ax, ay, aw, ah, mid, range;
int color;
float vscale;
if ( !cg_lagometer.integer || cgs.localServer ) {
CG_DrawDisconnect();
return;
}
//
// draw the graph
//
x = SCREEN_WIDTH - 48;
y = SCREEN_HEIGHT - 144;
trap_R_SetColor( NULL );
CG_DrawPic( x, y, 48, 48, cgs.media.lagometerShader );
ax = x;
ay = y;
aw = 48;
ah = 48;
color = -1;
range = ah / 3;
mid = ay + range;
vscale = range / MAX_LAGOMETER_RANGE;
// draw the frame interpoalte / extrapolate graph
for ( a = 0 ; a < aw ; a++ ) {
i = ( lagometer.frameCount - 1 - a ) & (LAG_SAMPLES - 1);
v = lagometer.frameSamples[i];
v *= vscale;
if ( v > 0 ) {
if ( color != 1 ) {
color = 1;
trap_R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] );
}
if ( v > range ) {
v = range;
}
trap_R_DrawStretchPic ( ax + aw - a, mid - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader );
} else if ( v < 0 ) {
if ( color != 2 ) {
color = 2;
trap_R_SetColor( g_color_table[ColorIndex(COLOR_BLUE)] );
}
v = -v;
if ( v > range ) {
v = range;
}
trap_R_DrawStretchPic( ax + aw - a, mid, 1, v, 0, 0, 0, 0, cgs.media.whiteShader );
}
}
// draw the snapshot latency / drop graph
range = ah / 2;
vscale = range / MAX_LAGOMETER_PING;
for ( a = 0 ; a < aw ; a++ ) {
i = ( lagometer.snapshotCount - 1 - a ) & (LAG_SAMPLES - 1);
v = lagometer.snapshotSamples[i];
if ( v > 0 ) {
if ( lagometer.snapshotFlags[i] & SNAPFLAG_RATE_DELAYED ) {
if ( color != 5 ) {
color = 5; // YELLOW for rate delay
trap_R_SetColor( g_color_table[ColorIndex(COLOR_YELLOW)] );
}
} else {
if ( color != 3 ) {
color = 3;
trap_R_SetColor( g_color_table[ColorIndex(COLOR_GREEN)] );
}
}
v = v * vscale;
if ( v > range ) {
v = range;
}
trap_R_DrawStretchPic( ax + aw - a, ay + ah - v, 1, v, 0, 0, 0, 0, cgs.media.whiteShader );
} else if ( v < 0 ) {
if ( color != 4 ) {
color = 4; // RED for dropped snapshots
trap_R_SetColor( g_color_table[ColorIndex(COLOR_RED)] );
}
trap_R_DrawStretchPic( ax + aw - a, ay + ah - range, 1, range, 0, 0, 0, 0, cgs.media.whiteShader );
}
}
trap_R_SetColor( NULL );
if ( cg_nopredict.integer || cg_synchronousClients.integer ) {
CG_DrawBigString( ax, ay, "snc", 1.0 );
}
CG_DrawDisconnect();
}
void CG_DrawSiegeMessage( const char *str, int objectiveScreen )
{
// if (!( trap_Key_GetCatcher() & KEYCATCH_UI ))
{
trap_OpenUIMenu(UIMENU_CLOSEALL);
trap_Cvar_Set("cg_siegeMessage", str);
if (objectiveScreen)
{
trap_OpenUIMenu(UIMENU_SIEGEOBJECTIVES);
}
else
{
trap_OpenUIMenu(UIMENU_SIEGEMESSAGE);
}
}
}
void CG_DrawSiegeMessageNonMenu( const char *str )
{
char text[1024];
if (str[0]=='@')
{
trap_SP_GetStringTextString(str+1, text, sizeof(text));
str = text;
}
//[Asteroids]
CG_CenterPrint(str, SCREEN_HEIGHT * 0.20, BIGCHAR_WIDTH);
// CG_CenterPrint(str, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH);
//[/Asteroids]
}
/*
===============================================================================
CENTER PRINTING
===============================================================================
*/
/*
==============
CG_CenterPrint
Called for important messages that should stay in the center of the screen
for a few moments
==============
*/
void CG_CenterPrint( const char *str, int y, int charWidth ) {
char *s;
//[BugFix19]
int i = 0;
//[/BugFix19]
Q_strncpyz( cg.centerPrint, str, sizeof(cg.centerPrint) );
cg.centerPrintTime = cg.time;
cg.centerPrintY = y;
cg.centerPrintCharWidth = charWidth;
// count the number of lines for centering
cg.centerPrintLines = 1;
s = cg.centerPrint;
while( *s )
{
//[BugFix19]
i++;
if(i >= 50)
{//maxed out a line of text, this will make the line spill over onto another line.
i = 0;
cg.centerPrintLines++;
}
else if (*s == '\n')
//if (*s == '\n')
//[/BugFix19]
cg.centerPrintLines++;
s++;
}
}
/*
===================
CG_DrawCenterString
===================
*/
static void CG_DrawCenterString( void ) {
char *start;
int l;
int x, y, w;
int h;
float *color;
const float scale = 1.0; //0.5
if ( !cg.centerPrintTime ) {
return;
}
color = CG_FadeColor( cg.centerPrintTime, 1000 * cg_centertime.value );
if ( !color ) {
return;
}
trap_R_SetColor( color );
start = cg.centerPrint;
y = cg.centerPrintY - cg.centerPrintLines * BIGCHAR_HEIGHT / 2;
while ( 1 )
{
char linebuffer[1024];
for ( l = 0; l < 50; l++ )
{
if ( !start[l] || start[l] == '\n' )
{
break;
}
linebuffer[l] = start[l];
}
linebuffer[l] = 0;
//[BugFix19]
if(!BG_IsWhiteSpace(start[l]) && !BG_IsWhiteSpace(linebuffer[l-1]) )
{//we might have cut a word off, attempt to find a spot where we won't cut words off at.
int savedL = l;
int counter = l-2;
for(; counter >= 0; counter--)
{
if(BG_IsWhiteSpace(start[counter]))
{//this location is whitespace, line break from this position
linebuffer[counter] = 0;
l = counter + 1;
break;
}
}
if(counter < 0)
{//couldn't find a break in the text, just go ahead and cut off the word mid-word.
l = savedL;
}
}
//[/BugFix19]
w = CG_Text_Width(linebuffer, scale, FONT_MEDIUM);
h = CG_Text_Height(linebuffer, scale, FONT_MEDIUM);
x = (SCREEN_WIDTH - w) / 2;
CG_Text_Paint(x, y + h, scale, color, linebuffer, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM);
y += h + 6;
//[BugFix19]
//this method of advancing to new line from the start of the array was causing long lines without
//new lines to be totally truncated.
if(start[l] && start[l] == '\n')
{//next char is a newline, advance past
l++;
}
if ( !start[l] )
{//end of string, we're done.
break;
}
//advance pointer to the last character that we didn't read in.
start = &start[l];
//[/BugFix19]
}
trap_R_SetColor( NULL );
}
/*
================================================================================
CROSSHAIR
================================================================================
*/
#define HEALTH_WIDTH 50.0f
#define HEALTH_HEIGHT 5.0f
//see if we can draw some extra info on this guy based on our class
void CG_DrawSiegeInfo(centity_t *cent, float chX, float chY, float chW, float chH)
{
siegeExtended_t *se = &cg_siegeExtendedData[cent->currentState.number];
clientInfo_t *ci;
const char *configstring, *v;
siegeClass_t *siegeClass;
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x;
float y;
float percent;
int ammoMax;
assert(cent->currentState.number < MAX_CLIENTS);
if (se->lastUpdated > cg.time)
{ //strange, shouldn't happen
return;
}
if ((cg.time - se->lastUpdated) > 10000)
{ //if you haven't received a status update on this guy in 10 seconds, forget about it
return;
}
if (cent->currentState.eFlags & EF_DEAD)
{ //he's dead, don't display info on him
return;
}
if (cent->currentState.weapon != se->weapon)
{ //data is invalidated until it syncs back again
return;
}
ci = &cgs.clientinfo[cent->currentState.number];
if (ci->team != cg.predictedPlayerState.persistant[PERS_TEAM])
{ //not on the same team
return;
}
configstring = CG_ConfigString( cg.predictedPlayerState.clientNum + CS_PLAYERS );
v = Info_ValueForKey( configstring, "siegeclass" );
if (!v || !v[0])
{ //don't have siege class in info?
return;
}
siegeClass = BG_SiegeFindClassByName(v);
if (!siegeClass)
{ //invalid
return;
}
if (!(siegeClass->classflags & (1<<CFL_STATVIEWER)))
{ //doesn't really have the ability to see others' stats
return;
}
x = chX+((chW/2)-(HEALTH_WIDTH/2));
y = (chY+chH) + 8.0f;
percent = ((float)se->health/(float)se->maxhealth)*HEALTH_WIDTH;
//color of the bar
aColor[0] = 0.0f;
aColor[1] = 1.0f;
aColor[2] = 0.0f;
aColor[3] = 0.4f;
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing health"
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.4f;
//draw the background (black)
CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor);
//then draw the other part greyed out
CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor);
//now draw his ammo
ammoMax = ammoData[weaponData[cent->currentState.weapon].ammoIndex].max;
if ( (cent->currentState.eFlags & EF_DOUBLE_AMMO) )
{
ammoMax *= 2;
}
x = chX+((chW/2)-(HEALTH_WIDTH/2));
y = (chY+chH) + HEALTH_HEIGHT + 10.0f;
if (!weaponData[cent->currentState.weapon].energyPerShot &&
!weaponData[cent->currentState.weapon].altEnergyPerShot)
{ //a weapon that takes no ammo, so show full
percent = HEALTH_WIDTH;
}
else
{
percent = ((float)se->ammo/(float)ammoMax)*HEALTH_WIDTH;
}
//color of the bar
aColor[0] = 1.0f;
aColor[1] = 1.0f;
aColor[2] = 0.0f;
aColor[3] = 0.4f;
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing health"
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.4f;
//draw the background (black)
CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor);
//then draw the other part greyed out
CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor);
}
//draw the health bar based on current "health" and maxhealth
void CG_DrawHealthBar(centity_t *cent, float chX, float chY, float chW, float chH)
{
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x = chX+((chW/2)-(HEALTH_WIDTH/2));
float y = (chY+chH) + 8.0f;
float percent = ((float)cent->currentState.health/(float)cent->currentState.maxhealth)*HEALTH_WIDTH;
if (percent <= 0)
{
return;
}
//color of the bar
if (!cent->currentState.teamowner || cgs.gametype < GT_TEAM)
{ //not owned by a team or teamplay
aColor[0] = 1.0f;
aColor[1] = 1.0f;
aColor[2] = 0.0f;
aColor[3] = 0.4f;
}
else if (cent->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM])
{ //owned by my team
aColor[0] = 0.0f;
aColor[1] = 1.0f;
aColor[2] = 0.0f;
aColor[3] = 0.4f;
}
else
{ //hostile
aColor[0] = 1.0f;
aColor[1] = 0.0f;
aColor[2] = 0.0f;
aColor[3] = 0.4f;
}
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing health"
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.4f;
//draw the background (black)
CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor);
//then draw the other part greyed out
CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor);
}
//same routine (at least for now), draw progress of a "hack" or whatever
void CG_DrawHaqrBar(float chX, float chY, float chW, float chH)
{
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x = chX+((chW/2)-(HEALTH_WIDTH/2));
float y = (chY+chH) + 8.0f;
float percent = (((float)cg.predictedPlayerState.hackingTime-(float)cg.time)/(float)cg.predictedPlayerState.hackingBaseTime)*HEALTH_WIDTH;
if (percent > HEALTH_WIDTH ||
percent < 1.0f)
{
return;
}
//color of the bar
aColor[0] = 1.0f;
aColor[1] = 1.0f;
aColor[2] = 0.0f;
aColor[3] = 0.4f;
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out done area
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.1f;
//draw the background (black)
CG_DrawRect(x, y, HEALTH_WIDTH, HEALTH_HEIGHT, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, y+1.0f, percent-1.0f, HEALTH_HEIGHT-1.0f, aColor);
//then draw the other part greyed out
CG_FillRect(x+percent, y+1.0f, HEALTH_WIDTH-percent-1.0f, HEALTH_HEIGHT-1.0f, cColor);
//draw the hacker icon
CG_DrawPic(x, y-HEALTH_WIDTH, HEALTH_WIDTH, HEALTH_WIDTH, cgs.media.hackerIconShader);
}
//generic timing bar
int cg_genericTimerBar = 0;
int cg_genericTimerDur = 0;
vec4_t cg_genericTimerColor;
#define CGTIMERBAR_H 50.0f
#define CGTIMERBAR_W 10.0f
#define CGTIMERBAR_X (SCREEN_WIDTH-CGTIMERBAR_W-120.0f)
#define CGTIMERBAR_Y (SCREEN_HEIGHT-CGTIMERBAR_H-20.0f)
void CG_DrawGenericTimerBar(void)
{
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x = CGTIMERBAR_X;
float y = CGTIMERBAR_Y;
float percent = ((float)(cg_genericTimerBar-cg.time)/(float)cg_genericTimerDur)*CGTIMERBAR_H;
if (percent > CGTIMERBAR_H)
{
return;
}
if (percent < 0.1f)
{
percent = 0.1f;
}
//color of the bar
aColor[0] = cg_genericTimerColor[0];
aColor[1] = cg_genericTimerColor[1];
aColor[2] = cg_genericTimerColor[2];
aColor[3] = cg_genericTimerColor[3];
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing fuel"
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.1f;
//draw the background (black)
CG_DrawRect(x, y, CGTIMERBAR_W, CGTIMERBAR_H, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, y+1.0f+(CGTIMERBAR_H-percent), CGTIMERBAR_W-2.0f, CGTIMERBAR_H-1.0f-(CGTIMERBAR_H-percent), aColor);
//then draw the other part greyed out
CG_FillRect(x+1.0f, y+1.0f, CGTIMERBAR_W-2.0f, CGTIMERBAR_H-percent, cColor);
}
/*
=================
CG_DrawCrosshair
=================
*/
float cg_crosshairPrevPosX = 0;
float cg_crosshairPrevPosY = 0;
#define CRAZY_CROSSHAIR_MAX_ERROR_X (100.0f*SCREEN_WIDTH/SCREEN_HEIGHT)
#define CRAZY_CROSSHAIR_MAX_ERROR_Y (100.0f)
void CG_LerpCrosshairPos( float *x, float *y )
{
if ( cg_crosshairPrevPosX )
{//blend from old pos
float maxMove = 30.0f * ((float)cg.frametime/500.0f) * SCREEN_WIDTH/SCREEN_HEIGHT;
float xDiff = (*x - cg_crosshairPrevPosX);
if ( fabs(xDiff) > CRAZY_CROSSHAIR_MAX_ERROR_X )
{
maxMove = CRAZY_CROSSHAIR_MAX_ERROR_X;
}
if ( xDiff > maxMove )
{
*x = cg_crosshairPrevPosX + maxMove;
}
else if ( xDiff < -maxMove )
{
*x = cg_crosshairPrevPosX - maxMove;
}
}
cg_crosshairPrevPosX = *x;
if ( cg_crosshairPrevPosY )
{//blend from old pos
float maxMove = 30.0f * ((float)cg.frametime/500.0f);
float yDiff = (*y - cg_crosshairPrevPosY);
if ( fabs(yDiff) > CRAZY_CROSSHAIR_MAX_ERROR_Y )
{
maxMove = CRAZY_CROSSHAIR_MAX_ERROR_X;
}
if ( yDiff > maxMove )
{
*y = cg_crosshairPrevPosY + maxMove;
}
else if ( yDiff < -maxMove )
{
*y = cg_crosshairPrevPosY - maxMove;
}
}
cg_crosshairPrevPosY = *y;
}
vec3_t cg_crosshairPos={0,0,0};
//[CoOp]
extern qboolean in_camera;
//[/CoOp]
static void CG_DrawCrosshair( vec3_t worldPoint, int chEntValid ) {
float w, h;
qhandle_t hShader = 0;
float f;
float x, y;
qboolean corona = qfalse;
vec4_t ecolor = {0,0,0,0};
centity_t *crossEnt = NULL;
float chX, chY;
//[CoOp]
if(in_camera)
{//no crosshair while in cutscenes
return;
}
//[/CoOp]
if ( worldPoint )
{
VectorCopy( worldPoint, cg_crosshairPos );
}
if ( !cg_drawCrosshair.integer )
{
return;
}
if (cg.snap->ps.fallingToDeath)
{
return;
}
if ( cg.predictedPlayerState.zoomMode != 0 && cg.predictedPlayerState.weapon != WP_BOWCASTER )
{//not while scoped
return;
}
if ( cg_crosshairHealth.integer )
{
vec4_t hcolor;
CG_ColorForHealth( hcolor );
trap_R_SetColor( hcolor );
}
else
{
//set color based on what kind of ent is under crosshair
if ( cg.crosshairClientNum >= ENTITYNUM_WORLD )
{
trap_R_SetColor( NULL );
}
//rwwFIXMEFIXME: Write this a different way, it's getting a bit too sloppy looking
else if (chEntValid &&
(cg_entities[cg.crosshairClientNum].currentState.number < MAX_CLIENTS ||
cg_entities[cg.crosshairClientNum].currentState.eType == ET_NPC ||
cg_entities[cg.crosshairClientNum].currentState.shouldtarget ||
cg_entities[cg.crosshairClientNum].currentState.health || //always show ents with health data under crosshair
(cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.bolt1 && cg.predictedPlayerState.weapon == WP_SABER) ||
(cg_entities[cg.crosshairClientNum].currentState.eType == ET_MOVER && cg_entities[cg.crosshairClientNum].currentState.teamowner)))
{
crossEnt = &cg_entities[cg.crosshairClientNum];
if ( crossEnt->currentState.powerups & (1 <<PW_CLOAKED) )
{ //don't show up for cloaked guys
ecolor[0] = 1.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 1.0;//B
}
else if ( crossEnt->currentState.number < MAX_CLIENTS )
{
//[CoOp]
//make other players show as allies in CoOp
//if (cgs.gametype >= GT_TEAM &&
if (cgs.gametype >= GT_SINGLE_PLAYER &&
//[/CoOp]
cgs.clientinfo[crossEnt->currentState.number].team == cgs.clientinfo[cg.snap->ps.clientNum].team )
{
//Allies are green
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else
{
if (cgs.gametype == GT_POWERDUEL &&
cgs.clientinfo[crossEnt->currentState.number].duelTeam == cgs.clientinfo[cg.snap->ps.clientNum].duelTeam)
{ //on the same duel team in powerduel, so he's a friend
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else
{ //Enemies are red
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
}
if (cg.snap->ps.duelInProgress)
{
if (crossEnt->currentState.number != cg.snap->ps.duelIndex)
{ //grey out crosshair for everyone but your foe if you're in a duel
ecolor[0] = 0.4;
ecolor[1] = 0.4;
ecolor[2] = 0.4;
}
}
else if (crossEnt->currentState.bolt1)
{ //this fellow is in a duel. We just checked if we were in a duel above, so
//this means we aren't and he is. Which of course means our crosshair greys out over him.
ecolor[0] = 0.4;
ecolor[1] = 0.4;
ecolor[2] = 0.4;
}
}
else if (crossEnt->currentState.shouldtarget || crossEnt->currentState.eType == ET_NPC)
{
//VectorCopy( crossEnt->startRGBA, ecolor );
if ( !ecolor[0] && !ecolor[1] && !ecolor[2] )
{
// We really don't want black, so set it to yellow
ecolor[0] = 1.0F;//R
ecolor[1] = 0.8F;//G
ecolor[2] = 0.3F;//B
}
if (crossEnt->currentState.eType == ET_NPC)
{
int plTeam;
if (cgs.gametype == GT_SIEGE)
{
plTeam = cg.predictedPlayerState.persistant[PERS_TEAM];
}
else
{
plTeam = NPCTEAM_PLAYER;
}
if ( crossEnt->currentState.powerups & (1 <<PW_CLOAKED) )
{
ecolor[0] = 1.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 1.0;//B
}
else if ( !crossEnt->currentState.teamowner )
{ //not on a team
if (!crossEnt->currentState.teamowner ||
crossEnt->currentState.NPC_class == CLASS_VEHICLE)
{ //neutral
if (crossEnt->currentState.owner < MAX_CLIENTS)
{ //base color on who is pilotting this thing
clientInfo_t *ci = &cgs.clientinfo[crossEnt->currentState.owner];
if (cgs.gametype >= GT_TEAM && ci->team == cg.predictedPlayerState.persistant[PERS_TEAM])
{ //friendly
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else
{ //hostile
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
}
else
{ //unmanned
ecolor[0] = 1.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
}
else
{
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
}
//[Grapple]
/*else if (crossEnt->currentState.eType == ET_GRAPPLE)
{
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}*/
else if ( crossEnt->currentState.teamowner != plTeam )
{// on enemy team
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
else
{ //a friend
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
}
else if ( crossEnt->currentState.teamowner == TEAM_RED
|| crossEnt->currentState.teamowner == TEAM_BLUE )
{
if (cgs.gametype < GT_TEAM)
{ //not teamplay, just neutral then
ecolor[0] = 1.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else if ( crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team )
{ //on the enemy team
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
else
{ //on my team
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
}
else if (crossEnt->currentState.owner == cg.snap->ps.clientNum ||
(cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner == cgs.clientinfo[cg.snap->ps.clientNum].team))
{
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else if (crossEnt->currentState.teamowner == 16 ||
(cgs.gametype >= GT_TEAM && crossEnt->currentState.teamowner && crossEnt->currentState.teamowner != cgs.clientinfo[cg.snap->ps.clientNum].team))
{
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
}
else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.bolt1 && cg.predictedPlayerState.weapon == WP_SABER)
{ //can push/pull this mover. Only show it if we're using the saber.
ecolor[0] = 0.2f;
ecolor[1] = 0.5f;
ecolor[2] = 1.0f;
corona = qtrue;
}
else if (crossEnt->currentState.eType == ET_MOVER && crossEnt->currentState.teamowner)
{ //a team owns this - if it's my team green, if not red, if not teamplay then yellow
if (cgs.gametype < GT_TEAM)
{
ecolor[0] = 1.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
else if (cg.predictedPlayerState.persistant[PERS_TEAM] != crossEnt->currentState.teamowner)
{ //not my team
ecolor[0] = 1.0;//R
ecolor[1] = 0.0;//G
ecolor[2] = 0.0;//B
}
else
{ //my team
ecolor[0] = 0.0;//R
ecolor[1] = 1.0;//G
ecolor[2] = 0.0;//B
}
}
else if (crossEnt->currentState.health)
{
if (!crossEnt->currentState.teamowner || cgs.gametype < GT_TEAM)
{ //not owned by a team or teamplay
ecolor[0] = 1.0f;
ecolor[1] = 1.0f;
ecolor[2] = 0.0f;
}
else if (crossEnt->currentState.teamowner == cg.predictedPlayerState.persistant[PERS_TEAM])
{ //owned by my team
ecolor[0] = 0.0f;
ecolor[1] = 1.0f;
ecolor[2] = 0.0f;
}
else
{ //hostile
ecolor[0] = 1.0f;
ecolor[1] = 0.0f;
ecolor[2] = 0.0f;
}
}
ecolor[3] = 1.0;
trap_R_SetColor( ecolor );
}
}
if ( cg.predictedPlayerState.m_iVehicleNum )
{//I'm in a vehicle
centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum];
if ( vehCent
&& vehCent->m_pVehicle
&& vehCent->m_pVehicle->m_pVehicleInfo
&& vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle )
{
hShader = vehCent->m_pVehicle->m_pVehicleInfo->crosshairShaderHandle;
}
//bigger by default
w = cg_crosshairSize.value*2.0f;
h = w;
}
else
{
w = h = cg_crosshairSize.value;
}
// pulse the size of the crosshair when picking up items
f = cg.time - cg.itemPickupBlendTime;
if ( f > 0 && f < ITEM_BLOB_TIME ) {
f /= ITEM_BLOB_TIME;
w *= ( 1 + f );
h *= ( 1 + f );
}
if ( worldPoint && VectorLength( worldPoint ) )
{
if ( !CG_WorldCoordToScreenCoordFloat( worldPoint, &x, &y ) )
{//off screen, don't draw it
return;
}
//CG_LerpCrosshairPos( &x, &y );
x -= 320;
y -= 240;
}
else
{
x = cg_crosshairX.integer;
y = cg_crosshairY.integer;
}
if ( !hShader )
{
hShader = cgs.media.crosshairShader[ cg_drawCrosshair.integer % NUM_CROSSHAIRS ];
}
chX = x + cg.refdef.x + 0.5 * (SCREEN_WIDTH - w);
chY = y + cg.refdef.y + 0.5 * (SCREEN_HEIGHT - h);
trap_R_DrawStretchPic( chX, chY, w, h, 0, 0, 1, 1, hShader );
//draw a health bar directly under the crosshair if we're looking at something
//that takes damage
if (crossEnt &&
crossEnt->currentState.maxhealth)
{
CG_DrawHealthBar(crossEnt, chX, chY, w, h);
chY += HEALTH_HEIGHT*2;
}
else if (crossEnt && crossEnt->currentState.number < MAX_CLIENTS)
{
if (cgs.gametype == GT_SIEGE)
{
CG_DrawSiegeInfo(crossEnt, chX, chY, w, h);
chY += HEALTH_HEIGHT*4;
}
if (cg.crosshairVehNum && cg.time == cg.crosshairVehTime)
{ //it was in the crosshair this frame
centity_t *hisVeh = &cg_entities[cg.crosshairVehNum];
if (hisVeh->currentState.eType == ET_NPC &&
hisVeh->currentState.NPC_class == CLASS_VEHICLE &&
hisVeh->currentState.maxhealth &&
hisVeh->m_pVehicle)
{ //draw the health for this vehicle
CG_DrawHealthBar(hisVeh, chX, chY, w, h);
chY += HEALTH_HEIGHT*2;
}
}
}
if (cg.predictedPlayerState.hackingTime)
{ //hacking something
CG_DrawHaqrBar(chX, chY, w, h);
}
if (cg_genericTimerBar > cg.time)
{ //draw generic timing bar, can be used for whatever
CG_DrawGenericTimerBar();
}
if ( corona ) // drawing extra bits
{
ecolor[3] = 0.5f;
ecolor[0] = ecolor[1] = ecolor[2] = (1 - ecolor[3]) * ( sin( cg.time * 0.001f ) * 0.08f + 0.35f ); // don't draw full color
ecolor[3] = 1.0f;
trap_R_SetColor( ecolor );
w *= 2.0f;
h *= 2.0f;
trap_R_DrawStretchPic( x + cg.refdef.x + 0.5 * (SCREEN_WIDTH - w),
y + cg.refdef.y + 0.5 * (SCREEN_HEIGHT - h),
w, h, 0, 0, 1, 1, cgs.media.forceCoronaShader );
}
}
qboolean CG_WorldCoordToScreenCoordFloat(vec3_t worldCoord, float *x, float *y)
{
float xcenter, ycenter;
vec3_t local, transformed;
vec3_t vfwd;
vec3_t vright;
vec3_t vup;
float xzi;
float yzi;
// xcenter = cg.refdef.width / 2;//gives screen coords adjusted for resolution
// ycenter = cg.refdef.height / 2;//gives screen coords adjusted for resolution
//NOTE: did it this way because most draw functions expect virtual 640x480 coords
// and adjust them for current resolution
xcenter = SCREEN_WIDTH / 2.0f;//gives screen coords in virtual 640x480, to be adjusted when drawn
ycenter = SCREEN_HEIGHT / 2.0f;//gives screen coords in virtual 640x480, to be adjusted when drawn
AngleVectors (cg.refdef.viewangles, vfwd, vright, vup);
VectorSubtract (worldCoord, cg.refdef.vieworg, local);
transformed[0] = DotProduct(local,vright);
transformed[1] = DotProduct(local,vup);
transformed[2] = DotProduct(local,vfwd);
// Make sure Z is not negative.
if(transformed[2] < 0.01f)
{
return qfalse;
}
xzi = xcenter / transformed[2] * (96.0f/cg.refdef.fov_x);
yzi = ycenter / transformed[2] * (102.0f/cg.refdef.fov_y);
*x = xcenter + xzi * transformed[0];
*y = ycenter - yzi * transformed[1];
return qtrue;
}
qboolean CG_WorldCoordToScreenCoord( vec3_t worldCoord, int *x, int *y )
{
float xF, yF;
qboolean retVal = CG_WorldCoordToScreenCoordFloat( worldCoord, &xF, &yF );
*x = (int)xF;
*y = (int)yF;
return retVal;
}
/*
====================
CG_SaberClashFlare
====================
*/
int cg_saberFlashTime = 0;
vec3_t cg_saberFlashPos = {0, 0, 0};
void CG_SaberClashFlare( void )
{
int t, maxTime = 150;
vec3_t dif;
vec3_t color;
int x,y;
float v, len;
trace_t tr;
t = cg.time - cg_saberFlashTime;
if ( t <= 0 || t >= maxTime )
{
return;
}
// Don't do clashes for things that are behind us
VectorSubtract( cg_saberFlashPos, cg.refdef.vieworg, dif );
if ( DotProduct( dif, cg.refdef.viewaxis[0] ) < 0.2 )
{
return;
}
CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, cg_saberFlashPos, -1, CONTENTS_SOLID );
if ( tr.fraction < 1.0f )
{
return;
}
len = VectorNormalize( dif );
// clamp to a known range
if ( len > 1200 )
{
return;
}
v = ( 1.0f - ((float)t / maxTime )) * ((1.0f - ( len / 800.0f )) * 2.0f + 0.35f);
if (v < 0.001f)
{
v = 0.001f;
}
CG_WorldCoordToScreenCoord( cg_saberFlashPos, &x, &y );
VectorSet( color, 0.8f, 0.8f, 0.8f );
trap_R_SetColor( color );
CG_DrawPic( x - ( v * 300 ), y - ( v * 300 ),
v * 600, v * 600,
trap_R_RegisterShader( "gfx/effects/saberFlare" ));
}
void CG_DottedLine( float x1, float y1, float x2, float y2, float dotSize, int numDots, vec4_t color, float alpha )
{
float x, y, xDiff, yDiff, xStep, yStep;
vec4_t colorRGBA;
int dotNum = 0;
VectorCopy4( color, colorRGBA );
colorRGBA[3] = alpha;
trap_R_SetColor( colorRGBA );
xDiff = x2-x1;
yDiff = y2-y1;
xStep = xDiff/(float)numDots;
yStep = yDiff/(float)numDots;
for ( dotNum = 0; dotNum < numDots; dotNum++ )
{
x = x1 + (xStep*dotNum) - (dotSize*0.5f);
y = y1 + (yStep*dotNum) - (dotSize*0.5f);
CG_DrawPic( x, y, dotSize, dotSize, cgs.media.whiteShader );
}
}
void CG_BracketEntity( centity_t *cent, float radius )
{
trace_t tr;
vec3_t dif;
float len, size, lineLength, lineWidth;
float x, y;
clientInfo_t *local;
qboolean isEnemy = qfalse;
VectorSubtract( cent->lerpOrigin, cg.refdef.vieworg, dif );
len = VectorNormalize( dif );
if ( cg.crosshairClientNum != cent->currentState.clientNum
&& (!cg.snap||cg.snap->ps.rocketLockIndex!= cent->currentState.clientNum) )
{//if they're the entity you're locking onto or under your crosshair, always draw bracket
//Hmm... for now, if they're closer than 2000, don't bracket?
if ( len < 2000.0f )
{
return;
}
CG_Trace( &tr, cg.refdef.vieworg, NULL, NULL, cent->lerpOrigin, -1, CONTENTS_OPAQUE );
//don't bracket if can't see them
if ( tr.fraction < 1.0f )
{
return;
}
}
if ( !CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y) )
{//off-screen, don't draw it
return;
}
//just to see if it's centered
//CG_DrawPic( x-2, y-2, 4, 4, cgs.media.whiteShader );
local = &cgs.clientinfo[cg.snap->ps.clientNum];
if ( cent->currentState.m_iVehicleNum //vehicle has a driver
&& cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].infoValid )
{
if ( cgs.gametype < GT_TEAM )
{//ffa?
isEnemy = qtrue;
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
}
else if ( cgs.clientinfo[ cent->currentState.m_iVehicleNum-1 ].team == local->team )
{
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_GREEN)] );
}
else
{
isEnemy = qtrue;
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
}
}
else if ( cent->currentState.teamowner )
{
if ( cgs.gametype < GT_TEAM )
{//ffa?
isEnemy = qtrue;
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
}
else if ( cent->currentState.teamowner != cg.predictedPlayerState.persistant[PERS_TEAM] )
{// on enemy team
isEnemy = qtrue;
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
}
else
{ //a friend
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_GREEN)] );
}
}
else
{//FIXME: if we want to ever bracket anything besides vehicles (like siege objectives we want to blow up), we should handle the coloring here
trap_R_SetColor ( NULL );
}
if ( len <= 1.0f )
{//super-close, max out at 400 times radius (which is HUGE)
size = radius*400.0f;
}
else
{//scale by dist
size = radius*(400.0f/len);
}
if ( size < 1.0f )
{
size = 1.0f;
}
//length scales with dist
lineLength = (size*0.1f);
if ( lineLength < 0.5f )
{//always visible
lineLength = 0.5f;
}
//always visible width
lineWidth = 1.0f;
x -= (size*0.5f);
y -= (size*0.5f);
{//brackets would be drawn on the screen, so draw them
//upper left corner
//horz
CG_DrawPic( x, y, lineLength, lineWidth, cgs.media.whiteShader );
//vert
CG_DrawPic( x, y, lineWidth, lineLength, cgs.media.whiteShader );
//upper right corner
//horz
CG_DrawPic( x+size-lineLength, y, lineLength, lineWidth, cgs.media.whiteShader );
//vert
CG_DrawPic( x+size-lineWidth, y, lineWidth, lineLength, cgs.media.whiteShader );
//lower left corner
//horz
CG_DrawPic( x, y+size-lineWidth, lineLength, lineWidth, cgs.media.whiteShader );
//vert
CG_DrawPic( x, y+size-lineLength, lineWidth, lineLength, cgs.media.whiteShader );
//lower right corner
//horz
CG_DrawPic( x+size-lineLength, y+size-lineWidth, lineLength, lineWidth, cgs.media.whiteShader );
//vert
CG_DrawPic( x+size-lineWidth, y+size-lineLength, lineWidth, lineLength, cgs.media.whiteShader );
}
//Lead Indicator...
if ( cg_drawVehLeadIndicator.integer )
{//draw the lead indicator
if ( isEnemy )
{//an enemy object
if ( cent->currentState.NPC_class == CLASS_VEHICLE )
{//enemy vehicle
if ( !VectorCompare( cent->currentState.pos.trDelta, vec3_origin ) )
{//enemy vehicle is moving
if ( cg.predictedPlayerState.m_iVehicleNum )
{//I'm in a vehicle
centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum];
if ( veh //vehicle cent
&& veh->m_pVehicle//vehicle
&& veh->m_pVehicle->m_pVehicleInfo//vehicle stats
&& veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE )//valid vehicle weapon
{
vehWeaponInfo_t *vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID];
if ( vehWeapon
&& vehWeapon->bIsProjectile//primary weapon's shot is a projectile
&& !vehWeapon->bHasGravity//primary weapon's shot is not affected by gravity
&& !vehWeapon->fHoming//primary weapon's shot is not homing
&& vehWeapon->fSpeed )//primary weapon's shot has speed
{//our primary weapon's projectile has a speed
vec3_t vehDiff, vehLeadPos;
float vehDist, eta;
float leadX, leadY;
VectorSubtract( cent->lerpOrigin, cg.predictedVehicleState.origin, vehDiff );
vehDist = VectorNormalize( vehDiff );
eta = (vehDist/vehWeapon->fSpeed);//how many seconds it would take for my primary weapon's projectile to get from my ship to theirs
//now extrapolate their position that number of seconds into the future based on their velocity
VectorMA( cent->lerpOrigin, eta, cent->currentState.pos.trDelta, vehLeadPos );
//now we have where we should be aiming at, project that onto the screen at a 2D co-ord
if ( !CG_WorldCoordToScreenCoordFloat(cent->lerpOrigin, &x, &y) )
{//off-screen, don't draw it
return;
}
if ( !CG_WorldCoordToScreenCoordFloat(vehLeadPos, &leadX, &leadY) )
{//off-screen, don't draw it
//just draw the line
CG_DottedLine( x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f );
return;
}
//draw a line from the ship's cur pos to the lead pos
CG_DottedLine( x, y, leadX, leadY, 1, 10, g_color_table[ColorIndex(COLOR_RED)], 0.5f );
//now draw the lead indicator
trap_R_SetColor ( g_color_table[ColorIndex(COLOR_RED)] );
CG_DrawPic( leadX-8, leadY-8, 16, 16, trap_R_RegisterShader( "gfx/menus/radar/lead" ) );
}
}
}
}
}
}
}
}
qboolean CG_InFighter( void )
{
if ( cg.predictedPlayerState.m_iVehicleNum )
{//I'm in a vehicle
centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum];
if ( vehCent
&& vehCent->m_pVehicle
&& vehCent->m_pVehicle->m_pVehicleInfo
&& vehCent->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER )
{//I'm in a fighter
return qtrue;
}
}
return qfalse;
}
qboolean CG_InATST( void )
{
if ( cg.predictedPlayerState.m_iVehicleNum )
{//I'm in a vehicle
centity_t *vehCent = &cg_entities[cg.predictedPlayerState.m_iVehicleNum];
if ( vehCent
&& vehCent->m_pVehicle
&& vehCent->m_pVehicle->m_pVehicleInfo
&& vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER )
{//I'm in an atst
return qtrue;
}
}
return qfalse;
}
void CG_DrawBracketedEntities( void )
{
int i;
for ( i = 0; i < cg.bracketedEntityCount; i++ )
{
centity_t *cent = &cg_entities[cg.bracketedEntities[i]];
CG_BracketEntity( cent, CG_RadiusForCent( cent ) );
}
}
//--------------------------------------------------------------
static void CG_DrawHolocronIcons(void)
//--------------------------------------------------------------
{
int icon_size = 40;
int i = 0;
int startx = 10;
int starty = 10;//SCREEN_HEIGHT - icon_size*3;
int endx = icon_size;
int endy = icon_size;
if (cg.snap->ps.zoomMode)
{ //don't display over zoom mask
return;
}
if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR)
{
return;
}
while (i < NUM_FORCE_POWERS)
{
if (cg.snap->ps.holocronBits & (1 << forcePowerSorted[i]))
{
CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]);
starty += (icon_size+2); //+2 for spacing
if ((starty+icon_size) >= SCREEN_HEIGHT-80)
{
starty = 10;//SCREEN_HEIGHT - icon_size*3;
startx += (icon_size+2);
}
}
i++;
}
}
static qboolean CG_IsDurationPower(int power)
{
if (power == FP_HEAL ||
//[ForceSys]
//power == FP_SPEED ||
//[/ForceSys]
power == FP_MINDTRICK ||
power == FP_RAGE ||
power == FP_MANIPULATE ||
power == FP_ABSORB ||
power == FP_SEE)
{
return qtrue;
}
return qfalse;
}
//--------------------------------------------------------------
static void CG_DrawActivePowers(void)
//--------------------------------------------------------------
{
int icon_size = 40;
int i = 0;
int startx = icon_size*2+16;
int starty = SCREEN_HEIGHT - icon_size*2;
int endx = icon_size;
int endy = icon_size;
if (cg.snap->ps.zoomMode)
{ //don't display over zoom mask
return;
}
if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR)
{
return;
}
while (i < NUM_FORCE_POWERS)
{
if ((cg.snap->ps.fd.forcePowersActive & (1 << forcePowerSorted[i])) &&
CG_IsDurationPower(forcePowerSorted[i]))
{
CG_DrawPic( startx, starty, endx, endy, cgs.media.forcePowerIcons[forcePowerSorted[i]]);
startx += (icon_size+2); //+2 for spacing
if ((startx+icon_size) >= SCREEN_WIDTH-80)
{
startx = icon_size*2+16;
starty += (icon_size+2);
}
}
i++;
}
//additionally, draw an icon force force rage recovery
if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time)
{
CG_DrawPic( startx, starty, endx, endy, cgs.media.rageRecShader);
}
}
//--------------------------------------------------------------
static void CG_DrawRocketLocking( int lockEntNum, int lockTime )
//--------------------------------------------------------------
{
int cx, cy;
vec3_t org;
static int oldDif = 0;
centity_t *cent = &cg_entities[lockEntNum];
vec4_t color={0.0f,0.0f,0.0f,0.0f};
float lockTimeInterval = ((cgs.gametype==GT_SIEGE)?2400.0f:1200.0f)/16.0f;
//FIXME: if in a vehicle, use the vehicle's lockOnTime...
int dif = (cg.time - cg.snap->ps.rocketLockTime)/lockTimeInterval;
int i;
if (!cg.snap->ps.rocketLockTime)
{
return;
}
if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR)
{
return;
}
if ( cg.snap->ps.m_iVehicleNum )
{//driving a vehicle
centity_t *veh = &cg_entities[cg.snap->ps.m_iVehicleNum];
if ( veh->m_pVehicle )
{
vehWeaponInfo_t *vehWeapon = NULL;
if ( cg.predictedVehicleState.weaponstate == WEAPON_CHARGING_ALT )
{
if ( veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID > VEH_WEAPON_BASE
&& veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID < MAX_VEH_WEAPONS )
{
vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[1].ID];
}
}
else
{
if ( veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID > VEH_WEAPON_BASE
&& veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID < MAX_VEH_WEAPONS )
{
vehWeapon = &g_vehWeaponInfo[veh->m_pVehicle->m_pVehicleInfo->weapon[0].ID];
}
}
if ( vehWeapon != NULL )
{//we are trying to lock on with a valid vehicle weapon, so use *its* locktime, not the hard-coded one
if ( !vehWeapon->iLockOnTime )
{//instant lock-on
dif = 10.0f;
}
else
{//use the custom vehicle lockOnTime
lockTimeInterval = (vehWeapon->iLockOnTime/16.0f);
dif = (cg.time - cg.snap->ps.rocketLockTime)/lockTimeInterval;
}
}
}
}
//We can't check to see in pmove if players are on the same team, so we resort
//to just not drawing the lock if a teammate is the locked on ent
if (cg.snap->ps.rocketLockIndex >= 0 &&
cg.snap->ps.rocketLockIndex < ENTITYNUM_NONE)
{
clientInfo_t *ci = NULL;
if (cg.snap->ps.rocketLockIndex < MAX_CLIENTS)
{
ci = &cgs.clientinfo[cg.snap->ps.rocketLockIndex];
}
else
{
ci = cg_entities[cg.snap->ps.rocketLockIndex].npcClient;
}
if (ci)
{
if (ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team)
{
if (cgs.gametype >= GT_TEAM)
{
return;
}
}
else if (cgs.gametype >= GT_TEAM)
{
centity_t *hitEnt = &cg_entities[cg.snap->ps.rocketLockIndex];
if (hitEnt->currentState.eType == ET_NPC &&
hitEnt->currentState.NPC_class == CLASS_VEHICLE &&
hitEnt->currentState.owner < ENTITYNUM_WORLD)
{ //this is a vehicle, if it has a pilot and that pilot is on my team, then...
if (hitEnt->currentState.owner < MAX_CLIENTS)
{
ci = &cgs.clientinfo[hitEnt->currentState.owner];
}
else
{
ci = cg_entities[hitEnt->currentState.owner].npcClient;
}
if (ci && ci->team == cgs.clientinfo[cg.snap->ps.clientNum].team)
{
return;
}
}
}
}
}
if (cg.snap->ps.rocketLockTime != -1)
{
lastvalidlockdif = dif;
}
else
{
dif = lastvalidlockdif;
}
if ( !cent )
{
return;
}
VectorCopy( cent->lerpOrigin, org );
if ( CG_WorldCoordToScreenCoord( org, &cx, &cy ))
{
// we care about distance from enemy to eye, so this is good enough
float sz = Distance( cent->lerpOrigin, cg.refdef.vieworg ) / 1024.0f;
if ( sz > 1.0f )
{
sz = 1.0f;
}
else if ( sz < 0.0f )
{
sz = 0.0f;
}
sz = (1.0f - sz) * (1.0f - sz) * 32 + 6;
//[Asteroids]
if ( cg.snap->ps.m_iVehicleNum )
{
sz *= 2.0f;
}
//[/Asteroids]
cy += sz * 0.5f;
if ( dif < 0 )
{
oldDif = 0;
return;
}
else if ( dif > 8 )
{
dif = 8;
}
// do sounds
if ( oldDif != dif )
{
if ( dif == 8 )
{
if ( cg.snap->ps.m_iVehicleNum )
{
trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/vehicles/weapons/common/lock.wav" ));
}
else
{
trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/weapons/rocket/lock.wav" ));
}
}
else
{
if ( cg.snap->ps.m_iVehicleNum )
{
trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/vehicles/weapons/common/tick.wav" ));
}
else
{
trap_S_StartSound( org, 0, CHAN_AUTO, trap_S_RegisterSound( "sound/weapons/rocket/tick.wav" ));
}
}
}
oldDif = dif;
for ( i = 0; i < dif; i++ )
{
color[0] = 1.0f;
color[1] = 0.0f;
color[2] = 0.0f;
color[3] = 0.1f * i + 0.2f;
trap_R_SetColor( color );
// our slices are offset by about 45 degrees.
CG_DrawRotatePic( cx - sz, cy - sz, sz, sz, i * 45.0f, trap_R_RegisterShaderNoMip( "gfx/2d/wedge" ));
}
// we are locked and loaded baby
if ( dif == 8 )
{
color[0] = color[1] = color[2] = sin( cg.time * 0.05f ) * 0.5f + 0.5f;
color[3] = 1.0f; // this art is additive, so the alpha value does nothing
trap_R_SetColor( color );
CG_DrawPic( cx - sz, cy - sz * 2, sz * 2, sz * 2, trap_R_RegisterShaderNoMip( "gfx/2d/lock" ));
}
}
}
extern void CG_CalcVehMuzzle(Vehicle_t *pVeh, centity_t *ent, int muzzleNum);
qboolean CG_CalcVehicleMuzzlePoint( int entityNum, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up)
{
centity_t *vehCent = &cg_entities[entityNum];
if ( vehCent->m_pVehicle && vehCent->m_pVehicle->m_pVehicleInfo->type == VH_WALKER )
{//draw from barrels
VectorCopy( vehCent->lerpOrigin, start );
start[2] += vehCent->m_pVehicle->m_pVehicleInfo->height-DEFAULT_MINS_2-48;
AngleVectors( vehCent->lerpAngles, d_f, d_rt, d_up );
}
else
{
//check to see if we're a turret gunner on this vehicle
if ( cg.predictedPlayerState.generic1 )//as a passenger
{//passenger in a vehicle
if ( vehCent->m_pVehicle
&& vehCent->m_pVehicle->m_pVehicleInfo
&& vehCent->m_pVehicle->m_pVehicleInfo->maxPassengers )
{//a vehicle capable of carrying passengers
int turretNum;
for ( turretNum = 0; turretNum < MAX_VEHICLE_TURRETS; turretNum++ )
{
if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iAmmoMax )
{// valid turret
if ( vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].passengerNum == cg.predictedPlayerState.generic1 )
{//I control this turret
//Go through all muzzles, average their positions and directions and use the result for crosshair trace
int vehMuzzle, numMuzzles = 0;
vec3_t muzzlesAvgPos={0},muzzlesAvgDir={0};
int i;
for ( i = 0; i < MAX_VEHICLE_TURRET_MUZZLES; i++ )
{
vehMuzzle = vehCent->m_pVehicle->m_pVehicleInfo->turret[turretNum].iMuzzle[i];
if ( vehMuzzle )
{
vehMuzzle -= 1;
CG_CalcVehMuzzle( vehCent->m_pVehicle, vehCent, vehMuzzle );
VectorAdd( muzzlesAvgPos, vehCent->m_pVehicle->m_vMuzzlePos[vehMuzzle], muzzlesAvgPos );
VectorAdd( muzzlesAvgDir, vehCent->m_pVehicle->m_vMuzzleDir[vehMuzzle], muzzlesAvgDir );
numMuzzles++;
}
if ( numMuzzles )
{
VectorScale( muzzlesAvgPos, 1.0f/(float)numMuzzles, start );
VectorScale( muzzlesAvgDir, 1.0f/(float)numMuzzles, d_f );
VectorClear( d_rt );
VectorClear( d_up );
return qtrue;
}
}
}
}
}
}
}
VectorCopy( vehCent->lerpOrigin, start );
AngleVectors( vehCent->lerpAngles, d_f, d_rt, d_up );
}
return qfalse;
}
//calc the muzzle point from the e-web itself
void CG_CalcEWebMuzzlePoint(centity_t *cent, vec3_t start, vec3_t d_f, vec3_t d_rt, vec3_t d_up)
{
int bolt = trap_G2API_AddBolt(cent->ghoul2, 0, "*cannonflash");
assert(bolt != -1);
if (bolt != -1)
{
mdxaBone_t boltMatrix;
trap_G2API_GetBoltMatrix_NoRecNoRot(cent->ghoul2, 0, bolt, &boltMatrix, cent->lerpAngles, cent->lerpOrigin, cg.time, NULL, cent->modelScale);
BG_GiveMeVectorFromMatrix(&boltMatrix, ORIGIN, start);
BG_GiveMeVectorFromMatrix(&boltMatrix, NEGATIVE_X, d_f);
//these things start the shot a little inside the bbox to assure not starting in something solid
VectorMA(start, -16.0f, d_f, start);
//I guess
VectorClear( d_rt );//don't really need this, do we?
VectorClear( d_up );//don't really need this, do we?
}
}
/*
=================
CG_`Entity
=================
*/
#define MAX_XHAIR_DIST_ACCURACY 20000.0f
static void CG_ScanForCrosshairEntity( void ) {
trace_t trace;
vec3_t start, end;
int content;
int ignore;
qboolean bVehCheckTraceFromCamPos = qfalse;
ignore = cg.predictedPlayerState.clientNum;
if ( cg_dynamicCrosshair.integer )
{
vec3_t d_f, d_rt, d_up;
//For now we still want to draw the crosshair in relation to the player's world coordinates
//even if we have a melee weapon/no weapon.
if ( cg.predictedPlayerState.m_iVehicleNum && (cg.predictedPlayerState.eFlags&EF_NODRAW) )
{//we're *inside* a vehicle
//do the vehicle's crosshair instead
centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum];
qboolean gunner = qfalse;
//if (veh->currentState.owner == cg.predictedPlayerState.clientNum)
{ //the pilot
ignore = cg.predictedPlayerState.m_iVehicleNum;
gunner = CG_CalcVehicleMuzzlePoint(cg.predictedPlayerState.m_iVehicleNum, start, d_f, d_rt, d_up);
}
if ( veh->m_pVehicle
&& veh->m_pVehicle->m_pVehicleInfo
&& veh->m_pVehicle->m_pVehicleInfo->type == VH_FIGHTER
&& cg.distanceCull > MAX_XHAIR_DIST_ACCURACY
&& !gunner )
{
//NOTE: on huge maps, the crosshair gets inaccurate at close range,
// so we'll do an extra G2 trace from the cg.refdef.vieworg
// to see if we hit anything closer and auto-aim at it if so
bVehCheckTraceFromCamPos = qtrue;
}
}
else if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex &&
cg_entities[cg.snap->ps.emplacedIndex].ghoul2 && cg_entities[cg.snap->ps.emplacedIndex].currentState.weapon == WP_NONE)
{ //locked into our e-web, calc the muzzle from it
CG_CalcEWebMuzzlePoint(&cg_entities[cg.snap->ps.emplacedIndex], start, d_f, d_rt, d_up);
}
else
{
if (cg.snap && cg.snap->ps.weapon == WP_EMPLACED_GUN && cg.snap->ps.emplacedIndex)
{
vec3_t pitchConstraint;
ignore = cg.snap->ps.emplacedIndex;
VectorCopy(cg.refdef.viewangles, pitchConstraint);
if (cg.renderingThirdPerson)
{
VectorCopy(cg.predictedPlayerState.viewangles, pitchConstraint);
}
else
{
VectorCopy(cg.refdef.viewangles, pitchConstraint);
}
if (pitchConstraint[PITCH] > 40)
{
pitchConstraint[PITCH] = 40;
}
AngleVectors( pitchConstraint, d_f, d_rt, d_up );
}
else
{
vec3_t pitchConstraint;
if (cg.renderingThirdPerson)
{
VectorCopy(cg.predictedPlayerState.viewangles, pitchConstraint);
}
else
{
VectorCopy(cg.refdef.viewangles, pitchConstraint);
}
AngleVectors( pitchConstraint, d_f, d_rt, d_up );
}
CG_CalcMuzzlePoint(cg.snap->ps.clientNum, start);
}
VectorMA( start, cg.distanceCull, d_f, end );
}
else
{
VectorCopy( cg.refdef.vieworg, start );
VectorMA( start, 131072, cg.refdef.viewaxis[0], end );
}
if ( cg_dynamicCrosshair.integer && cg_dynamicCrosshairPrecision.integer )
{ //then do a trace with ghoul2 models in mind
CG_G2Trace( &trace, start, vec3_origin, vec3_origin, end,
ignore, CONTENTS_SOLID|CONTENTS_BODY );
if ( bVehCheckTraceFromCamPos )
{
//NOTE: this MUST stay up to date with the method used in WP_VehCheckTraceFromCamPos
centity_t *veh = &cg_entities[cg.predictedPlayerState.m_iVehicleNum];
trace_t extraTrace;
vec3_t viewDir2End, extraEnd;
float minAutoAimDist = Distance( veh->lerpOrigin, cg.refdef.vieworg ) + (veh->m_pVehicle->m_pVehicleInfo->length/2.0f) + 200.0f;
VectorSubtract( end, cg.refdef.vieworg, viewDir2End );
VectorNormalize( viewDir2End );
VectorMA( cg.refdef.vieworg, MAX_XHAIR_DIST_ACCURACY, viewDir2End, extraEnd );
CG_G2Trace( &extraTrace, cg.refdef.vieworg, vec3_origin, vec3_origin, extraEnd,
ignore, CONTENTS_SOLID|CONTENTS_BODY );
if ( !extraTrace.allsolid
&& !extraTrace.startsolid )
{
if ( extraTrace.fraction < 1.0f )
{
if ( (extraTrace.fraction*MAX_XHAIR_DIST_ACCURACY) > minAutoAimDist )
{
if ( ((extraTrace.fraction*MAX_XHAIR_DIST_ACCURACY)-Distance( veh->lerpOrigin, cg.refdef.vieworg )) < (trace.fraction*cg.distanceCull) )
{//this trace hit *something* that's closer than the thing the main trace hit, so use this result instead
memcpy( &trace, &extraTrace, sizeof( trace_t ) );
}
}
}
}
}
}
else
{
CG_Trace( &trace, start, vec3_origin, vec3_origin, end,
ignore, CONTENTS_SOLID|CONTENTS_BODY );
}
if (trace.entityNum < MAX_CLIENTS)
{
if (CG_IsMindTricked(cg_entities[trace.entityNum].currentState.trickedentindex,
cg_entities[trace.entityNum].currentState.trickedentindex2,
cg_entities[trace.entityNum].currentState.trickedentindex3,
cg_entities[trace.entityNum].currentState.trickedentindex4,
cg.snap->ps.clientNum))
{
if (cg.crosshairClientNum == trace.entityNum)
{
cg.crosshairClientNum = ENTITYNUM_NONE;
cg.crosshairClientTime = 0;
}
CG_DrawCrosshair(trace.endpos, 0);
return; //this entity is mind-tricking the current client, so don't render it
}
}
if (cg.snap->ps.persistant[PERS_TEAM] != TEAM_SPECTATOR)
{
if (trace.entityNum < ENTITYNUM_WORLD)
{
cg.crosshairClientNum = trace.entityNum;
cg.crosshairClientTime = cg.time;
if (cg.crosshairClientNum < ENTITYNUM_WORLD)
{
centity_t *veh = &cg_entities[cg.crosshairClientNum];
if (veh->currentState.eType == ET_NPC &&
veh->currentState.NPC_class == CLASS_VEHICLE &&
veh->currentState.owner < MAX_CLIENTS)
{ //draw the name of the pilot then
cg.crosshairClientNum = veh->currentState.owner;
cg.crosshairVehNum = veh->currentState.number;
cg.crosshairVehTime = cg.time;
}
}
CG_DrawCrosshair(trace.endpos, 1);
}
else
{
CG_DrawCrosshair(trace.endpos, 0);
}
}
// if ( trace.entityNum >= MAX_CLIENTS ) {
// return;
// }
// if the player is in fog, don't show it
content = trap_CM_PointContents( trace.endpos, 0 );
if ( content & CONTENTS_FOG ) {
return;
}
// update the fade timer
cg.crosshairClientNum = trace.entityNum;
cg.crosshairClientTime = cg.time;
}
void CG_SanitizeString( char *in, char *out )
{
int i = 0;
int r = 0;
while (in[i])
{
if (i >= 128-1)
{ //the ui truncates the name here..
break;
}
if (in[i] == '^')
{
if (in[i+1] >= 48 && //'0'
in[i+1] <= 57) //'9'
{ //only skip it if there's a number after it for the color
i += 2;
continue;
}
else
{ //just skip the ^
i++;
continue;
}
}
if (in[i] < 32)
{
i++;
continue;
}
out[r] = in[i];
r++;
i++;
}
out[r] = 0;
}
/*
=====================
CG_DrawCrosshairNames
=====================
*/
static void CG_DrawCrosshairNames( void ) {
float *color;
vec4_t tcolor;
char *name;
char sanitized[1024];
int baseColor;
qboolean isVeh = qfalse;
//[CoOp]
if(in_camera)
{//no crosshair while in cutscenes
return;
}
//[/CoOp]
if ( !cg_drawCrosshair.integer ) {
return;
}
// scan the known entities to see if the crosshair is sighted on one
CG_ScanForCrosshairEntity();
if ( !cg_drawCrosshairNames.integer ) {
return;
}
//rww - still do the trace, our dynamic crosshair depends on it
if (cg.crosshairClientNum < ENTITYNUM_WORLD)
{
centity_t *veh = &cg_entities[cg.crosshairClientNum];
if (veh->currentState.eType == ET_NPC &&
veh->currentState.NPC_class == CLASS_VEHICLE &&
veh->currentState.owner < MAX_CLIENTS)
{ //draw the name of the pilot then
cg.crosshairClientNum = veh->currentState.owner;
cg.crosshairVehNum = veh->currentState.number;
cg.crosshairVehTime = cg.time;
isVeh = qtrue; //so we know we're drawing the pilot's name
}
}
if (cg.crosshairClientNum >= MAX_CLIENTS)
{
return;
}
if (cg_entities[cg.crosshairClientNum].currentState.powerups & (1 << PW_CLOAKED))
{
return;
}
// draw the name of the player being looked at
color = CG_FadeColor( cg.crosshairClientTime, 1000 );
if ( !color ) {
trap_R_SetColor( NULL );
return;
}
name = cgs.clientinfo[ cg.crosshairClientNum ].name;
//[CoOp]
//make other players show as allies in CoOp
//if (cgs.gametype >= GT_TEAM)
if (cgs.gametype >= GT_SINGLE_PLAYER)
//[/CoOp]
{
//if (cgs.gametype == GT_SIEGE)
if (1)
{ //instead of team-based we'll make it oriented based on which team we're on
if (cgs.clientinfo[cg.crosshairClientNum].team == cg.predictedPlayerState.persistant[PERS_TEAM])
{
baseColor = CT_GREEN;
}
else
{
baseColor = CT_RED;
}
}
else
{
if (cgs.clientinfo[cg.crosshairClientNum].team == TEAM_RED)
{
baseColor = CT_RED;
}
else
{
baseColor = CT_BLUE;
}
}
}
else
{
//baseColor = CT_WHITE;
if (cgs.gametype == GT_POWERDUEL &&
cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR &&
cgs.clientinfo[cg.crosshairClientNum].duelTeam == cgs.clientinfo[cg.predictedPlayerState.clientNum].duelTeam)
{ //on the same duel team in powerduel, so he's a friend
baseColor = CT_GREEN;
}
else
{
baseColor = CT_RED; //just make it red in nonteam modes since everyone is hostile and crosshair will be red on them too
}
}
if (cg.snap->ps.duelInProgress)
{
if (cg.crosshairClientNum != cg.snap->ps.duelIndex)
{ //grey out crosshair for everyone but your foe if you're in a duel
baseColor = CT_BLACK;
}
}
else if (cg_entities[cg.crosshairClientNum].currentState.bolt1)
{ //this fellow is in a duel. We just checked if we were in a duel above, so
//this means we aren't and he is. Which of course means our crosshair greys out over him.
baseColor = CT_BLACK;
}
tcolor[0] = colorTable[baseColor][0];
tcolor[1] = colorTable[baseColor][1];
tcolor[2] = colorTable[baseColor][2];
tcolor[3] = color[3]*0.5f;
CG_SanitizeString(name, sanitized);
if (isVeh)
{
char str[MAX_STRING_CHARS];
Com_sprintf(str, MAX_STRING_CHARS, "%s (pilot)", sanitized);
UI_DrawProportionalString(320, 170, str, UI_CENTER, tcolor);
}
else
{
UI_DrawProportionalString(320, 170, sanitized, UI_CENTER, tcolor);
}
trap_R_SetColor( NULL );
}
//==============================================================================
/*
=================
CG_DrawSpectator
=================
*/
static void CG_DrawSpectator(void)
{
const char* s;
s = CG_GetStringEdString("MP_INGAME", "SPECTATOR");
if ((cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL) &&
cgs.duelist1 != -1 &&
cgs.duelist2 != -1)
{
char text[1024];
int size = 64;
if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1)
{
Com_sprintf(text, sizeof(text), "%s^7 %s %s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name, CG_GetStringEdString("MP_INGAME", "AND"), cgs.clientinfo[cgs.duelist3].name);
}
else
{
Com_sprintf(text, sizeof(text), "%s^7 %s %s", cgs.clientinfo[cgs.duelist1].name, CG_GetStringEdString("MP_INGAME", "SPECHUD_VERSUS"), cgs.clientinfo[cgs.duelist2].name);
}
CG_Text_Paint ( 320 - CG_Text_Width ( text, 1.0f, 3 ) / 2, 420, 1.0f, colorWhite, text, 0, 0, 0, 3 );
trap_R_SetColor( colorTable[CT_WHITE] );
if ( cgs.clientinfo[cgs.duelist1].modelIcon )
{
CG_DrawPic( 10, SCREEN_HEIGHT-(size*1.5), size, size, cgs.clientinfo[cgs.duelist1].modelIcon );
}
if ( cgs.clientinfo[cgs.duelist2].modelIcon )
{
CG_DrawPic( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*1.5), size, size, cgs.clientinfo[cgs.duelist2].modelIcon );
}
// nmckenzie: DUEL_HEALTH
if (cgs.gametype == GT_DUEL)
{
if ( cgs.showDuelHealths >= 1)
{ // draw the healths on the two guys - how does this interact with power duel, though?
CG_DrawDuelistHealth ( 10, SCREEN_HEIGHT-(size*1.5) - 12, 64, 8, 1 );
CG_DrawDuelistHealth ( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*1.5) - 12, 64, 8, 2 );
}
}
if (cgs.gametype != GT_POWERDUEL)
{
Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist1].score, cgs.fraglimit );
CG_Text_Paint( 42 - CG_Text_Width( text, 1.0f, 2 ) / 2, SCREEN_HEIGHT-(size*1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2 );
Com_sprintf(text, sizeof(text), "%i/%i", cgs.clientinfo[cgs.duelist2].score, cgs.fraglimit );
CG_Text_Paint( SCREEN_WIDTH-size+22 - CG_Text_Width( text, 1.0f, 2 ) / 2, SCREEN_HEIGHT-(size*1.5) + 64, 1.0f, colorWhite, text, 0, 0, 0, 2 );
}
if (cgs.gametype == GT_POWERDUEL && cgs.duelist3 != -1)
{
if ( cgs.clientinfo[cgs.duelist3].modelIcon )
{
CG_DrawPic( SCREEN_WIDTH-size-10, SCREEN_HEIGHT-(size*2.8), size, size, cgs.clientinfo[cgs.duelist3].modelIcon );
}
}
}
else
{
CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 420, 1.0f, colorWhite, s, 0, 0, 0, 3 );
}
if ( cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL )
{
s = CG_GetStringEdString("MP_INGAME", "WAITING_TO_PLAY"); // "waiting to play";
CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3 );
}
else //if ( cgs.gametype >= GT_TEAM )
{
//s = "press ESC and use the JOIN menu to play";
s = CG_GetStringEdString("MP_INGAME", "SPEC_CHOOSEJOIN");
CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, 3 ) / 2, 440, 1.0f, colorWhite, s, 0, 0, 0, 3 );
}
}
/*
=================
CG_DrawVote
=================
*/
static void CG_DrawVote(void) {
const char *s;
int sec;
char sYes[20];
char sNo[20];
char sVote[20];
char sCmd[100];
//[VoteSys]
char sParm[100];
//const char* sParm = 0;
//[/VoteSys]
if ( !cgs.voteTime ) {
return;
}
// play a talk beep whenever it is modified
if ( cgs.voteModified ) {
cgs.voteModified = qfalse;
// trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND );
}
sec = ( VOTE_TIME - ( cg.time - cgs.voteTime ) ) / 1000;
if ( sec < 0 ) {
sec = 0;
}
//[VoteSys]
memset(sYes, 0, sizeof(sYes));
memset(sNo, 0, sizeof(sNo));
memset(sVote, 0, sizeof(sVote));
memset(sCmd, 0, sizeof(sCmd));
memset(sParm, 0, sizeof(sParm));
//[/VoteSys]
if (strncmp(cgs.voteString, "map_restart", 11)==0)
{
//[VoteSys]
Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "RESTART_MAP"), sizeof(sCmd));
//trap_SP_GetStringTextString("MENUS_RESTART_MAP", sCmd, sizeof(sCmd) );
//[/VoteSys]
}
else if (strncmp(cgs.voteString, "vstr nextmap", 12)==0)
{
//[VoteSys]
Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "NEXT_MAP"), sizeof(sCmd));
//trap_SP_GetStringTextString("MENUS_NEXT_MAP", sCmd, sizeof(sCmd) );
//[/VoteSys]
}
else if (strncmp(cgs.voteString, "g_doWarmup", 10)==0)
{
//[VoteSys]
Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "WARMUP"), sizeof(sCmd));
//trap_SP_GetStringTextString("MENUS_WARMUP", sCmd, sizeof(sCmd) );
//[/VoteSys]
}
else if (strncmp(cgs.voteString, "g_gametype", 10)==0)
{
//[VoteSys]
Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "GAME_TYPE"), sizeof(sCmd));
//trap_SP_GetStringTextString("MENUS_GAME_TYPE", sCmd, sizeof(sCmd) );
//[/VoteSys]
if ( stricmp("Free For All", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "FREE_FOR_ALL"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "FREE_FOR_ALL");
//[/VoteSys]
}
else if ( stricmp("Duel", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "DUEL"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "DUEL");
//[/VoteSys]
}
else if ( stricmp("Jedi Master", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("OJP_MENUS", "JEDIMASTER"), sizeof(sParm));
//sParm = CG_GetStringEdString("OJP_MENUS", "JEDIMASTER");
//[/VoteSys]
}
else if ( stricmp("Holocron FFA", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "HOLOCRON_FFA"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "HOLOCRON_FFA");
//[/VoteSys]
}
else if ( stricmp("Power Duel", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "POWERDUEL"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "POWERDUEL");
//[/VoteSys]
}
else if ( stricmp("Team FFA", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "TEAM_FFA"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "TEAM_FFA");
//[/VoteSys]
}
else if ( stricmp("Siege", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "SIEGE"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "SIEGE");
//[/VoteSys]
}
else if ( stricmp("Capture the Flag", cgs.voteString+11)==0 )
{
//[VoteSys]
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG");
//[/VoteSys]
}
else if ( stricmp("Capture the Ysalamiri", cgs.voteString+11)==0 )
{
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI");
}
//[CoOp]
//[VoteSys]
else if ( stricmp("Single Player", cgs.voteString+11)==0 )
{
Q_strncpyz(sParm, CG_GetStringEdString("OJP_MENUS", "COOP"), sizeof(sParm));
//sParm = CG_GetStringEdString("OJP_MENUS", "COOP");
}
//[/VoteSys]
//[/CoOp]
//[VoteSys]
else
{
Q_strncpyz(sParm, CG_GetStringEdString("MENUS", "SAGA"), sizeof(sParm));
//sParm = CG_GetStringEdString("MENUS", "SAGA");
}
//[/VoteSys]
}
else if (strncmp(cgs.voteString, "map", 3)==0)
{
//[VoteSys]
Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "NEW_MAP"), sizeof(sCmd));
Q_strncpyz(sParm, cgs.voteString+4, sizeof(sParm));
//trap_SP_GetStringTextString("MENUS_NEW_MAP", sCmd, sizeof(sCmd) );
//sParm = cgs.voteString+4;
//[/VoteSys]
}
else if (strncmp(cgs.voteString, "kick", 4)==0)
{
//[VoteSys]
Q_strncpyz(sCmd, CG_GetStringEdString("MENUS", "KICK_PLAYER"), sizeof(sCmd));
Q_strncpyz(sParm, cgs.voteString+5, sizeof(sParm));
//trap_SP_GetStringTextString("MENUS_KICK_PLAYER", sCmd, sizeof(sCmd) );
//sParm = cgs.voteString+5;
//[/VoteSys]
}
//[VoteSys]
else if (strncmp(cgs.voteString, "timelimit", 9)==0)
{
Q_strncpyz(sCmd, CG_GetStringEdString("MP_INGAME", "TIMELIMIT"), sizeof(sCmd));
Q_strncpyz(sParm, cgs.voteString+10, sizeof(sParm));
}
else if (strncmp(cgs.voteString, "fraglimit", 9)==0)
{
Q_strncpyz(sCmd, CG_GetStringEdString("MP_INGAME", "FRAGLIMIT"), sizeof(sCmd));
Q_strncpyz(sParm, cgs.voteString+10, sizeof(sParm));
}
else if (strncmp(cgs.voteString, "capturelimit", 12)==0)
{
Q_strncpyz(sCmd, CG_GetStringEdString("MP_INGAME", "CAPTURELIMIT"), sizeof(sCmd));
Q_strncpyz(sParm, cgs.voteString+13, sizeof(sParm));
}
else
{
Q_strncpyz(sCmd, cgs.voteString, sizeof(sCmd));
}
Q_strncpyz(sVote, CG_GetStringEdString("MENUS", "VOTE"), sizeof(sVote));
Q_strncpyz(sYes, CG_GetStringEdString("MENUS", "YES"), sizeof(sYes));
Q_strncpyz(sNo, CG_GetStringEdString("MENUS", "NO"), sizeof(sNo));
//trap_SP_GetStringTextString("MENUS_VOTE", sVote, sizeof(sVote) );
//trap_SP_GetStringTextString("MENUS_YES", sYes, sizeof(sYes) );
//trap_SP_GetStringTextString("MENUS_NO", sNo, sizeof(sNo) );
if (*sParm && sParm[0])
//if (sParm && sParm[0])
//[/VoteSys]
{
s = va("%s(%i):<%s %s> %s:%i %s:%i", sVote, sec, sCmd, sParm, sYes, cgs.voteYes, sNo, cgs.voteNo);
}
else
{
s = va("%s(%i):<%s> %s:%i %s:%i", sVote, sec, sCmd, sYes, cgs.voteYes, sNo, cgs.voteNo);
}
CG_DrawSmallString( 4, 58, s, 1.0F );
s = CG_GetStringEdString("MP_INGAME", "OR_PRESS_ESC_THEN_CLICK_VOTE"); // s = "or press ESC then click Vote";
CG_DrawSmallString( 4, 58 + SMALLCHAR_HEIGHT + 2, s, 1.0F );
}
/*
=================
CG_DrawTeamVote
=================
*/
static void CG_DrawTeamVote(void) {
char *s;
int sec, cs_offset;
if ( cgs.clientinfo->team == TEAM_RED )
cs_offset = 0;
else if ( cgs.clientinfo->team == TEAM_BLUE )
cs_offset = 1;
else
return;
if ( !cgs.teamVoteTime[cs_offset] ) {
return;
}
// play a talk beep whenever it is modified
if ( cgs.teamVoteModified[cs_offset] ) {
cgs.teamVoteModified[cs_offset] = qfalse;
// trap_S_StartLocalSound( cgs.media.talkSound, CHAN_LOCAL_SOUND );
}
sec = ( VOTE_TIME - ( cg.time - cgs.teamVoteTime[cs_offset] ) ) / 1000;
if ( sec < 0 ) {
sec = 0;
}
if (strstr(cgs.teamVoteString[cs_offset], "leader"))
{
int i = 0;
while (cgs.teamVoteString[cs_offset][i] && cgs.teamVoteString[cs_offset][i] != ' ')
{
i++;
}
if (cgs.teamVoteString[cs_offset][i] == ' ')
{
int voteIndex = 0;
char voteIndexStr[256];
i++;
while (cgs.teamVoteString[cs_offset][i])
{
voteIndexStr[voteIndex] = cgs.teamVoteString[cs_offset][i];
voteIndex++;
i++;
}
voteIndexStr[voteIndex] = 0;
voteIndex = atoi(voteIndexStr);
s = va("TEAMVOTE(%i):(Make %s the new team leader) yes:%i no:%i", sec, cgs.clientinfo[voteIndex].name,
cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] );
}
else
{
s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset],
cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] );
}
}
else
{
s = va("TEAMVOTE(%i):%s yes:%i no:%i", sec, cgs.teamVoteString[cs_offset],
cgs.teamVoteYes[cs_offset], cgs.teamVoteNo[cs_offset] );
}
CG_DrawSmallString( 4, 90, s, 1.0F );
}
static qboolean CG_DrawScoreboard() {
return CG_DrawOldScoreboard();
}
/*
=================
CG_DrawIntermission
=================
*/
static void CG_DrawIntermission( void ) {
// int key;
//if (cg_singlePlayer.integer) {
// CG_DrawCenterString();
// return;
//}
cg.scoreFadeTime = cg.time;
cg.scoreBoardShowing = CG_DrawScoreboard();
}
/*
=================
CG_DrawFollow
=================
*/
static qboolean CG_DrawFollow( void )
{
const char *s;
if ( !(cg.snap->ps.pm_flags & PMF_FOLLOW) )
{
return qfalse;
}
// s = "following";
if (cgs.gametype == GT_POWERDUEL)
{
clientInfo_t *ci = &cgs.clientinfo[ cg.snap->ps.clientNum ];
if (ci->duelTeam == DUELTEAM_LONE)
{
s = CG_GetStringEdString("MP_INGAME", "FOLLOWINGLONE");
}
else if (ci->duelTeam == DUELTEAM_DOUBLE)
{
s = CG_GetStringEdString("MP_INGAME", "FOLLOWINGDOUBLE");
}
else
{
s = CG_GetStringEdString("MP_INGAME", "FOLLOWING");
}
}
else
{
s = CG_GetStringEdString("MP_INGAME", "FOLLOWING");
}
CG_Text_Paint ( 320 - CG_Text_Width ( s, 1.0f, FONT_MEDIUM ) / 2, 60, 1.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM );
s = cgs.clientinfo[ cg.snap->ps.clientNum ].name;
CG_Text_Paint ( 320 - CG_Text_Width ( s, 2.0f, FONT_MEDIUM ) / 2, 80, 2.0f, colorWhite, s, 0, 0, 0, FONT_MEDIUM );
return qtrue;
}
/*
=================
CG_DrawWarmup
=================
*/
static void CG_DrawWarmup( void ) {
int w;
int sec;
int i;
float scale;
int cw;
const char *s;
sec = cg.warmup;
if ( !sec ) {
return;
}
if ( sec < 0 ) {
// s = "Waiting for players";
s = CG_GetStringEdString("MP_INGAME", "WAITING_FOR_PLAYERS");
w = CG_DrawStrlen( s ) * BIGCHAR_WIDTH;
CG_DrawBigString(320 - w / 2, 24, s, 1.0F);
cg.warmupCount = 0;
return;
}
if (cgs.gametype == GT_DUEL || cgs.gametype == GT_POWERDUEL)
{
// find the two active players
clientInfo_t *ci1, *ci2, *ci3;
ci1 = NULL;
ci2 = NULL;
ci3 = NULL;
if (cgs.gametype == GT_POWERDUEL)
{
if (cgs.duelist1 != -1)
{
ci1 = &cgs.clientinfo[cgs.duelist1];
}
if (cgs.duelist2 != -1)
{
ci2 = &cgs.clientinfo[cgs.duelist2];
}
if (cgs.duelist3 != -1)
{
ci3 = &cgs.clientinfo[cgs.duelist3];
}
}
else
{
for ( i = 0 ; i < cgs.maxclients ; i++ ) {
if ( cgs.clientinfo[i].infoValid && cgs.clientinfo[i].team == TEAM_FREE ) {
if ( !ci1 ) {
ci1 = &cgs.clientinfo[i];
} else {
ci2 = &cgs.clientinfo[i];
}
}
}
}
if ( ci1 && ci2 )
{
if (ci3)
{
s = va( "%s vs %s and %s", ci1->name, ci2->name, ci3->name );
}
else
{
s = va( "%s vs %s", ci1->name, ci2->name );
}
w = CG_Text_Width(s, 0.6f, FONT_MEDIUM);
CG_Text_Paint(320 - w / 2, 60, 0.6f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE,FONT_MEDIUM);
}
} else {
if ( cgs.gametype == GT_FFA ) {
s = CG_GetStringEdString("MENUS", "FREE_FOR_ALL");//"Free For All";
} else if ( cgs.gametype == GT_HOLOCRON ) {
s = CG_GetStringEdString("MENUS", "HOLOCRON_FFA");//"Holocron FFA";
} else if ( cgs.gametype == GT_JEDIMASTER ) {
//[OLDGAMETYPES]
//s = CG_GetStringEdString("MENUS", "POWERDUEL");//"Jedi Master";??
s = CG_GetStringEdString("OJP_MENUS", "JEDIMASTER");//"Jedi Master";??
//[/OLDGAMETYPES]
} else if ( cgs.gametype == GT_TEAM ) {
s = CG_GetStringEdString("MENUS", "TEAM_FFA");//"Team FFA";
} else if ( cgs.gametype == GT_SIEGE ) {
s = CG_GetStringEdString("MENUS", "SIEGE");//"Siege";
} else if ( cgs.gametype == GT_CTF ) {
s = CG_GetStringEdString("MENUS", "CAPTURE_THE_FLAG");//"Capture the Flag";
} else if ( cgs.gametype == GT_CTY ) {
s = CG_GetStringEdString("MENUS", "CAPTURE_THE_YSALIMARI");//"Capture the Ysalamiri";
//[CoOp]
} else if ( cgs.gametype == GT_SINGLE_PLAYER ) {
s = CG_GetStringEdString("OJP_MENUS", "COOP");//"Cooperative";
//[/CoOp]
} else {
s = "";
}
w = CG_Text_Width(s, 1.5f, FONT_MEDIUM);
CG_Text_Paint(320 - w / 2, 90, 1.5f, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE,FONT_MEDIUM);
}
sec = ( sec - cg.time ) / 1000;
if ( sec < 0 ) {
cg.warmup = 0;
sec = 0;
}
// s = va( "Starts in: %i", sec + 1 );
s = va( "%s: %i",CG_GetStringEdString("MP_INGAME", "STARTS_IN"), sec + 1 );
if ( sec != cg.warmupCount ) {
cg.warmupCount = sec;
if (cgs.gametype != GT_SIEGE)
{
switch ( sec ) {
case 0:
trap_S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER );
break;
case 1:
trap_S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER );
break;
case 2:
trap_S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER );
break;
default:
break;
}
}
}
scale = 0.45f;
switch ( cg.warmupCount ) {
case 0:
cw = 28;
scale = 1.25f;
break;
case 1:
cw = 24;
scale = 1.15f;
break;
case 2:
cw = 20;
scale = 1.05f;
break;
default:
cw = 16;
scale = 0.9f;
break;
}
w = CG_Text_Width(s, scale, FONT_MEDIUM);
CG_Text_Paint(320 - w / 2, 125, scale, colorWhite, s, 0, 0, ITEM_TEXTSTYLE_SHADOWEDMORE, FONT_MEDIUM);
}
//==================================================================================
/*
=================
CG_DrawTimedMenus
=================
*/
void CG_DrawTimedMenus() {
if (cg.voiceTime) {
int t = cg.time - cg.voiceTime;
if ( t > 2500 ) {
Menus_CloseByName("voiceMenu");
trap_Cvar_Set("cl_conXOffset", "0");
cg.voiceTime = 0;
}
}
}
void CG_DrawFlagStatus()
{
int myFlagTakenShader = 0;
int theirFlagShader = 0;
int team = 0;
int startDrawPos = 2;
int ico_size = 32;
if (!cg.snap)
{
return;
}
if (cgs.gametype != GT_CTF && cgs.gametype != GT_CTY)
{
return;
}
team = cg.snap->ps.persistant[PERS_TEAM];
if (cgs.gametype == GT_CTY)
{
if (team == TEAM_RED)
{
myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" );
theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_ys" );
}
else
{
myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" );
theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_ys" );
}
}
else
{
if (team == TEAM_RED)
{
myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag_x" );
theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag" );
}
else
{
myFlagTakenShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_bflag_x" );
theirFlagShader = trap_R_RegisterShaderNoMip( "gfx/hud/mpi_rflag" );
}
}
if (CG_YourTeamHasFlag())
{
//CG_DrawPic( startDrawPos, 330, ico_size, ico_size, theirFlagShader );
CG_DrawPic( 2, 330-startDrawPos, ico_size, ico_size, theirFlagShader );
startDrawPos += ico_size+2;
}
if (CG_OtherTeamHasFlag())
{
//CG_DrawPic( startDrawPos, 330, ico_size, ico_size, myFlagTakenShader );
CG_DrawPic( 2, 330-startDrawPos, ico_size, ico_size, myFlagTakenShader );
}
}
//draw meter showing jetpack fuel when it's not full
#define JPFUELBAR_H 60 //was JETPACK_MAXFUEL
#define JPFUELBAR_W 20.0f
#define JPFUELBAR_X (SCREEN_WIDTH-JPFUELBAR_W-8.0f)
//[NewHud]
//moved the jetpack fuel bar a little since the new hud overlapped it.
#define JPFUELBAR_Y 240.0f
//#define JPFUELBAR_Y 260.0f
//[/NewHud]
void CG_DrawJetpackFuel(void)
{
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x = JPFUELBAR_X;
float y = JPFUELBAR_Y;
float percent = ((float)cg.snap->ps.jetpackFuel / JETPACK_MAXFUEL) * JPFUELBAR_H;
if (percent > JPFUELBAR_H)
{
return;
}
if (percent < 0.1f)
{
percent = 0.1f;
}
//color of the bar
aColor[0] = 0.5f;
aColor[1] = 0.0f;
aColor[2] = 0.0f;
aColor[3] = 0.8f;
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing fuel"
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.1f;
//draw the background (black)
CG_DrawRect(x, y, JPFUELBAR_W, JPFUELBAR_H, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, (y+1.0f+(JPFUELBAR_H-percent)), (JPFUELBAR_W-1.0f), (JPFUELBAR_H-1.0f-(JPFUELBAR_H-percent)), aColor);
//then draw the other part greyed out
CG_FillRect(x+1.0f, y+1.0f, JPFUELBAR_W-1.0f, JPFUELBAR_H-percent, cColor);
}
//draw meter showing e-web health when it is in use
#define EWEBHEALTH_H 100.0f
#define EWEBHEALTH_W 20.0f
#define EWEBHEALTH_X (SCREEN_WIDTH-EWEBHEALTH_W-8.0f)
//[NewHud]
//moved to prevent overlap with new hud.
#define EWEBHEALTH_Y 240.0f
//#define EWEBHEALTH_Y 290.0f
//[/NewHud]
void CG_DrawEWebHealth(void)
{
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x = EWEBHEALTH_X;
float y = EWEBHEALTH_Y;
centity_t *eweb = &cg_entities[cg.predictedPlayerState.emplacedIndex];
float percent = ((float)eweb->currentState.health/eweb->currentState.maxhealth)*EWEBHEALTH_H;
if (percent > EWEBHEALTH_H)
{
return;
}
if (percent < 0.1f)
{
percent = 0.1f;
}
//kind of hacky, need to pass a coordinate in here
if (cg.snap->ps.jetpackFuel < JETPACK_MAXFUEL)
{
x -= (JPFUELBAR_W+8.0f);
}
if (cg.snap->ps.cloakFuel < 100)
{
x -= (JPFUELBAR_W+8.0f);
}
//color of the bar
aColor[0] = 0.5f;
aColor[1] = 0.0f;
aColor[2] = 0.0f;
aColor[3] = 0.8f;
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing fuel"
cColor[0] = 0.5f;
cColor[1] = 0.5f;
cColor[2] = 0.5f;
cColor[3] = 0.1f;
//draw the background (black)
CG_DrawRect(x, y, EWEBHEALTH_W, EWEBHEALTH_H, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much health there is in the color specified
CG_FillRect(x+1.0f, y+1.0f+(EWEBHEALTH_H-percent), EWEBHEALTH_W-1.0f, EWEBHEALTH_H-1.0f-(EWEBHEALTH_H-percent), aColor);
//then draw the other part greyed out
CG_FillRect(x+1.0f, y+1.0f, EWEBHEALTH_W-1.0f, EWEBHEALTH_H-percent, cColor);
}
//draw meter showing cloak fuel when it's not full
#define CLFUELBAR_H 100.0f
#define CLFUELBAR_W 20.0f
#define CLFUELBAR_X (SCREEN_WIDTH-CLFUELBAR_W-8.0f)
//[NewHud]
//moved to prevent overlap with new hud.
#define CLFUELBAR_Y 240.0f
//#define CLFUELBAR_Y 260.0f
//[/NewHud]
void CG_DrawCloakFuel(void)
{
vec4_t aColor;
vec4_t bColor;
vec4_t cColor;
float x = CLFUELBAR_X;
float y = CLFUELBAR_Y;
float percent = ((float)cg.snap->ps.cloakFuel/100.0f)*CLFUELBAR_H;
if (percent > CLFUELBAR_H)
{
return;
}
if ( cg.snap->ps.jetpackFuel < JETPACK_MAXFUEL )
{//if drawing jetpack fuel bar too, then move this over...?
x -= (JPFUELBAR_W+8.0f);
}
if (percent < 0.1f)
{
percent = 0.1f;
}
//color of the bar
aColor[0] = 0.0f;
aColor[1] = 0.0f;
aColor[2] = 0.6f;
aColor[3] = 0.8f;
//color of the border
bColor[0] = 0.0f;
bColor[1] = 0.0f;
bColor[2] = 0.0f;
bColor[3] = 0.3f;
//color of greyed out "missing fuel"
cColor[0] = 0.1f;
cColor[1] = 0.1f;
cColor[2] = 0.3f;
cColor[3] = 0.1f;
//draw the background (black)
CG_DrawRect(x, y, CLFUELBAR_W, CLFUELBAR_H, 1.0f, colorTable[CT_BLACK]);
//now draw the part to show how much fuel there is in the color specified
CG_FillRect(x+1.0f, y+1.0f+(CLFUELBAR_H-percent), CLFUELBAR_W-1.0f, CLFUELBAR_H-1.0f-(CLFUELBAR_H-percent), aColor);
//then draw the other part greyed out
CG_FillRect(x+1.0f, y+1.0f, CLFUELBAR_W-1.0f, CLFUELBAR_H-percent, cColor);
}
int cgRageTime = 0;
int cgRageFadeTime = 0;
float cgRageFadeVal = 0;
int cgRageRecTime = 0;
int cgRageRecFadeTime = 0;
float cgRageRecFadeVal = 0;
int cgAbsorbTime = 0;
int cgAbsorbFadeTime = 0;
float cgAbsorbFadeVal = 0;
int cgProtectTime = 0;
int cgProtectFadeTime = 0;
float cgProtectFadeVal = 0;
int cgYsalTime = 0;
int cgYsalFadeTime = 0;
float cgYsalFadeVal = 0;
qboolean gCGHasFallVector = qfalse;
vec3_t gCGFallVector;
/*
=================
CG_Draw2D
=================
*/
extern int cgSiegeRoundState;
extern int cgSiegeRoundTime;
extern int team1Timed;
extern int team2Timed;
int cg_beatingSiegeTime = 0;
int cgSiegeRoundBeganTime = 0;
int cgSiegeRoundCountTime = 0;
static void CG_DrawSiegeTimer(int timeRemaining, qboolean isMyTeam)
{ //rwwFIXMEFIXME: Make someone make assets and use them.
//this function is pretty much totally placeholder.
// int x = 0;
// int y = SCREEN_HEIGHT-160;
int fColor = 0;
int minutes = 0;
int seconds = 0;
char timeStr[1024];
menuDef_t *menuHUD = NULL;
itemDef_t *item = NULL;
menuHUD = Menus_FindByName("mp_timer");
if (!menuHUD)
{
return;
}
item = Menu_FindItemByName(menuHUD, "frame");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
seconds = timeRemaining;
while (seconds >= 60)
{
minutes++;
seconds -= 60;
}
strcpy(timeStr, va( "%i:%02i", minutes, seconds ));
if (isMyTeam)
{
fColor = CT_HUD_RED;
}
else
{
fColor = CT_HUD_GREEN;
}
// trap_Cvar_Set("ui_siegeTimer", timeStr);
// UI_DrawProportionalString( x+16, y+40, timeStr,
// UI_SMALLFONT|UI_DROPSHADOW, colorTable[fColor] );
item = Menu_FindItemByName(menuHUD, "timer");
if (item)
{
UI_DrawProportionalString(
item->window.rect.x,
item->window.rect.y,
timeStr,
UI_SMALLFONT|UI_DROPSHADOW,
colorTable[fColor] );
}
}
static void CG_DrawSiegeDeathTimer( int timeRemaining )
{
int minutes = 0;
int seconds = 0;
char timeStr[1024];
menuDef_t *menuHUD = NULL;
itemDef_t *item = NULL;
menuHUD = Menus_FindByName("mp_timer");
if (!menuHUD)
{
return;
}
item = Menu_FindItemByName(menuHUD, "frame");
if (item)
{
trap_R_SetColor( item->window.foreColor );
CG_DrawPic(
item->window.rect.x,
item->window.rect.y,
item->window.rect.w,
item->window.rect.h,
item->window.background );
}
seconds = timeRemaining;
while (seconds >= 60)
{
minutes++;
seconds -= 60;
}
if (seconds < 10)
{
strcpy(timeStr, va( "%i:0%i", minutes, seconds ));
}
else
{
strcpy(timeStr, va( "%i:%i", minutes, seconds ));
}
item = Menu_FindItemByName(menuHUD, "deathtimer");
if (item)
{
UI_DrawProportionalString(
item->window.rect.x,
item->window.rect.y,
timeStr,
UI_SMALLFONT|UI_DROPSHADOW,
item->window.foreColor );
}
}
int cgSiegeEntityRender = 0;
static void CG_DrawSiegeHUDItem(void)
{
void *g2;
qhandle_t handle;
vec3_t origin, angles;
vec3_t mins, maxs;
float len;
centity_t *cent = &cg_entities[cgSiegeEntityRender];
if (cent->ghoul2)
{
g2 = cent->ghoul2;
handle = 0;
}
else
{
handle = cgs.gameModels[cent->currentState.modelindex];
g2 = NULL;
}
if (handle)
{
trap_R_ModelBounds( handle, mins, maxs );
}
else
{
VectorSet(mins, -16, -16, -20);
VectorSet(maxs, 16, 16, 32);
}
origin[2] = -0.5 * ( mins[2] + maxs[2] );
origin[1] = 0.5 * ( mins[1] + maxs[1] );
len = 0.5 * ( maxs[2] - mins[2] );
origin[0] = len / 0.268;
VectorClear(angles);
angles[YAW] = cg.autoAngles[YAW];
CG_Draw3DModel( 8, 8, 64, 64, handle, g2, cent->currentState.g2radius, 0, origin, angles );
cgSiegeEntityRender = 0; //reset for next frame
}
/*====================================
chatbox functionality -rww
====================================*/
#define CHATBOX_CUTOFF_LEN 550
#define CHATBOX_FONT_HEIGHT 20
//utility func, insert a string into a string at the specified
//place (assuming this will not overflow the buffer)
void CG_ChatBox_StrInsert(char *buffer, int place, char *str)
{
int insLen = strlen(str);
int i = strlen(buffer);
int k = 0;
buffer[i+insLen+1] = 0; //terminate the string at its new length
while (i >= place)
{
buffer[i+insLen] = buffer[i];
i--;
}
i++;
while (k < insLen)
{
buffer[i] = str[k];
i++;
k++;
}
}
//add chatbox string
void CG_ChatBox_AddString(char *chatStr)
{
chatBoxItem_t *chat = &cg.chatItems[cg.chatItemActive];
float chatLen;
if (cg_chatBox.integer<=0)
{ //don't bother then.
return;
}
memset(chat, 0, sizeof(chatBoxItem_t));
if (strlen(chatStr) > sizeof(chat->string))
{ //too long, terminate at proper len.
chatStr[sizeof(chat->string)-1] = 0;
}
strcpy(chat->string, chatStr);
chat->time = cg.time + cg_chatBox.integer;
chat->lines = 1;
chatLen = CG_Text_Width(chat->string, 1.0f, FONT_SMALL);
if (chatLen > CHATBOX_CUTOFF_LEN)
{ //we have to break it into segments...
int i = 0;
int lastLinePt = 0;
char s[2];
chatLen = 0;
while (chat->string[i])
{
s[0] = chat->string[i];
s[1] = 0;
chatLen += CG_Text_Width(s, 0.65f, FONT_SMALL);
if (chatLen >= CHATBOX_CUTOFF_LEN)
{
int j = i;
while (j > 0 && j > lastLinePt)
{
if (chat->string[j] == ' ')
{
break;
}
j--;
}
if (chat->string[j] == ' ')
{
i = j;
}
chat->lines++;
CG_ChatBox_StrInsert(chat->string, i, "\n");
i++;
chatLen = 0;
lastLinePt = i+1;
}
i++;
}
}
cg.chatItemActive++;
if (cg.chatItemActive >= MAX_CHATBOX_ITEMS)
{
cg.chatItemActive = 0;
}
}
//insert item into array (rearranging the array if necessary)
void CG_ChatBox_ArrayInsert(chatBoxItem_t **array, int insPoint, int maxNum, chatBoxItem_t *item)
{
if (array[insPoint])
{ //recursively call, to move everything up to the top
if (insPoint+1 >= maxNum)
{
CG_Error("CG_ChatBox_ArrayInsert: Exceeded array size");
}
CG_ChatBox_ArrayInsert(array, insPoint+1, maxNum, array[insPoint]);
}
//now that we have moved anything that would be in this slot up, insert what we want into the slot
array[insPoint] = item;
}
//go through all the chat strings and draw them if they are not yet expired
static CGAME_INLINE void CG_ChatBox_DrawStrings(void)
{
chatBoxItem_t *drawThese[MAX_CHATBOX_ITEMS];
int numToDraw = 0;
int linesToDraw = 0;
int i = 0;
int x = 30;
int y = cg.scoreBoardShowing ? 475 : cg_chatBoxHeight.integer;
float fontScale = 0.65f;
if (!cg_chatBox.integer)
{
return;
}
memset(drawThese, 0, sizeof(drawThese));
while (i < MAX_CHATBOX_ITEMS)
{
if (cg.chatItems[i].time >= cg.time)
{
int check = numToDraw;
int insertionPoint = numToDraw;
while (check >= 0)
{
if (drawThese[check] &&
cg.chatItems[i].time < drawThese[check]->time)
{ //insert here
insertionPoint = check;
}
check--;
}
CG_ChatBox_ArrayInsert(drawThese, insertionPoint, MAX_CHATBOX_ITEMS, &cg.chatItems[i]);
numToDraw++;
linesToDraw += cg.chatItems[i].lines;
}
i++;
}
if (!numToDraw)
{ //nothing, then, just get out of here now.
return;
}
//move initial point up so we draw bottom-up (visually)
y -= (CHATBOX_FONT_HEIGHT*fontScale)*linesToDraw;
//we have the items we want to draw, just quickly loop through them now
i = 0;
while (i < numToDraw)
{
CG_Text_Paint(x, y, fontScale, colorWhite, drawThese[i]->string, 0, 0, ITEM_TEXTSTYLE_OUTLINED, FONT_SMALL );
y += ((CHATBOX_FONT_HEIGHT*fontScale)*drawThese[i]->lines);
i++;
}
}
//[CoOp]
void CGCam_DoFade(void);
//[/CoOp]
static void CG_Draw2DScreenTints( void )
{
float rageTime, rageRecTime, absorbTime, protectTime, ysalTime;
vec4_t hcolor;
//[CoOp]
//cutscene camera fade code
CGCam_DoFade();
//[/CoOp]
if (cgs.clientinfo[cg.snap->ps.clientNum].team != TEAM_SPECTATOR)
{
if (cg.snap->ps.fd.forcePowersActive & (1 << FP_RAGE))
{
if (!cgRageTime)
{
cgRageTime = cg.time;
}
rageTime = (float)(cg.time - cgRageTime);
rageTime /= 9000;
if (rageTime < 0)
{
rageTime = 0;
}
if (rageTime > 0.15)
{
rageTime = 0.15;
}
hcolor[3] = rageTime;
hcolor[0] = 0.7;
hcolor[1] = 0;
hcolor[2] = 0;
if (!cg.renderingThirdPerson)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
cgRageFadeTime = 0;
cgRageFadeVal = 0;
}
else if (cgRageTime)
{
if (!cgRageFadeTime)
{
cgRageFadeTime = cg.time;
cgRageFadeVal = 0.15;
}
rageTime = cgRageFadeVal;
cgRageFadeVal -= (cg.time - cgRageFadeTime)*0.000005;
if (rageTime < 0)
{
rageTime = 0;
}
if (rageTime > 0.15)
{
rageTime = 0.15;
}
if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time)
{
float checkRageRecTime = rageTime;
if (checkRageRecTime < 0.15)
{
checkRageRecTime = 0.15;
}
hcolor[3] = checkRageRecTime;
hcolor[0] = rageTime*4;
if (hcolor[0] < 0.2)
{
hcolor[0] = 0.2;
}
hcolor[1] = 0.2;
hcolor[2] = 0.2;
}
else
{
hcolor[3] = rageTime;
hcolor[0] = 0.7;
hcolor[1] = 0;
hcolor[2] = 0;
}
if (!cg.renderingThirdPerson && rageTime)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
else
{
if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time)
{
hcolor[3] = 0.15;
hcolor[0] = 0.2;
hcolor[1] = 0.2;
hcolor[2] = 0.2;
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
cgRageTime = 0;
}
}
else if (cg.snap->ps.fd.forceRageRecoveryTime > cg.time)
{
if (!cgRageRecTime)
{
cgRageRecTime = cg.time;
}
rageRecTime = (float)(cg.time - cgRageRecTime);
rageRecTime /= 9000;
if (rageRecTime < 0.15)//0)
{
rageRecTime = 0.15;//0;
}
if (rageRecTime > 0.15)
{
rageRecTime = 0.15;
}
hcolor[3] = rageRecTime;
hcolor[0] = 0.2;
hcolor[1] = 0.2;
hcolor[2] = 0.2;
if (!cg.renderingThirdPerson)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
cgRageRecFadeTime = 0;
cgRageRecFadeVal = 0;
}
else if (cgRageRecTime)
{
if (!cgRageRecFadeTime)
{
cgRageRecFadeTime = cg.time;
cgRageRecFadeVal = 0.15;
}
rageRecTime = cgRageRecFadeVal;
cgRageRecFadeVal -= (cg.time - cgRageRecFadeTime)*0.000005;
if (rageRecTime < 0)
{
rageRecTime = 0;
}
if (rageRecTime > 0.15)
{
rageRecTime = 0.15;
}
hcolor[3] = rageRecTime;
hcolor[0] = 0.2;
hcolor[1] = 0.2;
hcolor[2] = 0.2;
if (!cg.renderingThirdPerson && rageRecTime)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
else
{
cgRageRecTime = 0;
}
}
if (cg.snap->ps.fd.forcePowersActive & (1 << FP_ABSORB))
{
if (!cgAbsorbTime)
{
cgAbsorbTime = cg.time;
}
absorbTime = (float)(cg.time - cgAbsorbTime);
absorbTime /= 9000;
if (absorbTime < 0)
{
absorbTime = 0;
}
if (absorbTime > 0.15)
{
absorbTime = 0.15;
}
hcolor[3] = absorbTime/2;
hcolor[0] = 0;
hcolor[1] = 0;
hcolor[2] = 0.7;
if (!cg.renderingThirdPerson)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
cgAbsorbFadeTime = 0;
cgAbsorbFadeVal = 0;
}
else if (cgAbsorbTime)
{
if (!cgAbsorbFadeTime)
{
cgAbsorbFadeTime = cg.time;
cgAbsorbFadeVal = 0.15;
}
absorbTime = cgAbsorbFadeVal;
cgAbsorbFadeVal -= (cg.time - cgAbsorbFadeTime)*0.000005;
if (absorbTime < 0)
{
absorbTime = 0;
}
if (absorbTime > 0.15)
{
absorbTime = 0.15;
}
hcolor[3] = absorbTime/2;
hcolor[0] = 0;
hcolor[1] = 0;
hcolor[2] = 0.7;
if (!cg.renderingThirdPerson && absorbTime)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
else
{
cgAbsorbTime = 0;
}
}
if (cg.snap->ps.fd.forcePowersActive & (1 << FP_MANIPULATE))
{
if (!cgProtectTime)
{
cgProtectTime = cg.time;
}
protectTime = (float)(cg.time - cgProtectTime);
protectTime /= 9000;
if (protectTime < 0)
{
protectTime = 0;
}
if (protectTime > 0.15)
{
protectTime = 0.15;
}
hcolor[3] = protectTime/2;
hcolor[0] = 0;
hcolor[1] = 0.7;
hcolor[2] = 0;
if (!cg.renderingThirdPerson)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
cgProtectFadeTime = 0;
cgProtectFadeVal = 0;
}
else if (cgProtectTime)
{
if (!cgProtectFadeTime)
{
cgProtectFadeTime = cg.time;
cgProtectFadeVal = 0.15;
}
protectTime = cgProtectFadeVal;
cgProtectFadeVal -= (cg.time - cgProtectFadeTime)*0.000005;
if (protectTime < 0)
{
protectTime = 0;
}
if (protectTime > 0.15)
{
protectTime = 0.15;
}
hcolor[3] = protectTime/2;
hcolor[0] = 0;
hcolor[1] = 0.7;
hcolor[2] = 0;
if (!cg.renderingThirdPerson && protectTime)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
else
{
cgProtectTime = 0;
}
}
if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0)
{
CG_DrawRocketLocking( cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime );
}
if (BG_HasYsalamiri(cgs.gametype, &cg.snap->ps))
{
if (!cgYsalTime)
{
cgYsalTime = cg.time;
}
ysalTime = (float)(cg.time - cgYsalTime);
ysalTime /= 9000;
if (ysalTime < 0)
{
ysalTime = 0;
}
if (ysalTime > 0.15)
{
ysalTime = 0.15;
}
hcolor[3] = ysalTime/2;
hcolor[0] = 0.7;
hcolor[1] = 0.7;
hcolor[2] = 0;
if (!cg.renderingThirdPerson)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
cgYsalFadeTime = 0;
cgYsalFadeVal = 0;
}
else if (cgYsalTime)
{
if (!cgYsalFadeTime)
{
cgYsalFadeTime = cg.time;
cgYsalFadeVal = 0.15;
}
ysalTime = cgYsalFadeVal;
cgYsalFadeVal -= (cg.time - cgYsalFadeTime)*0.000005;
if (ysalTime < 0)
{
ysalTime = 0;
}
if (ysalTime > 0.15)
{
ysalTime = 0.15;
}
hcolor[3] = ysalTime/2;
hcolor[0] = 0.7;
hcolor[1] = 0.7;
hcolor[2] = 0;
if (!cg.renderingThirdPerson && ysalTime)
{
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
}
else
{
cgYsalTime = 0;
}
}
}
if ( (cg.refdef.viewContents&CONTENTS_LAVA) )
{//tint screen red
float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2;
hcolor[3] = 0.5 + (0.15f*sin( phase ));
hcolor[0] = 0.7f;
hcolor[1] = 0;
hcolor[2] = 0;
CG_DrawRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor );
}
else if ( (cg.refdef.viewContents&CONTENTS_SLIME) )
{//tint screen green
float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2;
hcolor[3] = 0.4 + (0.1f*sin( phase ));
hcolor[0] = 0;
hcolor[1] = 0.7f;
hcolor[2] = 0;
CG_DrawRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor );
}
else if ( (cg.refdef.viewContents&CONTENTS_WATER) )
{//tint screen light blue -- FIXME: don't do this if CONTENTS_FOG? (in case someone *does* make a water shader with fog in it?)
float phase = cg.time / 1000.0 * WAVE_FREQUENCY * M_PI * 2;
hcolor[3] = 0.3 + (0.05f*sin( phase ));
hcolor[0] = 0;
hcolor[1] = 0.2f;
hcolor[2] = 0.8;
CG_DrawRect( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor );
}
}
static void CG_Draw2D( void ) {
float inTime = cg.invenSelectTime+WEAPON_SELECT_TIME;
float wpTime = cg.weaponSelectTime+WEAPON_SELECT_TIME;
float fallTime;
float bestTime;
int drawSelect = 0;
// if we are taking a levelshot for the menu, don't draw anything
if ( cg.levelShot ) {
return;
}
if (cgs.clientinfo[cg.snap->ps.clientNum].team == TEAM_SPECTATOR)
{
cgRageTime = 0;
cgRageFadeTime = 0;
cgRageFadeVal = 0;
cgRageRecTime = 0;
cgRageRecFadeTime = 0;
cgRageRecFadeVal = 0;
cgAbsorbTime = 0;
cgAbsorbFadeTime = 0;
cgAbsorbFadeVal = 0;
cgProtectTime = 0;
cgProtectFadeTime = 0;
cgProtectFadeVal = 0;
cgYsalTime = 0;
cgYsalFadeTime = 0;
cgYsalFadeVal = 0;
}
if ( cg_draw2D.integer == 0 ) {
return;
}
if ( cg.snap->ps.pm_type == PM_INTERMISSION ) {
CG_DrawIntermission();
CG_ChatBox_DrawStrings();
return;
}
CG_Draw2DScreenTints();
if (cg.snap->ps.rocketLockIndex != ENTITYNUM_NONE && (cg.time - cg.snap->ps.rocketLockTime) > 0)
{
CG_DrawRocketLocking( cg.snap->ps.rocketLockIndex, cg.snap->ps.rocketLockTime );
}
if (cg.snap->ps.holocronBits)
{
CG_DrawHolocronIcons();
}
if (cg.snap->ps.fd.forcePowersActive || cg.snap->ps.fd.forceRageRecoveryTime > cg.time)
{
CG_DrawActivePowers();
}
if (cg.snap->ps.jetpackFuel < JETPACK_MAXFUEL)
{ //draw it as long as it isn't full
CG_DrawJetpackFuel();
}
if (cg.snap->ps.cloakFuel < 100)
{ //draw it as long as it isn't full
CG_DrawCloakFuel();
}
if (cg.predictedPlayerState.emplacedIndex > 0)
{
centity_t *eweb = &cg_entities[cg.predictedPlayerState.emplacedIndex];
if (eweb->currentState.weapon == WP_NONE)
{ //using an e-web, draw its health
CG_DrawEWebHealth();
}
}
// Draw this before the text so that any text won't get clipped off
CG_DrawZoomMask();
if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR ) {
CG_DrawSpectator();
CG_DrawCrosshair(NULL, 0);
CG_DrawCrosshairNames();
CG_SaberClashFlare();
} else {
// don't draw any status if dead or the scoreboard is being explicitly shown
if ( !cg.showScores && cg.snap->ps.stats[STAT_HEALTH] > 0 ) {
if ( 0 ) {
//Reenable if stats are drawn with menu system again
Menu_PaintAll();
CG_DrawTimedMenus();
}
//CG_DrawTemporaryStats();
CG_DrawCrosshairNames();
if (cg_drawStatus.integer)
{
CG_DrawIconBackground();
}
if (inTime > wpTime)
{
drawSelect = 1;
bestTime = cg.invenSelectTime;
}
else //only draw the most recent since they're drawn in the same place
{
drawSelect = 2;
bestTime = cg.weaponSelectTime;
}
if (cg.forceSelectTime > bestTime)
{
drawSelect = 3;
}
switch(drawSelect)
{
case 1:
CG_DrawInvenSelect();
break;
case 2:
CG_DrawWeaponSelect();
break;
case 3:
CG_DrawForceSelect();
break;
default:
break;
}
if (cg_drawStatus.integer)
{
//Powerups now done with upperright stuff
//CG_DrawPowerupIcons();
CG_DrawFlagStatus();
}
CG_SaberClashFlare();
if (cg_drawStatus.integer)
{
CG_DrawStats();
}
CG_DrawPickupItem();
//Do we want to use this system again at some point?
//CG_DrawReward();
}
}
if (cg.snap->ps.fallingToDeath)
{
vec4_t hcolor;
fallTime = (float)(cg.time - cg.snap->ps.fallingToDeath);
fallTime /= (FALL_FADE_TIME/2);
if (fallTime < 0)
{
fallTime = 0;
}
if (fallTime > 1)
{
fallTime = 1;
}
hcolor[3] = fallTime;
hcolor[0] = 0;
hcolor[1] = 0;
hcolor[2] = 0;
CG_DrawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH*SCREEN_HEIGHT, hcolor);
if (!gCGHasFallVector)
{
VectorCopy(cg.snap->ps.origin, gCGFallVector);
gCGHasFallVector = qtrue;
}
}
else
{
if (gCGHasFallVector)
{
gCGHasFallVector = qfalse;
VectorClear(gCGFallVector);
}
}
CG_DrawVote();
CG_DrawTeamVote();
CG_DrawLagometer();
if (!cg_paused.integer) {
CG_DrawBracketedEntities();
CG_DrawUpperRight();
}
if ( !CG_DrawFollow() ) {
CG_DrawWarmup();
}
if (cgSiegeRoundState)
{
char pStr[1024];
int rTime = 0;
//cgSiegeRoundBeganTime = 0;
switch (cgSiegeRoundState)
{
case 1:
CG_CenterPrint(CG_GetStringEdString("MP_INGAME", "WAITING_FOR_PLAYERS"), SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH);
break;
case 2:
rTime = (SIEGE_ROUND_BEGIN_TIME - (cg.time - cgSiegeRoundTime));
if (rTime < 0)
{
rTime = 0;
}
if (rTime > SIEGE_ROUND_BEGIN_TIME)
{
rTime = SIEGE_ROUND_BEGIN_TIME;
}
rTime /= 1000;
rTime += 1;
if (rTime < 1)
{
rTime = 1;
}
if (rTime <= 3 && rTime != cgSiegeRoundCountTime)
{
cgSiegeRoundCountTime = rTime;
switch (rTime)
{
case 1:
trap_S_StartLocalSound( cgs.media.count1Sound, CHAN_ANNOUNCER );
break;
case 2:
trap_S_StartLocalSound( cgs.media.count2Sound, CHAN_ANNOUNCER );
break;
case 3:
trap_S_StartLocalSound( cgs.media.count3Sound, CHAN_ANNOUNCER );
break;
default:
break;
}
}
strcpy(pStr, va("%s %i...", CG_GetStringEdString("MP_INGAME", "ROUNDBEGINSIN"), rTime));
CG_CenterPrint(pStr, SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH);
//same
break;
default:
break;
}
cgSiegeEntityRender = 0;
}
else if (cgSiegeRoundTime)
{
CG_CenterPrint("", SCREEN_HEIGHT * 0.30, BIGCHAR_WIDTH);
cgSiegeRoundTime = 0;
//cgSiegeRoundBeganTime = cg.time;
cgSiegeEntityRender = 0;
}
else if (cgSiegeRoundBeganTime)
{ //Draw how much time is left in the round based on local info.
int timedTeam = TEAM_FREE;
int timedValue = 0;
if (cgSiegeEntityRender)
{ //render the objective item model since this client has it
CG_DrawSiegeHUDItem();
}
if (team1Timed)
{
timedTeam = TEAM_RED; //team 1
if (cg_beatingSiegeTime)
{
timedValue = cg_beatingSiegeTime;
}
else
{
timedValue = team1Timed;
}
}
else if (team2Timed)
{
timedTeam = TEAM_BLUE; //team 2
if (cg_beatingSiegeTime)
{
timedValue = cg_beatingSiegeTime;
}
else
{
timedValue = team2Timed;
}
}
if (timedTeam != TEAM_FREE)
{ //one of the teams has a timer
int timeRemaining;
qboolean isMyTeam = qfalse;
if (cgs.siegeTeamSwitch && !cg_beatingSiegeTime)
{ //in switchy mode but not beating a time, so count up.
timeRemaining = (cg.time-cgSiegeRoundBeganTime);
if (timeRemaining < 0)
{
timeRemaining = 0;
}
}
else
{
timeRemaining = (((cgSiegeRoundBeganTime)+timedValue) - cg.time);
}
if (timeRemaining > timedValue)
{
timeRemaining = timedValue;
}
else if (timeRemaining < 0)
{
timeRemaining = 0;
}
if (timeRemaining)
{
timeRemaining /= 1000;
}
if (cg.predictedPlayerState.persistant[PERS_TEAM] == timedTeam)
{ //the team that's timed is the one this client is on
isMyTeam = qtrue;
}
CG_DrawSiegeTimer(timeRemaining, isMyTeam);
}
}
else
{
cgSiegeEntityRender = 0;
}
if ( cg_siegeDeathTime )
{
int timeRemaining = ( cg_siegeDeathTime - cg.time );
if ( timeRemaining < 0 )
{
timeRemaining = 0;
cg_siegeDeathTime = 0;
}
if ( timeRemaining )
{
timeRemaining /= 1000;
}
CG_DrawSiegeDeathTimer( timeRemaining );
}
// don't draw center string if scoreboard is up
cg.scoreBoardShowing = CG_DrawScoreboard();
if ( !cg.scoreBoardShowing) {
CG_DrawCenterString();
}
// always draw chat
CG_ChatBox_DrawStrings();
}
static void CG_DrawTourneyScoreboard() {
}
/*
=====================
CG_DrawActive
Perform all drawing needed to completely fill the screen
=====================
*/
void CG_DrawActive( stereoFrame_t stereoView ) {
float separation;
vec3_t baseOrg;
// optionally draw the info screen instead
if ( !cg.snap ) {
CG_DrawInformation();
return;
}
// optionally draw the tournement scoreboard instead
if ( cg.snap->ps.persistant[PERS_TEAM] == TEAM_SPECTATOR &&
( cg.snap->ps.pm_flags & PMF_SCOREBOARD ) ) {
CG_DrawTourneyScoreboard();
return;
}
switch ( stereoView ) {
case STEREO_CENTER:
separation = 0;
break;
case STEREO_LEFT:
separation = -cg_stereoSeparation.value / 2;
break;
case STEREO_RIGHT:
separation = cg_stereoSeparation.value / 2;
break;
default:
separation = 0;
CG_Error( "CG_DrawActive: Undefined stereoView" );
}
// clear around the rendered view if sized down
CG_TileClear();
// offset vieworg appropriately if we're doing stereo separation
VectorCopy( cg.refdef.vieworg, baseOrg );
if ( separation != 0 ) {
VectorMA( cg.refdef.vieworg, -separation, cg.refdef.viewaxis[1], cg.refdef.vieworg );
}
cg.refdef.rdflags |= RDF_DRAWSKYBOX;
// draw 3D view
trap_R_RenderScene( &cg.refdef );
// restore original viewpoint if running stereo
if ( separation != 0 ) {
VectorCopy( baseOrg, cg.refdef.vieworg );
}
// draw status bar and other floating elements
CG_Draw2D();
}
| [
"[email protected]@5776d9f2-9662-11de-ad41-3fcdc5e0e42d"
]
| [
[
[
1,
8656
]
]
]
|
fab84162ea03e75c206de028ac8bef8e0ccff2d7 | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /inc/TraficStatisticWindow.h | cd187ef9edfbf60393bc982538cbabdeb040e0b5 | []
| no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,897 | h | /*
============================================================================
Name : TraficStatisticWindow.h
Author : smallcat
Version :
Copyright : Your copyright notice
Description : CTraficStatisticWindow declaration
============================================================================
*/
#ifndef TRAFICSTATISTICWINDOW_H
#define TRAFICSTATISTICWINDOW_H
// INCLUDES
#include "Window.h"
#include "NotifyTimer.h"
class CMultiText;;
class CMainEngine;
class CFileReadByRow;
// CLASS DECLARATION
/**
* CTraficStatisticWindow
*
*/
class CTraficStatisticWindow : public CWindow,public MTimerNotifier
{
public: // Constructors and destructor
~CTraficStatisticWindow();
static CTraficStatisticWindow* NewL(CWindow* aParent,CMainEngine& aMainEngine);
static CTraficStatisticWindow* NewLC(CWindow* aParent,CMainEngine& aMainEngine);
private:
CTraficStatisticWindow(CWindow* aParent,CMainEngine& aMainEngine);
void ConstructL();
public://From CWindow
//派生类实现激活视图
virtual void DoActivateL();
//派生类实现冻结视图
virtual void DoDeactivate();
//派生类实现绘图
virtual void DoDraw(CGraphic& aGraphic)const;
//派生类实现按键事件响应
virtual TBool DoKeyEventL(TInt aKeyCode);
//派生类实现命令事件响应
virtual TBool DoHandleCommandL(TInt aCommand);
//派生类实现界面尺寸改变
virtual void DoSizeChanged();
//派生类实现设置左右按钮,以便覆盖按钮的控件返回时回复原样
virtual void ChangeButton();
public://From MTimerNotifier
virtual TBool DoPeriodTask();
private:
CNotifyTimer* iTimer;
private:
void InitSelectGroup();
private:
CMainEngine& iMainEngine;
CMultiText* iMultiText;//显示流量等等的内容
TReal i;
CFileReadByRow* iRes;
};
#endif // TRAFICSTATISTICWINDOW_H
| [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
]
| [
[
[
1,
73
]
]
]
|
0d9cba010689179c10433e0390e87edb7bde42f5 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /v5/594/c.cpp | 195be2dca4c49cb2ec3edb68702428a00b8a22a2 | []
| no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,342 | cpp |
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define REP(a,c,b) for(int _n=b,a=c;a<_n;a++)
unsigned long long toBase10(const char *in, int b) {
unsigned long long v = 0;
while((*in)!='\0' && (*in)!='\n' && (*in)!='\r') {
if((*in)>='0' && (*in)<='9') {
v = v * b + ((*in)-'0');
} else if((*in)>='A' && (*in)<='Z') {
v = v * b + ((*in)-'A'+10);
}
in++;
}
return v;
}
char *ltoa(long long n, char *out, int rout) {
int p = 0;
char temp[50];
long long t;
while(n > 0) {
t = n % rout;
if(t<10) temp[p] = '0' + t;
else temp[p] = 65 + t - 10;
p++;
n /= rout;
}
if(p==0) temp[p++] = '0';
for(int i=0;i!=p;i++) out[i] = temp[p-i-1];
out[p] = '\0';
return out;
}
char *base_convert(const char *in, char *out, int rin, int rout)
{
unsigned long long n = toBase10(in, rin);
return ltoa(n, out, rout);
}
int main() {
long long v;
int i,len,d;
char s[2][1000];
while((cin >> v)) {
ltoa(v,s[0],2);
len = strlen(s[0]);
d = 32 - len;
for(i=0;i!=d;i++) s[1][i]='0';
for(i=0;i!=len;i++) {
s[1][i+d] = s[0][len-1-i];
}
s[1][32]='\0';
cout << s[0] << " " << s[1] << endl;
cout << v << " converts to " << base_convert(s[1],s[0],2,10) << endl;
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
6eff44ef9b006f2e96aa603613b15f6171e9a9f7 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Common/ParticleMng.cpp | c581bf9725246df3e74dcd5d6527197d0d973521 | []
| no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 19,859 | cpp | #include "stdafx.h"
#include "ParticleMng.h"
const DWORD POINTVERTEX::FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE;
D3DXCOLOR g_clrColor = D3DXCOLOR( 1.0f, 0.5f, 0.5f, 1.0f );
DWORD g_clrColorFade = D3DXCOLOR( 1.0f, 0.25f, 0.25f, 1.0f );
//D3DXCOLOR g_clrColor2 = D3DXCOLOR( 0.125f, 0.5f, 1.0f, 1.0f );
D3DXCOLOR g_clrColor2 = D3DXCOLOR( 0.35f, 0.35f, 1.00f, 1.0f );
DWORD g_clrColorFade2 = D3DXCOLOR( 0.0f, 0.0f, 0.0f, 1.0f );
//CParticles g_Particle( 512, 2048, 0 );
//CParticles g_Particle2( 512, 2048, 1 );
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CParticles::CParticles()
{
Init();
}
CParticles::CParticles( DWORD dwFlush, DWORD dwDiscard, int nType )
{
Create( dwFlush, dwDiscard, nType );
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
CParticles::~CParticles()
{
Destroy();
}
void CParticles::Init( void )
{
m_bActive = 0;
m_bGravity = 0;
m_dwBase = 0;
m_dwFlush = 0;
m_dwDiscard = 0;
m_fSize = 0.3f;
m_dwParticles = 0;
m_dwParticlesLim = 0;
m_nType = 0;
m_pParticles = NULL;
m_pParticlesFree = NULL;
m_pVB = NULL;
m_pParticleTexture = NULL;
m_pPool = NULL;
// m_pPool = new PARTICLE[ m_dwParticlesLim ];
// memset( m_pPool, 0, sizeof(PARTICLE) * m_dwParticlesLim );
m_nPoolPtr = 0;
}
void CParticles::Destroy( void )
{
InvalidateDeviceObjects();
SAFE_RELEASE( m_pParticleTexture );
SAFE_DELETE_ARRAY( m_pPool );
}
void CParticles::Create( DWORD dwFlush, DWORD dwDiscard, int nType )
{
// int i;
Init();
m_bActive = TRUE;
m_dwBase = dwDiscard;
m_dwFlush = dwFlush;
m_dwDiscard = dwDiscard;
m_dwParticlesLim = dwDiscard;
m_nType = nType;
m_pPool = new PARTICLE[ m_dwParticlesLim ];
memset( m_pPool, 0, sizeof(PARTICLE) * m_dwParticlesLim );
}
HRESULT CParticles::InitDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR szFileName )
{
HRESULT hr;
if( m_bActive == FALSE ) return S_OK;
#ifdef __CLIENT
// Create the texture using D3DX
hr = LoadTextureFromRes( pd3dDevice, MakePath( DIR_MODELTEX, szFileName ),
D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN,
D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR,
D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, 0, NULL, NULL, &m_pParticleTexture );
if( hr == E_FAIL )
{
Error( "%s 읽기 실패", MakePath( DIR_MODELTEX, szFileName ) );
m_bActive = FALSE;
}
return hr;
#else
return E_FAIL;
#endif
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CParticles::RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice )
{
if( m_bActive == FALSE ) return S_OK;
if( m_pParticleTexture == NULL ) return S_OK;
HRESULT hr;
// Create a vertex buffer for the particle system. The size of this buffer
// does not relate to the number of particles that exist. Rather, the
// buffer is used as a communication channel with the device.. we fill in
// a bit, and tell the device to draw. While the device is drawing, we
// fill in the next bit using NOOVERWRITE. We continue doing this until
// we run out of vertex buffer space, and are forced to DISCARD the buffer
// and start over at the beginning.
if(FAILED(hr = pd3dDevice->CreateVertexBuffer( m_dwDiscard *
sizeof(POINTVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY | D3DUSAGE_POINTS,
POINTVERTEX::FVF, D3DPOOL_DEFAULT, &m_pVB, NULL )))
{
return E_FAIL;
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CParticles::InvalidateDeviceObjects()
{
SAFE_RELEASE( m_pVB );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name:
// Desc:
//-----------------------------------------------------------------------------
HRESULT CParticles::Update( void )
{
// if( m_nType == 1 ) return Update2();
if( m_bActive == FALSE ) return S_OK;
#ifdef __WORLDSERVER
return S_OK;
#endif
if( m_pParticleTexture == NULL ) return S_OK;
PARTICLE *pParticle, **ppParticle;
ppParticle = &m_pParticles;
while( *ppParticle )
{
pParticle = *ppParticle;
// Calculate new position
pParticle->m_fFade -= 0.015f;
pParticle->m_vPos += pParticle->m_vVel;
if( m_bGravity )
pParticle->m_vVel.y -= 0.005f; // 중력.
if( pParticle->m_fFade < 0.0f )
pParticle->m_fFade = 0;
// Kill old particles
// 희미해져 사라졌을때나 바닥에 떨어졌을때는 삭제됨.
if( pParticle->m_fFade <= 0 || (m_bGravity && pParticle->m_vPos.y < pParticle->m_fGroundY) )
{
// Kill particle
*ppParticle = pParticle->m_pNext;
pParticle->m_pNext = m_pParticlesFree;
m_pParticlesFree = pParticle;
// if(!pParticle->m_bSpark)
m_dwParticles--;
}
else
{
ppParticle = &pParticle->m_pNext;
}
}
return S_OK;
}
HRESULT CParticles::Update2( void )
{
if( m_bActive == FALSE ) return S_OK;
#ifdef __WORLDSERVER
return S_OK;
#endif
if( m_pParticleTexture == NULL ) return S_OK;
PARTICLE *pParticle, **ppParticle;
ppParticle = &m_pParticles;
while( *ppParticle )
{
pParticle = *ppParticle;
// Calculate new position
pParticle->m_fFade -= 0.015f;
pParticle->m_vPos += pParticle->m_vVel;
if( pParticle->m_fFade < 0 )
pParticle->m_fFade = 0;
// Kill old particles
if( pParticle->m_fFade <= 0 )
{
// Kill particle
*ppParticle = pParticle->m_pNext;
pParticle->m_pNext = m_pParticlesFree;
m_pParticlesFree = pParticle;
// if(!pParticle->m_bSpark)
m_dwParticles--;
}
else
{
ppParticle = &pParticle->m_pNext;
}
}
return S_OK;
}
// 파티클 객체 하나를 생성한다.
// vPos : 생성되는 시작위치
// vVel : 날아갈 방향.
HRESULT CParticles::CreateParticle( int nType, const D3DXVECTOR3 &vPos, const D3DXVECTOR3 &vVel, FLOAT fGroundY )
{
if( m_bActive == FALSE ) return S_OK;
#ifdef __WORLDSERVER
return S_OK;
#endif
if( m_pParticleTexture == NULL ) return S_OK;
PARTICLE *pParticle;
// static float fTime = 0.0f;
//fTime += fSecsPerFrame;
// Emit new particles - 새로운 파티클을 뿜어내다.
// DWORD dwParticlesEmit = m_dwParticles + dwNumParticlesToEmit;
// 파티클 갯수가 맥스치를 넘치 않게.
if( m_dwParticles >= m_dwParticlesLim ) return E_FAIL;
if( m_pParticlesFree ) // 비어있는 파티클 포인터가 있는가.
{
pParticle = m_pParticlesFree; // 생성될 파티클을 비어있는 포인터로 설정.
m_pParticlesFree = pParticle->m_pNext; // 파티클 리스트에 추가.
}
else
{
// if( NULL == ( pParticle = new PARTICLE ) ) // 나중에 메모리 풀로 바꾸자.,
// return E_OUTOFMEMORY;
pParticle = &m_pPool[ m_nPoolPtr++ ];
if( m_nPoolPtr >= (int)m_dwParticlesLim )
m_nPoolPtr = 0;
}
pParticle->m_pNext = m_pParticles; // 새로 생성된 파티클의 다음노드에 현재 파티클 설정.
m_pParticles = pParticle; // 새로 생성된 파티클을 현재 노드에 설정.
m_dwParticles++; // 파티클 개수 증가.
// Emit new particle
// 최초 위치 세팅
pParticle->m_vPos = vPos;
// 속도벡터 생성.
pParticle->m_vVel = vVel;
if( m_nType == 0 )
{
pParticle->m_clrDiffuse = g_clrColor;
pParticle->m_clrFade = g_clrColorFade;
} else
if( m_nType < 13 )
{
pParticle->m_clrDiffuse = g_clrColor2;
pParticle->m_clrFade = g_clrColorFade2;
} else
{
pParticle->m_clrDiffuse = D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f );;
pParticle->m_clrFade = D3DXCOLOR( 0.0f, 0.0f, 0.0f, 1.0f );
}
pParticle->m_fFade = 1.0f;
pParticle->m_fGroundY = fGroundY;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Renders the particle system using either pointsprites (if supported)
// or using 4 vertices per particle
//-----------------------------------------------------------------------------
HRESULT CParticles::Render( LPDIRECT3DDEVICE9 pd3dDevice )
{
if( m_bActive == FALSE ) return S_OK;
if( m_pParticleTexture == NULL ) return S_OK;
if( m_dwParticles <= 0 ) return S_OK;
D3DXMATRIX mWorld;
D3DXMatrixIdentity( &mWorld );
pd3dDevice->SetTransform( D3DTS_WORLD, &mWorld ); // Set World Transform
// Draw particles
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_CURRENT );
pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE );
pd3dDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ONE );
pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE );
pd3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0xffffffff );
// pd3dDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_FLAT );
//
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
pd3dDevice->SetTexture(0, m_pParticleTexture );
HRESULT hr;
// Set the render states for using point sprites
pd3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_POINTSCALEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_POINTSIZE, FtoDW(m_fSize) );
pd3dDevice->SetRenderState( D3DRS_POINTSIZE_MIN, FtoDW(1.00f) );
pd3dDevice->SetRenderState( D3DRS_POINTSCALE_A, FtoDW(0.00f) );
pd3dDevice->SetRenderState( D3DRS_POINTSCALE_B, FtoDW(0.00f) );
pd3dDevice->SetRenderState( D3DRS_POINTSCALE_C, FtoDW(1.00f) );
// Set up the vertex buffer to be rendered
pd3dDevice->SetStreamSource( 0, m_pVB, 0, sizeof(POINTVERTEX) );
pd3dDevice->SetVertexShader( NULL );
pd3dDevice->SetVertexDeclaration( NULL );
pd3dDevice->SetFVF( POINTVERTEX::FVF );
PARTICLE* pParticle = m_pParticles;
POINTVERTEX* pVertices;
DWORD dwNumParticlesToRender = 0;
// Lock the vertex buffer. We fill the vertex buffer in small
// chunks, using D3DLOCK_NOOVERWRITE. When we are done filling
// each chunk, we call DrawPrim, and lock the next chunk. When
// we run out of space in the vertex buffer, we start over at
// the beginning, using D3DLOCK_DISCARD.
m_dwBase += m_dwFlush;
if(m_dwBase >= m_dwDiscard)
m_dwBase = 0;
if( FAILED( hr = m_pVB->Lock( m_dwBase * sizeof(POINTVERTEX), m_dwFlush * sizeof(POINTVERTEX),
(void**) &pVertices, m_dwBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD ) ) )
{
return hr;
}
D3DXCOLOR clrDiffuse;
D3DXVECTOR3 vPos;
D3DXVECTOR3 vVel;
// 파티클 리스트를 따라 파티클을 렌더링한다.
while( pParticle )
{
vPos = pParticle->m_vPos;
vVel = pParticle->m_vVel;
/*
// 파티클의 잔상을 보여주기 위한 부분.
FLOAT fLengthSq = D3DXVec3LengthSq(&vVel);
UINT dwSteps;
if( fLengthSq < 1.0f ) dwSteps = 2;
else if( fLengthSq < 4.00f ) dwSteps = 3;
else if( fLengthSq < 9.00f ) dwSteps = 4;
else if( fLengthSq < 12.25f ) dwSteps = 5;
else if( fLengthSq < 16.00f ) dwSteps = 6;
else if( fLengthSq < 20.25f ) dwSteps = 7;
else dwSteps = 8;
vVel *= -0.04f / (FLOAT)dwSteps;
*/
D3DXColorLerp( &clrDiffuse, &pParticle->m_clrFade, &pParticle->m_clrDiffuse, pParticle->m_fFade );
DWORD dwDiffuse = (DWORD) clrDiffuse;
// Render each particle a bunch of times to get a blurring effect
// dwSteps = 1;
// for( DWORD i = 0; i < dwSteps; i++ )
{
pVertices->v = vPos;
pVertices->color = dwDiffuse;
pVertices++;
if( ++dwNumParticlesToRender == m_dwFlush )
{
// Done filling this chunk of the vertex buffer. Lets unlock and
// draw this portion so we can begin filling the next chunk.
m_pVB->Unlock();
if(FAILED(hr = pd3dDevice->DrawPrimitive( D3DPT_POINTLIST, m_dwBase, dwNumParticlesToRender)))
return hr;
// Lock the next chunk of the vertex buffer. If we are at the
// end of the vertex buffer, DISCARD the vertex buffer and start
// at the beginning. Otherwise, specify NOOVERWRITE, so we can
// continue filling the VB while the previous chunk is drawing.
m_dwBase += m_dwFlush;
if(m_dwBase >= m_dwDiscard)
m_dwBase = 0;
if( FAILED( hr = m_pVB->Lock( m_dwBase * sizeof(POINTVERTEX), m_dwFlush * sizeof(POINTVERTEX),
(void**) &pVertices, m_dwBase ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD ) ) )
{
return hr;
}
dwNumParticlesToRender = 0;
}
// vPos += vVel; // 잔상처리를 위한 부분.
} // for dwSteps
pParticle = pParticle->m_pNext;
} // particle list
// Unlock the vertex buffer
m_pVB->Unlock();
// Render any remaining particles
if( dwNumParticlesToRender ) // 위에서 512개씩 출력해주고 남은 파티클을 여기서 마저 다 그려줌.
{
if(FAILED(hr = pd3dDevice->DrawPrimitive( D3DPT_POINTLIST, m_dwBase, dwNumParticlesToRender )))
return hr;
}
// Reset render states
pd3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_POINTSCALEENABLE, FALSE );
pd3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
// pd3dDevice->SetRenderState( D3DRS_SHADEMODE, D3DSHADE_GOURAUD );
return S_OK;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// class CParticleMng
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CParticleMng g_ParticleMng;
CParticleMng::CParticleMng()
{
Init();
}
CParticleMng::~CParticleMng()
{
Destroy();
}
void CParticleMng::Init( void )
{
m_bActive = TRUE;
m_nMaxType = 0;
}
void CParticleMng::Destroy( void )
{
// 이곳에 파괴 코드를 넣으셈.
Init();
}
HRESULT CParticleMng::RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice )
{
int i;
for( i = 0; i < MAX_PARTICLE_TYPE; i ++ )
m_Particles[i].RestoreDeviceObjects( pd3dDevice );
return S_OK;
}
HRESULT CParticleMng::InvalidateDeviceObjects( void )
{
int i;
for( i = 0; i < MAX_PARTICLE_TYPE; i ++ )
m_Particles[i].InvalidateDeviceObjects();
return S_OK;
}
//
// 파티클 하나 생성.
//
CParticles *CParticleMng::CreateParticle( int nType, const D3DXVECTOR3 &vPos, const D3DXVECTOR3 &vVel, FLOAT fGroundY )
{
if( nType < 0 || nType >= MAX_PARTICLE_TYPE )
return NULL;
CParticles *pParticles = &m_Particles[ nType ];
if( pParticles->m_bActive == FALSE ) // 생성시킨적이 없는 파티클이면 최초 생성.
{
pParticles->Create( 512, 512, nType );
char szFileName[32];
switch( nType )
{
case 0: pParticles->m_fSize = 0.3f; strcpy( szFileName, "Sfx_ItemPatical01.dds" ); break;
case 1: pParticles->m_fSize = 0.2f; strcpy( szFileName, "etc_Particle2.bmp" ); break;
case 2: pParticles->m_fSize = 0.5f; strcpy( szFileName, "etc_Particle11.bmp" ); break;
case 3: pParticles->m_fSize = 0.3f; strcpy( szFileName, "etc_Particle11.bmp" ); break;
case 4: pParticles->m_fSize = 0.2f; strcpy( szFileName, "etc_Particle11.bmp" ); break;
case 5: pParticles->m_fSize = 0.3f; strcpy( szFileName, "Sfx_ItemPatical06-01.dds" ); break;
case 6: pParticles->m_fSize = 0.3f; strcpy( szFileName, "Sfx_ItemPatical06-02.dds" ); break;
case 7: pParticles->m_fSize = 0.3f; strcpy( szFileName, "Sfx_ItemPatical06-03.dds" ); break;
case 8: pParticles->m_fSize = 0.3f; strcpy( szFileName, "Sfx_ItemPatical06-04.dds" ); break;
case 9: pParticles->m_fSize = 0.3f; strcpy( szFileName, "Sfx_ItemPatical06-05.dds" ); break;
case 10: pParticles->m_fSize = 0.5f; strcpy( szFileName, "etc_ParticleCloud01.bmp" ); break;
case 11: pParticles->m_fSize = 0.3f; strcpy( szFileName, "etc_ParticleCloud01.bmp" ); break;
case 12: pParticles->m_fSize = 0.2f; strcpy( szFileName, "etc_ParticleCloud01.bmp" ); break;
// blue
case 13: pParticles->m_fSize = 0.15f; strcpy( szFileName, "etc_Particle11.bmp" ); break;
case 14: pParticles->m_fSize = 0.1f; strcpy( szFileName, "etc_Particle11.bmp" ); break;
case 15: pParticles->m_fSize = 0.07f; strcpy( szFileName, "etc_Particle11.bmp" ); break;
// red
case 16: pParticles->m_fSize = 0.15f; strcpy( szFileName, "etc_Particle12.bmp" ); break;
case 17: pParticles->m_fSize = 0.1f; strcpy( szFileName, "etc_Particle12.bmp" ); break;
case 18: pParticles->m_fSize = 0.07f; strcpy( szFileName, "etc_Particle12.bmp" ); break;
// white
case 19: pParticles->m_fSize = 0.15f; strcpy( szFileName, "etc_Particle13.bmp" ); break;
case 20: pParticles->m_fSize = 0.1f; strcpy( szFileName, "etc_Particle13.bmp" ); break;
case 21: pParticles->m_fSize = 0.07f; strcpy( szFileName, "etc_Particle13.bmp" ); break;
// green
case 22: pParticles->m_fSize = 0.15f; strcpy( szFileName, "etc_Particle14.bmp" ); break;
case 23: pParticles->m_fSize = 0.1f; strcpy( szFileName, "etc_Particle14.bmp" ); break;
case 24: pParticles->m_fSize = 0.07f; strcpy( szFileName, "etc_Particle14.bmp" ); break;
default:
strcpy( szFileName, "etc_Particle2.bmp" ); break;
}
pParticles->InitDeviceObjects( m_pd3dDevice, szFileName ); // 파티클 텍스쳐 로딩.
pParticles->RestoreDeviceObjects( m_pd3dDevice );
m_nMaxType ++;
}
pParticles->CreateParticle( nType, vPos, vVel, fGroundY ); // nType의 파티클 하나 생성.
return pParticles;
}
void CParticleMng::Process( void )
{
int i;
for( i = 0; i < MAX_PARTICLE_TYPE; i ++ )
m_Particles[i].Update();
}
void CParticleMng::Render( LPDIRECT3DDEVICE9 pd3dDevice )
{
int i;
for( i = 0; i < MAX_PARTICLE_TYPE; i ++ )
m_Particles[i].Render( pd3dDevice );
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
627
]
]
]
|
8e798e51d657f6f7953d58cb2f59a57756f87776 | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /include/isotopologue.h | f822d4d86f69644fb0dc2cba15506b27d35933da | []
| no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,315 | h | #ifndef ISOTOPOLOGUE_H
#define ISOTOPOLOGUE_H
#include <string>
#include <vector>
#include <map>
#include <math.h>
#include <iomanip>
#include <algorithm>
#include "chromatogram.h"
#include "msData.h"
using namespace std;
class MZwindows;
class IsotopeDistribution
{
public:
IsotopeDistribution();
IsotopeDistribution( vector< double > vItsMass, vector< double > vItsComposition );
~IsotopeDistribution();
vector< double > vMass;
vector< double > vProb;
double getMostAbundantMass();
double getAverageMass();
// print out the isotoptic distribution
// this is mainly used for debuging
void print();
};
class Isotopologue
{
public:
Isotopologue();
Isotopologue( string sName, string sTable );
~Isotopologue();
// setup all variables from configuration
bool setupIsotopologue( const string & sName, const string & sTable );
// compute MZ window for an amino acid sequence
bool computeMZwindows( string sSequence, int iChargeState, MZwindows & myMZwindows );
// compute the mass of the most abundant isotopologue
double computeMostAbundantMass( string sSequence );
double computeAverageMass( string sSequence );
// compute the mass of a peptide's Y-ion series
bool computeProductIonMass( string sSequence, vector< double > & vdYion, vector< double > & vdBion );
// compute isotoptic distribution for an amino acid sequence
bool computeIsotopicDistribution( string sSequence, IsotopeDistribution & myIsotopeDistribution );
// compute isotoptic distribution for a given atomic composition, which can be that of a residue's or a amino acid sequence's
bool computeIsotopicDistribution( vector< int > AtomicComposition, IsotopeDistribution & myIsotopeDistribution );
// compute the atomic composition for an amino acid sequence
bool computeAtomicComposition( string sSequence, vector< int > & myAtomicComposition );
string getName()
{ return sIsotoplogueName; }
private:
// functions for IsotopeDistribution's arithmetic
IsotopeDistribution sum( IsotopeDistribution distribution0, IsotopeDistribution distribution1);
IsotopeDistribution multiply( IsotopeDistribution distribution0, int count );
void formatSequence( string & sSequence );
// implementation of max and min
double maximum( double a, double b )
{ return (a > b) ? a : b; }
double minimum( double a, double b)
{ return (a < b) ? a : b; }
// when two peaks have a mass difference less than the MassPrecision
// they will be merged into one peak with their average mass and sum intensity
const double MassPrecision;
// when a peak have a probability less than the ProbabilityCutoff
// this peak will be ingnored, which makes the total probability space less than 1
const double ProbabilityCutoff; // 1*10E-9
// the name of atoms
const string AtomName;
// the number of natural CHONPS and enriched CHONPS
const int AtomNumber;
// variables for this isotopologue
string sIsotoplogueName;
map< string, vector< int > > mResidueAtomicComposition;
vector< IsotopeDistribution > vAtomIsotopicDistribution;
map< string, IsotopeDistribution > vResidueIsotopicDistribution;
};
#endif //ISOTOPOLOGUE_H
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
]
| [
[
[
1,
104
]
]
]
|
39da83bf9ae071f9a31779c898361253459de44f | 6eef3e34d3fe47a10336a53df1a96a591b15cd01 | /ASearch/AlkalineServer/PingThread.cpp | 021ea7acac822d2b7ec3e6d0b3ea79d7636afc51 | []
| no_license | praveenmunagapati/alkaline | 25013c233a80b07869e0fdbcf9b8dfa7888cc32e | 7cf43b115d3e40ba48854f80aca8d83b67f345ce | refs/heads/master | 2021-05-27T16:44:12.356701 | 2009-10-29T11:23:09 | 2009-10-29T11:23:09 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,448 | cpp | /*
© Vestris Inc., Geneva, Switzerland
http://www.vestris.com, 1994-1999 All Rights Reserved
_____________________________________________________
written by Daniel Doubrovkine - [email protected]
*/
#include <alkaline.hpp>
#include <Main/TraceTags.hpp>
#include "PingThread.hpp"
CAlkalinePingThread::CAlkalinePingThread(const CString& PingUrl, int Pid) :
CPingClient(PingUrl),
m_Pid(Pid)
{
m_PingInterval = 15;
m_PingRestart = 3;
}
CAlkalinePingThread::~CAlkalinePingThread(void) {
}
void CAlkalinePingThread::Execute(void * Arguments) {
CPingClient::Execute(Arguments);
}
void CAlkalinePingThread::PingFailed(int Count) const {
cout << "[ping: failed (url=" << m_PingUrl.GetHttpAll() << ", count=" << Count << "/" << m_PingRestart << ")]" << endl;
if ((Count >= m_PingRestart) && m_bPing) {
#ifdef _UNIX
if (! m_Pid) {
cout << "[ping: attempting a clean restart]" << endl;
kill(base_getpid(), SIGTERM);
kill(base_getpid(), SIGKILL);
_exit(0);
} else {
cout << "[ping: attempting signal SIGKILL " << m_Pid << "]" << endl;
kill(m_Pid, SIGTERM);
kill(m_Pid, SIGKILL);
}
#endif
}
}
void CAlkalinePingThread::PingSucceeded(void) const {
Trace(tagServer, levInfo, ("CAlkalinePingThread::PingSucceeded - ping-pong."));
}
| [
"[email protected]"
]
| [
[
[
1,
52
]
]
]
|
82fb8461a558ad69d906fdd43c2ae4dd3ba1fa0c | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SERenderers/SE_OGLES2_Renderer/SEOGLES2Rendering/SEOGLES2WireframeState.cpp | 51c9447394ab9cddc2dc49b0cb48f23cb644f915 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,352 | 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 "SEOGLES2RendererPCH.h"
#include "SEOGLES2Renderer.h"
using namespace Swing;
//----------------------------------------------------------------------------
void SEOGLES2Renderer::SetWireframeState(SEWireframeState* pState)
{
SERenderer::SetWireframeState(pState);
// OpenGL ES2不支持wireframe模式.
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
33
]
]
]
|
1eb5d87d783cd86a2297fa168e949af7118ed3d3 | e354a51eef332858855eac4c369024a7af5ff804 | /ilogger.h | 4ea43ebb0eff5d20e4c2f72c0e108ed0ef9b071d | []
| no_license | cjus/msgCourierLite | 0f9c1e05b71abf820c55f74a913555eec2267bb4 | 9efc1d54737ba47620a03686707b31b1eeb61586 | refs/heads/master | 2020-04-05T22:41:39.141740 | 2010-09-05T18:43:12 | 2010-09-05T18:43:12 | 887,172 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | h | #ifndef ILOGGER_H
#define ILOGGER_H
class cILogger
{
public:
virtual void Write(const char *pFormat, ...) = 0;
};
#endif // ILOGGER_H
| [
"[email protected]"
]
| [
[
[
1,
10
]
]
]
|
948f4cb5329fa25151a3433d1370134104a6ee3a | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-13/pcbnew/pcbplot.cpp | be9a800232e48a12ffdec1261e339bb6dce5750d | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 17,558 | cpp | /***********************/
/* fichier pcbplot.cpp */
/***********************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "plot_common.h"
#include "pcbnew.h"
#include "pcbplot.h"
#include "worksheet.h"
#include "id.h"
#include "protos.h"
#define PLOT_DEFAULT_MARGE 300 // mils
/* variables locale : */
long s_SelectedLayers = CUIVRE_LAYER | CMP_LAYER |
SILKSCREEN_LAYER_CMP | SILKSCREEN_LAYER_CU;
/* Routines Locales */
enum id_plotps
{
ID_CLOSE_PLOT = 8020,
ID_DRILL_SHAPE_OPT,
ID_SCALE_OPT,
ID_ROTATE_OPT,
ID_MIROR_OPT,
ID_EXEC_PLOT,
ID_PLOT_MODE_OPT,
ID_MASKVIA_OPT,
ID_PLOT_CENTRE_OPT,
ID_SEL_PLOT_FORMAT,
ID_SEL_GERBER_FORMAT,
ID_SAVE_OPT_PLOT,
ID_PRINT_REF,
ID_PRINT_VALUE,
ID_PRINT_MODULE_TEXTS,
ID_FORCE_PRINT_INVISIBLE_TEXT,
ID_PRINT_PAD_ON_SILKSCREEN,
ID_FORCE_PRINT_PAD,
ID_CREATE_DRILL_FILE
};
/*******************************/
/* Dialog box for plot control */
/*******************************/
class WinEDA_PlotFrame: public wxDialog
{
public:
WinEDA_BasePcbFrame * m_Parent;
wxButton * m_MergePlotButton;
wxCheckBox * m_BoxSelecLayer[32];
wxRadioBox * m_PlotFormatOpt;
wxRadioBox * m_Drill_Shape_Opt;
wxRadioBox * m_Scale_Opt;
wxRadioBox * m_PlotModeOpt;
wxCheckBox * m_PlotMirorOpt;
wxCheckBox * m_PlotNoViaOnMaskOpt;
wxCheckBox * m_HPGL_PlotCenter_Opt;
wxCheckBox * m_Plot_Sheet_Ref;
wxCheckBox * m_Plot_Invisible_Text;
wxCheckBox * m_Plot_Text_Value;
wxCheckBox * m_Plot_Text_Ref;
wxCheckBox * m_Plot_Text_Div;
wxCheckBox * m_Plot_Pads_on_Silkscreen;
wxCheckBox * m_Force_Plot_Pads;
WinEDA_ValueCtrl * m_GerbSpotSizeMinOpt;
WinEDA_ValueCtrl * m_LinesWidth;
WinEDA_ValueCtrl * m_HPGLPenSizeOpt;
WinEDA_ValueCtrl * m_HPGLPenSpeedOpt;
WinEDA_ValueCtrl * m_HPGLPenOverlayOpt;
WinEDA_DFloatValueCtrl * m_FineAdjustXscaleOpt, * m_FineAdjustYscaleOpt;
double m_XScaleAdjust, m_YScaleAdjust;
int m_PlotFormat;
public:
WinEDA_PlotFrame(WinEDA_BasePcbFrame * parent);
private:
void Plot(wxCommandEvent & event);
void OnQuit(wxCommandEvent & event);
void OnClose(wxCloseEvent & event);
void SetCommands(wxCommandEvent & event);
void SaveOptPlot(wxCommandEvent & event);
void CreateDrillFile(wxCommandEvent & event);
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(WinEDA_PlotFrame, wxDialog)
EVT_CLOSE(WinEDA_PlotFrame::OnClose)
EVT_BUTTON(ID_CLOSE_PLOT, WinEDA_PlotFrame::OnQuit)
EVT_BUTTON(ID_EXEC_PLOT, WinEDA_PlotFrame::Plot)
EVT_BUTTON(ID_SAVE_OPT_PLOT, WinEDA_PlotFrame::SaveOptPlot)
EVT_BUTTON(ID_CREATE_DRILL_FILE, WinEDA_PlotFrame::CreateDrillFile)
EVT_RADIOBOX(ID_SEL_PLOT_FORMAT, WinEDA_PlotFrame::SetCommands)
END_EVENT_TABLE()
#define UNITS_MILS 1000
#define H_SIZE 640
#define V_SIZE 430
WinEDA_PlotFrame::WinEDA_PlotFrame(WinEDA_BasePcbFrame * parent):
wxDialog(parent, -1, _("Plot"),
wxPoint(-1,-1), wxSize(H_SIZE, V_SIZE),
wxDEFAULT_DIALOG_STYLE)
{
wxPoint pos;
wxButton * Button;
int ii, jj, bottom = V_SIZE;
#define DELTA_Y 16
m_Parent = parent;
SetFont(*g_DialogFont);
Centre();
m_PlotFormat = format_plot;
m_Plot_Sheet_Ref = NULL;
pos.x = 360; pos.y = 5;
wxString fmtmsg[4] = { wxT("HPGL"), wxT("GERBER"), wxT("Postscript"), wxT("Postscript A4") };
m_PlotFormatOpt = new wxRadioBox(this, ID_SEL_PLOT_FORMAT,
_("Plot Format"), pos, wxSize(-1,-1),
4, fmtmsg, 1, wxRA_SPECIFY_COLS);
switch ( m_PlotFormat )
{
case PLOT_FORMAT_HPGL:
m_PlotFormatOpt->SetSelection(0); break;
case PLOT_FORMAT_POST:
m_PlotFormatOpt->SetSelection(2); break;
case PLOT_FORMAT_GERBER:
m_PlotFormatOpt->SetSelection(1); break;
case PLOT_FORMAT_POST_A4:
m_PlotFormatOpt->SetSelection(3); break;
}
/* Creation des menus d'option du format GERBER */
m_PlotFormatOpt->GetSize(&ii, &jj);
pos.y += jj + 10;
m_GerbSpotSizeMinOpt = new WinEDA_ValueCtrl(this, _("Spot min"),
spot_mini, UnitMetric, pos, UNITS_MILS);
/* Creation des menus d'option du format HPGL */
pos.y += m_GerbSpotSizeMinOpt->GetDimension().y + 8;
m_HPGLPenSizeOpt = new WinEDA_ValueCtrl(this, _("Pen Size"),
g_HPGL_Pen_Diam, UnitMetric, pos, UNITS_MILS);
pos.y += m_HPGLPenSizeOpt->GetDimension().y + 8;
/* unites standards = cm pour vitesse plume en HPLG */
m_HPGLPenSpeedOpt = new WinEDA_ValueCtrl(this, _("Pen Speed (cm/s)"),
g_HPGL_Pen_Speed, CENTIMETRE, pos, 1);
m_HPGLPenSpeedOpt->SetToolTip(_("Set pen speed in cm/s"));
pos.y += m_HPGLPenSpeedOpt->GetDimension().y + 8;
m_HPGLPenOverlayOpt = new WinEDA_ValueCtrl(this, _("Pen Ovr"),
g_HPGL_Pen_Recouvrement, UnitMetric, pos, UNITS_MILS);
m_HPGLPenOverlayOpt->SetToolTip(_("Set plot overlay for filling"));
pos.y += m_HPGLPenOverlayOpt->GetDimension().y + 8;
m_LinesWidth = new WinEDA_ValueCtrl(this, _("Lines Width"),
g_PlotLine_Width, UnitMetric, pos, PCB_INTERNAL_UNIT);
m_LinesWidth->SetToolTip(_("Set width for lines in Line plot mode"));
pos.y += m_LinesWidth->GetDimension().y + 8;
bottom = MAX (bottom, pos.y);
/* Creation des boutons de commande */
pos.x = 475; pos.y = 5;
Button = new wxButton(this, ID_EXEC_PLOT,
_("Plot"), pos);
Button->SetForegroundColour(*wxRED);
pos.y += Button->GetSize().y + 5;
Button = new wxButton(this, ID_CLOSE_PLOT,
_("Close"), pos);
Button->SetForegroundColour(*wxBLUE);
pos.y += Button->GetSize().y + 5;
Button = new wxButton(this, ID_SAVE_OPT_PLOT,
_("Save options"), pos);
Button->SetForegroundColour(wxColour(0,80,0) );
pos.y += Button->GetSize().y + 5;
Button = new wxButton(this, ID_CREATE_DRILL_FILE,
_("Create Drill File"), pos);
Button->SetForegroundColour(wxColour(0,80,80) );
// Create scale adjust option
m_XScaleAdjust = m_YScaleAdjust = 1.0;
if ( m_Parent->m_Parent->m_EDA_Config )
{
m_Parent->m_Parent->m_EDA_Config->Read(wxT("PlotXFineScaleAdj"), &m_XScaleAdjust);
m_Parent->m_Parent->m_EDA_Config->Read(wxT("PlotYFineScaleAdj"), &m_YScaleAdjust);
}
pos.y += Button->GetSize().y + 15;
m_FineAdjustXscaleOpt = new WinEDA_DFloatValueCtrl(this, _("X Scale Adjust"), m_XScaleAdjust, pos);
m_FineAdjustXscaleOpt->SetToolTip(_("Set X scale adjust for exact scale plotting"));
pos.y += m_FineAdjustXscaleOpt->GetDimension().y + 5;
m_FineAdjustYscaleOpt = new WinEDA_DFloatValueCtrl(this, _("Y Scale Adjust"), m_YScaleAdjust, pos);
m_FineAdjustYscaleOpt->SetToolTip(_("Set Y scale adjust for exact scale plotting"));
/* Creation de la liste des layers */
pos.x = 5; jj = pos.y = 5;
int mask = 1;
for ( ii = 0; ii < NB_LAYERS; ii++, mask <<= 1 )
{
if ( ii == 16 ) { pos.x += 90; jj = pos.y; pos.y = 5; }
m_BoxSelecLayer[ii] = new wxCheckBox(this, -1,
ReturnPcbLayerName(ii), pos);
if ( mask & s_SelectedLayers) m_BoxSelecLayer[ii]->SetValue(TRUE);
pos.y += 16;
}
// Option d'impression du cartouche:
pos.x = 5; pos.y = jj + 10;
if ( m_Parent->m_Print_Sheet_Ref )
{
m_Plot_Sheet_Ref = new wxCheckBox(this, ID_PRINT_REF, _("Print Sheet Ref"),
pos);
m_Plot_Sheet_Ref->SetValue(Plot_Sheet_Ref);
pos.y += DELTA_Y + 2;
}
else Plot_Sheet_Ref = FALSE;
// Option d'impression des pads sur toutes les couches
m_Plot_Pads_on_Silkscreen = new wxCheckBox(this,
ID_PRINT_PAD_ON_SILKSCREEN, _("Print Pads on Silkscreen"),
pos);
m_Plot_Pads_on_Silkscreen->SetValue(PlotPadsOnSilkLayer);
m_Plot_Pads_on_Silkscreen->SetToolTip(
_("Enable/disable print/plot pads on Silkscreen layers") );
pos.y += DELTA_Y;
m_Force_Plot_Pads = new wxCheckBox(this, ID_FORCE_PRINT_PAD, _("Always Print Pads"),
pos);
m_Force_Plot_Pads->SetValue(Plot_Pads_All_Layers);
m_Force_Plot_Pads->SetToolTip(_("Force print/plot pads on ALL layers") );
// Options d'impression des textes modules
pos.y += DELTA_Y;
m_Plot_Text_Value = new wxCheckBox(this, ID_PRINT_VALUE, _("Print Module Value"),
pos);
m_Plot_Text_Value->SetValue(Sel_Texte_Valeur);
m_Plot_Text_Value->SetToolTip(
_("Enable/disable print/plot module value on Silkscreen layers") );
pos.y += DELTA_Y;
m_Plot_Text_Ref = new wxCheckBox(this, ID_PRINT_REF, _("Print Module Reference"),
pos);
m_Plot_Text_Ref->SetValue(Sel_Texte_Reference);
m_Plot_Text_Ref->SetToolTip(
_("Enable/disable print/plot module reference on Silkscreen layers") );
pos.y += DELTA_Y;
m_Plot_Text_Div = new wxCheckBox(this, ID_PRINT_MODULE_TEXTS,
_("Print other module texts"),
pos);
m_Plot_Text_Div->SetValue(Sel_Texte_Divers);
m_Plot_Text_Div->SetToolTip(
_("Enable/disable print/plot module field texts on Silkscreen layers") );
pos.y += DELTA_Y;
m_Plot_Invisible_Text = new wxCheckBox(this,
ID_FORCE_PRINT_INVISIBLE_TEXT, _("Force Print Invisible Texts"),
pos);
m_Plot_Invisible_Text->SetValue(Sel_Texte_Invisible);
m_Plot_Invisible_Text->SetToolTip(
_("Force print/plot module invisible texts on Silkscreen layers") );
pos.x = 230; pos.y = 5;
wxString drillmsg[3] = { _("No Drill mark"), _("Small mark"), _("Real Drill") };
m_Drill_Shape_Opt = new wxRadioBox(this, ID_DRILL_SHAPE_OPT,
_("Pads Drill Opt"), pos, wxSize(-1,-1),
3, drillmsg, 1, wxRA_SPECIFY_COLS);
m_Drill_Shape_Opt->SetSelection(g_DrillShapeOpt);
m_Drill_Shape_Opt->GetSize(&ii, &jj);
pos.y += 15 + jj;
wxString scalemsg[5] =
{ _("Auto scale"), _("Scale 1"), _("Scale 1.5"), _("Scale 2"), _("Scale 3") };
m_Scale_Opt = new wxRadioBox(this, ID_SCALE_OPT,
_("Scale Opt"), pos, wxSize(-1,-1),
5, scalemsg, 1, wxRA_SPECIFY_COLS);
m_Scale_Opt->SetSelection(g_PlotScaleOpt);
m_Scale_Opt->GetSize(&ii, &jj);
pos.y += jj + 15;
wxString list_opt3[3] = {_("Line"), _("Filled"), _("Sketch") };
m_PlotModeOpt = new wxRadioBox(this, ID_PLOT_MODE_OPT, _("Plot mode"),
pos, wxDefaultSize,
3, list_opt3, 1);
m_PlotModeOpt->SetSelection(Plot_Mode);
m_PlotModeOpt->GetSize(&ii, &jj);
pos.y += jj + 15;
m_PlotMirorOpt = new wxCheckBox(this, ID_MIROR_OPT,
_("Plot Mirror"), pos);
m_PlotMirorOpt->SetValue(Plot_Set_MIROIR);
pos.y += 17;
m_PlotNoViaOnMaskOpt = new wxCheckBox(this, ID_MASKVIA_OPT,
_("Vias on Mask"), pos);
m_PlotNoViaOnMaskOpt->SetValue(g_DrawViaOnMaskLayer);
m_PlotNoViaOnMaskOpt->SetToolTip(
_("Print/plot vias on mask layers. They are in this case not protected") );
pos.y += 17;
m_HPGL_PlotCenter_Opt = new wxCheckBox(this, ID_PLOT_CENTRE_OPT,
_("Org = Centre"), pos);
m_HPGL_PlotCenter_Opt->SetValue(HPGL_Org_Centre);
m_HPGL_PlotCenter_Opt->SetToolTip(_("Draw origin ( 0,0 )in on sheet center") );
pos.y += 20;
if ( bottom < pos.y ) bottom = pos.y;
SetClientSize(wxSize(H_SIZE, bottom) );
// Mise a jour des activations des menus:
wxCommandEvent event;
SetCommands(event);
}
/***************************************************************/
void WinEDA_PlotFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
/***************************************************************/
/* Called by the close button
*/
{
Close(true); // true is to force the frame to close
}
/****************************************************/
void WinEDA_PlotFrame::OnClose(wxCloseEvent & event)
/****************************************************/
/* called when WinEDA_PlotFrame is closed
*/
{
EndModal(0);
}
/*********************************************************/
void WinEDA_PlotFrame::CreateDrillFile(wxCommandEvent & event)
/*********************************************************/
/* Create the board drill file used with gerber documents
*/
{
((WinEDA_PcbFrame * )m_Parent)->InstallDrillFrame(event);
}
/*********************************************************/
void WinEDA_PlotFrame::SetCommands(wxCommandEvent & event)
/*********************************************************/
/* active ou désactive les différents menus d'option selon le standard choisi
*/
{
int format;
int format_list[] =
{PLOT_FORMAT_HPGL, PLOT_FORMAT_GERBER, PLOT_FORMAT_POST, PLOT_FORMAT_POST_A4
};
format = format_list[m_PlotFormatOpt->GetSelection()];
switch ( format )
{
case PLOT_FORMAT_POST_A4:
case PLOT_FORMAT_POST:
m_Drill_Shape_Opt->Enable(TRUE);
m_PlotModeOpt->Enable(TRUE);
m_PlotMirorOpt->Enable(TRUE);
m_GerbSpotSizeMinOpt->Enable(FALSE);
m_LinesWidth->Enable(TRUE);
m_HPGLPenSizeOpt->Enable(FALSE);
m_HPGLPenSpeedOpt->Enable(FALSE);
m_HPGLPenOverlayOpt->Enable(FALSE);
m_HPGL_PlotCenter_Opt->Enable(FALSE);
m_Plot_Sheet_Ref->Enable(TRUE);
m_Scale_Opt->Enable(TRUE);
m_FineAdjustXscaleOpt->Enable(TRUE);
m_FineAdjustYscaleOpt->Enable(TRUE);
m_PlotFormat = PLOT_FORMAT_POST;
if ( format == PLOT_FORMAT_POST_A4 ) g_ForcePlotPS_On_A4 = TRUE;
else g_ForcePlotPS_On_A4 = FALSE;
break;
case PLOT_FORMAT_GERBER:
m_Drill_Shape_Opt->Enable(FALSE);
m_PlotModeOpt->Enable(FALSE);
m_PlotMirorOpt->Enable(FALSE);
m_GerbSpotSizeMinOpt->Enable(TRUE);
m_LinesWidth->Enable(TRUE);
m_HPGLPenSizeOpt->Enable(FALSE);
m_HPGLPenSpeedOpt->Enable(FALSE);
m_HPGLPenOverlayOpt->Enable(FALSE);
m_HPGL_PlotCenter_Opt->Enable(FALSE);
m_Plot_Sheet_Ref->Enable(FALSE);
m_Scale_Opt->Enable(FALSE);
m_FineAdjustXscaleOpt->Enable(FALSE);
m_FineAdjustYscaleOpt->Enable(FALSE);
m_PlotFormat = PLOT_FORMAT_GERBER;
break;
case PLOT_FORMAT_HPGL:
m_PlotMirorOpt->Enable(TRUE);
m_Drill_Shape_Opt->Enable(FALSE);
m_PlotModeOpt->Enable(TRUE);
m_GerbSpotSizeMinOpt->Enable(FALSE);
m_LinesWidth->Enable(FALSE);
m_HPGLPenSizeOpt->Enable(TRUE);
m_HPGLPenSpeedOpt->Enable(TRUE);
m_HPGLPenOverlayOpt->Enable(TRUE);
m_HPGL_PlotCenter_Opt->Enable(TRUE);
m_Plot_Sheet_Ref->Enable(TRUE);
m_Scale_Opt->Enable(TRUE);
m_FineAdjustXscaleOpt->Enable(FALSE);
m_FineAdjustYscaleOpt->Enable(FALSE);
m_PlotFormat = PLOT_FORMAT_HPGL;
break;
}
format_plot = m_PlotFormat;
}
/*********************************************************/
void WinEDA_PlotFrame::SaveOptPlot(wxCommandEvent & event)
/*********************************************************/
{
if ( m_Plot_Sheet_Ref )
Plot_Sheet_Ref = m_Plot_Sheet_Ref->GetValue();
PlotPadsOnSilkLayer = m_Plot_Pads_on_Silkscreen->GetValue();
Plot_Pads_All_Layers = m_Force_Plot_Pads->GetValue();
Sel_Texte_Valeur = m_Plot_Text_Value->GetValue();
Sel_Texte_Reference = m_Plot_Text_Ref->GetValue();
Sel_Texte_Divers = m_Plot_Text_Div->GetValue();
Sel_Texte_Invisible = m_Plot_Invisible_Text->GetValue();
g_PlotScaleOpt = m_Scale_Opt->GetSelection();
g_DrillShapeOpt = m_Drill_Shape_Opt->GetSelection();
Plot_Set_MIROIR = m_PlotMirorOpt->GetValue();
if ( Plot_Set_MIROIR ) g_PlotOrient = PLOT_MIROIR;
else g_PlotOrient = 0;
Plot_Mode = m_PlotModeOpt->GetSelection();
g_DrawViaOnMaskLayer = m_PlotNoViaOnMaskOpt->GetValue();
spot_mini = m_GerbSpotSizeMinOpt->GetValue();
g_HPGL_Pen_Diam = m_HPGLPenSizeOpt->GetValue();
g_HPGL_Pen_Speed = m_HPGLPenSpeedOpt->GetValue();
g_HPGL_Pen_Recouvrement = m_HPGLPenOverlayOpt->GetValue();
HPGL_Org_Centre = m_HPGL_PlotCenter_Opt->GetValue();
g_PlotLine_Width = m_LinesWidth->GetValue();
m_XScaleAdjust = m_FineAdjustXscaleOpt->GetValue();
m_YScaleAdjust = m_FineAdjustYscaleOpt->GetValue();
if ( m_Parent->m_Parent->m_EDA_Config )
{
m_Parent->m_Parent->m_EDA_Config->Write(wxT("PlotXFineScaleAdj"), m_XScaleAdjust);
m_Parent->m_Parent->m_EDA_Config->Write(wxT("PlotYFineScaleAdj"), m_YScaleAdjust);
}
}
/***************************************************/
void WinEDA_PlotFrame::Plot(wxCommandEvent & event)
/***************************************************/
{
int layer_to_plot;
wxString FullFileName, BaseFileName;
wxString ext;
SaveOptPlot(event);
switch ( g_PlotScaleOpt )
{
default:
Scale_X = Scale_Y = 1;
break;
case 2:
Scale_X = Scale_Y = 1.5;
break;
case 3:
Scale_X = Scale_Y = 2;
break;
case 4:
Scale_X = Scale_Y = 3;
break;
}
Scale_X *= m_XScaleAdjust;
Scale_Y *= m_YScaleAdjust;
BaseFileName = m_Parent->GetScreen()->m_FileName;
ChangeFileNameExt( BaseFileName, wxT("-") );
switch ( m_PlotFormat)
{
case PLOT_FORMAT_POST:
ext = wxT(".ps");
break;
case PLOT_FORMAT_GERBER:
ext = wxT(".pho");
break;
case PLOT_FORMAT_HPGL:
ext = wxT(".plt");
break;
}
int mask = 1;
s_SelectedLayers = 0;
for ( layer_to_plot = 0; layer_to_plot < 29; layer_to_plot++, mask <<= 1 )
{
if ( m_BoxSelecLayer[layer_to_plot]->GetValue() )
{
s_SelectedLayers |= mask;
/* Calcul du nom du fichier */
FullFileName = BaseFileName +ReturnPcbLayerName(layer_to_plot, TRUE) + ext;
switch ( m_PlotFormat)
{
case PLOT_FORMAT_POST:
m_Parent->Genere_PS(FullFileName, layer_to_plot);
break;
case PLOT_FORMAT_GERBER:
m_Parent->Genere_GERBER(FullFileName, layer_to_plot);
break;
case PLOT_FORMAT_HPGL:
m_Parent->Genere_HPGL(FullFileName, layer_to_plot);
break;
}
}
}
Close(TRUE);
}
/**************************************************************/
void WinEDA_BasePcbFrame::ToPlotter(wxCommandEvent& event)
/***************************************************************/
{
WinEDA_PlotFrame * frame = new WinEDA_PlotFrame(this);
frame->ShowModal(); frame->Destroy();
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
561
]
]
]
|
1cd976f30a14236cbda4bddf9356ff19e0dd6098 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/regx/ConditionToken.cpp | 654ec2126dafc3de501218f57de09b336aed78f8 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,639 | cpp | /*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: ConditionToken.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/ConditionToken.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ConditionToken: Constructors and Destructors
// ---------------------------------------------------------------------------
ConditionToken::ConditionToken(const unsigned int refNo, Token* const condTok,
Token* const yesTok, Token* const noTok, MemoryManager* const manager)
: Token(Token::T_CONDITION, manager)
, fRefNo(refNo)
, fConditionToken(condTok)
, fYesToken(yesTok)
, fNoToken(noTok)
{
}
ConditionToken::~ConditionToken() {
}
XERCES_CPP_NAMESPACE_END
/**
* End of file ConditionToken.cpp
*/
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
51
]
]
]
|
8cc6282926af4458f2237d9acd4693bb7fb61e7e | 56c17f756480a02c77aecc69b217c29294f4c180 | /Src/Libs/Rastering/DiamondQbertModelEnemyBall.h | 2784ff7fc804ec21ced5c9261c8cf1e18c184650 | []
| no_license | sangongs/qbert3d | 5fd88b9720b68ca7617a8c5510568911b3dc34c5 | 296b78451b73032e16e64ae1cc4f0200ef7ca734 | refs/heads/master | 2021-01-10T04:02:37.685309 | 2008-09-12T16:13:04 | 2008-09-12T16:13:04 | 46,944,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | h | #pragma once
#include "boost/shared_ptr.hpp"
#include "QbertEnemyObj.h"
namespace BGComplete
{
class DiamondQbertModelEnemyBall : public QbertEnemyObj
{
private:
void SetListOfBoxes();
public:
DiamondQbertModelEnemyBall(const std::string& name = "", Model* model = NULL, int score = 0, QbertBox_ptr box = QbertBox_ptr(), DWORD moveLegth = 100);
~DiamondQbertModelEnemyBall(void) {}
Direction WhereToMove();
};
typedef boost::shared_ptr<DiamondQbertModelEnemyBall> DiamondQbertModelEnemyBall_ptr;
} //namespace BGComplete
| [
"iliagore@97581c8e-fe54-0410-aa42-dd6ba39e7182"
]
| [
[
[
1,
26
]
]
]
|
02531af876ee1d1190cdf2bff70557690b5fbf17 | e07af5d5401cec17dc0bbf6dea61f6c048f07787 | /group.hpp | 8e3f54dabc710f9a607649993d56942c60d8b8fc | []
| no_license | Mosesofmason/nineo | 4189c378026f46441498a021d8571f75579ce55e | c7f774d83a7a1f59fde1ac089fde9aa0b0182d83 | refs/heads/master | 2016-08-04T16:33:00.101017 | 2009-12-26T15:25:54 | 2009-12-26T15:25:54 | 32,200,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,038 | hpp | #ifndef __NEXT_NINEO_GROUP_DEFINE__
#define __NEXT_NINEO_GROUP_DEFINE__
/**
* \file group.hpp
* \brief 组类型的实现
*
*
* \author NewBlue (peng hong zhen), [email protected]
*
* \internal
* Created: 2008-2-12
* Revision: $Id: doxygen.templates,v 1.4 2008/02 mehner Exp $
* Compiler: gcc/g++,borland free commandline, msvc6
* Company: NewBlue Studio.
* Copyright: Copyright (c) 2008, NewBlue
*
* =====================================================================================
*/
#include <wx/wx.h>
#include <wx/dynarray.h>
#include <wx/list.h>
#include "utils.hpp"
#include "regex.hpp"
#include <vector>
#include "string.hpp"
namespace NiGroup
{
/**
* \class NiGroup
* \brief 组数据类,基类
*/
class NiGroup
{
protected:
NiString::GroupString m_name;
public:
NiGroup ();
~NiGroup ();
//! 获取组名
wxString Name () const;
//! 设置组名
void SetName ( const wxString& name );
//! 组名前缀
wxString Prefix () const ;
//! 组名前缀的hash值
NiUtils::NiHASH PrefixHash () const;
//! 组名的hash值
NiUtils::NiHASH NameHash () const;
};
typedef std::vector <NiGroup> NiGroupArray;
typedef NiGroup Group;
typedef std::vector <Group> GroupList;
/**
* \class NiUnsubGroup
* \brief 未被订阅组类型
*/
class NiUnsubGroup : public NiGroup
{
private:
unsigned int m_last, m_first;
bool m_post;
public:
NiUnsubGroup ( const wxString& name,
const unsigned int& first,
const unsigned int& last,
const bool& post );
NiUnsubGroup ();
~NiUnsubGroup ();
bool IsValid () const;
unsigned int Last () const;
unsigned int First () const;
bool Post () const;
void Last ( const unsigned int& last );
void First ( const unsigned int& first );
void Post ( const bool& post );
NiUnsubGroup& operator() ( const wxString& line );
};
typedef std::vector <NiUnsubGroup> NiUnsubGroupArray;
typedef NiUnsubGroup UnsubGroup;
typedef std::vector <UnsubGroup> UnsubGroupList;
class SubGroup : public NiGroup
{
public:
SubGroup ( const wxString& server, const wxString& name );
SubGroup ();
~SubGroup ();
wxString GetServer () const;
void SetServer ( const wxString& server );
bool operator== ( const SubGroup& t );
private:
wxString m_server;
};
typedef std::vector <SubGroup> SubGroupList;
typedef std::vector <SubGroup*> SubGroupPtrList;
};
#endif //
| [
"[email protected]"
]
| [
[
[
1,
100
]
]
]
|
3fc52c31ae56410ef1583cc1f76b47923651f821 | 4f469243a2e6fc370f0d1859ec68de5efce90fa1 | /infected/src/game/shared/gamemovement.cpp | 652c51a682b364e3dd70a8bd71f70a84322a46df | []
| no_license | sideshowdave7/hl2-infected-mod | c710d3958cc143381eba28b7237c8f4ccdd49982 | a69fe39a2e13cbac3978ecf57c84cd8e9aa7bb0d | refs/heads/master | 2020-12-24T15:41:30.546220 | 2011-04-30T03:05:50 | 2011-04-30T03:05:50 | 61,587,106 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 135,950 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "gamemovement.h"
#include "in_buttons.h"
#include <stdarg.h>
#include "movevars_shared.h"
#include "engine/IEngineTrace.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "decals.h"
#include "coordsize.h"
#include "rumble_shared.h"
#if defined(HL2_DLL) || defined(HL2_CLIENT_DLL)
#include "hl_movedata.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define STOP_EPSILON 0.1
#define MAX_CLIP_PLANES 5
#include "filesystem.h"
#include <stdarg.h>
extern IFileSystem *filesystem;
#ifndef CLIENT_DLL
#include "env_player_surface_trigger.h"
static ConVar dispcoll_drawplane( "dispcoll_drawplane", "0" );
#endif
// tickcount currently isn't set during prediction, although gpGlobals->curtime and
// gpGlobals->frametime are. We should probably set tickcount (to player->m_nTickBase),
// but we're REALLY close to shipping, so we can change that later and people can use
// player->CurrentCommandNumber() in the meantime.
#define tickcount USE_PLAYER_CURRENT_COMMAND_NUMBER__INSTEAD_OF_TICKCOUNT
#if defined( HL2_DLL )
ConVar xc_uncrouch_on_jump( "xc_uncrouch_on_jump", "1", FCVAR_ARCHIVE, "Uncrouch when jump occurs" );
#endif
#if defined( HL2_DLL ) || defined( HL2_CLIENT_DLL )
ConVar player_limit_jump_speed( "player_limit_jump_speed", "1", FCVAR_REPLICATED );
#endif
// option_duck_method is a carrier convar. Its sole purpose is to serve an easy-to-flip
// convar which is ONLY set by the X360 controller menu to tell us which way to bind the
// duck controls. Its value is meaningless anytime we don't have the options window open.
ConVar option_duck_method("option_duck_method", "1", FCVAR_REPLICATED|FCVAR_ARCHIVE );// 0 = HOLD to duck, 1 = Duck is a toggle
// [MD] I'll remove this eventually. For now, I want the ability to A/B the optimizations.
bool g_bMovementOptimizations = true;
// Roughly how often we want to update the info about the ground surface we're on.
// We don't need to do this very often.
#define CATEGORIZE_GROUND_SURFACE_INTERVAL 0.3f
#define CATEGORIZE_GROUND_SURFACE_TICK_INTERVAL ( (int)( CATEGORIZE_GROUND_SURFACE_INTERVAL / TICK_INTERVAL ) )
#define CHECK_STUCK_INTERVAL 1.0f
#define CHECK_STUCK_TICK_INTERVAL ( (int)( CHECK_STUCK_INTERVAL / TICK_INTERVAL ) )
#define CHECK_STUCK_INTERVAL_SP 0.2f
#define CHECK_STUCK_TICK_INTERVAL_SP ( (int)( CHECK_STUCK_INTERVAL_SP / TICK_INTERVAL ) )
#define CHECK_LADDER_INTERVAL 0.2f
#define CHECK_LADDER_TICK_INTERVAL ( (int)( CHECK_LADDER_INTERVAL / TICK_INTERVAL ) )
#define NUM_CROUCH_HINTS 3
extern IGameMovement *g_pGameMovement;
#if defined( PLAYER_GETTING_STUCK_TESTING )
// If you ever get stuck walking around, then you can run this code to find the code which would leave the player in a bad spot
void CMoveData::SetAbsOrigin( const Vector &vec )
{
CGameMovement *gm = dynamic_cast< CGameMovement * >( g_pGameMovement );
if ( gm && gm->GetMoveData() &&
gm->player &&
gm->player->entindex() == 1 &&
gm->player->GetMoveType() == MOVETYPE_WALK )
{
trace_t pm;
gm->TracePlayerBBox( vec, vec, gm->PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
if ( pm.startsolid || pm.allsolid || pm.fraction != 1.0f )
{
Msg( "Player will become stuck at %f %f %f\n", VectorExpand( vec ) );
}
}
m_vecAbsOrigin = vec;
}
#endif
// See shareddefs.h
#if PREDICTION_ERROR_CHECK_LEVEL > 0
static ConVar diffcheck( "diffcheck", "0", FCVAR_REPLICATED );
class IDiffMgr
{
public:
virtual void StartCommand( bool bServer, int nCommandNumber ) = 0;
virtual void AddToDiff( bool bServer, int nCommandNumber, char const *string ) = 0;
virtual void Validate( bool bServer, int nCommandNumber ) = 0;
};
static IDiffMgr *g_pDiffMgr = NULL;
class CDiffStr
{
public:
CDiffStr()
{
m_str[ 0 ] = 0;
}
CDiffStr( char const *str )
{
Q_strncpy( m_str, str, sizeof( m_str ) );
}
CDiffStr( const CDiffStr &src )
{
Q_strncpy( m_str, src.m_str, sizeof( m_str ) );
}
char const *String()
{
return m_str;
}
private:
char m_str[ 128 ];
};
// Per tick data
class CDiffInfo
{
public:
CDiffInfo() : m_nCommandNumber( 0 ) {}
CDiffInfo( const CDiffInfo& src )
{
m_nCommandNumber = src.m_nCommandNumber;
for ( int i = 0; i < src.m_Lines.Count(); ++i )
{
m_Lines.AddToTail( src.m_Lines[ i ] );
}
}
static bool Less( const CDiffInfo& lhs, const CDiffInfo& rhs )
{
return lhs.m_nCommandNumber < rhs.m_nCommandNumber;
}
int m_nCommandNumber;
CUtlVector< CDiffStr > m_Lines;
bool m_bChecked;
};
class CDiffManager : public IDiffMgr
{
public:
CDiffManager() :
m_Client( 0, 0, CDiffInfo::Less ),
m_Server( 0, 0, CDiffInfo::Less ),
m_flLastSpew( -1.0f )
{
g_pDiffMgr = this;
}
virtual void StartCommand( bool bServer, int nCommandNumber )
{
#if defined( CLIENT_DLL )
if ( !diffcheck.GetInt() )
return;
g_pDiffMgr = reinterpret_cast< IDiffMgr * >( diffcheck.GetInt() );
g_pDiffMgr->StartCommand( bServer, nCommandNumber );
return;
#endif
// Msg( "%s Startcommand %d\n", bServer ? "sv" : "cl", nCommandNumber );
diffcheck.SetValue( reinterpret_cast< int >( this ) );
Assert( CBaseEntity::IsServer() );
CUtlRBTree< CDiffInfo, int >& rb = bServer ? m_Server : m_Client;
CDiffInfo search;
search.m_nCommandNumber = nCommandNumber;
int idx = rb.Find( search );
if ( idx == rb.InvalidIndex() )
{
idx = rb.Insert( search );
}
CDiffInfo *slot = &rb[ idx ];
slot->m_Lines.RemoveAll();
}
virtual void AddToDiff( bool bServer, int nCommandNumber, char const *string )
{
#if defined( CLIENT_DLL )
if ( !diffcheck.GetInt() )
return;
g_pDiffMgr = reinterpret_cast< IDiffMgr * >( diffcheck.GetInt() );
g_pDiffMgr->AddToDiff( bServer, nCommandNumber, string );
return;
#endif
Assert( CBaseEntity::IsServer() );
// Msg( "%s Add %d %s\n", bServer ? "sv" : "cl", nCommandNumber, string );
CUtlRBTree< CDiffInfo, int >& rb = bServer ? m_Server : m_Client;
CDiffInfo search;
search.m_nCommandNumber = nCommandNumber;
int idx = rb.Find( search );
if ( idx == rb.InvalidIndex() )
{
Assert( 0 );
idx = rb.Insert( search );
}
CDiffInfo *slot = &rb[ idx ];
CDiffStr line( string );
slot->m_Lines.AddToTail( line );
}
enum EMismatched
{
DIFFCHECK_NOTREADY = 0,
DIFFCHECK_MATCHED,
DIFFCHECK_DIFFERS
};
bool ClientRecordExists( int cmd )
{
CDiffInfo clsearch;
clsearch.m_nCommandNumber = cmd;
int clidx = m_Client.Find( clsearch );
return m_Client.IsValidIndex( clidx );
}
EMismatched IsMismatched( int svidx )
{
CDiffInfo *serverslot = &m_Server[ svidx ];
// Now find the client version of this one
CDiffInfo clsearch;
clsearch.m_nCommandNumber = serverslot->m_nCommandNumber;
int clidx = m_Client.Find( clsearch );
if ( clidx == m_Client.InvalidIndex() )
return DIFFCHECK_NOTREADY;
// Now compare them
CDiffInfo *clientslot = &m_Client[ clidx ];
bool bSpew = false;
if ( serverslot->m_Lines.Count() !=
clientslot->m_Lines.Count() )
{
return DIFFCHECK_DIFFERS;
}
int maxSlot = max( serverslot->m_Lines.Count(), clientslot->m_Lines.Count() );
if ( !bSpew )
{
for ( int i = 0; i < maxSlot; ++i )
{
CDiffStr *sv = NULL;
CDiffStr *cl = NULL;
if ( i < serverslot->m_Lines.Count() )
{
sv = &serverslot->m_Lines[ i ];
}
if ( i < clientslot->m_Lines.Count() )
{
cl = &clientslot->m_Lines[ i ];
}
if ( Q_stricmp( sv ? sv->String() : "(missing)", cl ? cl->String() : "(missing)" ) )
{
return DIFFCHECK_DIFFERS;
}
}
}
return DIFFCHECK_MATCHED;
}
virtual void Validate( bool bServer, int nCommandNumber )
{
#if defined( CLIENT_DLL )
if ( !diffcheck.GetInt() )
return;
g_pDiffMgr = reinterpret_cast< IDiffMgr * >( diffcheck.GetInt() );
g_pDiffMgr->Validate( bServer, nCommandNumber );
return;
#endif
Assert( CBaseEntity::IsServer() );
// Only do this on the client
if ( !bServer )
return;
// Find the last server command number
if ( m_Server.Count() <= 0 )
return;
int svidx = m_Server.LastInorder();
EMismatched eMisMatched = IsMismatched( svidx );
if ( eMisMatched == DIFFCHECK_NOTREADY )
{
return;
}
if ( eMisMatched == DIFFCHECK_DIFFERS )
{
CUtlVector< int > vecPrev;
int nCur = svidx;
do
{
int prev = m_Server.PrevInorder( nCur );
if ( m_Server.IsValidIndex( prev ) &&
ClientRecordExists( m_Server[ prev ].m_nCommandNumber ) )
{
//SpewRecords( "prev", prev );
vecPrev.AddToHead( prev );
}
else
{
break;
}
nCur = prev;
} while ( vecPrev.Count() < 10 );
Msg( "-----\n" );
for ( int p = 0; p < vecPrev.Count(); ++p )
{
SpewRecords( "prev", vecPrev[ p ] );
}
SpewRecords( "bad ", svidx );
}
}
void SpewRecords( char const *prefix, int svidx )
{
CDiffInfo *serverslot = &m_Server[ svidx ];
// Now find the client version of this one
CDiffInfo clsearch;
clsearch.m_nCommandNumber = serverslot->m_nCommandNumber;
int clidx = m_Client.Find( clsearch );
if ( clidx == m_Client.InvalidIndex() )
return;
// Now compare them
CDiffInfo *clientslot = &m_Client[ clidx ];
int maxSlot = max( serverslot->m_Lines.Count(), clientslot->m_Lines.Count() );
for ( int i = 0; i < maxSlot; ++i )
{
char const *sv = "(missing)";
char const *cl = "(missing)";
if ( i < serverslot->m_Lines.Count() )
{
sv = serverslot->m_Lines[ i ].String();
}
if ( i < clientslot->m_Lines.Count() )
{
cl = clientslot->m_Lines[ i ].String();
}
bool bDiffers = Q_stricmp( sv, cl ) ? true : false;
Msg( "%s%s%d: sv[%50.50s] cl[%50.50s]\n",
prefix,
bDiffers ? "+++" : " ",
serverslot->m_nCommandNumber,
sv,
cl );
}
}
private:
CUtlRBTree< CDiffInfo, int > m_Server;
CUtlRBTree< CDiffInfo, int > m_Client;
float m_flLastSpew;
};
static CDiffManager g_DiffMgr;
void DiffPrint( bool bServer, int nCommandNumber, char const *fmt, ... )
{
// Only track stuff for local player
CBasePlayer *pPlayer = CBaseEntity::GetPredictionPlayer();
if ( pPlayer && pPlayer->entindex() != 1 )
{
return;
}
va_list argptr;
char string[1024];
va_start (argptr,fmt);
int len = Q_vsnprintf(string, sizeof( string ), fmt,argptr);
va_end (argptr);
if ( g_pDiffMgr )
{
// Strip any \n at the end that the user accidently put int
if ( len > 0 && string[ len -1 ] == '\n' )
{
string[ len - 1 ] = 0;
}
g_pDiffMgr->AddToDiff( bServer, nCommandNumber, string );
}
}
void _CheckV( int tick, char const *ctx, const Vector &vel )
{
DiffPrint( CBaseEntity::IsServer(), tick, "%20.20s %f %f %f", ctx, vel.x, vel.y, vel.z );
}
#define CheckV( tick, ctx, vel ) _CheckV( tick, ctx, vel );
static void StartCommand( bool bServer, int nCommandNumber )
{
// Only track stuff for local player
CBasePlayer *pPlayer = CBaseEntity::GetPredictionPlayer();
if ( pPlayer && pPlayer->entindex() != 1 )
{
return;
}
if ( g_pDiffMgr )
{
g_pDiffMgr->StartCommand( bServer, nCommandNumber );
}
}
static void Validate( bool bServer, int nCommandNumber )
{
// Only track stuff for local player
CBasePlayer *pPlayer = CBaseEntity::GetPredictionPlayer();
if ( pPlayer && pPlayer->entindex() != 1 )
{
return;
}
if ( g_pDiffMgr )
{
g_pDiffMgr->Validate( bServer, nCommandNumber );
}
}
void CGameMovement::DiffPrint( char const *fmt, ... )
{
if ( !player )
return;
va_list argptr;
char string[1024];
va_start (argptr,fmt);
Q_vsnprintf(string, sizeof( string ), fmt,argptr);
va_end (argptr);
::DiffPrint( CBaseEntity::IsServer(), player->CurrentCommandNumber(), "%s", string );
}
#else
static void DiffPrint( bool bServer, int nCommandNumber, char const *fmt, ... )
{
// Nothing
}
static void StartCommand( bool bServer, int nCommandNumber )
{
}
static void Validate( bool bServer, int nCommandNumber )
{
}
#define CheckV( tick, ctx, vel )
void CGameMovement::DiffPrint( char const *fmt, ... )
{
}
#endif // !PREDICTION_ERROR_CHECK_LEVEL
#ifndef _XBOX
void COM_Log( char *pszFile, char *fmt, ...)
{
va_list argptr;
char string[1024];
FileHandle_t fp;
char *pfilename;
if ( !pszFile )
{
pfilename = "hllog.txt";
}
else
{
pfilename = pszFile;
}
va_start (argptr,fmt);
Q_vsnprintf(string, sizeof( string ), fmt,argptr);
va_end (argptr);
fp = filesystem->Open( pfilename, "a+t");
if (fp)
{
filesystem->FPrintf(fp, "%s", string);
filesystem->Close(fp);
}
}
#endif
#ifndef CLIENT_DLL
//-----------------------------------------------------------------------------
// Purpose: Debug - draw the displacement collision plane.
//-----------------------------------------------------------------------------
void DrawDispCollPlane( CBaseTrace *pTrace )
{
float flLength = 30.0f;
// Create a basis, based on the impact normal.
int nMajorAxis = 0;
Vector vecBasisU, vecBasisV, vecNormal;
vecNormal = pTrace->plane.normal;
float flAxisValue = vecNormal[0];
if ( fabs( vecNormal[1] ) > fabs( flAxisValue ) ) { nMajorAxis = 1; flAxisValue = vecNormal[1]; }
if ( fabs( vecNormal[2] ) > fabs( flAxisValue ) ) { nMajorAxis = 2; }
if ( ( nMajorAxis == 1 ) || ( nMajorAxis == 2 ) )
{
vecBasisU.Init( 1.0f, 0.0f, 0.0f );
}
else
{
vecBasisU.Init( 0.0f, 1.0f, 0.0f );
}
vecBasisV = vecNormal.Cross( vecBasisU );
VectorNormalize( vecBasisV );
vecBasisU = vecBasisV.Cross( vecNormal );
VectorNormalize( vecBasisU );
// Create the impact point. Push off the surface a bit.
Vector vecImpactPoint = pTrace->startpos + pTrace->fraction * ( pTrace->endpos - pTrace->startpos );
vecImpactPoint += vecNormal;
// Generate a quad to represent the plane.
Vector vecPlanePoints[4];
vecPlanePoints[0] = vecImpactPoint + ( vecBasisU * -flLength ) + ( vecBasisV * -flLength );
vecPlanePoints[1] = vecImpactPoint + ( vecBasisU * -flLength ) + ( vecBasisV * flLength );
vecPlanePoints[2] = vecImpactPoint + ( vecBasisU * flLength ) + ( vecBasisV * flLength );
vecPlanePoints[3] = vecImpactPoint + ( vecBasisU * flLength ) + ( vecBasisV * -flLength );
#if 0
// Test facing.
Vector vecEdges[2];
vecEdges[0] = vecPlanePoints[1] - vecPlanePoints[0];
vecEdges[1] = vecPlanePoints[2] - vecPlanePoints[0];
Vector vecCross = vecEdges[0].Cross( vecEdges[1] );
if ( vecCross.Dot( vecNormal ) < 0.0f )
{
// Reverse winding.
}
#endif
// Draw the plane.
NDebugOverlay::Triangle( vecPlanePoints[0], vecPlanePoints[1], vecPlanePoints[2], 125, 125, 125, 125, false, 5.0f );
NDebugOverlay::Triangle( vecPlanePoints[0], vecPlanePoints[2], vecPlanePoints[3], 125, 125, 125, 125, false, 5.0f );
NDebugOverlay::Line( vecPlanePoints[0], vecPlanePoints[1], 255, 255, 255, false, 5.0f );
NDebugOverlay::Line( vecPlanePoints[1], vecPlanePoints[2], 255, 255, 255, false, 5.0f );
NDebugOverlay::Line( vecPlanePoints[2], vecPlanePoints[3], 255, 255, 255, false, 5.0f );
NDebugOverlay::Line( vecPlanePoints[3], vecPlanePoints[0], 255, 255, 255, false, 5.0f );
// Draw the normal.
NDebugOverlay::Line( vecImpactPoint, vecImpactPoint + ( vecNormal * flLength ), 255, 0, 0, false, 5.0f );
}
#endif
//-----------------------------------------------------------------------------
// Purpose: Constructs GameMovement interface
//-----------------------------------------------------------------------------
CGameMovement::CGameMovement( void )
{
m_nOldWaterLevel = WL_NotInWater;
m_flWaterEntryTime = 0;
m_nOnLadder = 0;
mv = NULL;
memset( m_flStuckCheckTime, 0, sizeof(m_flStuckCheckTime) );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CGameMovement::~CGameMovement( void )
{
}
//-----------------------------------------------------------------------------
// Purpose: Allow bots etc to use slightly different solid masks
//-----------------------------------------------------------------------------
unsigned int CGameMovement::PlayerSolidMask( bool brushOnly )
{
return ( brushOnly ) ? MASK_PLAYERSOLID_BRUSHONLY : MASK_PLAYERSOLID;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : type -
// Output : int
//-----------------------------------------------------------------------------
int CGameMovement::GetCheckInterval( IntervalType_t type )
{
int tickInterval = 1;
switch ( type )
{
default:
tickInterval = 1;
break;
case GROUND:
tickInterval = CATEGORIZE_GROUND_SURFACE_TICK_INTERVAL;
break;
case STUCK:
// If we are in the process of being "stuck", then try a new position every command tick until m_StuckLast gets reset back down to zero
if ( player->m_StuckLast != 0 )
{
tickInterval = 1;
}
else
{
if ( gpGlobals->maxClients == 1 )
{
tickInterval = CHECK_STUCK_TICK_INTERVAL_SP;
}
else
{
tickInterval = CHECK_STUCK_TICK_INTERVAL;
}
}
break;
case LADDER:
tickInterval = CHECK_LADDER_TICK_INTERVAL;
break;
}
return tickInterval;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : type -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CGameMovement::CheckInterval( IntervalType_t type )
{
int tickInterval = GetCheckInterval( type );
if ( g_bMovementOptimizations )
{
return (player->CurrentCommandNumber() + player->entindex()) % tickInterval == 0;
}
else
{
return true;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : ducked -
// Output : const Vector
//-----------------------------------------------------------------------------
const Vector& CGameMovement::GetPlayerMins( bool ducked ) const
{
return ducked ? VEC_DUCK_HULL_MIN : VEC_HULL_MIN;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : ducked -
// Output : const Vector
//-----------------------------------------------------------------------------
const Vector& CGameMovement::GetPlayerMaxs( bool ducked ) const
{
return ducked ? VEC_DUCK_HULL_MAX : VEC_HULL_MAX;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output : const Vector
//-----------------------------------------------------------------------------
const Vector& CGameMovement::GetPlayerMins( void ) const
{
if ( player->IsObserver() )
{
return VEC_OBS_HULL_MIN;
}
else
{
return player->m_Local.m_bDucked ? VEC_DUCK_HULL_MIN : VEC_HULL_MIN;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output : const Vector
//-----------------------------------------------------------------------------
const Vector& CGameMovement::GetPlayerMaxs( void ) const
{
if ( player->IsObserver() )
{
return VEC_OBS_HULL_MAX;
}
else
{
return player->m_Local.m_bDucked ? VEC_DUCK_HULL_MAX : VEC_HULL_MAX;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : ducked -
// Output : const Vector
//-----------------------------------------------------------------------------
const Vector& CGameMovement::GetPlayerViewOffset( bool ducked ) const
{
return ducked ? VEC_DUCK_VIEW : VEC_VIEW;
}
#if 0
//-----------------------------------------------------------------------------
// Traces player movement + position
//-----------------------------------------------------------------------------
inline void CGameMovement::TracePlayerBBox( const Vector& start, const Vector& end, unsigned int fMask, int collisionGroup, trace_t& pm )
{
VPROF( "CGameMovement::TracePlayerBBox" );
Ray_t ray;
ray.Init( start, end, GetPlayerMins(), GetPlayerMaxs() );
UTIL_TraceRay( ray, fMask, mv->m_nPlayerHandle.Get(), collisionGroup, &pm );
}
#endif
CBaseHandle CGameMovement::TestPlayerPosition( const Vector& pos, int collisionGroup, trace_t& pm )
{
Ray_t ray;
ray.Init( pos, pos, GetPlayerMins(), GetPlayerMaxs() );
UTIL_TraceRay( ray, PlayerSolidMask(), mv->m_nPlayerHandle.Get(), collisionGroup, &pm );
if ( (pm.contents & PlayerSolidMask()) && pm.m_pEnt )
{
return pm.m_pEnt->GetRefEHandle();
}
else
{
return INVALID_EHANDLE_INDEX;
}
}
/*
// FIXME FIXME: Does this need to be hooked up?
bool CGameMovement::IsWet() const
{
return ((pev->flags & FL_INRAIN) != 0) || (m_WetTime >= gpGlobals->time);
}
//-----------------------------------------------------------------------------
// Plants player footprint decals
//-----------------------------------------------------------------------------
#define PLAYER_HALFWIDTH 12
void CGameMovement::PlantFootprint( surfacedata_t *psurface )
{
// Can't plant footprints on fake materials (ladders, wading)
if ( psurface->gameMaterial != 'X' )
{
int footprintDecal = -1;
// Figure out which footprint type to plant...
// Use the wet footprint if we're wet...
if (IsWet())
{
footprintDecal = DECAL_FOOTPRINT_WET;
}
else
{
// FIXME: Activate this once we decide to pull the trigger on it.
// NOTE: We could add in snow, mud, others here
// switch(psurface->gameMaterial)
// {
// case 'D':
// footprintDecal = DECAL_FOOTPRINT_DIRT;
// break;
// }
}
if (footprintDecal != -1)
{
Vector right;
AngleVectors( pev->angles, 0, &right, 0 );
// Figure out where the top of the stepping leg is
trace_t tr;
Vector hipOrigin;
VectorMA( pev->origin,
m_IsFootprintOnLeft ? -PLAYER_HALFWIDTH : PLAYER_HALFWIDTH,
right, hipOrigin );
// Find where that leg hits the ground
UTIL_TraceLine( hipOrigin, hipOrigin + Vector(0, 0, -COORD_EXTENT * 1.74),
MASK_SOLID_BRUSHONLY, edict(), COLLISION_GROUP_NONE, &tr);
unsigned char mType = TEXTURETYPE_Find( &tr );
// Splat a decal
CPVSFilter filter( tr.endpos );
te->FootprintDecal( filter, 0.0f, &tr.endpos, &right, ENTINDEX(tr.u.ent),
gDecals[footprintDecal].index, mType );
}
}
// Switch feet for next time
m_IsFootprintOnLeft = !m_IsFootprintOnLeft;
}
#define WET_TIME 5.f // how many seconds till we're completely wet/dry
#define DRY_TIME 20.f // how many seconds till we're completely wet/dry
void CBasePlayer::UpdateWetness()
{
// BRJ 1/7/01
// Check for whether we're in a rainy area....
// Do this by tracing a line straight down with a size guaranteed to
// be larger than the map
// Update wetness based on whether we're in rain or not...
trace_t tr;
UTIL_TraceLine( pev->origin, pev->origin + Vector(0, 0, -COORD_EXTENT * 1.74),
MASK_SOLID_BRUSHONLY, edict(), COLLISION_GROUP_NONE, &tr);
if (tr.surface.flags & SURF_WET)
{
if (! (pev->flags & FL_INRAIN) )
{
// Transition...
// Figure out how wet we are now (we were drying off...)
float wetness = (m_WetTime - gpGlobals->time) / DRY_TIME;
if (wetness < 0.0f)
wetness = 0.0f;
// Here, wet time represents the time at which we get totally wet
m_WetTime = gpGlobals->time + (1.0 - wetness) * WET_TIME;
pev->flags |= FL_INRAIN;
}
}
else
{
if ((pev->flags & FL_INRAIN) != 0)
{
// Transition...
// Figure out how wet we are now (we were getting more wet...)
float wetness = 1.0f + (gpGlobals->time - m_WetTime) / WET_TIME;
if (wetness > 1.0f)
wetness = 1.0f;
// Here, wet time represents the time at which we get totally dry
m_WetTime = gpGlobals->time + wetness * DRY_TIME;
pev->flags &= ~FL_INRAIN;
}
}
}
*/
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::CategorizeGroundSurface( trace_t &pm )
{
IPhysicsSurfaceProps *physprops = MoveHelper()->GetSurfaceProps();
player->m_surfaceProps = pm.surface.surfaceProps;
player->m_pSurfaceData = physprops->GetSurfaceData( player->m_surfaceProps );
physprops->GetPhysicsProperties( player->m_surfaceProps, NULL, NULL, &player->m_surfaceFriction, NULL );
// HACKHACK: Scale this to fudge the relationship between vphysics friction values and player friction values.
// A value of 0.8f feels pretty normal for vphysics, whereas 1.0f is normal for players.
// This scaling trivially makes them equivalent. REVISIT if this affects low friction surfaces too much.
player->m_surfaceFriction *= 1.25f;
if ( player->m_surfaceFriction > 1.0f )
player->m_surfaceFriction = 1.0f;
player->m_chTextureType = player->m_pSurfaceData->game.material;
}
bool CGameMovement::IsDead( void ) const
{
return ( player->m_iHealth <= 0 ) ? true : false;
}
//-----------------------------------------------------------------------------
// Figures out how the constraint should slow us down
//-----------------------------------------------------------------------------
float CGameMovement::ComputeConstraintSpeedFactor( void )
{
// If we have a constraint, slow down because of that too.
if ( !mv || mv->m_flConstraintRadius == 0.0f )
return 1.0f;
float flDistSq = mv->GetAbsOrigin().DistToSqr( mv->m_vecConstraintCenter );
float flOuterRadiusSq = mv->m_flConstraintRadius * mv->m_flConstraintRadius;
float flInnerRadiusSq = mv->m_flConstraintRadius - mv->m_flConstraintWidth;
flInnerRadiusSq *= flInnerRadiusSq;
// Only slow us down if we're inside the constraint ring
if ((flDistSq <= flInnerRadiusSq) || (flDistSq >= flOuterRadiusSq))
return 1.0f;
// Only slow us down if we're running away from the center
Vector vecDesired;
VectorMultiply( m_vecForward, mv->m_flForwardMove, vecDesired );
VectorMA( vecDesired, mv->m_flSideMove, m_vecRight, vecDesired );
VectorMA( vecDesired, mv->m_flUpMove, m_vecUp, vecDesired );
Vector vecDelta;
VectorSubtract( mv->GetAbsOrigin(), mv->m_vecConstraintCenter, vecDelta );
VectorNormalize( vecDelta );
VectorNormalize( vecDesired );
if (DotProduct( vecDelta, vecDesired ) < 0.0f)
return 1.0f;
float flFrac = (sqrt(flDistSq) - (mv->m_flConstraintRadius - mv->m_flConstraintWidth)) / mv->m_flConstraintWidth;
float flSpeedFactor = Lerp( flFrac, 1.0f, mv->m_flConstraintSpeedFactor );
return flSpeedFactor;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::CheckParameters( void )
{
QAngle v_angle;
if ( player->GetMoveType() != MOVETYPE_ISOMETRIC &&
player->GetMoveType() != MOVETYPE_NOCLIP &&
player->GetMoveType() != MOVETYPE_OBSERVER )
{
float spd;
float maxspeed;
spd = ( mv->m_flForwardMove * mv->m_flForwardMove ) +
( mv->m_flSideMove * mv->m_flSideMove ) +
( mv->m_flUpMove * mv->m_flUpMove );
maxspeed = mv->m_flClientMaxSpeed;
if ( maxspeed != 0.0 )
{
mv->m_flMaxSpeed = min( maxspeed, mv->m_flMaxSpeed );
}
// Slow down by the speed factor
float flSpeedFactor = 1.0f;
if (player->m_pSurfaceData)
{
flSpeedFactor = player->m_pSurfaceData->game.maxSpeedFactor;
}
// If we have a constraint, slow down because of that too.
float flConstraintSpeedFactor = ComputeConstraintSpeedFactor();
if (flConstraintSpeedFactor < flSpeedFactor)
flSpeedFactor = flConstraintSpeedFactor;
mv->m_flMaxSpeed *= flSpeedFactor;
if ( g_bMovementOptimizations )
{
// Same thing but only do the sqrt if we have to.
if ( ( spd != 0.0 ) && ( spd > mv->m_flMaxSpeed*mv->m_flMaxSpeed ) )
{
float fRatio = mv->m_flMaxSpeed / sqrt( spd );
mv->m_flForwardMove *= fRatio;
mv->m_flSideMove *= fRatio;
mv->m_flUpMove *= fRatio;
}
}
else
{
spd = sqrt( spd );
if ( ( spd != 0.0 ) && ( spd > mv->m_flMaxSpeed ) )
{
float fRatio = mv->m_flMaxSpeed / spd;
mv->m_flForwardMove *= fRatio;
mv->m_flSideMove *= fRatio;
mv->m_flUpMove *= fRatio;
}
}
}
if ( player->GetFlags() & FL_FROZEN ||
player->GetFlags() & FL_ONTRAIN ||
IsDead() )
{
mv->m_flForwardMove = 0;
mv->m_flSideMove = 0;
mv->m_flUpMove = 0;
}
DecayPunchAngle();
// Take angles from command.
if ( !IsDead() )
{
v_angle = mv->m_vecAngles;
v_angle = v_angle + player->m_Local.m_vecPunchAngle;
// Now adjust roll angle
if ( player->GetMoveType() != MOVETYPE_ISOMETRIC &&
player->GetMoveType() != MOVETYPE_NOCLIP )
{
mv->m_vecAngles[ROLL] = CalcRoll( v_angle, mv->m_vecVelocity, sv_rollangle.GetFloat(), sv_rollspeed.GetFloat() );
}
else
{
mv->m_vecAngles[ROLL] = 0.0; // v_angle[ ROLL ];
}
mv->m_vecAngles[PITCH] = v_angle[PITCH];
mv->m_vecAngles[YAW] = v_angle[YAW];
}
else
{
mv->m_vecAngles = mv->m_vecOldAngles;
}
// Set dead player view_offset
if ( IsDead() )
{
player->SetViewOffset( VEC_DEAD_VIEWHEIGHT );
}
// Adjust client view angles to match values used on server.
if ( mv->m_vecAngles[YAW] > 180.0f )
{
mv->m_vecAngles[YAW] -= 360.0f;
}
}
void CGameMovement::ReduceTimers( void )
{
float frame_msec = 1000.0f * gpGlobals->frametime;
if ( player->m_Local.m_flDucktime > 0 )
{
player->m_Local.m_flDucktime -= frame_msec;
if ( player->m_Local.m_flDucktime < 0 )
{
player->m_Local.m_flDucktime = 0;
}
}
if ( player->m_Local.m_flDuckJumpTime > 0 )
{
player->m_Local.m_flDuckJumpTime -= frame_msec;
if ( player->m_Local.m_flDuckJumpTime < 0 )
{
player->m_Local.m_flDuckJumpTime = 0;
}
}
if ( player->m_Local.m_flJumpTime > 0 )
{
player->m_Local.m_flJumpTime -= frame_msec;
if ( player->m_Local.m_flJumpTime < 0 )
{
player->m_Local.m_flJumpTime = 0;
}
}
if ( player->m_flSwimSoundTime > 0 )
{
player->m_flSwimSoundTime -= frame_msec;
if ( player->m_flSwimSoundTime < 0 )
{
player->m_flSwimSoundTime = 0;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pMove -
//-----------------------------------------------------------------------------
void CGameMovement::ProcessMovement( CBasePlayer *pPlayer, CMoveData *pMove )
{
Assert( pMove && pPlayer );
float flStoreFrametime = gpGlobals->frametime;
//!!HACK HACK: Adrian - slow down all player movement by this factor.
//!!Blame Yahn for this one.
gpGlobals->frametime *= pPlayer->GetLaggedMovementValue();
ResetGetPointContentsCache();
// Cropping movement speed scales mv->m_fForwardSpeed etc. globally
// Once we crop, we don't want to recursively crop again, so we set the crop
// flag globally here once per usercmd cycle.
m_bSpeedCropped = false;
// StartTrackPredictionErrors should have set this
Assert( player == pPlayer );
player = pPlayer;
mv = pMove;
mv->m_flMaxSpeed = sv_maxspeed.GetFloat();
// CheckV( player->CurrentCommandNumber(), "StartPos", mv->GetAbsOrigin() );
DiffPrint( "start %f %f %f", mv->GetAbsOrigin().x, mv->GetAbsOrigin().y, mv->GetAbsOrigin().z );
// Run the command.
PlayerMove();
FinishMove();
DiffPrint( "end %f %f %f", mv->GetAbsOrigin().x, mv->GetAbsOrigin().y, mv->GetAbsOrigin().z );
// CheckV( player->CurrentCommandNumber(), "EndPos", mv->GetAbsOrigin() );
//This is probably not needed, but just in case.
gpGlobals->frametime = flStoreFrametime;
player = NULL;
}
void CGameMovement::StartTrackPredictionErrors( CBasePlayer *pPlayer )
{
player = pPlayer;
#if PREDICTION_ERROR_CHECK_LEVEL > 0
StartCommand( CBaseEntity::IsServer(), player->CurrentCommandNumber() );
#endif
}
void CGameMovement::FinishTrackPredictionErrors( CBasePlayer *pPlayer )
{
#if PREDICTION_ERROR_CHECK_LEVEL > 0
Assert( player == pPlayer );
// DiffPrint( "end %f", player->m_Local.m_vecPunchAngleVel.m_Value.x );
// Call validate at end of checking
Validate( CBaseEntity::IsServer(), player->CurrentCommandNumber() );
#endif
}
//-----------------------------------------------------------------------------
// Purpose: Sets ground entity
//-----------------------------------------------------------------------------
void CGameMovement::FinishMove( void )
{
mv->m_nOldButtons = mv->m_nButtons;
}
#define PUNCH_DAMPING 9.0f // bigger number makes the response more damped, smaller is less damped
// currently the system will overshoot, with larger damping values it won't
#define PUNCH_SPRING_CONSTANT 65.0f // bigger number increases the speed at which the view corrects
//-----------------------------------------------------------------------------
// Purpose: Decays the punchangle toward 0,0,0.
// Modelled as a damped spring
//-----------------------------------------------------------------------------
void CGameMovement::DecayPunchAngle( void )
{
if ( player->m_Local.m_vecPunchAngle->LengthSqr() > 0.001 || player->m_Local.m_vecPunchAngleVel->LengthSqr() > 0.001 )
{
player->m_Local.m_vecPunchAngle += player->m_Local.m_vecPunchAngleVel * gpGlobals->frametime;
float damping = 1 - (PUNCH_DAMPING * gpGlobals->frametime);
if ( damping < 0 )
{
damping = 0;
}
player->m_Local.m_vecPunchAngleVel *= damping;
// torsional spring
// UNDONE: Per-axis spring constant?
float springForceMagnitude = PUNCH_SPRING_CONSTANT * gpGlobals->frametime;
springForceMagnitude = clamp(springForceMagnitude, 0, 2 );
player->m_Local.m_vecPunchAngleVel -= player->m_Local.m_vecPunchAngle * springForceMagnitude;
// don't wrap around
player->m_Local.m_vecPunchAngle.Init(
clamp(player->m_Local.m_vecPunchAngle->x, -89, 89 ),
clamp(player->m_Local.m_vecPunchAngle->y, -179, 179 ),
clamp(player->m_Local.m_vecPunchAngle->z, -89, 89 ) );
}
else
{
player->m_Local.m_vecPunchAngle.Init( 0, 0, 0 );
player->m_Local.m_vecPunchAngleVel.Init( 0, 0, 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::StartGravity( void )
{
float ent_gravity;
if (player->GetGravity())
ent_gravity = player->GetGravity();
else
ent_gravity = 1.0;
// Add gravity so they'll be in the correct position during movement
// yes, this 0.5 looks wrong, but it's not.
mv->m_vecVelocity[2] -= (ent_gravity * sv_gravity.GetFloat() * 0.5 * gpGlobals->frametime );
mv->m_vecVelocity[2] += player->GetBaseVelocity()[2] * gpGlobals->frametime;
Vector temp = player->GetBaseVelocity();
temp[ 2 ] = 0;
player->SetBaseVelocity( temp );
CheckVelocity();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::CheckWaterJump( void )
{
Vector flatforward;
Vector forward;
Vector flatvelocity;
float curspeed;
AngleVectors( mv->m_vecViewAngles, &forward ); // Determine movement angles
// Already water jumping.
if (player->m_flWaterJumpTime)
return;
// Don't hop out if we just jumped in
if (mv->m_vecVelocity[2] < -180)
return; // only hop out if we are moving up
// See if we are backing up
flatvelocity[0] = mv->m_vecVelocity[0];
flatvelocity[1] = mv->m_vecVelocity[1];
flatvelocity[2] = 0;
// Must be moving
curspeed = VectorNormalize( flatvelocity );
// see if near an edge
flatforward[0] = forward[0];
flatforward[1] = forward[1];
flatforward[2] = 0;
VectorNormalize (flatforward);
// Are we backing into water from steps or something? If so, don't pop forward
if ( curspeed != 0.0 && ( DotProduct( flatvelocity, flatforward ) < 0.0 ) )
return;
Vector vecStart;
// Start line trace at waist height (using the center of the player for this here)
vecStart= mv->GetAbsOrigin() + (GetPlayerMins() + GetPlayerMaxs() ) * 0.5;
Vector vecEnd;
VectorMA( vecStart, 24.0f, flatforward, vecEnd );
trace_t tr;
TracePlayerBBox( vecStart, vecEnd, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, tr );
if ( tr.fraction < 1.0 ) // solid at waist
{
IPhysicsObject *pPhysObj = tr.m_pEnt->VPhysicsGetObject();
if ( pPhysObj )
{
if ( pPhysObj->GetGameFlags() & FVPHYSICS_PLAYER_HELD )
return;
}
vecStart.z = mv->GetAbsOrigin().z + player->GetViewOffset().z + WATERJUMP_HEIGHT;
VectorMA( vecStart, 24.0f, flatforward, vecEnd );
VectorMA( vec3_origin, -50.0f, tr.plane.normal, player->m_vecWaterJumpVel );
TracePlayerBBox( vecStart, vecEnd, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, tr );
if ( tr.fraction == 1.0 ) // open at eye level
{
// Now trace down to see if we would actually land on a standable surface.
VectorCopy( vecEnd, vecStart );
vecEnd.z -= 1024.0f;
TracePlayerBBox( vecStart, vecEnd, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, tr );
if ( ( tr.fraction < 1.0f ) && ( tr.plane.normal.z >= 0.7 ) )
{
mv->m_vecVelocity[2] = 256.0f; // Push up
mv->m_nOldButtons |= IN_JUMP; // Don't jump again until released
player->AddFlag( FL_WATERJUMP );
player->m_flWaterJumpTime = 2000.0f; // Do this for 2 seconds
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::WaterJump( void )
{
if (player->m_flWaterJumpTime > 10000)
player->m_flWaterJumpTime = 10000;
if (!player->m_flWaterJumpTime)
return;
player->m_flWaterJumpTime -= 1000.0f * gpGlobals->frametime;
if (player->m_flWaterJumpTime <= 0 || !player->GetWaterLevel())
{
player->m_flWaterJumpTime = 0;
player->RemoveFlag( FL_WATERJUMP );
}
mv->m_vecVelocity[0] = player->m_vecWaterJumpVel[0];
mv->m_vecVelocity[1] = player->m_vecWaterJumpVel[1];
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::WaterMove( void )
{
int i;
Vector wishvel;
float wishspeed;
Vector wishdir;
Vector start, dest;
Vector temp;
trace_t pm;
float speed, newspeed, addspeed, accelspeed;
Vector forward, right, up;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
//
// user intentions
//
for (i=0 ; i<3 ; i++)
{
wishvel[i] = forward[i]*mv->m_flForwardMove + right[i]*mv->m_flSideMove;
}
// if we have the jump key down, move us up as well
if (mv->m_nButtons & IN_JUMP)
{
wishvel[2] += mv->m_flClientMaxSpeed;
}
// Sinking after no other movement occurs
else if (!mv->m_flForwardMove && !mv->m_flSideMove && !mv->m_flUpMove)
{
wishvel[2] -= 60; // drift towards bottom
}
else // Go straight up by upmove amount.
{
// exaggerate upward movement along forward as well
float upwardMovememnt = mv->m_flForwardMove * forward.z * 2;
upwardMovememnt = clamp( upwardMovememnt, 0, mv->m_flClientMaxSpeed );
wishvel[2] += mv->m_flUpMove + upwardMovememnt;
}
// Copy it over and determine speed
VectorCopy (wishvel, wishdir);
wishspeed = VectorNormalize(wishdir);
// Cap speed.
if (wishspeed > mv->m_flMaxSpeed)
{
VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
wishspeed = mv->m_flMaxSpeed;
}
// Slow us down a bit.
wishspeed *= 0.8;
// Water friction
VectorCopy(mv->m_vecVelocity, temp);
speed = VectorNormalize(temp);
if (speed)
{
newspeed = speed - gpGlobals->frametime * speed * sv_friction.GetFloat() * player->m_surfaceFriction;
if (newspeed < 0.1f)
{
newspeed = 0;
}
VectorScale (mv->m_vecVelocity, newspeed/speed, mv->m_vecVelocity);
}
else
{
newspeed = 0;
}
// water acceleration
if (wishspeed >= 0.1f) // old !
{
addspeed = wishspeed - newspeed;
if (addspeed > 0)
{
VectorNormalize(wishvel);
accelspeed = sv_accelerate.GetFloat() * wishspeed * gpGlobals->frametime * player->m_surfaceFriction;
if (accelspeed > addspeed)
{
accelspeed = addspeed;
}
for (i = 0; i < 3; i++)
{
float deltaSpeed = accelspeed * wishvel[i];
mv->m_vecVelocity[i] += deltaSpeed;
mv->m_outWishVel[i] += deltaSpeed;
}
}
}
VectorAdd (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity);
// Now move
// assume it is a stair or a slope, so press down from stepheight above
VectorMA (mv->GetAbsOrigin(), gpGlobals->frametime, mv->m_vecVelocity, dest);
TracePlayerBBox( mv->GetAbsOrigin(), dest, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
if ( pm.fraction == 1.0f )
{
VectorCopy( dest, start );
if ( player->m_Local.m_bAllowAutoMovement )
{
start[2] += player->m_Local.m_flStepSize + 1;
}
TracePlayerBBox( start, dest, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
if (!pm.startsolid && !pm.allsolid)
{
float stepDist = pm.endpos.z - mv->GetAbsOrigin().z;
mv->m_outStepHeight += stepDist;
// walked up the step, so just keep result and exit
mv->SetAbsOrigin( pm.endpos );
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
return;
}
// Try moving straight along out normal path.
TryPlayerMove();
}
else
{
if ( !player->GetGroundEntity() )
{
TryPlayerMove();
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
return;
}
StepMove( dest, pm );
}
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
}
//-----------------------------------------------------------------------------
// Purpose: Does the basic move attempting to climb up step heights. It uses
// the mv->GetAbsOrigin() and mv->m_vecVelocity. It returns a new
// new mv->GetAbsOrigin(), mv->m_vecVelocity, and mv->m_outStepHeight.
//-----------------------------------------------------------------------------
void CGameMovement::StepMove( Vector &vecDestination, trace_t &trace )
{
Vector vecEndPos;
VectorCopy( vecDestination, vecEndPos );
// Try sliding forward both on ground and up 16 pixels
// take the move that goes farthest
Vector vecPos, vecVel;
VectorCopy( mv->GetAbsOrigin(), vecPos );
VectorCopy( mv->m_vecVelocity, vecVel );
// Slide move down.
TryPlayerMove( &vecEndPos, &trace );
// Down results.
Vector vecDownPos, vecDownVel;
VectorCopy( mv->GetAbsOrigin(), vecDownPos );
VectorCopy( mv->m_vecVelocity, vecDownVel );
// Reset original values.
mv->SetAbsOrigin( vecPos );
VectorCopy( vecVel, mv->m_vecVelocity );
// Move up a stair height.
VectorCopy( mv->GetAbsOrigin(), vecEndPos );
if ( player->m_Local.m_bAllowAutoMovement )
{
vecEndPos.z += player->m_Local.m_flStepSize + DIST_EPSILON;
}
TracePlayerBBox( mv->GetAbsOrigin(), vecEndPos, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace );
if ( !trace.startsolid && !trace.allsolid )
{
mv->SetAbsOrigin( trace.endpos );
}
// Slide move up.
TryPlayerMove();
// Move down a stair (attempt to).
VectorCopy( mv->GetAbsOrigin(), vecEndPos );
if ( player->m_Local.m_bAllowAutoMovement )
{
vecEndPos.z -= player->m_Local.m_flStepSize + DIST_EPSILON;
}
TracePlayerBBox( mv->GetAbsOrigin(), vecEndPos, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace );
// If we are not on the ground any more then use the original movement attempt.
if ( trace.plane.normal[2] < 0.7 )
{
mv->SetAbsOrigin( vecDownPos );
VectorCopy( vecDownVel, mv->m_vecVelocity );
float flStepDist = mv->GetAbsOrigin().z - vecPos.z;
if ( flStepDist > 0.0f )
{
mv->m_outStepHeight += flStepDist;
}
return;
}
// If the trace ended up in empty space, copy the end over to the origin.
if ( !trace.startsolid && !trace.allsolid )
{
mv->SetAbsOrigin( trace.endpos );
}
// Copy this origin to up.
Vector vecUpPos;
VectorCopy( mv->GetAbsOrigin(), vecUpPos );
// decide which one went farther
float flDownDist = ( vecDownPos.x - vecPos.x ) * ( vecDownPos.x - vecPos.x ) + ( vecDownPos.y - vecPos.y ) * ( vecDownPos.y - vecPos.y );
float flUpDist = ( vecUpPos.x - vecPos.x ) * ( vecUpPos.x - vecPos.x ) + ( vecUpPos.y - vecPos.y ) * ( vecUpPos.y - vecPos.y );
if ( flDownDist > flUpDist )
{
mv->SetAbsOrigin( vecDownPos );
VectorCopy( vecDownVel, mv->m_vecVelocity );
}
else
{
// copy z value from slide move
mv->m_vecVelocity.z = vecDownVel.z;
}
float flStepDist = mv->GetAbsOrigin().z - vecPos.z;
if ( flStepDist > 0 )
{
mv->m_outStepHeight += flStepDist;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::Friction( void )
{
float speed, newspeed, control;
float friction;
float drop;
// If we are in water jump cycle, don't apply friction
if (player->m_flWaterJumpTime)
return;
// Calculate speed
speed = VectorLength( mv->m_vecVelocity );
// If too slow, return
if (speed < 0.1f)
{
return;
}
drop = 0;
// apply ground friction
if (player->GetGroundEntity() != NULL) // On an entity that is the ground
{
friction = sv_friction.GetFloat() * player->m_surfaceFriction;
// Bleed off some speed, but if we have less than the bleed
// threshold, bleed the threshold amount.
if ( IsX360() )
{
if( player->m_Local.m_bDucked )
{
control = (speed < sv_stopspeed.GetFloat()) ? sv_stopspeed.GetFloat() : speed;
}
else
{
#if defined ( TF_DLL ) || defined ( TF_CLIENT_DLL )
control = (speed < sv_stopspeed.GetFloat()) ? sv_stopspeed.GetFloat() : speed;
#else
control = (speed < sv_stopspeed.GetFloat()) ? (sv_stopspeed.GetFloat() * 2.0f) : speed;
#endif
}
}
else
{
control = (speed < sv_stopspeed.GetFloat()) ? sv_stopspeed.GetFloat() : speed;
}
// Add the amount to the drop amount.
drop += control*friction*gpGlobals->frametime;
}
// scale the velocity
newspeed = speed - drop;
if (newspeed < 0)
newspeed = 0;
if ( newspeed != speed )
{
// Determine proportion of old speed we are using.
newspeed /= speed;
// Adjust velocity according to proportion.
VectorScale( mv->m_vecVelocity, newspeed, mv->m_vecVelocity );
}
mv->m_outWishVel -= (1.f-newspeed) * mv->m_vecVelocity;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FinishGravity( void )
{
float ent_gravity;
if ( player->m_flWaterJumpTime )
return;
if ( player->GetGravity() )
ent_gravity = player->GetGravity();
else
ent_gravity = 1.0;
// Get the correct velocity for the end of the dt
mv->m_vecVelocity[2] -= (ent_gravity * sv_gravity.GetFloat() * gpGlobals->frametime * 0.5);
CheckVelocity();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : wishdir -
// accel -
//-----------------------------------------------------------------------------
void CGameMovement::AirAccelerate( Vector& wishdir, float wishspeed, float accel )
{
int i;
float addspeed, accelspeed, currentspeed;
float wishspd;
wishspd = wishspeed;
if (player->pl.deadflag)
return;
if (player->m_flWaterJumpTime)
return;
// Cap speed
if (wishspd > 30)
wishspd = 30;
// Determine veer amount
currentspeed = mv->m_vecVelocity.Dot(wishdir);
// See how much to add
addspeed = wishspd - currentspeed;
// If not adding any, done.
if (addspeed <= 0)
return;
// Determine acceleration speed after acceleration
accelspeed = accel * wishspeed * gpGlobals->frametime * player->m_surfaceFriction;
// Cap it
if (accelspeed > addspeed)
accelspeed = addspeed;
// Adjust pmove vel.
for (i=0 ; i<3 ; i++)
{
mv->m_vecVelocity[i] += accelspeed * wishdir[i];
mv->m_outWishVel[i] += accelspeed * wishdir[i];
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::AirMove( void )
{
int i;
Vector wishvel;
float fmove, smove;
Vector wishdir;
float wishspeed;
Vector forward, right, up;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
// Copy movement amounts
fmove = mv->m_flForwardMove;
smove = mv->m_flSideMove;
// Zero out z components of movement vectors
forward[2] = 0;
right[2] = 0;
VectorNormalize(forward); // Normalize remainder of vectors
VectorNormalize(right); //
for (i=0 ; i<2 ; i++) // Determine x and y parts of velocity
wishvel[i] = forward[i]*fmove + right[i]*smove;
wishvel[2] = 0; // Zero out z part of velocity
VectorCopy (wishvel, wishdir); // Determine maginitude of speed of move
wishspeed = VectorNormalize(wishdir);
//
// clamp to server defined max speed
//
if ( wishspeed != 0 && (wishspeed > mv->m_flMaxSpeed))
{
VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
wishspeed = mv->m_flMaxSpeed;
}
AirAccelerate( wishdir, wishspeed, sv_airaccelerate.GetFloat() );
// Add in any base velocity to the current velocity.
VectorAdd(mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
TryPlayerMove();
// Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?)
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
}
bool CGameMovement::CanAccelerate()
{
// Dead players don't accelerate.
if (player->pl.deadflag)
return false;
// If waterjumping, don't accelerate
if (player->m_flWaterJumpTime)
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : wishdir -
// wishspeed -
// accel -
//-----------------------------------------------------------------------------
void CGameMovement::Accelerate( Vector& wishdir, float wishspeed, float accel )
{
int i;
float addspeed, accelspeed, currentspeed;
// This gets overridden because some games (CSPort) want to allow dead (observer) players
// to be able to move around.
if ( !CanAccelerate() )
return;
// See if we are changing direction a bit
currentspeed = mv->m_vecVelocity.Dot(wishdir);
// Reduce wishspeed by the amount of veer.
addspeed = wishspeed - currentspeed;
// If not going to add any speed, done.
if (addspeed <= 0)
return;
// Determine amount of accleration.
accelspeed = accel * gpGlobals->frametime * wishspeed * player->m_surfaceFriction;
// Cap at addspeed
if (accelspeed > addspeed)
accelspeed = addspeed;
// Adjust velocity.
for (i=0 ; i<3 ; i++)
{
mv->m_vecVelocity[i] += accelspeed * wishdir[i];
}
}
//-----------------------------------------------------------------------------
// Purpose: Try to keep a walking player on the ground when running down slopes etc
//-----------------------------------------------------------------------------
void CGameMovement::StayOnGround( void )
{
trace_t trace;
Vector start( mv->GetAbsOrigin() );
Vector end( mv->GetAbsOrigin() );
start.z += 2;
end.z -= player->GetStepSize();
// See how far up we can go without getting stuck
TracePlayerBBox( mv->GetAbsOrigin(), start, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace );
start = trace.endpos;
// using trace.startsolid is unreliable here, it doesn't get set when
// tracing bounding box vs. terrain
// Now trace down from a known safe position
TracePlayerBBox( start, end, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace );
if ( trace.fraction > 0.0f && // must go somewhere
trace.fraction < 1.0f && // must hit something
!trace.startsolid && // can't be embedded in a solid
trace.plane.normal[2] >= 0.7 ) // can't hit a steep slope that we can't stand on anyway
{
float flDelta = fabs(mv->GetAbsOrigin().z - trace.endpos.z);
//This is incredibly hacky. The real problem is that trace returning that strange value we can't network over.
if ( flDelta > 0.5f * COORD_RESOLUTION)
{
mv->SetAbsOrigin( trace.endpos );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::WalkMove( void )
{
int i;
Vector wishvel;
float spd;
float fmove, smove;
Vector wishdir;
float wishspeed;
Vector dest;
trace_t pm;
Vector forward, right, up;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
CHandle< CBaseEntity > oldground;
oldground = player->GetGroundEntity();
// Copy movement amounts
fmove = mv->m_flForwardMove;
smove = mv->m_flSideMove;
// Zero out z components of movement vectors
if ( g_bMovementOptimizations )
{
if ( forward[2] != 0 )
{
forward[2] = 0;
VectorNormalize( forward );
}
if ( right[2] != 0 )
{
right[2] = 0;
VectorNormalize( right );
}
}
else
{
forward[2] = 0;
right[2] = 0;
VectorNormalize (forward); // Normalize remainder of vectors.
VectorNormalize (right); //
}
for (i=0 ; i<2 ; i++) // Determine x and y parts of velocity
wishvel[i] = forward[i]*fmove + right[i]*smove;
wishvel[2] = 0; // Zero out z part of velocity
VectorCopy (wishvel, wishdir); // Determine maginitude of speed of move
wishspeed = VectorNormalize(wishdir);
//
// Clamp to server defined max speed
//
if ((wishspeed != 0.0f) && (wishspeed > mv->m_flMaxSpeed))
{
VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
wishspeed = mv->m_flMaxSpeed;
}
// Set pmove velocity
mv->m_vecVelocity[2] = 0;
Accelerate ( wishdir, wishspeed, sv_accelerate.GetFloat() );
mv->m_vecVelocity[2] = 0;
// Add in any base velocity to the current velocity.
VectorAdd (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
spd = VectorLength( mv->m_vecVelocity );
if ( spd < 1.0f )
{
mv->m_vecVelocity.Init();
// Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?)
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
return;
}
// first try just moving to the destination
dest[0] = mv->GetAbsOrigin()[0] + mv->m_vecVelocity[0]*gpGlobals->frametime;
dest[1] = mv->GetAbsOrigin()[1] + mv->m_vecVelocity[1]*gpGlobals->frametime;
dest[2] = mv->GetAbsOrigin()[2];
// first try moving directly to the next spot
TracePlayerBBox( mv->GetAbsOrigin(), dest, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
// If we made it all the way, then copy trace end as new player position.
mv->m_outWishVel += wishdir * wishspeed;
if ( pm.fraction == 1 )
{
mv->SetAbsOrigin( pm.endpos );
// Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?)
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
StayOnGround();
return;
}
// Don't walk up stairs if not on ground.
if ( oldground == NULL && player->GetWaterLevel() == 0 )
{
// Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?)
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
return;
}
// If we are jumping out of water, don't do anything more.
if ( player->m_flWaterJumpTime )
{
// Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?)
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
return;
}
StepMove( dest, pm );
// Now pull the base velocity back out. Base velocity is set if you are on a moving object, like a conveyor (or maybe another monster?)
VectorSubtract( mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity );
StayOnGround();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FullWalkMove( )
{
if ( !CheckWater() )
{
StartGravity();
}
// If we are leaping out of the water, just update the counters.
if (player->m_flWaterJumpTime)
{
WaterJump();
TryPlayerMove();
// See if we are still in water?
CheckWater();
return;
}
// If we are swimming in the water, see if we are nudging against a place we can jump up out
// of, and, if so, start out jump. Otherwise, if we are not moving up, then reset jump timer to 0
if ( player->GetWaterLevel() >= WL_Waist )
{
if ( player->GetWaterLevel() == WL_Waist )
{
CheckWaterJump();
}
// If we are falling again, then we must not trying to jump out of water any more.
if ( mv->m_vecVelocity[2] < 0 &&
player->m_flWaterJumpTime )
{
player->m_flWaterJumpTime = 0;
}
// Was jump button pressed?
if (mv->m_nButtons & IN_JUMP)
{
CheckJumpButton();
}
else
{
mv->m_nOldButtons &= ~IN_JUMP;
}
// Perform regular water movement
WaterMove();
// Redetermine position vars
CategorizePosition();
// If we are on ground, no downward velocity.
if ( player->GetGroundEntity() != NULL )
{
mv->m_vecVelocity[2] = 0;
}
}
else
// Not fully underwater
{
// Was jump button pressed?
if (mv->m_nButtons & IN_JUMP)
{
CheckJumpButton();
}
else
{
mv->m_nOldButtons &= ~IN_JUMP;
}
// Fricion is handled before we add in any base velocity. That way, if we are on a conveyor,
// we don't slow when standing still, relative to the conveyor.
if (player->GetGroundEntity() != NULL)
{
mv->m_vecVelocity[2] = 0.0;
Friction();
}
// Make sure velocity is valid.
CheckVelocity();
if (player->GetGroundEntity() != NULL)
{
WalkMove();
}
else
{
AirMove(); // Take into account movement when in air.
}
// Set final flags.
CategorizePosition();
// Make sure velocity is valid.
CheckVelocity();
// Add any remaining gravitational component.
if ( !CheckWater() )
{
FinishGravity();
}
// If we are on ground, no downward velocity.
if ( player->GetGroundEntity() != NULL )
{
mv->m_vecVelocity[2] = 0;
}
CheckFalling();
}
if ( ( m_nOldWaterLevel == WL_NotInWater && player->GetWaterLevel() != WL_NotInWater ) ||
( m_nOldWaterLevel != WL_NotInWater && player->GetWaterLevel() == WL_NotInWater ) )
{
PlaySwimSound();
#if !defined( CLIENT_DLL )
player->Splash();
#endif
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FullObserverMove( void )
{
int mode = player->GetObserverMode();
if ( mode == OBS_MODE_IN_EYE || mode == OBS_MODE_CHASE )
{
CBaseEntity * target = player->GetObserverTarget();
if ( target != NULL )
{
mv->SetAbsOrigin( target->GetAbsOrigin() );
mv->m_vecViewAngles = target->GetAbsAngles();
mv->m_vecVelocity = target->GetAbsVelocity();
}
return;
}
if ( mode != OBS_MODE_ROAMING )
{
// don't move in fixed or death cam mode
return;
}
if ( sv_specnoclip.GetBool() )
{
// roam in noclip mode
FullNoClipMove( sv_specspeed.GetFloat(), sv_specaccelerate.GetFloat() );
return;
}
// do a full clipped free roam move:
Vector wishvel;
Vector forward, right, up;
Vector wishdir, wishend;
float wishspeed;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
// Copy movement amounts
float factor = sv_specspeed.GetFloat();
if ( mv->m_nButtons & IN_SPEED )
{
factor /= 2.0f;
}
float fmove = mv->m_flForwardMove * factor;
float smove = mv->m_flSideMove * factor;
VectorNormalize (forward); // Normalize remainder of vectors
VectorNormalize (right); //
for (int i=0 ; i<3 ; i++) // Determine x and y parts of velocity
wishvel[i] = forward[i]*fmove + right[i]*smove;
wishvel[2] += mv->m_flUpMove;
VectorCopy (wishvel, wishdir); // Determine maginitude of speed of move
wishspeed = VectorNormalize(wishdir);
//
// Clamp to server defined max speed
//
float maxspeed = sv_maxvelocity.GetFloat();
if (wishspeed > maxspeed )
{
VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
wishspeed = maxspeed;
}
// Set pmove velocity, give observer 50% acceration bonus
Accelerate ( wishdir, wishspeed, sv_specaccelerate.GetFloat() );
float spd = VectorLength( mv->m_vecVelocity );
if (spd < 1.0f)
{
mv->m_vecVelocity.Init();
return;
}
float friction = sv_friction.GetFloat();
// Add the amount to the drop amount.
float drop = spd * friction * gpGlobals->frametime;
// scale the velocity
float newspeed = spd - drop;
if (newspeed < 0)
newspeed = 0;
// Determine proportion of old speed we are using.
newspeed /= spd;
VectorScale( mv->m_vecVelocity, newspeed, mv->m_vecVelocity );
CheckVelocity();
TryPlayerMove();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FullNoClipMove( float factor, float maxacceleration )
{
Vector wishvel;
Vector forward, right, up;
Vector wishdir;
float wishspeed;
float maxspeed = sv_maxspeed.GetFloat() * factor;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
if ( mv->m_nButtons & IN_SPEED )
{
factor /= 2.0f;
}
// Copy movement amounts
float fmove = mv->m_flForwardMove * factor;
float smove = mv->m_flSideMove * factor;
VectorNormalize (forward); // Normalize remainder of vectors
VectorNormalize (right); //
for (int i=0 ; i<3 ; i++) // Determine x and y parts of velocity
wishvel[i] = forward[i]*fmove + right[i]*smove;
wishvel[2] += mv->m_flUpMove * factor;
VectorCopy (wishvel, wishdir); // Determine maginitude of speed of move
wishspeed = VectorNormalize(wishdir);
//
// Clamp to server defined max speed
//
if (wishspeed > maxspeed )
{
VectorScale (wishvel, maxspeed/wishspeed, wishvel);
wishspeed = maxspeed;
}
if ( maxacceleration > 0.0 )
{
// Set pmove velocity
Accelerate ( wishdir, wishspeed, maxacceleration );
float spd = VectorLength( mv->m_vecVelocity );
if (spd < 1.0f)
{
mv->m_vecVelocity.Init();
return;
}
// Bleed off some speed, but if we have less than the bleed
// threshhold, bleed the theshold amount.
float control = (spd < maxspeed/4.0) ? maxspeed/4.0 : spd;
float friction = sv_friction.GetFloat() * player->m_surfaceFriction;
// Add the amount to the drop amount.
float drop = control * friction * gpGlobals->frametime;
// scale the velocity
float newspeed = spd - drop;
if (newspeed < 0)
newspeed = 0;
// Determine proportion of old speed we are using.
newspeed /= spd;
VectorScale( mv->m_vecVelocity, newspeed, mv->m_vecVelocity );
}
else
{
VectorCopy( wishvel, mv->m_vecVelocity );
}
// Just move ( don't clip or anything )
Vector out;
VectorMA( mv->GetAbsOrigin(), gpGlobals->frametime, mv->m_vecVelocity, out );
mv->SetAbsOrigin( out );
// Zero out velocity if in noaccel mode
if ( maxacceleration < 0.0f )
{
mv->m_vecVelocity.Init();
}
}
//-----------------------------------------------------------------------------
// Checks to see if we should actually jump
//-----------------------------------------------------------------------------
void CGameMovement::PlaySwimSound()
{
MoveHelper()->StartSound( mv->GetAbsOrigin(), "Player.Swim" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CGameMovement::CheckJumpButton( void )
{
if (player->pl.deadflag)
{
mv->m_nOldButtons |= IN_JUMP ; // don't jump again until released
return false;
}
// See if we are waterjumping. If so, decrement count and return.
if (player->m_flWaterJumpTime)
{
player->m_flWaterJumpTime -= gpGlobals->frametime;
if (player->m_flWaterJumpTime < 0)
player->m_flWaterJumpTime = 0;
return false;
}
// If we are in the water most of the way...
if ( player->GetWaterLevel() >= 2 )
{
// swimming, not jumping
SetGroundEntity( NULL );
if(player->GetWaterType() == CONTENTS_WATER) // We move up a certain amount
mv->m_vecVelocity[2] = 100;
else if (player->GetWaterType() == CONTENTS_SLIME)
mv->m_vecVelocity[2] = 80;
// play swiming sound
if ( player->m_flSwimSoundTime <= 0 )
{
// Don't play sound again for 1 second
player->m_flSwimSoundTime = 1000;
PlaySwimSound();
}
return false;
}
// No more effect
if (player->GetGroundEntity() == NULL)
{
mv->m_nOldButtons |= IN_JUMP;
return false; // in air, so no effect
}
// Don't allow jumping when the player is in a stasis field.
#ifndef HL2_EPISODIC
if ( player->m_Local.m_bSlowMovement )
return false;
#endif
if ( mv->m_nOldButtons & IN_JUMP )
return false; // don't pogo stick
// Cannot jump will in the unduck transition.
if ( player->m_Local.m_bDucking && ( player->GetFlags() & FL_DUCKING ) )
return false;
// Still updating the eye position.
if ( player->m_Local.m_flDuckJumpTime > 0.0f )
return false;
// In the air now.
SetGroundEntity( NULL );
player->PlayStepSound( (Vector &)mv->GetAbsOrigin(), player->m_pSurfaceData, 1.0, true );
MoveHelper()->PlayerSetAnimation( PLAYER_JUMP );
float flGroundFactor = 1.0f;
if (player->m_pSurfaceData)
{
flGroundFactor = player->m_pSurfaceData->game.jumpFactor;
}
float flMul;
if ( g_bMovementOptimizations )
{
#if defined(HL2_DLL) || defined(HL2_CLIENT_DLL)
Assert( sv_gravity.GetFloat() == 600.0f );
flMul = 260.0f; // approx. 21 units.
#else
Assert( sv_gravity.GetFloat() == 800.0f );
flMul = 368.3281572999747f;
#endif
}
else
{
flMul = sqrt(2 * sv_gravity.GetFloat() * GAMEMOVEMENT_JUMP_HEIGHT);
}
// Acclerate upward
// If we are ducking...
float startz = mv->m_vecVelocity[2];
if ( ( player->m_Local.m_bDucking ) || ( player->GetFlags() & FL_DUCKING ) )
{
// d = 0.5 * g * t^2 - distance traveled with linear accel
// t = sqrt(2.0 * 45 / g) - how long to fall 45 units
// v = g * t - velocity at the end (just invert it to jump up that high)
// v = g * sqrt(2.0 * 45 / g )
// v^2 = g * g * 2.0 * 45 / g
// v = sqrt( g * 2.0 * 45 )
mv->m_vecVelocity[2] = flGroundFactor * flMul; // 2 * gravity * height
}
else
{
mv->m_vecVelocity[2] += flGroundFactor * flMul; // 2 * gravity * height
}
// Add a little forward velocity based on your current forward velocity - if you are not sprinting.
#if defined( HL2_DLL ) || defined( HL2_CLIENT_DLL )
if ( gpGlobals->maxClients == 1 )
{
CHLMoveData *pMoveData = ( CHLMoveData* )mv;
Vector vecForward;
AngleVectors( mv->m_vecViewAngles, &vecForward );
vecForward.z = 0;
VectorNormalize( vecForward );
// We give a certain percentage of the current forward movement as a bonus to the jump speed. That bonus is clipped
// to not accumulate over time.
float flSpeedBoostPerc = ( !pMoveData->m_bIsSprinting && !player->m_Local.m_bDucked ) ? 0.5f : 0.1f;
float flSpeedAddition = fabs( mv->m_flForwardMove * flSpeedBoostPerc );
float flMaxSpeed = mv->m_flMaxSpeed + ( mv->m_flMaxSpeed * flSpeedBoostPerc );
float flNewSpeed = ( flSpeedAddition + mv->m_vecVelocity.Length2D() );
// If we're over the maximum, we want to only boost as much as will get us to the goal speed
if ( flNewSpeed > flMaxSpeed )
{
flSpeedAddition -= flNewSpeed - flMaxSpeed;
}
if ( mv->m_flForwardMove < 0.0f )
flSpeedAddition *= -1.0f;
// Add it on
VectorAdd( (vecForward*flSpeedAddition), mv->m_vecVelocity, mv->m_vecVelocity );
}
#endif
FinishGravity();
CheckV( player->CurrentCommandNumber(), "CheckJump", mv->m_vecVelocity );
mv->m_outJumpVel.z += mv->m_vecVelocity[2] - startz;
mv->m_outStepHeight += 0.15f;
// Set jump time.
if ( gpGlobals->maxClients == 1 )
{
player->m_Local.m_flJumpTime = GAMEMOVEMENT_JUMP_TIME;
player->m_Local.m_bInDuckJump = true;
}
#if defined( HL2_DLL )
if ( xc_uncrouch_on_jump.GetBool() )
{
// Uncrouch when jumping
if ( player->GetToggledDuckState() )
{
player->ToggleDuck();
}
}
#endif
// Flag that we jumped.
mv->m_nOldButtons |= IN_JUMP; // don't jump again until released
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FullLadderMove()
{
CheckWater();
// Was jump button pressed? If so, set velocity to 270 away from ladder.
if ( mv->m_nButtons & IN_JUMP )
{
CheckJumpButton();
}
else
{
mv->m_nOldButtons &= ~IN_JUMP;
}
// Perform the move accounting for any base velocity.
VectorAdd (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity);
TryPlayerMove();
VectorSubtract (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity);
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CGameMovement::TryPlayerMove( Vector *pFirstDest, trace_t *pFirstTrace )
{
int bumpcount, numbumps;
Vector dir;
float d;
int numplanes;
Vector planes[MAX_CLIP_PLANES];
Vector primal_velocity, original_velocity;
Vector new_velocity;
int i, j;
trace_t pm;
Vector end;
float time_left, allFraction;
int blocked;
numbumps = 4; // Bump up to four times
blocked = 0; // Assume not blocked
numplanes = 0; // and not sliding along any planes
VectorCopy (mv->m_vecVelocity, original_velocity); // Store original velocity
VectorCopy (mv->m_vecVelocity, primal_velocity);
allFraction = 0;
time_left = gpGlobals->frametime; // Total time for this movement operation.
new_velocity.Init();
for (bumpcount=0 ; bumpcount < numbumps; bumpcount++)
{
if ( mv->m_vecVelocity.Length() == 0.0 )
break;
// Assume we can move all the way from the current origin to the
// end point.
VectorMA( mv->GetAbsOrigin(), time_left, mv->m_vecVelocity, end );
// See if we can make it from origin to end point.
if ( g_bMovementOptimizations )
{
// If their velocity Z is 0, then we can avoid an extra trace here during WalkMove.
if ( pFirstDest && end == *pFirstDest )
pm = *pFirstTrace;
else
{
#if defined( PLAYER_GETTING_STUCK_TESTING )
trace_t foo;
TracePlayerBBox( mv->GetAbsOrigin(), mv->GetAbsOrigin(), PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, foo );
if ( foo.startsolid || foo.fraction != 1.0f )
{
Msg( "bah\n" );
}
#endif
TracePlayerBBox( mv->GetAbsOrigin(), end, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
}
}
else
{
TracePlayerBBox( mv->GetAbsOrigin(), end, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
}
allFraction += pm.fraction;
// If we started in a solid object, or we were in solid space
// the whole way, zero out our velocity and return that we
// are blocked by floor and wall.
if (pm.allsolid)
{
// entity is trapped in another solid
VectorCopy (vec3_origin, mv->m_vecVelocity);
return 4;
}
// If we moved some portion of the total distance, then
// copy the end position into the pmove.origin and
// zero the plane counter.
if( pm.fraction > 0 )
{
if ( numbumps > 0 && pm.fraction == 1 )
{
// There's a precision issue with terrain tracing that can cause a swept box to successfully trace
// when the end position is stuck in the triangle. Re-run the test with an uswept box to catch that
// case until the bug is fixed.
// If we detect getting stuck, don't allow the movement
trace_t stuck;
TracePlayerBBox( pm.endpos, pm.endpos, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, stuck );
if ( stuck.startsolid || stuck.fraction != 1.0f )
{
//Msg( "Player will become stuck!!!\n" );
VectorCopy (vec3_origin, mv->m_vecVelocity);
break;
}
}
#if defined( PLAYER_GETTING_STUCK_TESTING )
trace_t foo;
TracePlayerBBox( pm.endpos, pm.endpos, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, foo );
if ( foo.startsolid || foo.fraction != 1.0f )
{
Msg( "Player will become stuck!!!\n" );
}
#endif
// actually covered some distance
mv->SetAbsOrigin( pm.endpos);
VectorCopy (mv->m_vecVelocity, original_velocity);
numplanes = 0;
}
// If we covered the entire distance, we are done
// and can return.
if (pm.fraction == 1)
{
break; // moved the entire distance
}
// Save entity that blocked us (since fraction was < 1.0)
// for contact
// Add it if it's not already in the list!!!
MoveHelper( )->AddToTouched( pm, mv->m_vecVelocity );
// If the plane we hit has a high z component in the normal, then
// it's probably a floor
if (pm.plane.normal[2] > 0.7)
{
blocked |= 1; // floor
}
// If the plane has a zero z component in the normal, then it's a
// step or wall
if (!pm.plane.normal[2])
{
blocked |= 2; // step / wall
}
// Reduce amount of m_flFrameTime left by total time left * fraction
// that we covered.
time_left -= time_left * pm.fraction;
// Did we run out of planes to clip against?
if (numplanes >= MAX_CLIP_PLANES)
{
// this shouldn't really happen
// Stop our movement if so.
VectorCopy (vec3_origin, mv->m_vecVelocity);
//Con_DPrintf("Too many planes 4\n");
break;
}
// Set up next clipping plane
VectorCopy (pm.plane.normal, planes[numplanes]);
numplanes++;
// modify original_velocity so it parallels all of the clip planes
//
// reflect player velocity
// Only give this a try for first impact plane because you can get yourself stuck in an acute corner by jumping in place
// and pressing forward and nobody was really using this bounce/reflection feature anyway...
if ( numplanes == 1 &&
player->GetMoveType() == MOVETYPE_WALK &&
player->GetGroundEntity() == NULL )
{
for ( i = 0; i < numplanes; i++ )
{
if ( planes[i][2] > 0.7 )
{
// floor or slope
ClipVelocity( original_velocity, planes[i], new_velocity, 1 );
VectorCopy( new_velocity, original_velocity );
}
else
{
ClipVelocity( original_velocity, planes[i], new_velocity, 1.0 + sv_bounce.GetFloat() * (1 - player->m_surfaceFriction) );
}
}
VectorCopy( new_velocity, mv->m_vecVelocity );
VectorCopy( new_velocity, original_velocity );
}
else
{
for (i=0 ; i < numplanes ; i++)
{
ClipVelocity (
original_velocity,
planes[i],
mv->m_vecVelocity,
1);
for (j=0 ; j<numplanes ; j++)
if (j != i)
{
// Are we now moving against this plane?
if (mv->m_vecVelocity.Dot(planes[j]) < 0)
break; // not ok
}
if (j == numplanes) // Didn't have to clip, so we're ok
break;
}
// Did we go all the way through plane set
if (i != numplanes)
{ // go along this plane
// pmove.velocity is set in clipping call, no need to set again.
;
}
else
{ // go along the crease
if (numplanes != 2)
{
VectorCopy (vec3_origin, mv->m_vecVelocity);
break;
}
CrossProduct (planes[0], planes[1], dir);
dir.NormalizeInPlace();
d = dir.Dot(mv->m_vecVelocity);
VectorScale (dir, d, mv->m_vecVelocity );
}
//
// if original velocity is against the original velocity, stop dead
// to avoid tiny occilations in sloping corners
//
d = mv->m_vecVelocity.Dot(primal_velocity);
if (d <= 0)
{
//Con_DPrintf("Back\n");
VectorCopy (vec3_origin, mv->m_vecVelocity);
break;
}
}
}
if ( allFraction == 0 )
{
VectorCopy (vec3_origin, mv->m_vecVelocity);
}
// Check if they slammed into a wall
float fSlamVol = 0.0f;
float fLateralStoppingAmount = primal_velocity.Length2D() - mv->m_vecVelocity.Length2D();
if ( fLateralStoppingAmount > PLAYER_MAX_SAFE_FALL_SPEED * 2.0f )
{
fSlamVol = 1.0f;
}
else if ( fLateralStoppingAmount > PLAYER_MAX_SAFE_FALL_SPEED )
{
fSlamVol = 0.85f;
}
PlayerRoughLandingEffects( fSlamVol );
return blocked;
}
//-----------------------------------------------------------------------------
// Purpose: Determine whether or not the player is on a ladder (physprop or world).
//-----------------------------------------------------------------------------
inline bool CGameMovement::OnLadder( trace_t &trace )
{
if ( trace.contents & CONTENTS_LADDER )
return true;
IPhysicsSurfaceProps *pPhysProps = MoveHelper( )->GetSurfaceProps();
if ( pPhysProps )
{
const surfacedata_t *pSurfaceData = pPhysProps->GetSurfaceData( trace.surface.surfaceProps );
if ( pSurfaceData )
{
if ( pSurfaceData->game.climbable != 0 )
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CGameMovement::LadderMove( void )
{
trace_t pm;
bool onFloor;
Vector floor;
Vector wishdir;
Vector end;
if ( player->GetMoveType() == MOVETYPE_NOCLIP )
return false;
if ( !GameHasLadders() )
return false;
// If I'm already moving on a ladder, use the previous ladder direction
if ( player->GetMoveType() == MOVETYPE_LADDER )
{
wishdir = -player->m_vecLadderNormal;
}
else
{
// otherwise, use the direction player is attempting to move
if ( mv->m_flForwardMove || mv->m_flSideMove )
{
for (int i=0 ; i<3 ; i++) // Determine x and y parts of velocity
wishdir[i] = m_vecForward[i]*mv->m_flForwardMove + m_vecRight[i]*mv->m_flSideMove;
VectorNormalize(wishdir);
}
else
{
// Player is not attempting to move, no ladder behavior
return false;
}
}
// wishdir points toward the ladder if any exists
VectorMA( mv->GetAbsOrigin(), LadderDistance(), wishdir, end );
TracePlayerBBox( mv->GetAbsOrigin(), end, LadderMask(), COLLISION_GROUP_PLAYER_MOVEMENT, pm );
// no ladder in that direction, return
if ( pm.fraction == 1.0f || !OnLadder( pm ) )
return false;
player->SetMoveType( MOVETYPE_LADDER );
player->SetMoveCollide( MOVECOLLIDE_DEFAULT );
player->m_vecLadderNormal = pm.plane.normal;
// On ladder, convert movement to be relative to the ladder
VectorCopy( mv->GetAbsOrigin(), floor );
floor[2] += GetPlayerMins()[2] - 1;
if( enginetrace->GetPointContents( floor ) == CONTENTS_SOLID || player->GetGroundEntity() != NULL )
{
onFloor = true;
}
else
{
onFloor = false;
}
player->SetGravity( 0 );
float climbSpeed = ClimbSpeed();
float forwardSpeed = 0, rightSpeed = 0;
if ( mv->m_nButtons & IN_BACK )
forwardSpeed -= climbSpeed;
if ( mv->m_nButtons & IN_FORWARD )
forwardSpeed += climbSpeed;
if ( mv->m_nButtons & IN_MOVELEFT )
rightSpeed -= climbSpeed;
if ( mv->m_nButtons & IN_MOVERIGHT )
rightSpeed += climbSpeed;
if ( mv->m_nButtons & IN_JUMP )
{
player->SetMoveType( MOVETYPE_WALK );
player->SetMoveCollide( MOVECOLLIDE_DEFAULT );
VectorScale( pm.plane.normal, 270, mv->m_vecVelocity );
}
else
{
if ( forwardSpeed != 0 || rightSpeed != 0 )
{
Vector velocity, perp, cross, lateral, tmp;
//ALERT(at_console, "pev %.2f %.2f %.2f - ",
// pev->velocity.x, pev->velocity.y, pev->velocity.z);
// Calculate player's intended velocity
//Vector velocity = (forward * gpGlobals->v_forward) + (right * gpGlobals->v_right);
VectorScale( m_vecForward, forwardSpeed, velocity );
VectorMA( velocity, rightSpeed, m_vecRight, velocity );
// Perpendicular in the ladder plane
VectorCopy( vec3_origin, tmp );
tmp[2] = 1;
CrossProduct( tmp, pm.plane.normal, perp );
VectorNormalize( perp );
// decompose velocity into ladder plane
float normal = DotProduct( velocity, pm.plane.normal );
// This is the velocity into the face of the ladder
VectorScale( pm.plane.normal, normal, cross );
// This is the player's additional velocity
VectorSubtract( velocity, cross, lateral );
// This turns the velocity into the face of the ladder into velocity that
// is roughly vertically perpendicular to the face of the ladder.
// NOTE: It IS possible to face up and move down or face down and move up
// because the velocity is a sum of the directional velocity and the converted
// velocity through the face of the ladder -- by design.
CrossProduct( pm.plane.normal, perp, tmp );
VectorMA( lateral, -normal, tmp, mv->m_vecVelocity );
if ( onFloor && normal > 0 ) // On ground moving away from the ladder
{
VectorMA( mv->m_vecVelocity, MAX_CLIMB_SPEED, pm.plane.normal, mv->m_vecVelocity );
}
//pev->velocity = lateral - (CrossProduct( trace.vecPlaneNormal, perp ) * normal);
}
else
{
mv->m_vecVelocity.Init();
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : axis -
// Output : const char
//-----------------------------------------------------------------------------
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
const char *DescribeAxis( int axis )
{
static char sz[ 32 ];
switch ( axis )
{
case 0:
Q_strncpy( sz, "X", sizeof( sz ) );
break;
case 1:
Q_strncpy( sz, "Y", sizeof( sz ) );
break;
case 2:
default:
Q_strncpy( sz, "Z", sizeof( sz ) );
break;
}
return sz;
}
#else
const char *DescribeAxis( int axis );
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::CheckVelocity( void )
{
int i;
//
// bound velocity
//
Vector org = mv->GetAbsOrigin();
for (i=0; i < 3; i++)
{
// See if it's bogus.
if (IS_NAN(mv->m_vecVelocity[i]))
{
DevMsg( 1, "PM Got a NaN velocity %s\n", DescribeAxis( i ) );
mv->m_vecVelocity[i] = 0;
}
if (IS_NAN(org[i]))
{
DevMsg( 1, "PM Got a NaN origin on %s\n", DescribeAxis( i ) );
org[ i ] = 0;
mv->SetAbsOrigin( org );
}
// Bound it.
if (mv->m_vecVelocity[i] > sv_maxvelocity.GetFloat())
{
DevMsg( 1, "PM Got a velocity too high on %s\n", DescribeAxis( i ) );
mv->m_vecVelocity[i] = sv_maxvelocity.GetFloat();
}
else if (mv->m_vecVelocity[i] < -sv_maxvelocity.GetFloat())
{
DevMsg( 1, "PM Got a velocity too low on %s\n", DescribeAxis( i ) );
mv->m_vecVelocity[i] = -sv_maxvelocity.GetFloat();
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::AddGravity( void )
{
float ent_gravity;
if ( player->m_flWaterJumpTime )
return;
if (player->GetGravity())
ent_gravity = player->GetGravity();
else
ent_gravity = 1.0;
// Add gravity incorrectly
mv->m_vecVelocity[2] -= (ent_gravity * sv_gravity.GetFloat() * gpGlobals->frametime);
mv->m_vecVelocity[2] += player->GetBaseVelocity()[2] * gpGlobals->frametime;
Vector temp = player->GetBaseVelocity();
temp[2] = 0;
player->SetBaseVelocity( temp );
CheckVelocity();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : push -
// Output : trace_t
//-----------------------------------------------------------------------------
void CGameMovement::PushEntity( Vector& push, trace_t *pTrace )
{
Vector end;
VectorAdd (mv->GetAbsOrigin(), push, end);
TracePlayerBBox( mv->GetAbsOrigin(), end, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, *pTrace );
mv->SetAbsOrigin( pTrace->endpos );
// So we can run impact function afterwards.
// If
if ( pTrace->fraction < 1.0 && !pTrace->allsolid )
{
MoveHelper( )->AddToTouched( *pTrace, mv->m_vecVelocity );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : in -
// normal -
// out -
// overbounce -
// Output : int
//-----------------------------------------------------------------------------
int CGameMovement::ClipVelocity( Vector& in, Vector& normal, Vector& out, float overbounce )
{
float backoff;
float change;
float angle;
int i, blocked;
angle = normal[ 2 ];
blocked = 0x00; // Assume unblocked.
if (angle > 0) // If the plane that is blocking us has a positive z component, then assume it's a floor.
blocked |= 0x01; //
if (!angle) // If the plane has no Z, it is vertical (wall/step)
blocked |= 0x02; //
// Determine how far along plane to slide based on incoming direction.
backoff = DotProduct (in, normal) * overbounce;
for (i=0 ; i<3 ; i++)
{
change = normal[i]*backoff;
out[i] = in[i] - change;
}
// iterate once to make sure we aren't still moving through the plane
float adjust = DotProduct( out, normal );
if( adjust < 0.0f )
{
out -= ( normal * adjust );
// Msg( "Adjustment = %lf\n", adjust );
}
// Return blocking flags.
return blocked;
}
//-----------------------------------------------------------------------------
// Purpose: Computes roll angle for a certain movement direction and velocity
// Input : angles -
// velocity -
// rollangle -
// rollspeed -
// Output : float
//-----------------------------------------------------------------------------
float CGameMovement::CalcRoll ( const QAngle &angles, const Vector &velocity, float rollangle, float rollspeed )
{
float sign;
float side;
float value;
Vector forward, right, up;
AngleVectors (angles, &forward, &right, &up);
side = DotProduct (velocity, right);
sign = side < 0 ? -1 : 1;
side = fabs(side);
value = rollangle;
if (side < rollspeed)
{
side = side * value / rollspeed;
}
else
{
side = value;
}
return side*sign;
}
#define CHECKSTUCK_MINTIME 0.05 // Don't check again too quickly.
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
Vector rgv3tStuckTable[54];
#else
extern Vector rgv3tStuckTable[54];
#endif
#if !defined(_STATIC_LINKED) || defined(CLIENT_DLL)
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CreateStuckTable( void )
{
float x, y, z;
int idx;
int i;
float zi[3];
static int firsttime = 1;
if ( !firsttime )
return;
firsttime = 0;
memset(rgv3tStuckTable, 0, sizeof(rgv3tStuckTable));
idx = 0;
// Little Moves.
x = y = 0;
// Z moves
for (z = -0.125 ; z <= 0.125 ; z += 0.125)
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
x = z = 0;
// Y moves
for (y = -0.125 ; y <= 0.125 ; y += 0.125)
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
y = z = 0;
// X moves
for (x = -0.125 ; x <= 0.125 ; x += 0.125)
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
// Remaining multi axis nudges.
for ( x = - 0.125; x <= 0.125; x += 0.250 )
{
for ( y = - 0.125; y <= 0.125; y += 0.250 )
{
for ( z = - 0.125; z <= 0.125; z += 0.250 )
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
}
}
// Big Moves.
x = y = 0;
zi[0] = 0.0f;
zi[1] = 1.0f;
zi[2] = 6.0f;
for (i = 0; i < 3; i++)
{
// Z moves
z = zi[i];
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
x = z = 0;
// Y moves
for (y = -2.0f ; y <= 2.0f ; y += 2.0)
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
y = z = 0;
// X moves
for (x = -2.0f ; x <= 2.0f ; x += 2.0f)
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
// Remaining multi axis nudges.
for (i = 0 ; i < 3; i++)
{
z = zi[i];
for (x = -2.0f ; x <= 2.0f ; x += 2.0f)
{
for (y = -2.0f ; y <= 2.0f ; y += 2.0)
{
rgv3tStuckTable[idx][0] = x;
rgv3tStuckTable[idx][1] = y;
rgv3tStuckTable[idx][2] = z;
idx++;
}
}
}
Assert( idx < sizeof(rgv3tStuckTable)/sizeof(rgv3tStuckTable[0]));
}
#else
extern void CreateStuckTable( void );
#endif
//-----------------------------------------------------------------------------
// Purpose:
// Input : nIndex -
// server -
// offset -
// Output : int
//-----------------------------------------------------------------------------
int GetRandomStuckOffsets( CBasePlayer *pPlayer, Vector& offset)
{
// Last time we did a full
int idx;
idx = pPlayer->m_StuckLast++;
VectorCopy(rgv3tStuckTable[idx % 54], offset);
return (idx % 54);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : nIndex -
// server -
//-----------------------------------------------------------------------------
void ResetStuckOffsets( CBasePlayer *pPlayer )
{
pPlayer->m_StuckLast = 0;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &input -
// Output : int
//-----------------------------------------------------------------------------
int CGameMovement::CheckStuck( void )
{
Vector base;
Vector offset;
Vector test;
EntityHandle_t hitent;
int idx;
float fTime;
trace_t traceresult;
CreateStuckTable();
hitent = TestPlayerPosition( mv->GetAbsOrigin(), COLLISION_GROUP_PLAYER_MOVEMENT, traceresult );
if ( hitent == INVALID_ENTITY_HANDLE )
{
ResetStuckOffsets( player );
return 0;
}
// Deal with stuckness...
#ifndef _LINUX
if ( developer.GetBool() )
{
bool isServer = player->IsServer();
engine->Con_NPrintf( isServer, "%s stuck on object %i/%s",
isServer ? "server" : "client",
hitent.GetEntryIndex(), MoveHelper()->GetName(hitent) );
}
#endif
VectorCopy( mv->GetAbsOrigin(), base );
//
// Deal with precision error in network.
//
// World or BSP model
if ( !player->IsServer() )
{
if ( MoveHelper()->IsWorldEntity( hitent ) )
{
int nReps = 0;
ResetStuckOffsets( player );
do
{
GetRandomStuckOffsets( player, offset );
VectorAdd( base, offset, test );
if ( TestPlayerPosition( test, COLLISION_GROUP_PLAYER_MOVEMENT, traceresult ) == INVALID_ENTITY_HANDLE )
{
ResetStuckOffsets( player );
mv->SetAbsOrigin( test );
return 0;
}
nReps++;
} while (nReps < 54);
}
}
// Only an issue on the client.
idx = player->IsServer() ? 0 : 1;
fTime = engine->Time();
// Too soon?
if ( m_flStuckCheckTime[ player->entindex() ][ idx ] >= fTime - CHECKSTUCK_MINTIME )
{
return 1;
}
m_flStuckCheckTime[ player->entindex() ][ idx ] = fTime;
MoveHelper( )->AddToTouched( traceresult, mv->m_vecVelocity );
GetRandomStuckOffsets( player, offset );
VectorAdd( base, offset, test );
if ( TestPlayerPosition( test, COLLISION_GROUP_PLAYER_MOVEMENT, traceresult ) == INVALID_ENTITY_HANDLE)
{
ResetStuckOffsets( player );
mv->SetAbsOrigin( test );
return 0;
}
return 1;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : bool
//-----------------------------------------------------------------------------
bool CGameMovement::InWater( void )
{
return ( player->GetWaterLevel() > WL_Feet );
}
void CGameMovement::ResetGetPointContentsCache()
{
for ( int slot = 0; slot < MAX_PC_CACHE_SLOTS; ++slot )
{
for ( int i = 0; i < MAX_PLAYERS; ++i )
{
m_CachedGetPointContents[ i ][ slot ] = -9999;
}
}
}
int CGameMovement::GetPointContentsCached( const Vector &point, int slot )
{
if ( g_bMovementOptimizations )
{
Assert( player );
Assert( slot >= 0 && slot < MAX_PC_CACHE_SLOTS );
int idx = player->entindex() - 1;
if ( m_CachedGetPointContents[ idx ][ slot ] == -9999 || point.DistToSqr( m_CachedGetPointContentsPoint[ idx ][ slot ] ) > 1 )
{
m_CachedGetPointContents[ idx ][ slot ] = enginetrace->GetPointContents ( point );
m_CachedGetPointContentsPoint[ idx ][ slot ] = point;
}
return m_CachedGetPointContents[ idx ][ slot ];
}
else
{
return enginetrace->GetPointContents ( point );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &input -
// Output : bool
//-----------------------------------------------------------------------------
bool CGameMovement::CheckWater( void )
{
Vector point;
int cont;
// Pick a spot just above the players feet.
point[0] = mv->GetAbsOrigin()[0] + (GetPlayerMins()[0] + GetPlayerMaxs()[0]) * 0.5;
point[1] = mv->GetAbsOrigin()[1] + (GetPlayerMins()[1] + GetPlayerMaxs()[1]) * 0.5;
point[2] = mv->GetAbsOrigin()[2] + GetPlayerMins()[2] + 1;
// Assume that we are not in water at all.
player->SetWaterLevel( WL_NotInWater );
player->SetWaterType( CONTENTS_EMPTY );
// Grab point contents.
cont = GetPointContentsCached( point, 0 );
// Are we under water? (not solid and not empty?)
if ( cont & MASK_WATER )
{
// Set water type
player->SetWaterType( cont );
// We are at least at level one
player->SetWaterLevel( WL_Feet );
// Now check a point that is at the player hull midpoint.
point[2] = mv->GetAbsOrigin()[2] + (GetPlayerMins()[2] + GetPlayerMaxs()[2])*0.5;
cont = GetPointContentsCached( point, 1 );
// If that point is also under water...
if ( cont & MASK_WATER )
{
// Set a higher water level.
player->SetWaterLevel( WL_Waist );
// Now check the eye position. (view_ofs is relative to the origin)
point[2] = mv->GetAbsOrigin()[2] + player->GetViewOffset()[2];
cont = GetPointContentsCached( point, 2 );
if ( cont & MASK_WATER )
player->SetWaterLevel( WL_Eyes ); // In over our eyes
}
// Adjust velocity based on water current, if any.
if ( cont & MASK_CURRENT )
{
Vector v;
VectorClear(v);
if ( cont & CONTENTS_CURRENT_0 )
v[0] += 1;
if ( cont & CONTENTS_CURRENT_90 )
v[1] += 1;
if ( cont & CONTENTS_CURRENT_180 )
v[0] -= 1;
if ( cont & CONTENTS_CURRENT_270 )
v[1] -= 1;
if ( cont & CONTENTS_CURRENT_UP )
v[2] += 1;
if ( cont & CONTENTS_CURRENT_DOWN )
v[2] -= 1;
// BUGBUG -- this depends on the value of an unspecified enumerated type
// The deeper we are, the stronger the current.
Vector temp;
VectorMA( player->GetBaseVelocity(), 50.0*player->GetWaterLevel(), v, temp );
player->SetBaseVelocity( temp );
}
}
// if we just transitioned from not in water to in water, record the time it happened
if ( ( WL_NotInWater == m_nOldWaterLevel ) && ( player->GetWaterLevel() > WL_NotInWater ) )
{
m_flWaterEntryTime = gpGlobals->curtime;
}
return ( player->GetWaterLevel() > WL_Feet );
}
void CGameMovement::SetGroundEntity( trace_t *pm )
{
CBaseEntity *newGround = pm ? pm->m_pEnt : NULL;
CBaseEntity *oldGround = player->GetGroundEntity();
Vector vecBaseVelocity = player->GetBaseVelocity();
if ( !oldGround && newGround )
{
// Subtract ground velocity at instant we hit ground jumping
vecBaseVelocity -= newGround->GetAbsVelocity();
vecBaseVelocity.z = newGround->GetAbsVelocity().z;
}
else if ( oldGround && !newGround )
{
// Add in ground velocity at instant we started jumping
vecBaseVelocity += oldGround->GetAbsVelocity();
vecBaseVelocity.z = oldGround->GetAbsVelocity().z;
}
player->SetBaseVelocity( vecBaseVelocity );
player->SetGroundEntity( newGround );
// If we are on something...
if ( newGround )
{
CategorizeGroundSurface( *pm );
// Then we are not in water jump sequence
player->m_flWaterJumpTime = 0;
// Standing on an entity other than the world, so signal that we are touching something.
if ( !pm->DidHitWorld() )
{
MoveHelper()->AddToTouched( *pm, mv->m_vecVelocity );
}
mv->m_vecVelocity.z = 0.0f;
}
}
//-----------------------------------------------------------------------------
// Traces the player's collision bounds in quadrants, looking for a plane that
// can be stood upon (normal's z >= 0.7f). Regardless of success or failure,
// replace the fraction and endpos with the original ones, so we don't try to
// move the player down to the new floor and get stuck on a leaning wall that
// the original trace hit first.
//-----------------------------------------------------------------------------
void TracePlayerBBoxForGround( const Vector& start, const Vector& end, const Vector& minsSrc,
const Vector& maxsSrc, IHandleEntity *player, unsigned int fMask,
int collisionGroup, trace_t& pm )
{
VPROF( "TracePlayerBBoxForGround" );
Ray_t ray;
Vector mins, maxs;
float fraction = pm.fraction;
Vector endpos = pm.endpos;
// Check the -x, -y quadrant
mins = minsSrc;
maxs.Init( min( 0, maxsSrc.x ), min( 0, maxsSrc.y ), maxsSrc.z );
ray.Init( start, end, mins, maxs );
UTIL_TraceRay( ray, fMask, player, collisionGroup, &pm );
if ( pm.m_pEnt && pm.plane.normal[2] >= 0.7)
{
pm.fraction = fraction;
pm.endpos = endpos;
return;
}
// Check the +x, +y quadrant
mins.Init( max( 0, minsSrc.x ), max( 0, minsSrc.y ), minsSrc.z );
maxs = maxsSrc;
ray.Init( start, end, mins, maxs );
UTIL_TraceRay( ray, fMask, player, collisionGroup, &pm );
if ( pm.m_pEnt && pm.plane.normal[2] >= 0.7)
{
pm.fraction = fraction;
pm.endpos = endpos;
return;
}
// Check the -x, +y quadrant
mins.Init( minsSrc.x, max( 0, minsSrc.y ), minsSrc.z );
maxs.Init( min( 0, maxsSrc.x ), maxsSrc.y, maxsSrc.z );
ray.Init( start, end, mins, maxs );
UTIL_TraceRay( ray, fMask, player, collisionGroup, &pm );
if ( pm.m_pEnt && pm.plane.normal[2] >= 0.7)
{
pm.fraction = fraction;
pm.endpos = endpos;
return;
}
// Check the +x, -y quadrant
mins.Init( max( 0, minsSrc.x ), minsSrc.y, minsSrc.z );
maxs.Init( maxsSrc.x, min( 0, maxsSrc.y ), maxsSrc.z );
ray.Init( start, end, mins, maxs );
UTIL_TraceRay( ray, fMask, player, collisionGroup, &pm );
if ( pm.m_pEnt && pm.plane.normal[2] >= 0.7)
{
pm.fraction = fraction;
pm.endpos = endpos;
return;
}
pm.fraction = fraction;
pm.endpos = endpos;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &input -
//-----------------------------------------------------------------------------
void CGameMovement::CategorizePosition( void )
{
Vector point;
trace_t pm;
// Reset this each time we-recategorize, otherwise we have bogus friction when we jump into water and plunge downward really quickly
player->m_surfaceFriction = 1.0f;
// if the player hull point one unit down is solid, the player
// is on ground
// see if standing on something solid
// Doing this before we move may introduce a potential latency in water detection, but
// doing it after can get us stuck on the bottom in water if the amount we move up
// is less than the 1 pixel 'threshold' we're about to snap to. Also, we'll call
// this several times per frame, so we really need to avoid sticking to the bottom of
// water on each call, and the converse case will correct itself if called twice.
CheckWater();
// observers don't have a ground entity
if ( player->IsObserver() )
return;
float flOffset = 2.0f;
point[0] = mv->GetAbsOrigin()[0];
point[1] = mv->GetAbsOrigin()[1];
point[2] = mv->GetAbsOrigin()[2] - flOffset;
Vector bumpOrigin;
bumpOrigin = mv->GetAbsOrigin();
// Shooting up really fast. Definitely not on ground.
// On ladder moving up, so not on ground either
// NOTE: 145 is a jump.
#define NON_JUMP_VELOCITY 140.0f
float zvel = mv->m_vecVelocity[2];
bool bMovingUp = zvel > 0.0f;
bool bMovingUpRapidly = zvel > NON_JUMP_VELOCITY;
float flGroundEntityVelZ = 0.0f;
if ( bMovingUpRapidly )
{
// Tracker 73219, 75878: ywb 8/2/07
// After save/restore (and maybe at other times), we can get a case where we were saved on a lift and
// after restore we'll have a high local velocity due to the lift making our abs velocity appear high.
// We need to account for standing on a moving ground object in that case in order to determine if we really
// are moving away from the object we are standing on at too rapid a speed. Note that CheckJump already sets
// ground entity to NULL, so this wouldn't have any effect unless we are moving up rapidly not from the jump button.
CBaseEntity *ground = player->GetGroundEntity();
if ( ground )
{
flGroundEntityVelZ = ground->GetAbsVelocity().z;
bMovingUpRapidly = ( zvel - flGroundEntityVelZ ) > NON_JUMP_VELOCITY;
}
}
// Was on ground, but now suddenly am not
if ( bMovingUpRapidly ||
( bMovingUp && player->GetMoveType() == MOVETYPE_LADDER ) )
{
SetGroundEntity( NULL );
}
else
{
// Try and move down.
TracePlayerBBox( bumpOrigin, point, MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, pm );
// Was on ground, but now suddenly am not. If we hit a steep plane, we are not on ground
if ( !pm.m_pEnt || pm.plane.normal[2] < 0.7 )
{
// Test four sub-boxes, to see if any of them would have found shallower slope we could actually stand on
TracePlayerBBoxForGround( bumpOrigin, point, GetPlayerMins(), GetPlayerMaxs(), mv->m_nPlayerHandle.Get(), MASK_PLAYERSOLID, COLLISION_GROUP_PLAYER_MOVEMENT, pm );
if ( !pm.m_pEnt || pm.plane.normal[2] < 0.7 )
{
SetGroundEntity( NULL );
// probably want to add a check for a +z velocity too!
if ( ( mv->m_vecVelocity.z > 0.0f ) &&
( player->GetMoveType() != MOVETYPE_NOCLIP ) )
{
player->m_surfaceFriction = 0.25f;
}
}
else
{
SetGroundEntity( &pm );
}
}
else
{
SetGroundEntity( &pm ); // Otherwise, point to index of ent under us.
}
#ifndef CLIENT_DLL
//Adrian: vehicle code handles for us.
if ( player->IsInAVehicle() == false )
{
// If our gamematerial has changed, tell any player surface triggers that are watching
IPhysicsSurfaceProps *physprops = MoveHelper()->GetSurfaceProps();
surfacedata_t *pSurfaceProp = physprops->GetSurfaceData( pm.surface.surfaceProps );
char cCurrGameMaterial = pSurfaceProp->game.material;
if ( !player->GetGroundEntity() )
{
cCurrGameMaterial = 0;
}
// Changed?
if ( player->m_chPreviousTextureType != cCurrGameMaterial )
{
CEnvPlayerSurfaceTrigger::SetPlayerSurface( player, cCurrGameMaterial );
}
player->m_chPreviousTextureType = cCurrGameMaterial;
}
#endif
}
}
//-----------------------------------------------------------------------------
// Purpose: Determine if the player has hit the ground while falling, apply
// damage, and play the appropriate impact sound.
//-----------------------------------------------------------------------------
void CGameMovement::CheckFalling( void )
{
if ( player->GetGroundEntity() != NULL &&
!IsDead() &&
player->m_Local.m_flFallVelocity >= PLAYER_FALL_PUNCH_THRESHOLD )
{
bool bAlive = true;
float fvol = 0.5;
if ( player->GetWaterLevel() > 0 )
{
// They landed in water.
}
else
{
// Scale it down if we landed on something that's floating...
if ( player->GetGroundEntity()->IsFloating() )
{
player->m_Local.m_flFallVelocity -= PLAYER_LAND_ON_FLOATING_OBJECT;
}
//
// They hit the ground.
//
if( player->GetGroundEntity()->GetAbsVelocity().z < 0.0f )
{
// Player landed on a descending object. Subtract the velocity of the ground entity.
player->m_Local.m_flFallVelocity += player->GetGroundEntity()->GetAbsVelocity().z;
player->m_Local.m_flFallVelocity = max( 0.1f, player->m_Local.m_flFallVelocity );
}
if ( player->m_Local.m_flFallVelocity > PLAYER_MAX_SAFE_FALL_SPEED )
{
//
// If they hit the ground going this fast they may take damage (and die).
//
bAlive = MoveHelper( )->PlayerFallingDamage();
fvol = 1.0;
}
else if ( player->m_Local.m_flFallVelocity > PLAYER_MAX_SAFE_FALL_SPEED / 2 )
{
fvol = 0.85;
}
else if ( player->m_Local.m_flFallVelocity < PLAYER_MIN_BOUNCE_SPEED )
{
fvol = 0;
}
}
PlayerRoughLandingEffects( fvol );
if (bAlive)
{
MoveHelper( )->PlayerSetAnimation( PLAYER_WALK );
}
}
//
// Clear the fall velocity so the impact doesn't happen again.
//
if ( player->GetGroundEntity() != NULL )
{
player->m_Local.m_flFallVelocity = 0;
}
}
void CGameMovement::PlayerRoughLandingEffects( float fvol )
{
if ( fvol > 0.0 )
{
//
// Play landing sound right away.
player->m_flStepSoundTime = 400;
// Play step sound for current texture.
player->PlayStepSound( (Vector &)mv->GetAbsOrigin(), player->m_pSurfaceData, fvol, true );
//
// Knock the screen around a little bit, temporary effect.
//
player->m_Local.m_vecPunchAngle.Set( ROLL, player->m_Local.m_flFallVelocity * 0.013 );
if ( player->m_Local.m_vecPunchAngle[PITCH] > 8 )
{
player->m_Local.m_vecPunchAngle.Set( PITCH, 8 );
}
#if !defined( CLIENT_DLL )
player->RumbleEffect( ( fvol > 0.85f ) ? ( RUMBLE_FALL_LONG ) : ( RUMBLE_FALL_SHORT ), 0, RUMBLE_FLAGS_NONE );
#endif
}
}
//-----------------------------------------------------------------------------
// Purpose: Use for ease-in, ease-out style interpolation (accel/decel) Used by ducking code.
// Input : value -
// scale -
// Output : float
//-----------------------------------------------------------------------------
float CGameMovement::SplineFraction( float value, float scale )
{
float valueSquared;
value = scale * value;
valueSquared = value * value;
// Nice little ease-in, ease-out spline-like curve
return 3 * valueSquared - 2 * valueSquared * value;
}
//-----------------------------------------------------------------------------
// Purpose: Determine if crouch/uncrouch caused player to get stuck in world
// Input : direction -
//-----------------------------------------------------------------------------
void CGameMovement::FixPlayerCrouchStuck( bool upward )
{
EntityHandle_t hitent;
int i;
Vector test;
trace_t dummy;
int direction = upward ? 1 : 0;
hitent = TestPlayerPosition( mv->GetAbsOrigin(), COLLISION_GROUP_PLAYER_MOVEMENT, dummy );
if (hitent == INVALID_ENTITY_HANDLE )
return;
VectorCopy( mv->GetAbsOrigin(), test );
for ( i = 0; i < 36; i++ )
{
Vector org = mv->GetAbsOrigin();
org.z += direction;
mv->SetAbsOrigin( org );
hitent = TestPlayerPosition( mv->GetAbsOrigin(), COLLISION_GROUP_PLAYER_MOVEMENT, dummy );
if (hitent == INVALID_ENTITY_HANDLE )
return;
}
mv->SetAbsOrigin( test ); // Failed
}
bool CGameMovement::CanUnduck()
{
int i;
trace_t trace;
Vector newOrigin;
VectorCopy( mv->GetAbsOrigin(), newOrigin );
if ( player->GetGroundEntity() != NULL )
{
for ( i = 0; i < 3; i++ )
{
newOrigin[i] += ( VEC_DUCK_HULL_MIN[i] - VEC_HULL_MIN[i] );
}
}
else
{
// If in air an letting go of crouch, make sure we can offset origin to make
// up for uncrouching
Vector hullSizeNormal = VEC_HULL_MAX - VEC_HULL_MIN;
Vector hullSizeCrouch = VEC_DUCK_HULL_MAX - VEC_DUCK_HULL_MIN;
Vector viewDelta = ( hullSizeNormal - hullSizeCrouch );
viewDelta.Negate();
VectorAdd( newOrigin, viewDelta, newOrigin );
}
bool saveducked = player->m_Local.m_bDucked;
player->m_Local.m_bDucked = false;
TracePlayerBBox( mv->GetAbsOrigin(), newOrigin, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace );
player->m_Local.m_bDucked = saveducked;
if ( trace.startsolid || ( trace.fraction != 1.0f ) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Stop ducking
//-----------------------------------------------------------------------------
void CGameMovement::FinishUnDuck( void )
{
int i;
trace_t trace;
Vector newOrigin;
VectorCopy( mv->GetAbsOrigin(), newOrigin );
if ( player->GetGroundEntity() != NULL )
{
for ( i = 0; i < 3; i++ )
{
newOrigin[i] += ( VEC_DUCK_HULL_MIN[i] - VEC_HULL_MIN[i] );
}
}
else
{
// If in air an letting go of crouch, make sure we can offset origin to make
// up for uncrouching
Vector hullSizeNormal = VEC_HULL_MAX - VEC_HULL_MIN;
Vector hullSizeCrouch = VEC_DUCK_HULL_MAX - VEC_DUCK_HULL_MIN;
Vector viewDelta = ( hullSizeNormal - hullSizeCrouch );
viewDelta.Negate();
VectorAdd( newOrigin, viewDelta, newOrigin );
}
player->m_Local.m_bDucked = false;
player->RemoveFlag( FL_DUCKING );
player->m_Local.m_bDucking = false;
player->m_Local.m_bInDuckJump = false;
player->SetViewOffset( GetPlayerViewOffset( false ) );
player->m_Local.m_flDucktime = 0;
mv->SetAbsOrigin( newOrigin );
// Recategorize position since ducking can change origin
CategorizePosition();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameMovement::UpdateDuckJumpEyeOffset( void )
{
if ( player->m_Local.m_flDuckJumpTime != 0.0f )
{
float flDuckMilliseconds = max( 0.0f, GAMEMOVEMENT_DUCK_TIME - ( float )player->m_Local.m_flDuckJumpTime );
float flDuckSeconds = flDuckMilliseconds / GAMEMOVEMENT_DUCK_TIME;
if ( flDuckSeconds > TIME_TO_UNDUCK )
{
player->m_Local.m_flDuckJumpTime = 0.0f;
SetDuckedEyeOffset( 0.0f );
}
else
{
float flDuckFraction = SimpleSpline( 1.0f - ( flDuckSeconds / TIME_TO_UNDUCK ) );
SetDuckedEyeOffset( flDuckFraction );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FinishUnDuckJump( trace_t &trace )
{
Vector vecNewOrigin;
VectorCopy( mv->GetAbsOrigin(), vecNewOrigin );
// Up for uncrouching.
Vector hullSizeNormal = VEC_HULL_MAX - VEC_HULL_MIN;
Vector hullSizeCrouch = VEC_DUCK_HULL_MAX - VEC_DUCK_HULL_MIN;
Vector viewDelta = ( hullSizeNormal - hullSizeCrouch );
float flDeltaZ = viewDelta.z;
viewDelta.z *= trace.fraction;
flDeltaZ -= viewDelta.z;
player->RemoveFlag( FL_DUCKING );
player->m_Local.m_bDucked = false;
player->m_Local.m_bDucking = false;
player->m_Local.m_bInDuckJump = false;
player->m_Local.m_flDucktime = 0.0f;
player->m_Local.m_flDuckJumpTime = 0.0f;
player->m_Local.m_flJumpTime = 0.0f;
Vector vecViewOffset = GetPlayerViewOffset( false );
vecViewOffset.z -= flDeltaZ;
player->SetViewOffset( vecViewOffset );
VectorSubtract( vecNewOrigin, viewDelta, vecNewOrigin );
mv->SetAbsOrigin( vecNewOrigin );
// Recategorize position since ducking can change origin
CategorizePosition();
}
//-----------------------------------------------------------------------------
// Purpose: Finish ducking
//-----------------------------------------------------------------------------
void CGameMovement::FinishDuck( void )
{
int i;
player->AddFlag( FL_DUCKING );
player->m_Local.m_bDucked = true;
player->m_Local.m_bDucking = false;
player->SetViewOffset( GetPlayerViewOffset( true ) );
// HACKHACK - Fudge for collision bug - no time to fix this properly
if ( player->GetGroundEntity() != NULL )
{
for ( i = 0; i < 3; i++ )
{
Vector org = mv->GetAbsOrigin();
org[ i ]-= ( VEC_DUCK_HULL_MIN[i] - VEC_HULL_MIN[i] );
mv->SetAbsOrigin( org );
}
}
else
{
Vector hullSizeNormal = VEC_HULL_MAX - VEC_HULL_MIN;
Vector hullSizeCrouch = VEC_DUCK_HULL_MAX - VEC_DUCK_HULL_MIN;
Vector viewDelta = ( hullSizeNormal - hullSizeCrouch );
Vector out;
VectorAdd( mv->GetAbsOrigin(), viewDelta, out );
mv->SetAbsOrigin( out );
}
// See if we are stuck?
FixPlayerCrouchStuck( true );
// Recategorize position since ducking can change origin
CategorizePosition();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::StartUnDuckJump( void )
{
player->AddFlag( FL_DUCKING );
player->m_Local.m_bDucked = true;
player->m_Local.m_bDucking = false;
player->SetViewOffset( GetPlayerViewOffset( true ) );
Vector hullSizeNormal = VEC_HULL_MAX - VEC_HULL_MIN;
Vector hullSizeCrouch = VEC_DUCK_HULL_MAX - VEC_DUCK_HULL_MIN;
Vector viewDelta = ( hullSizeNormal - hullSizeCrouch );
Vector out;
VectorAdd( mv->GetAbsOrigin(), viewDelta, out );
mv->SetAbsOrigin( out );
// See if we are stuck?
FixPlayerCrouchStuck( true );
// Recategorize position since ducking can change origin
CategorizePosition();
}
//
//-----------------------------------------------------------------------------
// Purpose:
// Input : duckFraction -
//-----------------------------------------------------------------------------
void CGameMovement::SetDuckedEyeOffset( float duckFraction )
{
Vector vDuckHullMin = GetPlayerMins( true );
Vector vStandHullMin = GetPlayerMins( false );
float fMore = ( vDuckHullMin.z - vStandHullMin.z );
Vector vecDuckViewOffset = GetPlayerViewOffset( true );
Vector vecStandViewOffset = GetPlayerViewOffset( false );
Vector temp = player->GetViewOffset();
temp.z = ( ( vecDuckViewOffset.z - fMore ) * duckFraction ) +
( vecStandViewOffset.z * ( 1 - duckFraction ) );
player->SetViewOffset( temp );
}
//-----------------------------------------------------------------------------
// Purpose: Crop the speed of the player when ducking and on the ground.
// Input: bInDuck - is the player already ducking
// bInAir - is the player in air
// NOTE: Only crop player speed once.
//-----------------------------------------------------------------------------
void CGameMovement::HandleDuckingSpeedCrop( void )
{
if ( !m_bSpeedCropped && ( player->GetFlags() & FL_DUCKING ) && ( player->GetGroundEntity() != NULL ) )
{
float frac = 0.33333333f;
mv->m_flForwardMove *= frac;
mv->m_flSideMove *= frac;
mv->m_flUpMove *= frac;
m_bSpeedCropped = true;
}
}
//-----------------------------------------------------------------------------
// Purpose: Check to see if we are in a situation where we can unduck jump.
//-----------------------------------------------------------------------------
bool CGameMovement::CanUnDuckJump( trace_t &trace )
{
// Trace down to the stand position and see if we can stand.
Vector vecEnd( mv->GetAbsOrigin() );
vecEnd.z -= 36.0f; // This will have to change if bounding hull change!
TracePlayerBBox( mv->GetAbsOrigin(), vecEnd, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, trace );
if ( trace.fraction < 1.0f )
{
// Find the endpoint.
vecEnd.z = mv->GetAbsOrigin().z + ( -36.0f * trace.fraction );
// Test a normal hull.
trace_t traceUp;
bool bWasDucked = player->m_Local.m_bDucked;
player->m_Local.m_bDucked = false;
TracePlayerBBox( vecEnd, vecEnd, PlayerSolidMask(), COLLISION_GROUP_PLAYER_MOVEMENT, traceUp );
player->m_Local.m_bDucked = bWasDucked;
if ( !traceUp.startsolid )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: See if duck button is pressed and do the appropriate things
//-----------------------------------------------------------------------------
void CGameMovement::Duck( void )
{
int buttonsChanged = ( mv->m_nOldButtons ^ mv->m_nButtons ); // These buttons have changed this frame
int buttonsPressed = buttonsChanged & mv->m_nButtons; // The changed ones still down are "pressed"
int buttonsReleased = buttonsChanged & mv->m_nOldButtons; // The changed ones which were previously down are "released"
// Check to see if we are in the air.
bool bInAir = ( player->GetGroundEntity() == NULL );
bool bInDuck = ( player->GetFlags() & FL_DUCKING ) ? true : false;
bool bDuckJump = ( player->m_Local.m_flJumpTime > 0.0f );
bool bDuckJumpTime = ( player->m_Local.m_flDuckJumpTime > 0.0f );
if ( mv->m_nButtons & IN_DUCK )
{
mv->m_nOldButtons |= IN_DUCK;
}
else
{
mv->m_nOldButtons &= ~IN_DUCK;
}
// Handle death.
if ( IsDead() )
return;
// Slow down ducked players.
HandleDuckingSpeedCrop();
// If the player is holding down the duck button, the player is in duck transition, ducking, or duck-jumping.
if ( ( mv->m_nButtons & IN_DUCK ) || player->m_Local.m_bDucking || bInDuck || bDuckJump )
{
// DUCK
if ( ( mv->m_nButtons & IN_DUCK ) || bDuckJump )
{
// XBOX SERVER ONLY
#if !defined(CLIENT_DLL)
if ( IsX360() && buttonsPressed & IN_DUCK )
{
// Hinting logic
if ( player->GetToggledDuckState() && player->m_nNumCrouches < NUM_CROUCH_HINTS )
{
UTIL_HudHintText( player, "#Valve_Hint_Crouch" );
player->m_nNumCrouches++;
}
}
#endif
// Have the duck button pressed, but the player currently isn't in the duck position.
if ( ( buttonsPressed & IN_DUCK ) && !bInDuck && !bDuckJump && !bDuckJumpTime )
{
player->m_Local.m_flDucktime = GAMEMOVEMENT_DUCK_TIME;
player->m_Local.m_bDucking = true;
}
// The player is in duck transition and not duck-jumping.
if ( player->m_Local.m_bDucking && !bDuckJump && !bDuckJumpTime )
{
float flDuckMilliseconds = max( 0.0f, GAMEMOVEMENT_DUCK_TIME - ( float )player->m_Local.m_flDucktime );
float flDuckSeconds = flDuckMilliseconds * 0.001f;
// Finish in duck transition when transition time is over, in "duck", in air.
if ( ( flDuckSeconds > TIME_TO_DUCK ) || bInDuck || bInAir )
{
FinishDuck();
}
else
{
// Calc parametric time
float flDuckFraction = SimpleSpline( flDuckSeconds / TIME_TO_DUCK );
SetDuckedEyeOffset( flDuckFraction );
}
}
if ( bDuckJump )
{
// Make the bounding box small immediately.
if ( !bInDuck )
{
StartUnDuckJump();
}
else
{
// Check for a crouch override.
if ( !( mv->m_nButtons & IN_DUCK ) )
{
trace_t trace;
if ( CanUnDuckJump( trace ) )
{
FinishUnDuckJump( trace );
player->m_Local.m_flDuckJumpTime = ( GAMEMOVEMENT_TIME_TO_UNDUCK * ( 1.0f - trace.fraction ) ) + GAMEMOVEMENT_TIME_TO_UNDUCK_INV;
}
}
}
}
}
// UNDUCK (or attempt to...)
else
{
if ( player->m_Local.m_bInDuckJump )
{
// Check for a crouch override.
if ( !( mv->m_nButtons & IN_DUCK ) )
{
trace_t trace;
if ( CanUnDuckJump( trace ) )
{
FinishUnDuckJump( trace );
if ( trace.fraction < 1.0f )
{
player->m_Local.m_flDuckJumpTime = ( GAMEMOVEMENT_TIME_TO_UNDUCK * ( 1.0f - trace.fraction ) ) + GAMEMOVEMENT_TIME_TO_UNDUCK_INV;
}
}
}
else
{
player->m_Local.m_bInDuckJump = false;
}
}
if ( bDuckJumpTime )
return;
// Try to unduck unless automovement is not allowed
// NOTE: When not onground, you can always unduck
if ( player->m_Local.m_bAllowAutoMovement || bInAir || player->m_Local.m_bDucking )
{
// We released the duck button, we aren't in "duck" and we are not in the air - start unduck transition.
if ( ( buttonsReleased & IN_DUCK ) )
{
if ( bInDuck && !bDuckJump )
{
player->m_Local.m_flDucktime = GAMEMOVEMENT_DUCK_TIME;
}
else if ( player->m_Local.m_bDucking && !player->m_Local.m_bDucked )
{
// Invert time if release before fully ducked!!!
float unduckMilliseconds = 1000.0f * TIME_TO_UNDUCK;
float duckMilliseconds = 1000.0f * TIME_TO_DUCK;
float elapsedMilliseconds = GAMEMOVEMENT_DUCK_TIME - player->m_Local.m_flDucktime;
float fracDucked = elapsedMilliseconds / duckMilliseconds;
float remainingUnduckMilliseconds = fracDucked * unduckMilliseconds;
player->m_Local.m_flDucktime = GAMEMOVEMENT_DUCK_TIME - unduckMilliseconds + remainingUnduckMilliseconds;
}
}
// Check to see if we are capable of unducking.
if ( CanUnduck() )
{
// or unducking
if ( ( player->m_Local.m_bDucking || player->m_Local.m_bDucked ) )
{
float flDuckMilliseconds = max( 0.0f, GAMEMOVEMENT_DUCK_TIME - (float)player->m_Local.m_flDucktime );
float flDuckSeconds = flDuckMilliseconds * 0.001f;
// Finish ducking immediately if duck time is over or not on ground
if ( flDuckSeconds > TIME_TO_UNDUCK || ( bInAir && !bDuckJump ) )
{
FinishUnDuck();
}
else
{
// Calc parametric time
float flDuckFraction = SimpleSpline( 1.0f - ( flDuckSeconds / TIME_TO_UNDUCK ) );
SetDuckedEyeOffset( flDuckFraction );
player->m_Local.m_bDucking = true;
}
}
}
else
{
// Still under something where we can't unduck, so make sure we reset this timer so
// that we'll unduck once we exit the tunnel, etc.
if ( player->m_Local.m_flDucktime != GAMEMOVEMENT_DUCK_TIME )
{
SetDuckedEyeOffset(1.0f);
player->m_Local.m_flDucktime = GAMEMOVEMENT_DUCK_TIME;
player->m_Local.m_bDucked = true;
player->m_Local.m_bDucking = false;
player->AddFlag( FL_DUCKING );
}
}
}
}
}
// HACK: (jimd 5/25/2006) we have a reoccuring bug (#50063 in Tracker) where the player's
// view height gets left at the ducked height while the player is standing, but we haven't
// been able to repro it to find the cause. It may be fixed now due to a change I'm
// also making in UpdateDuckJumpEyeOffset but just in case, this code will sense the
// problem and restore the eye to the proper position. It doesn't smooth the transition,
// but it is preferable to leaving the player's view too low.
//
// If the player is still alive and not an observer, check to make sure that
// his view height is at the standing height.
else if ( !IsDead() && !player->IsObserver() && !player->IsInAVehicle() )
{
if ( ( player->m_Local.m_flDuckJumpTime == 0.0f ) && ( fabs(player->GetViewOffset().z - GetPlayerViewOffset( false ).z) > 0.1 ) )
{
// we should rarely ever get here, so assert so a coder knows when it happens
Assert(0);
DevMsg( 1, "Restoring player view height\n" );
// set the eye height to the non-ducked height
SetDuckedEyeOffset(0.0f);
}
}
}
static ConVar sv_optimizedmovement( "sv_optimizedmovement", "1", FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::PlayerMove( void )
{
VPROF( "CGameMovement::PlayerMove" );
CheckParameters();
// clear output applied velocity
mv->m_outWishVel.Init();
mv->m_outJumpVel.Init();
MoveHelper( )->ResetTouchList(); // Assume we don't touch anything
ReduceTimers();
AngleVectors (mv->m_vecViewAngles, &m_vecForward, &m_vecRight, &m_vecUp ); // Determine movement angles
// Always try and unstick us unless we are using a couple of the movement modes
if ( player->GetMoveType() != MOVETYPE_NOCLIP &&
player->GetMoveType() != MOVETYPE_NONE &&
player->GetMoveType() != MOVETYPE_ISOMETRIC &&
player->GetMoveType() != MOVETYPE_OBSERVER &&
!player->pl.deadflag )
{
if ( CheckInterval( STUCK ) )
{
if ( CheckStuck() )
{
// Can't move, we're stuck
return;
}
}
}
// Now that we are "unstuck", see where we are (player->GetWaterLevel() and type, player->GetGroundEntity()).
if ( player->GetMoveType() != MOVETYPE_WALK ||
mv->m_bGameCodeMovedPlayer ||
!sv_optimizedmovement.GetBool() )
{
CategorizePosition();
}
else
{
if ( mv->m_vecVelocity.z > 250.0f )
{
SetGroundEntity( NULL );
}
}
// Store off the starting water level
m_nOldWaterLevel = player->GetWaterLevel();
// If we are not on ground, store off how fast we are moving down
if ( player->GetGroundEntity() == NULL )
{
player->m_Local.m_flFallVelocity = -mv->m_vecVelocity[ 2 ];
}
m_nOnLadder = 0;
player->UpdateStepSound( player->m_pSurfaceData, mv->GetAbsOrigin(), mv->m_vecVelocity );
UpdateDuckJumpEyeOffset();
Duck();
// Don't run ladder code if dead on on a train
if ( !player->pl.deadflag && !(player->GetFlags() & FL_ONTRAIN) )
{
// If was not on a ladder now, but was on one before,
// get off of the ladder
// TODO: this causes lots of weirdness.
//bool bCheckLadder = CheckInterval( LADDER );
//if ( bCheckLadder || player->GetMoveType() == MOVETYPE_LADDER )
{
if ( !LadderMove() &&
( player->GetMoveType() == MOVETYPE_LADDER ) )
{
// Clear ladder stuff unless player is dead or riding a train
// It will be reset immediately again next frame if necessary
player->SetMoveType( MOVETYPE_WALK );
player->SetMoveCollide( MOVECOLLIDE_DEFAULT );
}
}
}
// Handle movement modes.
switch (player->GetMoveType())
{
case MOVETYPE_NONE:
break;
case MOVETYPE_NOCLIP:
FullNoClipMove( sv_noclipspeed.GetFloat(), sv_noclipaccelerate.GetFloat() );
break;
case MOVETYPE_FLY:
case MOVETYPE_FLYGRAVITY:
FullTossMove();
break;
case MOVETYPE_LADDER:
FullLadderMove();
break;
case MOVETYPE_WALK:
FullWalkMove();
break;
case MOVETYPE_ISOMETRIC:
//IsometricMove();
// Could also try: FullTossMove();
FullWalkMove();
break;
case MOVETYPE_OBSERVER:
FullObserverMove(); // clips against world&players
break;
default:
DevMsg( 1, "Bogus pmove player movetype %i on (%i) 0=cl 1=sv\n", player->GetMoveType(), player->IsServer());
break;
}
}
//-----------------------------------------------------------------------------
// Performs the collision resolution for fliers.
//-----------------------------------------------------------------------------
void CGameMovement::PerformFlyCollisionResolution( trace_t &pm, Vector &move )
{
Vector base;
float vel;
float backoff;
switch (player->GetMoveCollide())
{
case MOVECOLLIDE_FLY_CUSTOM:
// Do nothing; the velocity should have been modified by touch
// FIXME: It seems wrong for touch to modify velocity
// given that it can be called in a number of places
// where collision resolution do *not* in fact occur
// Should this ever occur for players!?
Assert(0);
break;
case MOVECOLLIDE_FLY_BOUNCE:
case MOVECOLLIDE_DEFAULT:
{
if (player->GetMoveCollide() == MOVECOLLIDE_FLY_BOUNCE)
backoff = 2.0 - player->m_surfaceFriction;
else
backoff = 1;
ClipVelocity (mv->m_vecVelocity, pm.plane.normal, mv->m_vecVelocity, backoff);
}
break;
default:
// Invalid collide type!
Assert(0);
break;
}
// stop if on ground
if (pm.plane.normal[2] > 0.7)
{
base.Init();
if (mv->m_vecVelocity[2] < sv_gravity.GetFloat() * gpGlobals->frametime)
{
// we're rolling on the ground, add static friction.
SetGroundEntity( &pm );
mv->m_vecVelocity[2] = 0;
}
vel = DotProduct( mv->m_vecVelocity, mv->m_vecVelocity );
// Con_DPrintf("%f %f: %.0f %.0f %.0f\n", vel, trace.fraction, ent->velocity[0], ent->velocity[1], ent->velocity[2] );
if (vel < (30 * 30) || (player->GetMoveCollide() != MOVECOLLIDE_FLY_BOUNCE))
{
SetGroundEntity( &pm );
mv->m_vecVelocity.Init();
}
else
{
VectorScale (mv->m_vecVelocity, (1.0 - pm.fraction) * gpGlobals->frametime * 0.9, move);
PushEntity( move, &pm );
}
VectorSubtract( mv->m_vecVelocity, base, mv->m_vecVelocity );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameMovement::FullTossMove( void )
{
trace_t pm;
Vector move;
CheckWater();
// add velocity if player is moving
if ( (mv->m_flForwardMove != 0.0f) || (mv->m_flSideMove != 0.0f) || (mv->m_flUpMove != 0.0f))
{
Vector forward, right, up;
float fmove, smove;
Vector wishdir, wishvel;
float wishspeed;
int i;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
// Copy movement amounts
fmove = mv->m_flForwardMove;
smove = mv->m_flSideMove;
VectorNormalize (forward); // Normalize remainder of vectors.
VectorNormalize (right); //
for (i=0 ; i<3 ; i++) // Determine x and y parts of velocity
wishvel[i] = forward[i]*fmove + right[i]*smove;
wishvel[2] += mv->m_flUpMove;
VectorCopy (wishvel, wishdir); // Determine maginitude of speed of move
wishspeed = VectorNormalize(wishdir);
//
// Clamp to server defined max speed
//
if (wishspeed > mv->m_flMaxSpeed)
{
VectorScale (wishvel, mv->m_flMaxSpeed/wishspeed, wishvel);
wishspeed = mv->m_flMaxSpeed;
}
// Set pmove velocity
Accelerate ( wishdir, wishspeed, sv_accelerate.GetFloat() );
}
if ( mv->m_vecVelocity[2] > 0 )
{
SetGroundEntity( NULL );
}
// If on ground and not moving, return.
if ( player->GetGroundEntity() != NULL )
{
if (VectorCompare(player->GetBaseVelocity(), vec3_origin) &&
VectorCompare(mv->m_vecVelocity, vec3_origin))
return;
}
CheckVelocity();
// add gravity
if ( player->GetMoveType() == MOVETYPE_FLYGRAVITY )
{
AddGravity();
}
// move origin
// Base velocity is not properly accounted for since this entity will move again after the bounce without
// taking it into account
VectorAdd (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity);
CheckVelocity();
VectorScale (mv->m_vecVelocity, gpGlobals->frametime, move);
VectorSubtract (mv->m_vecVelocity, player->GetBaseVelocity(), mv->m_vecVelocity);
PushEntity( move, &pm ); // Should this clear basevelocity
CheckVelocity();
if (pm.allsolid)
{
// entity is trapped in another solid
SetGroundEntity( &pm );
mv->m_vecVelocity.Init();
return;
}
if (pm.fraction != 1)
{
PerformFlyCollisionResolution( pm, move );
}
// check for in water
CheckWater();
}
//-----------------------------------------------------------------------------
// Purpose: TF2 commander mode movement logic
//-----------------------------------------------------------------------------
#pragma warning (disable : 4701)
void CGameMovement::IsometricMove( void )
{
int i;
Vector wishvel;
float fmove, smove;
Vector forward, right, up;
AngleVectors (mv->m_vecViewAngles, &forward, &right, &up); // Determine movement angles
// Copy movement amounts
fmove = mv->m_flForwardMove;
smove = mv->m_flSideMove;
// No up / down movement
forward[2] = 0;
right[2] = 0;
VectorNormalize (forward); // Normalize remainder of vectors
VectorNormalize (right); //
for (i=0 ; i<3 ; i++) // Determine x and y parts of velocity
wishvel[i] = forward[i]*fmove + right[i]*smove;
//wishvel[2] += mv->m_flUpMove;
Vector out;
VectorMA (mv->GetAbsOrigin(), gpGlobals->frametime, wishvel, out );
mv->SetAbsOrigin( out );
// Zero out the velocity so that we don't accumulate a huge downward velocity from
// gravity, etc.
mv->m_vecVelocity.Init();
}
#pragma warning (default : 4701)
bool CGameMovement::GameHasLadders() const
{
return true;
} | [
"[email protected]"
]
| [
[
[
1,
4750
]
]
]
|
c8d7d4deb3a4e643d43f5f577d0870413c09d2bd | 4be39d7d266a00f543cf89bcf5af111344783205 | /test_boost_regex/main.cpp | 2231b33c47098a36c4aec304509da695b51d4dc7 | []
| no_license | nkzxw/lastigen-haustiere | 6316bb56b9c065a52d7c7edb26131633423b162a | bdf6219725176ae811c1063dd2b79c2d51b4bb6a | refs/heads/master | 2021-01-10T05:42:05.591510 | 2011-02-03T14:59:11 | 2011-02-03T14:59:11 | 47,530,529 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,145 | cpp |
#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
void parseUrl( const std::string& url)
{
//std::string regExStr = "(ftp|http|https):\\/\\/((\\w+\\.)*(\\w*))\\/([\\w\\d]+\\/{0,1})+";
/*
//std::string regExStr = "^(?#Protocol)(?:(?:ht|f)tp(?:s?)\\:\\/\\/|~/|/)?(?#Username:Password)(?:\\w+:\\w+@)?(?#Subdomains)(?:(?:[-\\w]+\\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|/)+|\\?|#)?(?#Query)(?:(?:\\?(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)(?:&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*(?#Anchor)(?:#(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?$ ";
std::string regExStr = "^(?#Protocol)(?:(?:ht|f)tp(?:s?)\\:\\/\\/|~/|/)?
(?#Username:Password)(?:\\w+:\\w+@)?
(?#Subdomains)(?:(?:[-\\w]+\\.)+
(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2})
)
(?#Port)(?::[\\d]{1,5})?
(?#Directories)(?:(?:(?:/(?:[-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|/)+|\\?|#)?
(?#Query)(?:(?:\\?(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)(?:&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*
(?#Anchor)(?:#(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?$ ";
*/
/*
std::string regExStr = "(ftp|http|https)
:\\/\\/
(
(\\w+\\.)*
(\\w*)
)
\\/
([\\w\\d]+\\/{0,1})+";
std::string regExStr = "(ftp|http|https)
:\\/\\/
(^:+)
\\/
([\\w\\d]+\\/{0,1})+";
std::string regExStr = "(ftp|http|https)
:\\/\\/
(^:+)
(:[\\d]{1,5})?
";
*/
//std::string regExStr = "(ftp|http|https):\\/\\/((\\w+\\.)*(\\w*))\\/([\\w\\d]+\\/{0,1})+";
//std::string regExStr = "(ftp|http|https):\\/\\/(^:+)\\/([\\w\\d]+\\/{0,1})+";
std::string regExStr = "(ftp|http|https):\\/\\/(^:+)(:[\\d]{1,5})?";
boost::regex regEx;
boost::cmatch matches;
try
{
// Assignment and construction initialize the FSM used for regexp parsing
regEx = regExStr;
}
catch (boost::regex_error& e)
{
cout << regExStr << " is not a valid regular expression: \"" << e.what() << "\"" << endl;
return;
}
// if (boost::regex_match(s.begin(), s.end(), regEx))
//if (boost::regex_match(url, matches, regEx))
if (boost::regex_match(url.c_str(), matches, regEx))
{
// matches[0] contains the original string. matches[n] contains a sub_match object for each matching subexpression
for (int i = 1; i < matches.size(); i++)
{
// sub_match::first and sub_match::second are iterators that refer to the first and one past the last chars of the matching subexpression
string match(matches[i].first, matches[i].second);
cout << "\tmatches[" << i << "] = " << match << endl;
}
}
else
{
cout << "The regexp \"" << regExStr << "\" does not match \"" << url << "\"" << endl;
}
}
int main( )
{
//std::string url = "http://www.foo.com/bar";
std::string url = "http://www.foo.com:8080";
parseUrl(url);
std::cin.sync();
std::cin.get();
}
//----------------------------------------------------------------------------------------------------
//int main(int argc, char **argv)
//{
//
// std::string html = "<ul><li><a href=\"http://www.clarin.com/shared/v9/moviles/\" title=\"Clarín Móviles\" target=\"_blank\">Clarín Móviles</a></li><li><a href=\"http://www.clarin.com/shared/v9/moviles/sms.html\" title=\"Clarín SMS\" target=\"_blank\">Clarín SMS</a></li><li><a href=\"http://www.clarin.com/shared/v9/moviles/pda.html\" title=\"Versión Palm\" target=\"_blank\">Versión Palm</a></li><li><a href=\"http://toolbar.clarin.com/\" title=\"Toolbar Clarín.com\" target=\"_blank\">Toolbar Clarín.com</a></li><li><a href=\"http://www.clarin.com/shared/v9/rss.html\" title=\"Noticias RSS\" target=\"_blank\">Noticias RSS</a></li><li><a href=\"http://www.clarin.com/servicios/rss/lector/v8/help.html\" title=\"Lector de noticias RSS\" target=\"_blank\">Lector de noticias RSS</a></li><li><a href=\"http://www.clarin.com/shared/v9/rss.html\" title=\"Noticias gratis en su sitio\" target=\"_blank\">Noticias gratis en su sitio</a></li><!--li><a href=\"http://www.clarin.com/shared/v9/moviles/podcast.html\" title=\"Podcasting\" target=\"_blank\">Podcasting</a></li--><li><a href=\"http://www.clarin.com/shared/v9/ayuda-clarin/index.html\" title=\"Ayuda\" target=\"_blank\">Ayuda</a></li><li><a href=\"http://www.clarin.com/servicios/edicionesanteriores/\" title=\"Archivo\" target=\"_blank\">Archivo</a></li><li><a href=\"http://www.buscador.clarin.com/\" title=\"Buscador\" target=\"_blank\">Buscador</a></li></ul>";
//
// std::string fulls = html;
// boost::regex re("<a href=\"([^\"]*)\"");
// boost::sregex_iterator begin(fulls.begin(), fulls.end(), re), end;
//
//
//
//
//
// std::string sub;
//
// for (;begin!=end;++begin)
// {
// boost::smatch const &what = *begin;
// //sub = CString(what[0].first,what[0].length());
// sub = ""; //what[0].first;
//
// //std::cout << what[0].first ;
//
// if ( what[0].matched )
// {
// what[0].first ;
// //printf(what[0].first) ;
//
// //AfxMessageBox(sub);
// std::cout << sub << std::endl;
//
// }
//
//
// }
//
// return 0;
//}
//----------------------------------------------------------------------------------------------------
//#define BOOST_REGEX_MATCH_EXTRA
//
//
//
//#include <boost/regex.hpp>
//#include <iostream>
//
//
//void print_captures(const std::string& regx, const std::string& text)
//{
// boost::regex e(regx);
// boost::smatch what;
// std::cout << "Expression: \"" << regx << "\"\n";
// std::cout << "Text: \"" << text << "\"\n";
// if(boost::regex_match(text, what, e, boost::match_extra))
// {
// unsigned i, j;
// std::cout << "** Match found **\n Sub-Expressions:\n";
// for(i = 0; i < what.size(); ++i)
// std::cout << " $" << i << " = \"" << what[i] << "\"\n";
// std::cout << " Captures:\n";
// for(i = 0; i < what.size(); ++i)
// {
// std::cout << " $" << i << " = {";
// for(j = 0; j < what.captures(i).size(); ++j)
// {
// if(j)
// std::cout << ", ";
// else
// std::cout << " ";
// std::cout << "\"" << what.captures(i)[j] << "\"";
// }
// std::cout << " }\n";
// }
// }
// else
// {
// std::cout << "** No Match found **\n";
// }
//}
//
//int main(int , char* [])
//{
// print_captures("(([[:lower:]]+)|([[:upper:]]+))+", "aBBcccDDDDDeeeeeeee");
// print_captures("(.*)bar|(.*)bah", "abcbar");
// print_captures("(.*)bar|(.*)bah", "abcbah");
// print_captures("^(?:(\\w+)|(?>\\W+))*$", "now is the time for all good men to come to the aid of the party");
// return 0;
//}
| [
"fpelliccioni@c29dda52-a065-11de-a33f-1de61d9b9616"
]
| [
[
[
1,
203
]
]
]
|
00f37e3b2d8d5ff18d3f735a95f7a35072d36876 | 7f6f9788d020e97f729af85df4f6741260274bee | /src/gui/Event.cpp | ba172dfb994c68e5e437843634f224e71897e964 | []
| no_license | cnsuhao/nyanco | 0fb88ed1cf2aa9390fa62f6723e8424ba9a42ed4 | ba199267a33d4c6d2e473ed4b777765057aaf844 | refs/heads/master | 2021-05-31T05:37:51.892873 | 2008-05-27T05:23:19 | 2008-05-27T05:23:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,007 | cpp | /*!
@file Event.cpp
@author dasyprocta
*/
#include "Event.h"
#include <iostream>
// test
BEGIN_NO_NAMESPACE
#if 0
void testEventServer()
{
using namespace nyanco::gui;
struct Button {};
struct List {};
struct CheckBox {};
class Frame : public EventServer
{
void onClickButton(Event<Button> const& e)
{
std::cout << "hello button!!\n";
}
void onClickList(Event<List> const& e)
{
std::cout << "hello list!!\n";
}
public:
Frame()
{
;
registerHandler(ButtonId, &Frame::onClickButton);
registerHandler(ListId, &Frame::onClickList);
}
enum ComponentId
{
ButtonId,
ListId,
CheckBoxId,
};
};
EventServer es;
es.queueEvent(Frame::ButtonId, Event<Button>());
es.invokeHandler();
}
#endif
END_NO_NAMESPACE
| [
"dasyprocta@27943c09-b335-0410-ab52-7f3c671fdcc1"
]
| [
[
[
1,
55
]
]
]
|
403e17af6d75b9f36cb33419e2bfc5d69392ac9a | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/GumpEditor/entity/GumpPaperdoll.cpp | d3190fc17f1ba3fda4bf96a91bde851f3b8a3b6d | []
| 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 | 760 | cpp | #include "StdAfx.h"
#include "GumpEditor.h"
#include ".\gumppaperdoll.h"
CGumpPaperdoll::CGumpPaperdoll(CGumpPtr pGump) : CGumpPicture(NULL)
{
SetGump(pGump);
SetTitle("paperdoll");
SetType("paperdoll");
CString strName;
strName.Format("paperdoll_%x", pGump ? pGump->GetGumpID() : 0);
SetName(strName);
//AddPropertyPage( &m_page );
}
CGumpPaperdoll::~CGumpPaperdoll(void)
{
}
CDiagramEntity* CGumpPaperdoll::Clone()
{
CGumpPaperdoll* obj = new CGumpPaperdoll(m_pGump);
obj->Copy( this );
return obj;
}
CGumpEntity* CGumpPaperdoll::CreateFromNode( XML::Node* node )
{
CGumpPaperdoll* obj = new CGumpPaperdoll(NULL);
if (!obj->FromString( node ))
{
delete obj;
obj = NULL;
}
return obj;
}
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
42
]
]
]
|
4328e67a23bfc4ed305c4cb62838bbd8ba4b67a8 | 7575692fd3800ec48e7c941cdd40210d02ca96d0 | /advanced-cpp-pa1/advanced-cpp-pa1/intArray_t.h | 41d07dabccfe84631d552a63337dced3864e71dd | []
| no_license | husamMaruf/advanced-programming-2011 | bf577a8cc51d53599ed032c22ae31fc15db217fb | db285ae560495bd051400f0e372a2eec2434afe1 | refs/heads/master | 2021-01-10T10:12:46.760433 | 2011-05-21T17:00:12 | 2011-05-21T17:00:12 | 36,380,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | #pragma once
#include "stdafx.h"
#include <iostream>
#define CAPACITY_EXPAND_FACTOR 16
using namespace std;
class intArray_t {
public:
intArray_t();
intArray_t(const int& initCapacity);
~intArray_t();
int isEmpty() const { return length == 0; }
int numOfItems() const { return length; }
int capacity() const { return cap; }
int* first() const { return isEmpty() ? NULL : intArray[0]; }
int* last() const { return isEmpty() ? NULL : intArray[length-1]; }
int* remove(const int& value);
void removeAll();
int removeAndDelete(const int& value);
void removeAndDeleteAll();
void insert(int* element);
int* find(const int& value) const;
int append(const int& index, int* element);
int prepend(const int& index, int* element);
ostream& printToStream(ostream& os) const;
private:
intArray_t(const intArray_t&);
intArray_t& operator= (const intArray_t&);
void expand(const int& addedCapacity);
int addElement(const int& index, int* element, bool isPrepend);
int** intArray;
int cap;
int length;
};
ostream &operator<<(ostream& os, const intArray_t& intArray); | [
"dankilman@a7c0e201-94a5-d3f3-62b2-47f0ba67a830",
"[email protected]"
]
| [
[
[
1,
1
],
[
3,
10
],
[
13,
18
],
[
22,
24
],
[
27,
28
],
[
33,
38
]
],
[
[
2,
2
],
[
11,
12
],
[
19,
21
],
[
25,
26
],
[
29,
32
]
]
]
|
008f2626155e7b37559ece48ccb057a6e648feb4 | 1a671980a21ef2e96ea8907a961a200381295407 | /Rain/RainEditor/EngineWidget.cpp | fe6d37ac443966eb4b8b58a38daa55acc2522287 | []
| no_license | aosyang/existproj | 7061abccec18f08ea07e742cf1ac988aa9f03a0c | 78d92d81cc15234507305c83f3dff3b94edf091e | refs/heads/master | 2021-01-02T08:52:06.056633 | 2010-03-14T14:36:48 | 2010-03-14T14:36:48 | 34,500,388 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,466 | cpp | #include "EngineWidget.h"
#include <QResizeEvent>
EngineWidget::EngineWidget(QWidget* parent, Qt::WindowFlags f)
: QWidget(parent, f),
m_ExistTimer(NULL),
m_Game(NULL)
{
}
EngineWidget::~EngineWidget()
{
m_Game->Shutdown();
Engine::Instance().Shutdown();
SAFE_DELETE(m_ExistTimer);
SAFE_DELETE(m_Game);
}
void EngineWidget::resizeEvent(QResizeEvent* event)
{
int w = event->size().width();
int h = event->size().height();
Engine::Instance().ResizeWindow(w, h);
}
void EngineWidget::InitEngine()
{
// 这个方法将获取窗体的HWND(Win32)
WId hwnd = winId();
m_ExistTimer = new Timer();
m_ExistTimer->Reset();
m_LastUpdateTime = m_ExistTimer->GetMilliseconds();
m_Game = new RainGame();
Engine::Instance().SetGame(m_Game);
System::Instance().SetRenderWindowHandle(static_cast<RenderWindowHandle>(hwnd));
Engine::Instance().Initialize(false);
System::Instance().LoadResources("resources.cfg");
m_Game->StartGame();
}
void EngineWidget::UpdateEngine()
{
if (!m_ExistTimer) return;
unsigned long deltaTime = m_ExistTimer->GetMilliseconds() - m_LastUpdateTime;
m_LastUpdateTime = m_ExistTimer->GetMilliseconds();
Engine::Instance().ManualUpdate(deltaTime);
}
void EngineWidget::mousePressEvent(QMouseEvent* event)
{
// 点击渲染空间,在游戏中选择对象
Zone* zone = m_Game->SelectZoneByClick(event->x(), event->y());
emit ZoneSelected(zone);
}
| [
"aosyang@72c02e12-28e2-11df-b412-b12aa31876ca"
]
| [
[
[
1,
65
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.